Conditional Random Fields, one defect at a time
A tutorial that builds up to the linear-chain CRF by walking a ladder of
sequence-labeling models. Each rung exists because the rung below it is broken
in a specific, demonstrable way, and each rung is anchored to a published paper,
a public course note, or an open-source library you can check the answer against.
Nothing here is a survey. Every claim in the prose is either derived in the text
or cited to a source you can open, and every algorithm is implemented from
scratch and then checked — against brute-force enumeration of the definition,
and, for the CRF, against two established libraries.
Task throughout: part-of-speech tagging on the Universal Dependencies English
Web Treebank. One task the whole way up, so that every rung is measured against
the one below it on identical data.
The ladder
Chapters 5 and 6 are the two the title promises. Chapters 1–4 exist so that when
you get there, global normalization reads as the obvious fix to a problem you
have already watched happen, rather than as a definition to memorize.
The two chapters that carry the argument
Chapter 4 builds Lafferty et al.'s rib/rob automaton and shows a trained
MEMM failing on it:
x = r i b p(rib | x) = 0.4875 p(rob | x) = 0.5122 -> rob
x = r o b p(rib | x) = 0.4874 p(rob | x) = 0.5123 -> rob
Changing the one letter that decides the answer moves the model’s belief by
0.0001. The four-line proof of why is in seqlab/labelbias.py, and it works by
taking the observations as an argument and never reading them.
Chapter 8 puts the CRF on the same data, with the same features and the same
code path:
x = r i b p(rib | x) = 0.9658 p(rob | x) = 0.0341 -> rib
x = r o b p(rib | x) = 0.0329 p(rob | x) = 0.9670 -> rob
Chapter 4 also derives the precise version of the claim, which the usual telling
omits: every CRF can be written as a MEMM whose local conditionals carry the
backward message β_t. Local normalization is not the defect — a bounded
feature window is. Measured both ways: one symbol of lookahead takes the same
MEMM from 49.6% error to 7.4%, against a derived Bayes floor of 6.25%.
Results
UD_English-EWT dev, 2,001 sentences / 25,148 tokens. Every model on identical
config — same sigma, same min_count, same training subset — because a ladder
is only a ladder if the rungs differ in one thing.
Trained on 2,000 sentences:
| Chapter |
Model |
Token |
Sentence |
OOV |
| 0 |
Most-frequent-tag baseline |
80.56% |
— |
— |
| 1 |
HMM + Viterbi |
80.28% |
15.99% |
28.95% |
| 2 |
Log-linear, per token, no chain |
89.39% |
35.38% |
72.50% |
| 3 |
MEMM + Viterbi |
89.53% |
37.93% |
72.69% |
| 6–8 |
CRF + Viterbi |
90.15% |
40.68% |
73.96% |
(OOV rate on dev: 18.71%.)
Read the columns, not just the bold number. In the token column the entire
sequence-modeling half of this tutorial — Chapters 3 through 8 — is worth 0.76
points over a classifier that cannot see a single neighbouring label. In the
sentence column the same three models are 35.38%, 37.93% and 40.68%: gaps three
to four times larger. A chain buys coherence across a whole sequence, and a
metric that averages over tokens independently is close to the wrong instrument
for measuring it.
That metric was chosen before the CRF was trained, not after the token column
came out flat. Chapter 8 says so, and says why the ordering matters.
What is checked against what
Every algorithm is validated, and the validation is always against something
that shares no code with it:
| Chapter |
Claim |
Checked against |
Result |
| 1 |
Viterbi, forward |
enumeration of all K^T paths |
exact |
| 2 |
log-linear gradient |
finite differences |
7.8e-09 |
| 3 |
MEMM is a proper distribution |
enumeration |
exact |
| 4 |
label bias |
a closed-form proof + Lafferty §5.1’s generator |
— |
| 5 |
Gibbs ⇒ Markov |
the enumerated joint |
2.2e-16 |
| 6 |
Σ_k λ_k f_k = table lookup |
a literal loop over all K² indicators |
exact |
| 6 |
every HMM is a CRF |
the HMM’s own conditional |
3.6e-15 |
| 7 |
log Z, marginals, Viterbi |
enumeration of all K^T sequences |
1.4e-14 |
| 8 |
the CRF gradient |
finite differences |
2.62e-09 |
| 9 |
the torch CRF layer |
crf.py and pytorch-crf |
0.0, 7.1e-15 |
| 9 |
Chapter 8’s gradient |
torch autograd |
5.6e-16 |
| 10 |
log Z, Viterbi |
pytorch-crf |
7.1e-15 |
| 10 |
the whole trained model |
sklearn-crfsuite, end to end |
98.25% token agreement |
| 11 |
semi-Markov log Z |
enumeration over segmentations |
7.1e-15 |
Why part-of-speech tagging, and why this corpus
CRFs were introduced on sequence labeling, and every source cited here uses a
labeling task. Keeping the same domain as the literature means you can put this
tutorial next to the original papers and the symbols line up.
The corpus is UD_English-EWT,
CC BY-SA 4.0 — genuinely redistributable, unlike the usual choice.
A licensing note worth knowing. Most CRF tutorials use CoNLL-2000 chunking
or CoNLL-2003 NER. Both are derived from corpora you cannot freely
redistribute: CoNLL-2000 comes from Penn Treebank WSJ sections 15–18 and 20
(LDC99T42), and CoNLL-2003’s English
half is built on the Reuters RCV1 corpus, which is why
its official page
distributes annotations only. This repository ships no corpus at all;
scripts/download_data.py fetches UD-EWT at run time and data/ is
gitignored.
Running it
pip install -r requirements.txt
python scripts/download_data.py # fetches UD_English-EWT into data/
./scripts/run_all_checks.sh # every chapter, a few minutes
./scripts/run_all_checks.sh --full # full training set; use a compute node
python tests/check_ch07.py # or one chapter at a time
Most chapters’ checks need no corpus at all and run in seconds. The ones that
train — 2, 3, 8, 9, 10 — take a couple of minutes on the default 2,000-sentence
subset and a couple of hours in total with --full.
If training crawls, it is your BLAS. The matrices here are small enough
that a threaded BLAS spends all its time synchronising: measured, the same fit
took 235s multi-threaded and 4.0s pinned to one thread, bit-identical
result. The check scripts set OMP_NUM_THREADS=1 before importing numpy.
That ordering is load-bearing — those variables are read when numpy loads, so
setting them afterwards silently does nothing.
How the code is meant to be read
Every chapter is a markdown file that explains the idea and a module in
seqlab/ with the implementation.
Each function in those modules states its exercise in the docstring — the
derivation, the recurrence, the bug to avoid — and then gives the
implementation below it. To use them as a problem set, delete a body back to
raise NotImplementedError and rebuild it from the docstring;
tests/check_chNN.py will tell you whether you got it right, using
hand-computed values, brute-force enumeration, and — in Chapters 9 and 10 — a
reference library.
seqlab/crf.py carries Chapters 6–8 and says which order to rebuild its
functions in. It is not the gradient first.
Licence
- Code (
seqlab/, tests/, scripts/): MIT — see LICENSE.
- Prose (
tutorial/, README.md, REFERENCES.md): CC BY 4.0 — see
LICENSE-PROSE.
- Data: not distributed here. UD_English-EWT is CC BY-SA 4.0 and is fetched
at run time; its terms are its own.
See NOTICE.md for attribution and for what this repository does and
does not borrow.
References
The full annotated bibliography — what each source is good for, and which
chapter leans on it — is in REFERENCES.md. The short version:
The papers the model comes from
- Lafferty, J., McCallum, A. & Pereira, F. (2001). Conditional Random Fields:
Probabilistic Models for Segmenting and Labeling Sequence Data. ICML 2001,
282–289. PDF
— the origin. §2 is the label-bias argument and is still the clearest
statement of why; §5.1 is the experiment Chapter 4 replicates.
- Sutton, C. & McCallum, A. (2011). An Introduction to Conditional Random
Fields. Foundations and Trends in ML 4(4), 267–373.
arXiv:1011.4088 — the standing reference.
If you read one thing, read this.
- Rabiner, L. (1989). A Tutorial on Hidden Markov Models and Selected
Applications in Speech Recognition. Proc. IEEE 77(2).
- McCallum, A., Freitag, D. & Pereira, F. (2000). Maximum Entropy Markov Models
for Information Extraction and Segmentation. ICML 2000.
Course notes — where the derivations are actually spelled out
- Michael Collins, Log-Linear Models, MEMMs, and CRFs, Columbia.
PDF — the cleanest derivation
of the CRF gradient in print, and it is six pages.
- Michael Collins, Log-Linear Models.
PDF
Blog posts, for intuition before the algebra
- Edwin Chen (2012), Introduction to Conditional Random Fields.
link
— the POS-tagging feature-function walkthrough that most people learn this from.
- Awni Hannun (2019), The Label Bias Problem.
link — the clearest modern treatment of
Chapter 4, and it separates label bias from exposure bias.
- David Batista (2017), Conditional Random Fields for Sequence Prediction.
link
— the HMM → MEMM → CRF comparison, laid out side by side.
- Marcos Treviso, Implementing a linear-chain CRF in PyTorch.
link
Libraries — the answer keys
On maintenance. sklearn-crfsuite and pytorch-crf are both stable but
effectively dormant — neither has cut a release in over a year. They are still
the right things to check against, because a correct implementation of a
2001 algorithm does not rot. Versions are pinned in requirements.txt so this
tutorial keeps working regardless.
评论