Beam search is a heuristic search algorithm that expands the most promising nodes in a limited set, where the beam width k determines the number of partial hypotheses retained at each time step. Unlike greedy search, which commits to a single best token and suffers from irreversible error propagation, beam search keeps k candidate sequences alive simultaneously, scoring them by cumulative log-probability to find a near-optimal global solution without the exponential cost of full breadth-first search.
Glossary
Beam Search

What is Beam Search?
Beam search is a heuristic search algorithm that maintains a fixed number of the most probable partial hypotheses at each step, balancing the efficiency of greedy decoding with the accuracy of exhaustive search.
In dependency parsing, beam search mitigates the cascading errors inherent in deterministic transition-based parsers by maintaining multiple partial parse states. At each step, the parser generates all valid actions for each state in the beam, scores them using a trained model, and prunes to the top k configurations. This allows the parser to recover from local ambiguities—such as prepositional phrase attachment—by deferring commitment until more disambiguating context is observed, significantly improving Labeled Attachment Score (LAS) over greedy alternatives.
Key Characteristics of Beam Search
Beam search is a heuristic search algorithm that explores a state space by expanding the most promising nodes at each depth level, maintaining a fixed number of best partial hypotheses (the beam width) to balance between the efficiency of greedy search and the thoroughness of exhaustive search.
Fixed Beam Width (k)
The algorithm maintains exactly k candidate sequences at each decoding step, where k is the beam width. After expanding all possible next tokens for each candidate, the top-k highest-scoring sequences are retained and the rest are pruned. This parameter directly controls the trade-off between accuracy and computational cost:
- k=1: Equivalent to greedy search—fast but prone to error propagation
- k=5-10: Standard for neural machine translation, balancing quality and speed
- k=50+: Used in dependency parsing to avoid losing correct but initially low-probability arcs
The fixed budget ensures linear time complexity O(k × n × |V|) where n is sequence length and |V| is vocabulary size, making it tractable for real-time applications.
Log-Probability Scoring
Beam search ranks partial hypotheses using cumulative log-probability scores rather than raw probabilities. This prevents numerical underflow when multiplying many small probability values together. The score for a partial sequence y₁...yₜ is:
codescore(y₁...yₜ) = Σᵢ₌₁ᵗ log P(yᵢ | y₁...yᵢ₋₁, x)
A critical implementation detail is length normalization, which divides the cumulative score by a length penalty factor to prevent the algorithm from favoring shorter sequences. Without normalization, beam search exhibits a well-known length bias—preferring shorter hypotheses because each additional token reduces the cumulative probability.
Pruning and Diversity
Standard beam search suffers from hypothesis convergence, where the top-k candidates become near-identical after a few decoding steps, differing only in the final few tokens. This reduces the effective search diversity and can cause the algorithm to miss globally optimal solutions.
Mitigation strategies include:
- Diverse beam search: Adds a dissimilarity penalty between sibling hypotheses to encourage exploration of distinct syntactic structures
- Stochastic beam search: Samples candidates from the top-k distribution rather than deterministically selecting the highest-scoring ones
- Coverage mechanisms: Penalize tokens that have received attention in previous steps to reduce repetition
In dependency parsing, this diversity is critical for maintaining alternative attachment decisions for prepositional phrases and relative clauses.
Transition-Based Parsing Application
In transition-based dependency parsing, beam search mitigates the error propagation inherent in greedy shift-reduce decisions. At each parser state, instead of committing to a single action (SHIFT, LEFT-ARC, RIGHT-ARC), the algorithm maintains k parallel parser states with their respective stacks and buffers.
Key implementation details:
- State representation: Each beam element tracks its own stack, buffer, and partial dependency arcs
- Action expansion: All valid transitions are applied to each state, generating k × |actions| candidates
- State merging: Identical parser states from different histories are merged to avoid redundant computation
- Dynamic oracle training: Enables exploration of non-gold states during learning, teaching the parser to recover from suboptimal beam positions
This approach allows the parser to delay attachment decisions until disambiguating context is observed, significantly improving Labeled Attachment Score (LAS).
Early Stopping and Pruning Heuristics
Beam search efficiency can be improved through aggressive pruning heuristics that eliminate candidates unlikely to recover:
- Relative threshold pruning: Discard any hypothesis whose score falls below the current best score minus a threshold δ
- Top-k within threshold: Keep only the top-k candidates that are within the relative threshold
- Histogram pruning: Group candidates by score buckets and keep only the top candidates per bucket
For sequence generation tasks, early stopping occurs when a complete hypothesis (ending with an end-of-sequence token) achieves a score that no incomplete hypothesis can surpass, even with maximally optimistic future scores. This guarantees optimality without exploring the full search space.
Comparison with Alternative Search Strategies
Beam search occupies a middle ground in the search strategy spectrum:
- Greedy search: Selects only the single best action at each step. Fastest (O(n)) but cannot recover from early mistakes. Used when latency is critical.
- Beam search: Maintains k hypotheses. Balances speed and accuracy. The de facto standard for neural sequence generation.
- Viterbi decoding: Finds the exact maximum-probability sequence via dynamic programming. Optimal but only tractable for models with Markov assumptions and small state spaces.
- A search*: Uses an admissible heuristic to guide exploration toward the goal. Can be optimal if the heuristic is admissible, but requires a well-defined goal state and heuristic function.
For neural models without Markov structure, beam search provides the best practical trade-off between optimality guarantees and computational feasibility.
Beam Search vs. Greedy Search vs. Exhaustive Search
A comparison of search strategies used in dependency parsing and sequence generation, evaluating their trade-offs between optimality, computational cost, and error resilience.
| Feature | Beam Search | Greedy Search | Exhaustive Search |
|---|---|---|---|
Search Strategy | Maintains top-k partial hypotheses at each step | Selects single best action at each step | Explores every possible path in the search space |
Optimality Guarantee | |||
Time Complexity | O(n × k × log k) | O(n) | Exponential O(c^n) |
Error Propagation Risk | Moderate (mitigated by beam width) | High (no recovery from local errors) | None (global optimum guaranteed) |
Memory Usage | Moderate (k × state size) | Minimal (single state) | Prohibitive (exponential growth) |
Practical for Dependency Parsing | |||
Typical Beam Width (k) | 8-64 | 1 (degenerate case) | N/A (unbounded) |
Use Case | Transition-based parsing, neural MT, ASR | Real-time applications, baselines | Small search spaces, formal verification |
Applications of Beam Search in AI
Beam search is a fundamental heuristic algorithm that balances the efficiency of greedy decoding with the accuracy of exhaustive search. By maintaining a fixed beam width of the most probable partial hypotheses, it is essential for structured prediction tasks where local decisions have global consequences.
Neural Machine Translation
Beam search is the standard decoding strategy for sequence-to-sequence models. Instead of selecting the single most probable token at each time step, the decoder maintains k candidate translations. At each step, the model expands all k hypotheses by the top k tokens, scores the resulting k² sequences, and prunes back to the top k to prevent exponential explosion.
- Typical beam width: 4 to 8 for translation
- Mitigates the exposure bias of greedy decoding
- Often combined with length normalization to avoid favoring short sequences
Speech Recognition Decoding
Modern end-to-end ASR systems use beam search to decode acoustic model outputs into text. The algorithm integrates the acoustic model, pronunciation lexicon, and language model into a unified search graph. The beam prunes unlikely phoneme sequences early, keeping computation tractable.
- Weighted Finite State Transducers compose the search space
- External language models are integrated via shallow fusion
- Beam width is dynamically adjusted based on pruning thresholds
Dependency Parsing
In transition-based dependency parsing, beam search mitigates the error propagation inherent in greedy shift-reduce algorithms. At each parser state, the model scores all valid actions and retains the top k partial parse trees. This allows the parser to explore alternative attachment decisions before committing.
- Enables recovery from garden-path sentences
- Used with dynamic oracles to explore non-gold states
- Balances linear time complexity with improved accuracy
Image Captioning
Visual captioning models use beam search to generate fluent, contextually relevant descriptions. The algorithm explores multiple narrative paths simultaneously, preventing the model from committing to a generic opening phrase that leads to a suboptimal caption.
- Beam width of 3 to 5 is common
- Combined with CIDEr optimization for task-specific scoring
- Prevents premature commitment to high-frequency phrases
Constrained Text Generation
Beam search can enforce lexical constraints by filtering the candidate set at each step. This is critical for lexically constrained decoding where specific terms must appear in the output. The algorithm prunes any hypothesis that cannot satisfy the constraints within the remaining length budget.
- Used for controlled summarization with mandatory keywords
- Enables grid beam search for multiple simultaneous constraints
- Maintains fluency while guaranteeing term coverage
Protein Structure Prediction
In computational biology, beam search explores the combinatorial space of amino acid residue conformations. The algorithm builds protein backbone structures incrementally, maintaining a diverse set of low-energy candidates. This prevents premature convergence to local energy minima.
- Used in fragment assembly methods like Rosetta
- Beam tracks torsion angle combinations
- Balances energy minimization with structural diversity
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.
Frequently Asked Questions
Clarifying the heuristic search algorithm that balances computational efficiency with global accuracy in dependency parsing and sequence generation tasks.
Beam search is a heuristic search algorithm that explores a state space by expanding the most promising nodes at each step, maintaining a fixed number of best partial solutions—the beam width—and discarding the rest. Unlike greedy parsing, which commits irrevocably to the single highest-probability action at each step, beam search keeps multiple hypotheses alive simultaneously. At each time step, the algorithm generates all possible successors for each state in the beam, scores them using a model-derived probability, and retains only the top-k candidates. This controlled branching factor provides a practical middle ground between exhaustive breadth-first search and myopic greedy selection, making it essential for transition-based dependency parsing where early attachment decisions critically constrain later options. The beam width k directly trades off accuracy against computational cost: wider beams explore more of the search space but require proportionally more memory and processing time.
Related Terms
Understanding beam search requires familiarity with the core parsing paradigms and evaluation metrics it optimizes. Explore these related concepts to build a complete picture of modern dependency parsing.
Transition-Based Parsing
A deterministic parsing paradigm that processes a sentence from left to right using a stack and buffer. It applies a sequence of shift-reduce actions to incrementally build a dependency tree. Beam search is critical here to mitigate the cascading error propagation inherent in purely greedy action selection.
Graph-Based Parsing
A parsing paradigm that scores all possible dependency arcs in a sentence simultaneously to find the highest-scoring maximum spanning tree. While often solved exactly with the Chu-Liu/Edmonds algorithm, beam search is used in higher-order or non-projective variants where exhaustive search is intractable.
Greedy Parsing
A deterministic strategy where the single most probable action is selected at each step without backtracking. It offers linear-time complexity but is highly susceptible to error propagation. Beam search directly addresses this limitation by maintaining a fixed-width buffer of alternative hypotheses.
Dynamic Oracle
A training technique that defines the set of optimal actions from any valid parser state, even after previous errors. This allows beam search to explore non-gold states during training, making the model robust enough to recover when a perfect parse is not in the beam.
Labeled Attachment Score (LAS)
The primary evaluation metric for dependency parsers. It measures the percentage of tokens assigned both the correct syntactic head and the correct dependency relation label. Beam search directly optimizes for this metric by searching for the highest-probability global structure.
Non-Projective Parse
A dependency tree containing crossing arcs, common in languages with free word order. Decoding non-projective structures is computationally harder, often requiring beam search with specific transition systems like Swap-based parsing to handle the increased complexity.

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