Skip to main content

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 decoding
  • forward_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

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.2forward_and_decode (fused loss + Viterbi), pytest suite, docs, publish workflow.
  • 0.1.1 — initial release; full list of differences from pytorch-crf.

Acknowledgements

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pyt_crf-0.1.2.tar.gz (8.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pyt_crf-0.1.2-py3-none-any.whl (9.8 kB view details)

Uploaded Python 3

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

Hashes for pyt_crf-0.1.2.tar.gz
Algorithm Hash digest
SHA256 d948da3ed10d35df4e080564443c023a8763a84109af39d95f4f65d2a4b7a335
MD5 63ccf8ecad82162265d35aa2d79f8ec3
BLAKE2b-256 921cdcc9791f3faed671db83055061e507614a4ed355f30b806d6f51392e947d

See more details on using hashes here.

Provenance

The following attestation bundles were made for pyt_crf-0.1.2.tar.gz:

Publisher: publish.yml on id4thomas/pyt-crf

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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

Hashes for pyt_crf-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 25e9c032944a81e103b590ceefaa3dc0bda416c2cda74bbe0b722bd4f936aa4e
MD5 9b0947403c5dcf48bd124bdbae6f9e30
BLAKE2b-256 f418c9e7ab45a93489114c5091666f9850e292137241571fe0c3f43e1618c5b1

See more details on using hashes here.

Provenance

The following attestation bundles were made for pyt_crf-0.1.2-py3-none-any.whl:

Publisher: publish.yml on id4thomas/pyt-crf

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page