Skip to main content
Core Pattern · Interactive Simhard•DECEMBER 2026•20 MIN

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.

discriminative sequence modellog-potentialspartition function Z(x)forward-backwardviterbi decodingl-bfgs optimizationclassical mlnlpgraphical modelssequence labeling

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-PER cannot follow O in valid BIO tagging (O → I-PER is 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 generate x, it assumes observations x_t are conditionally independent given y_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 step t.
  • 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 function Z(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 words x_{t-1}, x_{t+1}).
  • ψ_trans(y_{t-1}, y_t) = u_{y_{t-1}, y_t} (a K × K matrix scoring how compatible tag y_{t-1} is with y_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").

LOADING CRF TRELLIS & SCORE MATRIX EXPLORER...

Anatomy of a Single Trellis Node (e.g. joined → O = 14.0)

In the default "Ada Lovelace" example:

  1. 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).
  2. At t = 2 (Lovelace), I-PER checks all 4 predecessors and picks B-PER (3.4 + 2.8 + 3.1 = 9.3).
  3. At t = 3 (joined), tag O (ψ_emit = +3.6) evaluates all 4 incoming transitions into O:
    • 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)
  4. At t = 4 (Babbage), B-ORG (14.0 + 1.5 + 2.8 = 18.3) beats B-PER (14.0 + 1.4 + 2.6 = 18.0) by 0.3, yielding B-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.

LOADING CRF PARTITION & FORWARD-BACKWARD EXPLORER...

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) ||θ||^2

Because 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) ] + λ θ_j
  • E_data[f_j]: How often feature f_j actually appears in the gold labels.
  • E_θ[f_j]: How often the model expects feature f_j to appear under its current weights, computed from the Forward-Backward marginals P(y_t | x) and P(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 × d Hessian inverse H^{-1}, which is O(d^2) memory (impossible for d = 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 (typically m = 5..10) parameter differences s_k = θ_{k+1} - θ_k and gradient differences y_k = ∇L_{k+1} - ∇L_k, using a two-loop recursion in O(m · d) time to approximate H_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.

LOADING CRF L-BFGS TRAINING LAB...

6. Comparison & Failure Modes

ModelObjectiveNormalizationOverlapping Features in xLabel Bias?Inference / Training
HMMGenerative P(x, y)Local P(x_t | y_t) & P(y_t | y_{t-1})Hard (violates independence)NoViterbi / Counting or Baum-Welch EM
MEMMDiscriminative P(y | x)Local per-step P(y_t | y_{t-1}, x)YesYesViterbi / Per-step Logistic Regression
Linear-Chain CRFDiscriminative P(y | x)Global Z(x)YesNoViterbi / Forward-Backward + L-BFGS
BiLSTM / Transformer-CRFNeural emissions + CRF ψ_transGlobal Z(x)Learned contextual embeddingsNoViterbi / Forward-Backward + AdamW

Common Failure Modes & Practical Notes

  • First-order Markov assumption: A linear-chain CRF only links y_{t-1} to y_t. Long-range label constraints (e.g., matching opening/closing tags across 20 tokens) cannot be enforced by ψ_trans alone without higher-order factors (O(T · K^3) or worse).
  • Numerical overflow in exp(score): Never compute Z(x) = Σ exp(score) directly in float64 for long sentences; always work in log-space using logSumExp with max-subtraction.
  • Why Neural-CRF still exists: Modern Transformers already contextualize x, so emissions are strong—yet adding a lightweight K × K CRF transition layer on top still prevents illegal BIO jumps (O → I-PER) during structured decoding.

Related Lab Entries