A modern linear-chain CRF (Conditional Random Field) layer for PyTorch
Project description
pyt-crf
A modern linear-chain CRF (Conditional Random Field) layer for PyTorch.
forward()returns the negative log-likelihood directly (ready for.backward())decode()runs batched Viterbi decodingforward_and_decode()computes both in one fused sweep (for eval during training), with separate loss/decode masks- Batch-first (
batch, seq_len, num_tags) by default
See docs/explanation.md for how the CRF math maps to
the code.
Requirements
- Python >= 3.12
- PyTorch >= 2.10
Usage
import torch
from pyt_crf import CRF
crf = CRF(num_tags=5)
emissions = torch.randn(2, 7, 5) # (batch, seq_len, num_tags)
tags = torch.randint(5, (2, 7)) # (batch, seq_len)
mask = torch.ones(2, 7, dtype=torch.bool) # True = real token, False = padding
loss = crf(emissions, tags, mask) # scalar NLL loss
loss.backward()
best_paths = crf.decode(emissions, mask) # List[List[int]]
# eval during training: loss + decode in one fused sweep,
# with separate masks for the loss (-100 labels) and decoding (attention mask)
loss, best_paths = crf.forward_and_decode(
emissions, tags, loss_mask=mask, decode_mask=mask
)
[!WARNING] Run the CRF in float32. The forward/Viterbi recursions accumulate
logsumexp/max scores over the whole sequence, which is numerically unstable in bf16/fp16. Keep the CRF parameters in fp32 and cast emissions before the layer —crf(emissions.float(), ...)— even when the backbone runs in bf16/autocast.
Examples
examples/conll2003— NER fine-tuning on tner/conll2003 with a Gemma3-based backbone + CRF head.
Build (wheel)
uv build
# or, without uv:
pip install build
python -m build
Both commands produce dist/pyt_crf-<version>-py3-none-any.whl (plus the
sdist dist/pyt_crf-<version>.tar.gz). The version comes from
pyproject.toml.
Install
# from the built wheel
pip install dist/pyt_crf-<version>-py3-none-any.whl
# or editable, for development
pip install -e .
Test
Tests live in tests/ and run with pytest. pyproject.toml already puts
src/ on the import path for pytest, so no install is needed beforehand.
conda activate py312
pip install pytest
pytest # run the whole suite
pytest -v # per-test names
pytest -k fused # only tests matching a keyword
# or with uv (pytest comes from the dev dependency group):
uv run pytest
The suite checks forward/decode against brute-force enumeration of all
tag paths (including masks with mid-sequence holes), verifies
forward_and_decode returns exactly the same loss/paths/gradients as the
separate calls, and covers input validation.
Changelog
- 0.1.2 —
forward_and_decode(fused loss + Viterbi), pytest suite, docs, publish workflow. - 0.1.1 — initial release; full list of differences from pytorch-crf.
Acknowledgements
- This package mostly follows implementation of kmkurn/pytorch-crf.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file pyt_crf-0.1.2.tar.gz.
File metadata
- Download URL: pyt_crf-0.1.2.tar.gz
- Upload date:
- Size: 8.6 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
d948da3ed10d35df4e080564443c023a8763a84109af39d95f4f65d2a4b7a335
|
|
| MD5 |
63ccf8ecad82162265d35aa2d79f8ec3
|
|
| BLAKE2b-256 |
921cdcc9791f3faed671db83055061e507614a4ed355f30b806d6f51392e947d
|
Provenance
The following attestation bundles were made for pyt_crf-0.1.2.tar.gz:
Publisher:
publish.yml on id4thomas/pyt-crf
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
pyt_crf-0.1.2.tar.gz -
Subject digest:
d948da3ed10d35df4e080564443c023a8763a84109af39d95f4f65d2a4b7a335 - Sigstore transparency entry: 2135248193
- Sigstore integration time:
-
Permalink:
id4thomas/pyt-crf@74ad81f6bd1b2d65c7868546bf329eaa4010daf9 -
Branch / Tag:
refs/tags/v0.1.2 - Owner: https://github.com/id4thomas
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@74ad81f6bd1b2d65c7868546bf329eaa4010daf9 -
Trigger Event:
push
-
Statement type:
File details
Details for the file pyt_crf-0.1.2-py3-none-any.whl.
File metadata
- Download URL: pyt_crf-0.1.2-py3-none-any.whl
- Upload date:
- Size: 9.8 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
25e9c032944a81e103b590ceefaa3dc0bda416c2cda74bbe0b722bd4f936aa4e
|
|
| MD5 |
9b0947403c5dcf48bd124bdbae6f9e30
|
|
| BLAKE2b-256 |
f418c9e7ab45a93489114c5091666f9850e292137241571fe0c3f43e1618c5b1
|
Provenance
The following attestation bundles were made for pyt_crf-0.1.2-py3-none-any.whl:
Publisher:
publish.yml on id4thomas/pyt-crf
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
pyt_crf-0.1.2-py3-none-any.whl -
Subject digest:
25e9c032944a81e103b590ceefaa3dc0bda416c2cda74bbe0b722bd4f936aa4e - Sigstore transparency entry: 2135248223
- Sigstore integration time:
-
Permalink:
id4thomas/pyt-crf@74ad81f6bd1b2d65c7868546bf329eaa4010daf9 -
Branch / Tag:
refs/tags/v0.1.2 - Owner: https://github.com/id4thomas
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@74ad81f6bd1b2d65c7868546bf329eaa4010daf9 -
Trigger Event:
push
-
Statement type: