Beam search decoding is a heuristic search algorithm that maintains a fixed number (beam width) of the most probable partial sequences at each generation step to find a near-optimal output sequence. Unlike greedy decoding, which selects only the single highest-probability token at each step, beam search keeps k candidate hypotheses alive simultaneously, exploring multiple possible continuations before selecting the final sequence with the highest cumulative probability.
Glossary
Beam Search Decoding

What is Beam Search Decoding?
Beam search decoding is a heuristic search algorithm that maintains a fixed number (beam width) of the most probable partial sequences at each generation step to find a near-optimal output sequence, balancing computational efficiency with output quality.
The algorithm's core trade-off lies in its beam width parameter: a larger k explores more of the search space, potentially finding higher-quality outputs, but increases computational cost linearly. Beam search is the standard decoding strategy for tasks requiring coherent, deterministic outputs like neural machine translation and abstractive summarization, where it outperforms pure sampling methods by avoiding locally optimal but globally suboptimal token choices.
Key Characteristics of Beam Search
Beam search is a heuristic search algorithm that maintains a fixed number of the most probable partial sequences at each generation step to find a near-optimal output sequence.
Beam Width (k)
The beam width is the single most critical hyperparameter, defining the number of candidate sequences retained at each time step. A width of k=1 reduces to greedy decoding, always selecting the single most probable token. A larger k explores more of the search space, increasing the chance of finding a globally optimal sequence, but at a linear increase in computational cost and memory usage. Typical values range from 3 to 10 for text generation tasks.
Score Normalization
Without normalization, beam search exhibits a length bias, unfairly penalizing longer sequences because the product of many probabilities (each < 1) becomes vanishingly small. To correct this, the cumulative log-probability score is divided by a length penalty term. A common formula is:
score = (1 / length^α) * Σ log P(token)- The hyperparameter
α(often 0.6–1.0) controls the strength of the normalization, preventing the model from favoring short, generic outputs.
Pruning and Diversity
Standard beam search often produces sequences that differ by only a single token, creating a lack of diversity in the candidate set. To combat this, advanced variants enforce diversity constraints:
- Diverse Beam Search: Divides the beam into groups and penalizes tokens already selected by other groups.
- N-gram Blocking: Explicitly prevents the generation of repeated n-grams within a single beam candidate, reducing degenerate repetition.
Computational Complexity
The time complexity of beam search is O(k * V * L), where k is the beam width, V is the vocabulary size, and L is the sequence length. At each step, the algorithm must evaluate k * V possible next tokens, sort them, and select the top k. This makes it significantly more expensive than greedy decoding but far more tractable than an exhaustive breadth-first search, which would explode exponentially with sequence length.
Use Cases and Limitations
Beam search excels in tasks requiring high-precision, deterministic outputs where a single optimal answer exists:
- Machine Translation: Finding the most probable translation.
- Speech Recognition: Mapping audio to the most likely transcript.
- Code Generation: Producing syntactically correct code.
However, it is poorly suited for open-ended creative tasks like story generation or dialogue, where it produces bland, generic, and repetitive text. For these, stochastic methods like top-p (nucleus) sampling are preferred.
Early Stopping
To prevent wasted computation, beam search often employs early stopping heuristics. A candidate sequence is considered complete when it generates a dedicated End-of-Sequence (EOS) token. The search can terminate when k complete sequences are found, or when the score of the best incomplete candidate falls below the score of the worst completed candidate, guaranteeing no better sequence can be discovered.
Beam Search vs. Other Decoding Strategies
A technical comparison of beam search against greedy decoding, pure sampling, and nucleus sampling across key performance and output quality dimensions.
| Feature | Beam Search | Greedy Decoding | Nucleus Sampling |
|---|---|---|---|
Search Strategy | Maintains k parallel hypotheses | Single highest-probability path | Stochastic sampling from top-p mass |
Output Determinism | Deterministic | Deterministic | Non-deterministic |
Diversity of Output | Low | Lowest | High |
Risk of Repetition | Moderate | High | Low |
Computational Cost | O(k × vocab_size) per step | O(vocab_size) per step | O(vocab_size) per step |
Typical Beam Width (k) | 3-10 | 1 (implicit) | |
Best Use Case | Translation, summarization | Simple classification | Creative writing, dialogue |
Handles Long-Range Dependencies |
Frequently Asked Questions
Explore the mechanics, trade-offs, and practical applications of beam search, a foundational heuristic search algorithm used to generate high-probability sequences in natural language generation pipelines.
Beam search decoding is a heuristic search algorithm that maintains a fixed number (the beam width k) of the most probable partial sequences at each generation step to find a near-optimal output sequence. Unlike greedy decoding, which selects only the single highest-probability token at each step, beam search expands the search tree by keeping k active hypotheses. At each time step, the algorithm generates all possible next tokens for each of the k beams, calculates the conditional probability of the resulting sequences, and prunes the tree back to the top k candidates. This process balances the computational efficiency of greedy search with the exhaustive nature of breadth-first search, making it a standard technique in autoregressive generation for tasks like machine translation and summarization.
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
Beam search exists within a broader ecosystem of decoding algorithms and sequence generation techniques. Understanding these related concepts is essential for selecting the optimal strategy for a given task.
Greedy Decoding
The simplest decoding strategy that selects the single token with the highest probability at each step, with no backtracking or consideration of future outcomes. While computationally efficient, greedy decoding often produces suboptimal sequences because a locally optimal choice can lead to a globally poor path. It is deterministic and lacks diversity, making it unsuitable for creative text generation but adequate for tasks where speed is paramount and output variability is low.
Top-k Sampling
A stochastic decoding method that randomly samples the next token from the k most likely candidates at each step, where k is a fixed integer. By truncating the tail of the probability distribution, top-k sampling balances fluency with diversity. However, a static k value struggles with dynamic distributions: a flat distribution may still include improbable tokens, while a peaked distribution may exclude valid alternatives. This limitation led to the development of nucleus sampling.
Top-p (Nucleus) Sampling
A dynamic sampling strategy that selects from the smallest set of tokens whose cumulative probability mass exceeds a threshold p. Unlike top-k, the candidate pool size adapts to the shape of the distribution at each step. A peaked distribution yields a small candidate set, while a flat distribution expands it. This adaptability makes nucleus sampling the preferred method for open-ended generation tasks where both coherence and diversity are required.
Length Penalty
A hyperparameter applied during beam search to prevent the algorithm from favoring abnormally short sequences. Because the log-probability of a sequence is the sum of negative values, shorter sequences naturally accumulate higher scores. Length penalty normalizes scores by sequence length using the formula: score = log_prob / (length ^ alpha), where alpha typically ranges from 0.6 to 1.0. Without this correction, beam search often produces truncated, incomplete outputs.
Diverse Beam Search
An extension of standard beam search that partitions the beam into groups and penalizes similarity between them. By adding a dissimilarity term to the scoring function, diverse beam search encourages the generation of syntactically or semantically distinct hypotheses. This is critical for applications like machine translation and image captioning, where a user benefits from seeing multiple, meaningfully different output options rather than minor variations of the same sequence.
Constrained Decoding
A generation technique that forces a model's output to conform to a predefined formal grammar, schema, or set of valid tokens at each step. Unlike beam search, which optimizes for probability, constrained decoding optimizes for validity. It is implemented via finite-state automata or token masking, ensuring outputs like valid JSON, SQL queries, or domain-specific structured formats. This is essential for programmatic content infrastructure where outputs must be machine-readable.

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