Viterbi decoding is the standard inference algorithm for linear-chain Conditional Random Fields (CRFs), used to predict the optimal sequence of labels for a tokenized input sequence. Rather than greedily selecting the highest-probability label for each token independently, the algorithm computes the globally optimal path by recursively maximizing the product of emission scores and transition probabilities across the entire sequence, ensuring that the final label sequence respects valid structural constraints like BIO tagging syntax.
Glossary
Viterbi Decoding

What is Viterbi Decoding?
Viterbi decoding is a dynamic programming algorithm that finds the most probable sequence of hidden states in a linear-chain Conditional Random Field (CRF) by efficiently computing the maximum over all possible label paths.
The algorithm operates using a dynamic programming trellis, where each column represents a token and each row represents a possible label state. For each step, it calculates the maximum cumulative score reaching each state by considering all incoming transitions from the previous column, storing backpointers to reconstruct the winning path. This guarantees the most probable joint label assignment without exhaustively enumerating all exponential possibilities, making it essential for production named entity recognition systems.
Key Characteristics of Viterbi Decoding
The Viterbi algorithm is the optimal decoding strategy for linear-chain Conditional Random Fields (CRFs), efficiently computing the most probable sequence of hidden states (entity labels) given an observation sequence. It resolves the ambiguity of independent token predictions by enforcing global structural consistency.
Maximum A Posteriori (MAP) Inference
The Viterbi algorithm performs exact MAP inference by finding the single best label sequence that maximizes the conditional probability P(Y|X). Unlike greedy decoding, which selects the highest-probability label at each step independently, Viterbi considers the entire sequence context to avoid invalid transitions, such as an I-ORG tag following an O tag in BIO notation.
Dynamic Programming Trellis
The algorithm operates on a trellis diagram where columns represent observation tokens and rows represent possible hidden states. At each time step, it recursively computes the maximum cumulative score for reaching each state by considering:
- The emission score from the CRF for the current token
- The transition score from the previous state
- The previous path probability stored in the dynamic programming table
Transition Constraint Enforcement
A critical function of Viterbi decoding is enforcing hard grammatical constraints on label sequences. The transition matrix learned by the CRF assigns near-zero probabilities to illegal transitions. During decoding, Viterbi naturally avoids paths like:
- B-LOC → I-PER (type mismatch)
- I-ORG → B-ORG (missing beginning tag)
- O → I-MISC (inside without beginning) This guarantees a well-formed BIO output without post-processing rules.
Backpointer Reconstruction
To retrieve the optimal path, Viterbi maintains a backpointer matrix that records which previous state led to the maximum score for each current state. After the forward pass reaches the final token, the algorithm traces backward from the highest-scoring final state through these pointers to reconstruct the complete label sequence. This avoids storing all exponential possible paths explicitly.
Log-Space Computation for Stability
In practice, Viterbi is implemented in log-probability space to prevent numerical underflow. Multiplying many small transition and emission probabilities quickly approaches zero. By summing log-probabilities instead, the algorithm maintains numerical stability even for very long sequences. The log-sum-exp trick is used when combining path scores.
Computational Complexity
The time complexity of Viterbi decoding is O(T × S²) where T is the sequence length and S is the number of states. This is dramatically more efficient than the naive O(Sᵀ) brute-force enumeration. For a typical NER task with 9 BIO states and a 50-token sentence, Viterbi evaluates approximately 4,050 transitions instead of 9⁵⁰ possible paths.
Viterbi Decoding vs. Greedy Decoding vs. Beam Search
A comparison of the three primary algorithms used to decode the most probable label sequence from a linear-chain CRF or sequence model's emission scores.
| Feature | Viterbi Decoding | Greedy Decoding | Beam Search |
|---|---|---|---|
Guarantee | Globally optimal sequence | Locally optimal per token | Approximately optimal |
Search Space | All possible paths | Single best token at each step | Top-k paths at each step |
Computational Complexity | O(T × N²) | O(T × N) | O(T × N × K) |
Typical Accuracy (NER F1) | 93.5% | 91.2% | 93.3% |
Handles Label Dependencies | |||
Risk of Label Bias | |||
Decoding Speed | Moderate | Fast | Slower |
Use Case | Production NER with CRF layer | Real-time inference with low latency requirements | Machine translation and long-sequence generation |
Frequently Asked Questions
Clear, technically precise answers to the most common questions about the Viterbi algorithm and its role in sequence labeling for named entity recognition.
Viterbi decoding is a dynamic programming algorithm that finds the single most probable sequence of hidden states (labels) given a sequence of observations (tokens) in a probabilistic graphical model. It operates by constructing a trellis diagram where each column represents a time step and each node represents a possible state. The algorithm recursively computes the maximum probability path to each node using the recurrence v[t][j] = max_i (v[t-1][i] * a[i][j] * b[j](o_t)), where a[i][j] is the transition probability from state i to j and b[j](o_t) is the emission probability of observation o_t given state j. By storing backpointers at each step, the algorithm traces back from the highest-scoring final state to reconstruct the optimal label sequence in O(T * S^2) time, where T is sequence length and S is the number of states.
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Related Terms
Core concepts and alternative architectures that interact with or replace the Viterbi algorithm in modern sequence labeling pipelines.
Greedy Decoding
The simplest decoding strategy that selects the highest-probability label independently at each position without considering transition constraints. While computationally trivial compared to Viterbi, greedy decoding can produce invalid BIO sequences (e.g., I-ORG without a preceding B-ORG). Often used as a baseline or in architectures where a CRF layer enforces global consistency post-hoc.

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us