Registry / ai-ml / pytorch-crf

pytorch-crf

JSON →
library0.7.2pypypiunverified

PyTorch CRF is a library for implementing Conditional Random Fields (CRF) in PyTorch. Version 0.7.2 is the latest stable release. It provides a CRF layer that can be used in sequence labeling models. The library is lightweight and well-maintained, released under the MIT license.

pip install pytorch-crf
INSTALL
IMPORT
SIG · PYTORCH-CRF
P
pytorch-crf
ai-mlpythonv0.7.2
harness data pending
Install & Compatibility
Where this runs

No compatibility data collected yet for this library.

Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

CRF
✓ from crf import CRF
✗ from torchcrf import CRF

Initialize a CRF layer, compute negative log-likelihood loss for a batch of sequences.

import torch from torchcrf import CRF num_tags = 5 model = CRF(num_tags, batch_first=True) # Example emission scores (batch_size, seq_len, num_tags) emissions = torch.randn(2, 10, num_tags) tags = torch.randint(0, num_tags, (2, 10)) mask = torch.ones(2, 10, dtype=torch.bool) # Compute negative log-likelihood loss loss = -model(emissions, tags, mask=mask) print(f"Loss: {loss.item()}")
Debug
Known issues
breakingPyTorch 2.x changes: The CRF forward method may have issues with torch.no_grad() in inference. Ensure you use model.eval() and torch.inference_mode() for inference.
fix
Wrap inference in torch.inference_mode() or with torch.no_grad() appropriately.
affects: >=0.7.2 with PyTorch >=2.0
breakingBatch first vs batch second: The CRF constructor expects 'batch_first' argument. If you omit it, default is False (batch dimension second). Mismatch causes shape errors.
fix
Always specify batch_first=True if your emissions have shape (batch, seq_len, num_tags).
affects: all
gotchaMask is mandatory for variable-length sequences: If you pass sequences of different lengths, you must provide a mask of dtype torch.bool. Otherwise, the CRF will treat all positions as valid, leading to incorrect gradients.
fix
Create a padding mask (True for valid positions, False for padding) and pass it to the CRF functions.
affects: all
gotchaBackward compatibility with old PyTorch: If you use torch<1.7, CRF may not work due to missing torch.bool dtype. Upgrade PyTorch to at least 1.7.
fix
pip install torch>=1.7
affects: 0.7.x
Upgrade
Version history
0.7.2latest on PyPI · released Feb 4, 2019
Audit
Dependencies
torchrequiredCRF is built on PyTorch tensors and autograd.
Agent activity
32 hits · last 30 days
node
30
OpenAI (training)
1
Resources
pytorch-crf — pip install pytorch-crf · libregistry