Viterbi Decoding, CRFs, and Neural Taggers
The HMM reduced tagging to an argmax over exponentially many tag sequences. This lesson builds the decoder that makes it tractable — the Viterbi dynamic program, worked through a full numeric trace on real WSJ probabilities — then keeps that same decoder while replacing the HMM's rigid tables.
╌╌╌╌
This builds on Sequence Labeling: POS and NER, which set up part-of-speech and named-entity tagging and built the hidden Markov model. That lesson ended with an obstacle: tagging is an argmax over tag sequences, far too many to enumerate. Here the Viterbi dynamic program makes it tractable; we trace it through real numbers, then swap the HMM's two rigid tables for a discriminative model that conditions on any feature of the whole sentence — and keep Viterbi as the decoder the whole way through, into the neural taggers that learn their features instead of hand-coding them.
Decoding with Viterbi
The decoding algorithm for HMMs is the Viterbi algorithm, a dynamic program.1 Like the minimum-edit-distance recurrence, it fills a table so that each cell reuses the solutions to smaller subproblems, turning an exponential search into a polynomial fill. The subproblem is the best path to a given state at a given time.
The algorithm builds a trellis (or lattice): a grid with one column per observation and one row per state . The cell holds the probability of the single most probable path that ends in state after emitting the first words:
The dynamic-programming insight is that a best path to state at time must extend some best path to a state at time ; nothing earlier can be revisited or improved. So each cell is computed by taking the max over the previous column of (path so far) (transition into ) (emission of the current word):
Three quantities multiply: , the best score reaching state one step back; , the transition; and , the emission of the current word. Alongside the score, each cell stores a backpointer to the state that achieved the max, so that once the last column is filled we can trace the winning path back to the start.
Written as pseudocode, the recurrence becomes three phases — initialize the first column from the start distribution, recurse column by column filling each cell from the previous one, then read off and backtrace the best final path:
- 1input: observations , states
- 2create tables and
- 3for each state doinitialization
- 4
- 5
- 6for each time step dorecursion
- 7for each state do
- 8
- 9
- 10termination
- 11
- 12states from following back to
- 13return ,
The table is , and filling each cell costs a max over predecessors,
so Viterbi runs in time — polynomial in sentence length, where naive
enumeration was exponential. That reduction is the entire reason the model is
usable. To tag Janet will back the bill,
the trellis has rows and five
columns; most cells are zero (the word Janet can only be NNP), the max in each
surviving cell picks the best predecessor, and backtracing from the last column
recovers the gold sequence NNP MD VB DT NN.
A full Viterbi trace
Run the recurrence with the real WSJ probabilities.1 Restrict attention to seven tags. The transition table , with the start state as a row, holds :
| NNP | MD | VB | JJ | NN | RB | DT | |
|---|---|---|---|---|---|---|---|
| NNP | |||||||
| MD | |||||||
| VB | |||||||
| DT |
The emission table holds for the five words of Janet will back the bill (only the non-zero cells matter):
| Janet | will | back | the | bill | |
|---|---|---|---|---|---|
| NNP | |||||
| MD | |||||
| VB | |||||
| JJ | |||||
| NN | |||||
| RB | |||||
| DT |
Column 1 (Janet). Initialize , using the row for . Only NNP emits Janet with non-zero probability, so only its cell survives: . Every other tag has emission and dies here.
Column 2 (will). For each tag , . Since only NNP is alive in column 1, the max collapses to that one predecessor. For MD: , with backpointer NNP. Jurafsky & Martin's normalized trellis records once the shared and transition factor are folded in; the winner in column 2 is MD, because will as a modal is far likelier than will as a noun ().
Column 3 (back). back is the ambiguous word: VB , JJ , NN , RB . Even though RB has the largest emission, the transition against tips the product toward VB. The best path through column 3 lands on VB, backpointer MD.
Columns 4–5 (the, bill). the forces DT (the only non-zero emitter, ), reached from VB by . bill is emitted by NN () or VB (); NN wins by two orders of magnitude and is reached from DT by . Backtracing from NN in the last column follows the pointers NN DT VB MD NNP, recovering the gold sequence NNP MD VB DT NN.
Notice how sparsity did most of the work: three of the five columns had a single non-zero emitter, so the trellis was nearly deterministic and only back required a real competition among tags. This is typical — the ambiguity that makes tagging hard concentrates in a few tokens, and Viterbi resolves each using the transition probabilities of its neighbors.
The numbers expose one subtlety. Filling the cells with the actual
values — the same arithmetic worked above, , then — exposes what the earlier VB wins at back
gloss hides.
At column three the cell value of RB is actually the largest, , ahead of , because RB's emission
of back swamps the transition gap. What decides the tag is not that column but the
next one: reaching DT at column four takes the max over predecessors, and
beats , so DT's backpointer selects VB, not RB. The globally best path can route
through a cell that was not the local winner — exactly the property that makes the
full trellis, rather than a greedy left-to-right choice, necessary.
Viterbi is a general decoder, not a property of the HMM. Any model that scores a tag sequence by a product (or sum) of terms depending only on adjacent tags can be decoded by the same trellis. The conditional random field is exactly such a model.
Conditional random fields
The HMM is useful but rigid. Its two tables represent only tag bigrams and word identities, so it performs poorly on unknown words — proper names and acronyms it never saw in training — precisely where features like capitalized, ends in -ed, or preceded by the would help.2 The problem is that an HMM is generative: every source of knowledge has to be forced into or , and arbitrary features do not fit those tables.
The conditional random field (CRF) is the discriminative answer. It is a log-linear model — a sequence-length version of logistic regression — that computes the posterior over the whole tag sequence given the whole word sequence directly, without the generative detour through Bayes' rule. The linear-chain CRF is the variant used for language, and its conditioning matches the HMM's.
A CRF assigns a probability to an entire output sequence through global feature functions , each weighted by a learned :
Each global feature is a sum of local features over the positions of the
sequence, . This decomposition
carries one constraint and one freedom. A local feature may depend on the current tag
, the previous tag , the position , and — this is what the HMM
could not do — the entire input sequence . A feature can look at the word two
places to the right, at whether the current word is capitalized, at its suffix, at
whether it appears in a gazetteer of place names. The tag pair is
what keeps the chain linear,
so Viterbi still works; everything else is free to
inspect the whole sentence.
That freedom is why CRFs beat HMMs for NER. Deciding whether L'Occitane begins a
PER or an ORG span turns on cues an HMM cannot represent: the word's shape
(X'Xxxxxxxx), its capitalization, its prefixes and suffixes, whether a neighbor
sits in a gazetteer, the parts of speech of surrounding words. A CRF folds all of
these into local features that condition on the full sentence, so the tag of one
token can draw on evidence anywhere in the input.
Worked example: local features on one token
For example, consider tagging the word Villanueva at
position in Jane Villanueva of United Airlines,
where the previous tag is
and we are scoring the candidate current tag . A handful of local features fire — each is
an indicator, when its condition holds and otherwise:2
| feature | condition | fires? |
|---|---|---|
| is capitalized | ||
| ends in -eva | ||
Features through fire; does not (it is about a different tag). The score the CRF assigns this tag transition is , the sum of the learned weights on the firing features. Two of these — (shape) and (suffix) — an HMM structurally cannot express, because they condition on the word form rather than on tag bigrams or a single emission. This is the extra evidence that lets a CRF label an unseen proper name correctly, and , the tag-pair feature, is the only one Viterbi needs to see as a transition score.
| HMM | Linear-chain CRF | |
|---|---|---|
| Type | generative, models | discriminative, models |
| Knowledge | tag bigrams + word identity only | arbitrary features over all of |
| Unknown words | weak (unseen emission) | strong (shape, affix, gazetteer features) |
| Trains | count-and-divide MLE | gradient descent on log-likelihood |
| Decodes with | Viterbi | Viterbi |
Decoding a CRF is, once more, Viterbi. To find we drop the constant and the monotone , leaving a sum of weighted features to maximize over tag sequences. The trellis fills by the same recurrence as the HMM, with the product of and replaced by the CRF's weighted feature score for the tag transition into the current cell:
Only the per-cell scoring changed; the dynamic program is identical. Training swaps counting for stochastic gradient descent on the log-likelihood of the labelled corpus, with a forward-backward pass supplying the gradient and or regularization, exactly as for logistic regression.
Neural sequence taggers
Jurafsky & Martin forward-reference the neural approach; the public literature traces the progression. Three papers mark the shift from hand-built features to learned representations, all keeping the CRF's Viterbi-decodable structure.
biLSTM-CRF (Huang, Xu, and Yu, 2015).3 The first widely-cited neural
sequence tagger replaced the CRF's hand-engineered features with the hidden states of
a bidirectional LSTM, then kept a CRF layer on top to score tag-to-tag transitions.
The LSTM supplies a context-aware vector for each token; the CRF layer enforces valid
label sequences (an I-PER may not follow a B-ORG). On POS, chunking, and NER
benchmarks it matched or beat the best feature-engineered CRFs while needing far less
task-specific feature design.
Character-aware NER (Lample et al., 2016).4 The state-of-the-art NER architecture of its era added a second representation: alongside each word's embedding, a character-level biLSTM reads the word's spelling and produces a vector that captures morphology and shape — capitalization, hyphenation, suffixes — the very cues the CRF had encoded by hand. Concatenating the word and character representations, feeding them through a word-level biLSTM, and decoding with a CRF layer, Lample and colleagues reported on CoNLL-2003 English NER, then the best result without external gazetteers. The character encoder solved the unknown-word problem structurally: any name, however rare, still has letters.
ELMo and contextual features (Peters et al., 2018).5 The next jump came from pretraining the representations. ELMo derives each token's vector from a bidirectional LSTM language model trained on a large unlabelled corpus, then feeds those contextual vectors into a task-specific biLSTM-CRF. Adding ELMo raised CoNLL-2003 NER to roughly , a large gain from representations learned before any NER labels were seen — the same pretraining idea that the next module's transformer models push further.
What survives: features change, Viterbi stays
Jurafsky & Martin themselves forward-reference this neural direction as the modern default: a biLSTM producing a context-aware vector for each token, usually with a CRF layer on top to score tag-to-tag transitions.6 Across the whole progression one thing never changes. HMM to CRF to biLSTM-CRF changes only how a tag sequence is scored — count tables, then weighted features over the whole input, then learned and pretrained vectors — but the decoding is Viterbi in every one, because each model keeps the tag-bigram (linear-chain) structure that makes the trellis exact.
The next lesson, recurrent networks and LSTMs, builds the biLSTM that supplies those learned representations, and shows how the same sequence-labeling task looks once the features are learned rather than written down by hand.
Footnotes
- Jurafsky & Martin, §8.4.5 — The Viterbi Algorithm: the dynamic-programming decoder for HMMs, the trellis recurrence with backpointers, related to minimum edit distance. ↩ ↩2
- Jurafsky & Martin, §8.5 — Conditional Random Fields: the linear-chain CRF as a discriminative log-linear sequence model with global feature functions decomposed into local features over the whole input, decoded by Viterbi. ↩ ↩2
- Huang, Xu, and Yu (2015), Bidirectional LSTM-CRF Models for Sequence Tagging, arXiv — a bidirectional LSTM producing per-token representations with a CRF output layer scoring tag transitions, matching feature-engineered CRFs on POS, chunking, and NER. ↩
- Lample, Ballesteros, Subramanian, Kawakami, and Dyer (2016), Neural Architectures for Named Entity Recognition, NAACL — a word-and-character biLSTM with a CRF decoding layer, reporting on CoNLL-2003 English NER without external gazetteers. ↩
- Peters, Neumann, Iyyer, Gardner, Clark, Lee, and Zettlemoyer (2018), Deep Contextualized Word Representations, NAACL — ELMo, pretrained bidirectional-LSTM language-model representations that, added to a biLSTM-CRF tagger, raised CoNLL-2003 NER to about . ↩
- Jurafsky & Martin, §8.7.1 — Bidirectionality: neural biLSTM sequence models, often with a CRF layer, as the standard modern approach, forward-referenced to the sequence-processing chapter. ↩
╌╌ END ╌╌