Inferensys

Glossary

Beam Search

Beam search is a heuristic search algorithm used in sequence generation tasks that explores multiple likely candidates at each step, keeping only the top-k most probable paths.
Stylish WeWork-like workspace with hot desks and document wall, professional searching through enterprise knowledge base on a mounted ultrawide display, warm industrial pendants overhead.
DECODING ALGORITHM

What is Beam Search?

Beam search is a heuristic search algorithm used in sequence generation tasks (like machine translation or text summarization) that explores multiple likely sequence candidates at each step, keeping only the top-k (the beam width) most probable paths.

Beam search is a heuristic search algorithm used for sequence generation in models like transformers, designed as a compromise between greedy decoding and exhaustive breadth-first search. At each step of generating a sequence (e.g., the next word in a sentence), the algorithm expands the top-k most probable partial sequences, where k is the beam width. It prunes all other lower-probability paths, maintaining a manageable set of hypotheses called the beam. This balances computational efficiency with the exploration of plausible alternatives, reducing the risk of myopic errors common in greedy approaches.

The algorithm terminates when all sequences in the beam reach an end-of-sequence token or a maximum length. The final output is typically the sequence with the highest cumulative score, often a normalized log probability. Key hyperparameters are the beam width, which controls the search space and computational cost, and length normalization, which prevents bias towards shorter sequences. While more computationally intensive than greedy decoding, beam search is a standard technique for improving output quality in machine translation, text summarization, and automatic speech recognition.

DECODING ALGORITHM

Key Features of Beam Search

Beam search is a heuristic search algorithm that balances the computational cost of exhaustive search with the myopia of greedy decoding by maintaining a fixed number of the most promising sequence candidates at each generation step.

01

Beam Width (k)

The beam width (k) is the core hyperparameter that defines the number of candidate sequences (or beams) the algorithm keeps in memory at each step. A width of k=1 is equivalent to greedy search, while a larger k explores more possibilities at the cost of increased memory and computation. The optimal value is task-dependent, balancing output quality and inference latency.

  • Small k (e.g., 4-10): Common for machine translation, offering a good quality/speed trade-off.
  • Large k (e.g., 50-100): Used in tasks requiring high precision, like automated theorem proving, but incurs significant overhead.
02

Pruning & Hypothesis Management

At each step, beam search prunes the exponentially growing tree of possible sequences. It expands all k current beams, generating k * V possible next tokens (where V is vocabulary size). It then scores each new partial sequence (e.g., using log probability) and selects only the top-k overall to carry forward. This process of hypothesis management prevents combinatorial explosion.

  • Scoring: Typically uses the sum of log probabilities for the sequence so far.
  • Efficiency: Pruning makes the search tractable, with complexity roughly O(k * n * log(V)), where n is sequence length.
03

Length Normalization

A critical refinement to the basic probability scoring is length normalization. Since longer sequences naturally accumulate lower probabilities (more multiplicative terms < 1), the algorithm would unfairly favor shorter, often incomplete outputs. To correct this, scores are divided by the sequence length (or length^α, where α is a tunable parameter).

  • Formula: score = (1 / (length^α)) * Σ log(P(token))
  • Impact: Ensures the final selected sequence is not artificially short, leading to more coherent and complete generations in tasks like summarization or dialogue.
04

Termination Criteria

Beam search requires explicit termination criteria to decide when to stop generating tokens for all beams. The most common method is to wait until a predefined number of beams have produced an end-of-sequence (EOS) token. Once a beam hits EOS, it is considered complete and is set aside. Generation stops when a target number of beams (e.g., all k beams or a minimum batch) are complete, or when a maximum sequence length is reached.

  • Early Stopping: Can halt once a minimum number of beams are finished, improving latency.
  • Max Length: A hard stop to prevent infinite loops in degenerate cases.
05

Comparison to Greedy & Exhaustive Search

Beam search occupies a middle ground between two extremes:

  • Greedy Decoding (k=1): At each step, selects the single most probable next token. It's fast but can get trapped in sub-optimal sequences due to local maxima (e.g., producing repetitive text).
  • Exhaustive Search (k=∞): Explores all possible sequences to find the globally optimal one. This is computationally intractable for all but the shortest sequences.

Beam Search provides a tunable compromise, exploring multiple high-probability paths simultaneously to find a better overall sequence than greedy search, without the prohibitive cost of an exhaustive search.

06

Common Applications & Limitations

Primary Applications:

  • Machine Translation: The classic use case, generating fluent, accurate translations.
  • Text Summarization: Producing coherent summaries from long documents.
  • Speech Recognition: Decoding audio features into word sequences.
  • Image Captioning: Generating descriptive sentences from visual features.

Key Limitations:

  • Lack of Diversity: All beams can become very similar, leading to generic outputs. Techniques like diverse beam search address this.
  • Fixed Computation: Allocates the same compute to easy and hard parts of a sequence.
  • Not Optimal: It's a heuristic; the final sequence is not guaranteed to be the globally best one.
DECODING ALGORITHM COMPARISON

Beam Search vs. Other Decoding Strategies

A technical comparison of heuristic search and sampling-based algorithms used for sequence generation in autoregressive models, such as large language models.

Feature / MetricBeam SearchGreedy DecodingTop-k SamplingTop-p (Nucleus) Sampling

Core Mechanism

Maintains top-k (beam width) candidate sequences at each step.

Selects the single most probable token at each step.

Samples from the k most probable tokens at each step.

Samples from the smallest set of tokens whose cumulative probability ≥ p.

Primary Objective

Maximize overall sequence probability (approximate).

Maximize local token probability.

Introduce controlled randomness for diversity.

Dynamically adjust candidate set size based on distribution confidence.

Hyperparameters

Beam width (k), length penalty.

None.

k (sample size).

p (cumulative probability threshold).

Output Diversity

Low; deterministic for given width & penalty.

None; fully deterministic.

Moderate to high, controlled by k.

High, adapts to distribution shape.

Risk of Repetition

Moderate; can get stuck in loops.

High; prone to degenerate loops.

Low to moderate.

Low; dynamic vocabulary reduces repetition.

Computational Cost

High; scales with beam width k.

Lowest; single path.

Low; single sampling step.

Low; requires sorting probabilities.

Typical Use Cases

Machine translation, formal text summarization.

Debugging, deterministic baselines.

Creative writing, chatbot responses.

Open-ended generation, story writing.

Handles Uncertainty

Explores multiple high-probability futures.

Ignores uncertainty; commits to top choice.

Explores within a fixed-size set.

Explores within a probability mass; set size varies.

SEQUENCE GENERATION

Common Use Cases for Beam Search

Beam search is a core algorithm for generating high-quality, coherent sequences in AI systems. Its ability to balance exploration and efficiency makes it indispensable across several key domains.

01

Machine Translation

Beam search is the standard decoding algorithm for sequence-to-sequence models in neural machine translation (NMT). It generates fluent, grammatically correct translations by exploring multiple partial translation hypotheses in parallel.

  • At each step, it expands the top-k (beam width) most probable sequences of target-language words.
  • This prevents the model from committing to a single, potentially suboptimal word choice early on, which is a common failure mode of greedy decoding.
  • The algorithm effectively navigates the vast space of possible translations to find a sequence that maximizes overall probability, not just local choices.
02

Text Summarization & Generation

For abstractive text summarization and autoregressive language model output (e.g., from GPT, Llama), beam search produces coherent, multi-sentence text.

  • In summarization, it constructs a concise summary by sequentially generating words, using the beam to maintain several promising summary candidates.
  • For open-ended generation, it helps avoid repetitive or nonsensical output by considering a broader set of plausible continuations than greedy sampling.
  • It is often combined with length normalization to prevent the algorithm from unfairly favoring shorter sequences, which inherently have higher cumulative probability.
03

Automatic Speech Recognition (ASR)

In end-to-end ASR systems that directly map audio spectrograms to text (using models like Connectionist Temporal Classification), beam search decodes the most probable word sequence.

  • The audio signal is processed into a sequence of frame-level predictions over characters or subword units.
  • Beam search merges paths that result in the same transcript so far, summing their probabilities, which is crucial for handling the alignment ambiguity between audio frames and output symbols.
  • This allows the system to recover from local mispredictions in noisy audio, yielding more accurate transcripts.
04

Image Captioning

Beam search generates descriptive natural language captions for images in encoder-decoder architectures (e.g., where a CNN encodes the image and an RNN/Transformer decodes the caption).

  • The image encoder produces a fixed context vector.
  • The decoder language model uses this context to initialize generation, with beam search exploring the space of possible descriptive phrases.
  • By keeping multiple candidates, it can balance between generic captions ("a dog in a park") and more specific, likely correct ones ("a golden retriever playing fetch on a grassy field").
05

Code Generation & Completion

AI-powered code assistants use beam search to generate syntactically correct and semantically plausible code snippets from natural language prompts or partial code.

  • The search space is constrained by programming language syntax, making beam search effective for navigating valid token sequences (keywords, identifiers, operators).
  • It helps produce code that compiles by considering multiple structural pathways, reducing the likelihood of early syntax errors that derail generation.
  • For code completion, a narrow beam can quickly provide the top few most likely completions for the next line or function block.
06

Constraint Decoding & Guided Generation

Beam search can be modified to incorporate hard or soft constraints, forcing the output sequence to contain specific keywords, follow a template, or avoid certain terms.

  • Constrained beam search algorithms, like Grid Beam Search, treat constraints as finite-state machines, allowing the beam to track satisfaction progress.
  • This is critical for task-oriented dialogue systems where responses must include specific information (e.g., a booking code) or for generating text that adheres to a predefined schema.
  • It demonstrates beam search's flexibility beyond pure probability maximization, enabling controlled, deterministic output behavior when required.
BEAM SEARCH

Frequently Asked Questions

Beam search is a core algorithm for sequence generation in machine translation, text summarization, and other autoregressive models. These questions address its mechanics, trade-offs, and practical applications for engineers and architects.

Beam search is a heuristic search algorithm used in sequence generation tasks that expands multiple likely sequence candidates at each step, retaining only the top-k (the beam width) most probable paths to manage computational complexity. Unlike greedy decoding, which commits to the single most probable token at each step, beam search maintains a beam—a shortlist of the b most promising partial sequences (hypotheses). At each decoding step, every hypothesis in the current beam is expanded with the top b most likely next tokens, generating b * b candidate sequences. These candidates are then scored by their cumulative log probability (or a length-normalized score), and only the top b sequences are kept for the next iteration. This process repeats until an end-of-sequence token is generated for all beams or a maximum length is reached, with the highest-scoring completed sequence selected as the final output.

Prasad Kumkar

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.