Conditional Random Fields (CRF): Potentials, Z(x), Viterbi & L-BFGS
Deep-dive into linear-chain CRFs: how emission and transition log-potentials combine, how Forward-Backward computes the partition function Z(x), how Viterbi decodes the global MAP sequence, and how L-BFGS learns weights.
1. Problem & Discriminative Framing
Sequence labeling assigns a tag y_t (such as B-PER, I-PER, B-ORG, O in Named Entity Recognition) to every token x_t in a sentence x = (x_1, ..., x_T).
Why not classify each token independently with logistic regression? Because tags are structurally coupled:
I-PERcannot followOin valid BIO tagging (O → I-PERis structurally invalid).- Ambiguous tokens like
"Jordan"or"Apple"depend on neighboring tags ("Michael [B-PER] Jordan [I-PER]"vs."Apple [B-ORG] opened [O]").
Why not use a Hidden Markov Model (HMM) or Maximum Entropy Markov Model (MEMM)?
- HMM (Generative): Models the joint
P(x, y) = Π P(y_t | y_{t-1}) P(x_t | y_t). Because it must generatex, it assumes observationsx_tare conditionally independent giveny_t—making overlapping features (capitalization + suffix + previous word + next word) awkward to incorporate. - MEMM (Locally Normalized Discriminative): Normalizes
P(y_t | y_{t-1}, x)at each time step. This causes the label bias problem: states with low-entropy outgoing transitions (only one likely next tag) ignore strong observation evidence because their outgoing probabilities must already sum to 1 at stept. - Linear-Chain CRF (Globally Normalized Discriminative): Drops per-step normalization and models
P(y | x)directly over the entire sequence by summing unnormalized log-potentials and dividing once by a global partition functionZ(x).
2. Scoring & Potential Machinery
A linear-chain CRF defines the unnormalized score of a complete tag sequence y = (y_1, ..., y_T) given input x as the sum of emission (unary) potentials and transition (pairwise) potentials:
score(x, y) = Σ_{t=1..T} ψ_emit(y_t, x_t) + Σ_{t=2..T} ψ_trans(y_{t-1}, y_t)In a trained CRF, each potential is a dot product of learned weights θ and feature functions f:
ψ_emit(y_t, x_t) = w · f_emit(y_t, x, t)(word identity, capitalization, prefix/suffix, word shape, neighboring wordsx_{t-1}, x_{t+1}).ψ_trans(y_{t-1}, y_t) = u_{y_{t-1}, y_t}(aK × Kmatrix scoring how compatible tagy_{t-1}is withy_t).
Interactive CRF Matrix & Viterbi Trellis Explorer
Click any node in the Viterbi trellis (or any cell in the Emission matrix) to inspect the exact incoming candidates and arithmetic. Toggle Compare Greedy Argmax or drag the Emission / Transition weight sliders to see when local emissions lose to global transitions (try "Michael Jordan").
Anatomy of a Single Trellis Node (e.g. joined → O = 14.0)
In the default "Ada Lovelace" example:
- At
t = 1(Ada), there is no predecessor, soδ_1(y) = ψ_emit(y, Ada)(B-PER = +3.4,I-PER = +0.2,B-ORG = +1.3,O = +0.1). - At
t = 2(Lovelace),I-PERchecks all 4 predecessors and picksB-PER(3.4 + 2.8 + 3.1 = 9.3). - At
t = 3(joined), tagO(ψ_emit = +3.6) evaluates all 4 incoming transitions intoO:- from
B-PER(4.0 + 0.9 + 3.6 = 8.5) - from
I-PER(9.3 + 1.1 + 3.6 = 14.0) ← Winner - from
B-ORG(4.6 + 1.2 + 3.6 = 9.4) - from
O(4.5 + 1.6 + 3.6 = 9.7)
- from
- At
t = 4(Babbage),B-ORG(14.0 + 1.5 + 2.8 = 18.3) beatsB-PER(14.0 + 1.4 + 2.6 = 18.0) by0.3, yieldingB-PER I-PER O B-ORG.
3. From Raw Scores to Probabilities: Z(x) & Forward-Backward
To turn score(x, y) into a valid conditional probability distribution over all K^T possible tag sequences:
P(y | x) = exp(score(x, y)) / Z(x)
where Z(x) = Σ_{y' ∈ Y^T} exp(score(x, y'))Computing Z(x) by brute force requires O(K^T) time—impossible for real sentences (4^30 ≈ 10^18). Instead, CRFs exploit the linear-chain structure using Dynamic Programming in O(T · K^2) time via the Forward (α) and Backward (β) passes in log-space:
Forward (log-space):
α_1(y) = ψ_emit(y, x_1)
α_t(y) = logsumexp_{y'} [ α_{t-1}(y') + ψ_trans(y', y) + ψ_emit(y, x_t) ]
log Z(x) = logsumexp_{y} [ α_T(y) ]
Backward (log-space):
β_T(y) = 0
β_t(y) = logsumexp_{y'} [ ψ_trans(y, y') + ψ_emit(y', x_{t+1}) + β_{t+1}(y') ]
Token & Pairwise Marginals:
P(y_t = y | x) = exp( α_t(y) + β_t(y) - log Z(x) )
P(y_{t-1} = i, y_t = j|x) = exp( α_{t-1}(i) + ψ_trans(i, j) + ψ_emit(j, x_t) + β_t(j) - log Z(x) )Notice the structural duality: Forward-Backward replaces max with logsumexp (soft-max) to sum over all paths, whereas Viterbi uses max to find the single best path.
Interactive Partition Function & Marginal Explorer
Switch between Forward-Backward Marginals (click any cell to see α_t, β_t, and log Z(x)) and All 256 Paths → Z(x) to verify that the O(T K^2) Forward pass matches the brute-force sum over all 4^4 = 256 sequences.
4. Inference & Decoding: Viterbi vs. Greedy
At inference time, we want y* = argmax_y P(y | x). Because Z(x) is constant across all y for a fixed sentence x, maximizing P(y | x) is identical to maximizing score(x, y):
δ_t(y) = max_{y'} [ δ_{t-1}(y') + ψ_trans(y', y) ] + ψ_emit(y, x_t)
bp_t(y) = argmax_{y'} [ δ_{t-1}(y') + ψ_trans(y', y) ]Once δ_T(y) is computed at the final token, we pick y*_T = argmax_y δ_T(y) and follow bp_t(y*_t) backwards from T down to 1. Total complexity: O(T · K^2) time and O(T · K) space for backpointers.
5. Training & Optimization: Log-Likelihood & L-BFGS
Given training pairs (x^(n), y^(n)), a CRF minimizes the regularized Negative Log-Likelihood (NLL):
L(θ) = -Σ_n log P(y^(n) | x^(n); θ) + (λ / 2) ||θ||^2
= Σ_n [ log Z(x^(n); θ) - score(x^(n), y^(n); θ) ] + (λ / 2) ||θ||^2Because log Z(x) is a log-sum-exp of linear functions of θ, L(θ) is strictly convex (with L2 regularization). There are no local minima! Taking the gradient with respect to any parameter θ_j gives a clean, intuitive equation:
∂L / ∂θ_j = E_θ[ f_j(x, y) ] - E_data[ f_j(x, y) ] + λ θ_jE_data[f_j]: How often featuref_jactually appears in the gold labels.E_θ[f_j]: How often the model expects featuref_jto appear under its current weights, computed from the Forward-Backward marginalsP(y_t | x)andP(y_{t-1}, y_t | x).- At the global optimum, model expectations match empirical counts (modulo L2 shrinkage).
Why L-BFGS Instead of Plain Gradient Descent?
In NLP, θ can have 10^5 to 10^7 sparse features.
- Newton's Method needs the full
d × dHessian inverseH^{-1}, which isO(d^2)memory (impossible ford = 10^6). - Vanilla Gradient Descent zig-zags slowly across ill-conditioned feature scales (e.g., common words vs. rare bigrams).
- L-BFGS (Limited-memory BFGS) stores only the last
m(typicallym = 5..10) parameter differencess_k = θ_{k+1} - θ_kand gradient differencesy_k = ∇L_{k+1} - ∇L_k, using a two-loop recursion inO(m · d)time to approximateH_k^{-1} ∇L_k, followed by an Armijo backtracking line search.
Interactive L-BFGS Training Lab
Step through L-BFGS from uniform zero weights (P(y* | x) = 1/256 = 0.39%) and watch how E_θ - E_data drives invalid transitions negative and gold transitions positive.
6. Comparison & Failure Modes
| Model | Objective | Normalization | Overlapping Features in x | Label Bias? | Inference / Training |
|---|---|---|---|---|---|
| HMM | Generative P(x, y) | Local P(x_t | y_t) & P(y_t | y_{t-1}) | Hard (violates independence) | No | Viterbi / Counting or Baum-Welch EM |
| MEMM | Discriminative P(y | x) | Local per-step P(y_t | y_{t-1}, x) | Yes | Yes | Viterbi / Per-step Logistic Regression |
| Linear-Chain CRF | Discriminative P(y | x) | Global Z(x) | Yes | No | Viterbi / Forward-Backward + L-BFGS |
| BiLSTM / Transformer-CRF | Neural emissions + CRF ψ_trans | Global Z(x) | Learned contextual embeddings | No | Viterbi / Forward-Backward + AdamW |
Common Failure Modes & Practical Notes
- First-order Markov assumption: A linear-chain CRF only links
y_{t-1}toy_t. Long-range label constraints (e.g., matching opening/closing tags across 20 tokens) cannot be enforced byψ_transalone without higher-order factors (O(T · K^3)or worse). - Numerical overflow in
exp(score): Never computeZ(x) = Σ exp(score)directly in float64 for long sentences; always work in log-space usinglogSumExpwith max-subtraction. - Why Neural-CRF still exists: Modern Transformers already contextualize
x, so emissions are strong—yet adding a lightweightK × KCRF transition layer on top still prevents illegal BIO jumps (O → I-PER) during structured decoding.