Text Generation Strategies: Greedy vs Beam Search

#nlp #text generation #language models #decoding strategies #greedy search #beam search #python #evaluation metrics

1. Overview of Text Generation in NLP

Overview of Text Generation in NLP

Text generation in natural language processing refers to the task of producing coherent and contextually relevant sequences of words from a given input or initial state. Modern approaches leverage probabilistic language models that estimate the conditional probability distribution over possible word sequences, typically factorized autoregressively:

$$ P(w_1, w_2, ..., w_T) = \prod_{t=1}^T P(w_t | w_{

where wt represents the word at position t, w<t denotes all preceding words, and θ encapsulates the model parameters. This factorization enables tractable computation while maintaining the ability to capture long-range dependencies through the model's hidden state.

Architectural Foundations

Contemporary text generation systems predominantly employ transformer-based architectures, which utilize self-attention mechanisms to compute dynamic representations of input sequences. The attention weights αij between positions i and j are computed as:

$$ \alpha_{ij} = \frac{\exp(e_{ij})}{\sum_{k=1}^n \exp(e_{ik})} $$ $$ e_{ij} = \frac{(W_Qx_i)^T(W_Kx_j)}{\sqrt{d_k}} $$

where WQ, WK are learned projection matrices and dk is the dimension of the key vectors. This mechanism allows the model to selectively focus on relevant context when generating each token.

Decoding Strategies

The choice of decoding strategy significantly impacts the quality and characteristics of generated text. Two fundamental approaches dominate:

  • Deterministic methods like greedy search that select the most probable token at each step
  • Stochastic methods that sample from the model's probability distribution

These strategies present distinct trade-offs between computational efficiency, output diversity, and coherence. The quality of generated text is typically evaluated through both automated metrics (e.g., perplexity, BLEU) and human assessment of fluency, coherence, and relevance.

Practical Considerations

In real-world applications, text generation systems must balance several competing objectives:

  • Maintaining semantic consistency with the input prompt or context
  • Producing grammatically correct and fluent output
  • Avoiding repetition and degenerate text patterns
  • Controlling for desired stylistic or content attributes

Recent advances incorporate techniques like constrained decoding, discriminative reranking, and controllable generation through learned latent representations to address these challenges.

Role of Decoding Strategies in Language Models

Decoding strategies govern how language models generate sequences by selecting tokens from a probability distribution at each step. The choice of strategy significantly impacts the quality, diversity, and computational efficiency of the generated text. Two primary approaches dominate modern implementations: greedy search and beam search, each with distinct trade-offs in performance and output characteristics.

Probability Distributions and Token Selection

At each step t, a language model outputs a probability distribution P(yt | y<t, x) over the vocabulary, where y<t represents previously generated tokens and x is the input context. The decoding strategy determines how to select the next token yt from this distribution. The simplest approach, greedy search, selects the token with the highest probability:

$$ y_t = \argmax_{w \in V} P(w | y_{<t}, x) $$

where V is the vocabulary. While computationally efficient, this approach often leads to suboptimal sequences due to its myopic nature—it cannot revise earlier choices even if a lower-probability token at step t would lead to a higher-probability sequence overall.

Beam Search: Balancing Quality and Efficiency

Beam search addresses this limitation by maintaining k candidate sequences (beams) at each step, where k is the beam width. At step t, it extends each partial sequence in the beam with the top k most probable next tokens, resulting in k2 candidates. These are pruned back to the top k sequences based on their cumulative log probabilities:

$$ \sum_{i=1}^t \log P(y_i | y_{<i}, x) $$

The process repeats until sequences reach an end-of-sequence token or a maximum length. Beam search often produces higher-quality outputs than greedy search but at increased computational cost. Variations like length normalization adjust scores to avoid bias toward shorter sequences:

$$ \frac{1}{t^\alpha} \sum_{i=1}^t \log P(y_i | y_{<i}, x) $$

where α is a tunable parameter typically between 0.6 and 1.0.

Practical Considerations

In real-world applications, the choice between greedy and beam search depends on the task:

Advanced variants like diverse beam search introduce mechanisms to promote diversity among beams, mitigating the common issue of repetitive or generic outputs in standard beam search. Meanwhile, stochastic methods like top-k sampling and nucleus sampling offer alternative approaches for generating diverse and creative text.

Role of Decoding Strategies in Language Models – Text Generation Strategies: Greedy vs Beam Search – Tutorial Diagram
Diagram Description: The diagram would physically show the step-by-step token selection process in greedy search versus beam search, illustrating how beam search maintains multiple candidate sequences.

Key Metrics for Evaluating Generated Text

Evaluating the quality of machine-generated text requires a combination of automated metrics and human judgment. While no single metric captures all aspects of text quality, several well-established measures provide quantitative insights into different dimensions of generated output.

Perplexity

Perplexity measures how well a language model predicts a given sequence of words. It is derived from the cross-entropy loss and represents the exponential of the average negative log-likelihood per token:

$$ PP(W) = \exp\left(-\frac{1}{N}\sum_{i=1}^N \log P(w_i|w_{

where W is the test sequence, N is the number of tokens, and P(wi|w) is the model's predicted probability for token wi given the preceding context. Lower perplexity indicates better predictive performance, with values typically ranging from 10 to 100 for strong modern language models.

BLEU Score

The Bilingual Evaluation Understudy (BLEU) score compares generated text to one or more reference translations using modified n-gram precision:

$$ BLEU = BP \cdot \exp\left(\sum_{n=1}^N w_n \log p_n\right) $$

where pn is the modified n-gram precision, wn are weights (typically uniform), and BP is the brevity penalty:

$$ BP = \begin{cases} 1 & \text{if } c > r \\ e^{1-r/c} & \text{if } c \leq r \end{cases} $$

BLEU ranges from 0 to 1, with higher scores indicating better matches to reference texts. While widely used, BLEU has limitations in capturing semantic similarity and fluency.

ROUGE Metrics

Recall-Oriented Understudy for Gisting Evaluation (ROUGE) measures overlap between generated and reference texts. Common variants include:

  • ROUGE-N: N-gram recall between system and reference texts
  • ROUGE-L: Longest common subsequence (LCS) based metric
  • ROUGE-W: Weighted LCS that favors consecutive matches

The ROUGE-L F-score combines precision and recall of the LCS:

$$ R_{lcs} = \frac{LCS(X,Y)}{m}, \quad P_{lcs} = \frac{LCS(X,Y)}{n} $$ $$ F_{lcs} = \frac{(1+\beta^2)R_{lcs}P_{lcs}}{R_{lcs} + \beta^2 P_{lcs}} $$

where X is the generated text (length n), Y is the reference (length m), and β controls recall/precision balance.

METEOR

Metric for Evaluation of Translation with Explicit ORdering addresses some BLEU limitations by incorporating:

  • Exact, stem, synonym, and paraphrase matching
  • Alignment between system and reference texts
  • Penalties for fragmentation

The METEOR score combines alignment precision and recall with fragmentation penalty:

$$ M = (1 - \gamma f^\theta) \cdot \frac{P \cdot R}{\alpha P + (1-\alpha)R} $$

where γ, θ, and α are tunable parameters, and f measures fragmentation.

BERTScore

BERTScore leverages contextual embeddings from models like BERT to evaluate semantic similarity:

$$ R_{BERT} = \frac{1}{|y|} \sum_{y_i \in y} \max_{x_j \in x} \mathbf{y_i}^T \mathbf{x_j} $$ $$ P_{BERT} = \frac{1}{|x|} \sum_{x_j \in x} \max_{y_i \in y} \mathbf{x_j}^T \mathbf{y_i} $$ $$ F_{BERT} = 2 \frac{P_{BERT} \cdot R_{BERT}}{P_{BERT} + R_{BERT}} $$

where x and y are BERT embeddings of generated and reference texts. BERTScore correlates better with human judgment than n-gram metrics but requires more computation.

Diversity Metrics

For open-ended generation, diversity measures prevent repetitive outputs:

  • Distinct-n: Ratio of unique n-grams to total n-grams
  • Self-BLEU: BLEU score between generated samples
  • Entropy: Shannon entropy of n-gram distributions

These metrics complement quality measures by ensuring generated text exhibits appropriate lexical and semantic variation.

Human Evaluation

While automated metrics provide scalability, human evaluation remains essential for assessing:

  • Fluency and grammaticality
  • Coherence and logical flow
  • Factual accuracy
  • Stylistic appropriateness

Common human evaluation protocols use Likert scales or pairwise comparisons, with careful attention to inter-annotator agreement measured by Cohen's kappa or Krippendorff's alpha.

2. How Greedy Search Works Step-by-Step

2.1 How Greedy Search Works Step-by-Step

Greedy search is a deterministic decoding strategy for autoregressive text generation where, at each timestep t, the model selects the token with the highest predicted probability from the vocabulary distribution P(wt|w1:t-1, x). Unlike beam search, it maintains only a single active sequence, making it computationally efficient but prone to locally optimal choices.

Mathematical Formulation

Given an input sequence x and partially generated output w1:t-1, the greedy selection criterion is:

$$ w_t = \underset{v \in V}{\text{argmax}} \ P(v|w_{1:t-1}, x) $$

where V is the vocabulary and P is the model's output distribution. The search terminates when either:

Step-by-Step Execution

Consider generating text from a transformer-based language model with vocabulary V = {A, B, C, EOS}:

  1. Initialization: Start with the input prompt "The" and hidden state h0
  2. Timestep 1:
    $$ P(w_1|\text{"The"}) = \{A:0.6, B:0.3, C:0.1\} $$
    Select w1 = A (highest probability)
  3. Timestep 2:
    $$ P(w_2|\text{"The A"}) = \{A:0.2, B:0.7, C:0.1\} $$
    Select w2 = B
  4. Termination:
    $$ P(w_3|\text{"The A B"}) = \{A:0.1, EOS:0.8, C:0.1\} $$
    Select w3 = EOS, yielding final output "The A B"

Computational Complexity

The time complexity for generating n tokens is O(n|V|d), where d is the model's hidden dimension. This linear scaling makes greedy search attractive for real-time applications, though it requires n sequential forward passes.

Limitations and Failure Modes

Greedy search frequently produces degenerate outputs due to:

For the sequence "The A B" above, the joint probability is 0.6 × 0.7 × 0.8 = 0.336, while a potentially better sequence "The B A EOS" with probabilities 0.3 × 0.6 × 0.9 = 0.162 would never be discovered.

Practical Considerations

Greedy search performs adequately when:

Modern implementations often combine greedy search with:

Advantages and Limitations of Greedy Search

Greedy search is a deterministic decoding strategy that selects the token with the highest probability at each step in the sequence generation process. Formally, given a sequence of previously generated tokens y<t, the next token yt is chosen as:

$$ y_t = \underset{w \in V}{\arg\max} \, P(w | y_{

where V is the vocabulary and θ represents the model parameters. This locally optimal choice leads to several computational advantages but also introduces key limitations in text generation quality.

Computational Efficiency

Greedy search has O(1) time complexity per token during decoding, as it only requires a single forward pass through the model to select the highest-probability token. This makes it significantly faster than beam search, which maintains k candidates and has complexity O(k|V|) per step. For autoregressive models like GPT-3 or T5, greedy decoding achieves:

  • 2-5x faster inference compared to beam search with k=5
  • Constant memory usage regardless of sequence length
  • Trivially parallelizable token selection

Repetition and Degeneration

The local optimization strategy frequently leads to repetitive loops and semantic drift. When the model enters a state where:

$$ P(y_t | y_{

for repeated tokens, greedy search cannot recover. This manifests as:

  • Infinite repetition of n-grams (e.g., "the the the")
  • Topic drift due to error accumulation
  • Premature termination when the EOS token becomes dominant

Suboptimal Global Sequences

The globally optimal sequence ŷ often differs from the greedy path. Consider two potential continuations:

$$ P(\text{"quick"}) = 0.4, \quad P(\text{"brown"}) = 0.35 $$ $$ P(\text{"fast"} | \text{"quick"}) = 0.3 $$ $$ P(\text{"fox"} | \text{"brown"}) = 0.9 $$

Greedy search selects "quick" (0.4 > 0.35), leading to joint probability 0.12, while the "brown fox" path yields 0.315. This local-global mismatch becomes exponentially worse with sequence length.

Practical Use Cases

Despite limitations, greedy search remains useful when:

  • Generating short sequences (e.g., classification labels)
  • Speed is prioritized over diversity (real-time systems)
  • The model's distribution is sharply peaked (low entropy outputs)

Modern variants address some limitations through:

  • Temperature scaling to sharpen distributions
  • Top-k filtering to eliminate low-probability tokens
  • Repetition penalties during inference

2.3 Practical Example: Implementing Greedy Search in Python

Greedy search operates by selecting the token with the highest probability at each decoding step without considering future consequences. This local optimization strategy is computationally efficient but may lead to suboptimal global sequences. Let's implement it step-by-step using PyTorch and Hugging Face's Transformers library.

Core Implementation Components

The greedy decoding process requires three key components:

Complete Python Implementation

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

def greedy_decode(model, tokenizer, input_text, max_length=50):
    # Tokenize input and convert to tensor
    input_ids = tokenizer.encode(input_text, return_tensors='pt')
    
    # Initialize output sequence with input_ids
    generated = input_ids
    
    # Disable gradient calculation for inference
    with torch.no_grad():
        for _ in range(max_length):
            # Forward pass through model
            outputs = model(generated)
            
            # Get logits of last token position
            next_token_logits = outputs.logits[:, -1, :]
            
            # Apply temperature scaling (optional)
            temperature = 1.0
            next_token_logits = next_token_logits / temperature
            
            # Greedy selection: argmax
            next_token = torch.argmax(next_token_logits, dim=-1, keepdim=True)
            
            # Append to generated sequence
            generated = torch.cat((generated, next_token), dim=-1)
            
            # Stop if EOS token is generated
            if next_token.item() == tokenizer.eos_token_id:
                break
    
    return tokenizer.decode(generated[0], skip_special_tokens=True)

# Example usage
model_name = "gpt2"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)

input_text = "The future of AI is"
output_text = greedy_decode(model, tokenizer, input_text)
print(output_text)

Mathematical Foundation

The greedy search algorithm implements the following decision rule at each timestep t:

$$ y_t = \underset{w \in V}{\arg\max}\, P(w|y_{1:t-1}, x) $$

where V is the vocabulary, x is the input context, and y1:t-1 represents previously generated tokens. The joint probability of the sequence decomposes as:

$$ P(y_{1:T}|x) = \prod_{t=1}^T P(y_t|y_{1:t-1}, x) $$

Performance Considerations

The implementation makes several optimizations:

Practical Limitations

While simple to implement, greedy search suffers from several weaknesses:

Advanced Variants

Simple modifications can improve greedy search performance:

# Temperature-scaled greedy decoding
def temperature_scaled_greedy(..., temperature=0.7):
    ...
    next_token_logits = next_token_logits / temperature
    next_token = torch.argmax(next_token_logits, dim=-1)
    ...

Temperature scaling (T ∈ (0,1]) softens the probability distribution before argmax:

$$ P_T(w) = \frac{\exp(z_w/T)}{\sum_{w'\in V} \exp(z_{w'}/T)} $$

3. Core Algorithm of Beam Search

Core Algorithm of Beam Search

Beam search is a heuristic search algorithm that explores multiple candidate sequences in parallel while maintaining a fixed-size subset of the most promising hypotheses, known as the beam width (k). Unlike greedy search, which selects the single highest-probability token at each step, beam search retains k partial sequences, expanding them iteratively to balance exploration and exploitation.

Mathematical Formulation

Given a sequence of tokens y<t generated up to step t, beam search aims to maximize the joint probability of the entire sequence:

$$ P(y_{1:T} | x) = \prod_{t=1}^T P(y_t | y_{

where x is the input context (e.g., a prompt or encoder output). At each step t, the algorithm:

  • Computes the probability distribution over the vocabulary for each candidate in the beam.
  • Extends each candidate with all possible next tokens, generating k × V hypotheses (where V is vocabulary size).
  • Prunes the expanded set to retain only the top-k highest-scoring sequences based on cumulative log-probability.

Step-by-Step Execution

For a beam width k and maximum sequence length T:

  1. Initialization: Start with k copies of the initial token (e.g., <s>), each with a score of 0.
  2. Expansion: For each candidate in the beam, compute log-probabilities for all possible next tokens. Scores are additive in log-space to avoid underflow:
    $$ \text{score}(y_{1:t}) = \sum_{i=1}^t \log P(y_i | y_{
  3. Pruning: Select the top-k sequences from the k × V candidates. Ties are broken arbitrarily.
  4. Termination: Stop when all sequences in the beam reach an end-of-sequence token or exceed T.

Practical Considerations

Length Normalization: To penalize longer sequences (which inherently have lower joint probabilities), scores are often normalized by sequence length t:

$$ \text{normalized score} = \frac{1}{t^\alpha} \sum_{i=1}^t \log P(y_i | y_{

where α is a hyperparameter (typically 0.7–1.0). This mitigates the bias toward shorter outputs.

Early Stopping: In practice, beams may converge to identical sequences. To reduce redundancy, some implementations stop when a minimum number of unique hypotheses are reached.

Visualization of Beam Search

Consider a beam width of 2 and vocabulary {A, B, C}. At each step, the algorithm:

Step 1 A (score: -0.2) B (score: -0.3)

Dashed lines represent pruned paths. The top-2 candidates (A, B) are expanded in the next step.

Trade-offs and Limitations

  • Computational Cost: Memory and runtime scale linearly with k, but the search space remains more tractable than exhaustive methods.
  • Local Optima: Unlike sampling-based methods (e.g., nucleus sampling), beam search may miss high-probability sequences obscured by early pruning.
  • Repetition: Without constraints, beams can get stuck in loops (e.g., repeating "the the"). Techniques like n-gram blocking mitigate this.
Core Algorithm of Beam Search – Text Generation Strategies: Greedy vs Beam Search – Tutorial Diagram
Diagram Description: The diagram would physically show the branching and pruning of candidate sequences during beam search, with paths for top-k hypotheses and pruned branches marked.

3.2 Hyperparameters: Beam Width and Length Penalties

The effectiveness of beam search hinges on two critical hyperparameters: beam width and length normalization. These parameters directly influence the trade-off between computational efficiency and output quality.

Beam Width (k)

Beam width determines the number of candidate sequences retained at each decoding step. A larger k increases the likelihood of finding high-probability sequences but at the cost of higher computational overhead. The probability of a sequence y given input x is:

$$ P(y|x) = \prod_{t=1}^{T} P(y_t | y_{

For beam width k, the decoder maintains the top-k partial sequences at each step. The optimal value of k varies by task:

  • Machine Translation: Typically k = 4–10, balancing diversity and fluency.
  • Summarization: Often k = 5–8 to avoid degenerate repetitions.
  • Dialogue Systems: Higher k (8–12) may improve coherence but risks generic responses.

Length Normalization

Beam search tends to favor shorter sequences due to the multiplicative nature of sequence probabilities. Length normalization counteracts this bias by adjusting the scoring function:

$$ \text{Score}(y) = \frac{1}{(1 + |y|)^\alpha} \sum_{t=1}^{|y|} \log P(y_t | y_{

Here, α controls the strength of the penalty:

  • α = 0: No normalization (raw log probabilities).
  • α = 1: Standard length normalization.
  • α > 1: Aggressive penalty for long sequences.

Empirical studies show α = 0.6–0.7 works well for translation, while α = 0.8–1.0 suits abstractive summarization.

Dynamic Beam Adjustment

Advanced implementations use adaptive beam widths, such as:

  • Variable Beam Search: Expands k when candidate scores cluster within a threshold.
  • Stochastic Beam Search: Samples k sequences proportionally to their scores.

These methods mitigate the risk of premature convergence to suboptimal paths while maintaining computational bounds.

Case Study: Neural Machine Translation

In Transformer-based NMT, beam width interacts with model confidence. For example, a 6-layer Transformer achieves:

$$ \text{BLEU}_{k=4} = 38.2 \quad \text{vs.} \quad \text{BLEU}_{k=8} = 38.9 $$

Despite the 2× computational cost, the marginal gain of 0.7 BLEU may not justify k > 4 for production systems.

3.3 Trade-offs Between Diversity and Coherence

Text generation strategies like greedy search and beam search inherently face a fundamental tension between diversity and coherence. Greedy search, which selects the token with the highest probability at each step, tends to produce highly coherent but often repetitive and predictable outputs. Beam search mitigates this by maintaining multiple candidate sequences, but even then, the likelihood-focused objective can lead to generic or overly safe responses.

Quantifying the Diversity-Coherence Trade-off

The trade-off can be formalized using entropy-based metrics. For a sequence of tokens y1:t generated by a language model with vocabulary V, the conditional entropy at step t+1 is:

$$ H(y_{t+1} | y_{1:t}) = - \sum_{w \in V} P(w | y_{1:t}) \log P(w | y_{1:t}) $$

Higher entropy indicates greater diversity in potential next tokens, while lower entropy suggests more deterministic, coherent continuations. Beam search with a narrow beam width k effectively truncates the probability distribution, reducing entropy and favoring high-probability (coherent) tokens.

Techniques for Balancing the Trade-off

Several methods have been proposed to explicitly control this trade-off:

$$ P_{\tau}(w | y_{1:t}) = \frac{\exp(z_w / \tau)}{\sum_{v \in V} \exp(z_v / \tau)} $$

where τ → 0 approaches greedy sampling (high coherence), and τ → ∞ yields uniform sampling (high diversity).

Empirical Observations

Recent studies on open-ended generation tasks reveal that human-like text requires navigating a "narrow pathway" between these extremes. For example:

The optimal balance depends heavily on the application domain—technical documentation generation prioritizes coherence, while poetry generation may intentionally sacrifice some coherence for artistic diversity.

Emerging Approaches

Advanced methods like contrastive search explicitly optimize for both aspects by selecting tokens that:

$$ w_{t+1} = \underset{w \in V}{\text{argmax}} \{(1-\alpha) \log P(w|y_{1:t}) - \alpha \max_{1 \leq i \leq t} \text{cosine}(h_w, h_{y_i})\} $$

where α controls the diversity penalty based on token embedding similarity. This achieves state-of-the-art results by dynamically adjusting the coherence-diversity balance during generation.

Trade-offs Between Diversity and Coherence – Text Generation Strategies: Greedy vs Beam Search – Tutorial Diagram
Diagram Description: The diagram would visually contrast the probability distributions of greedy search (sharp peak) versus beam search (multiple candidate peaks) versus temperature-scaled sampling (flattened distribution).

3.4 Case Study: Beam Search in Machine Translation

Beam search is a critical component in neural machine translation (NMT) systems, where generating fluent and accurate translations requires balancing exploration and exploitation. Unlike greedy search, which selects the highest-probability token at each step, beam search maintains k partial hypotheses (beams) and expands them iteratively, pruning low-scoring candidates.

Mathematical Formulation

Given a source sentence X and target sentence Y, the translation probability is modeled as:

$$ P(Y|X) = \prod_{t=1}^{T} P(y_t | y_{

At each decoding step t, beam search computes the joint probability of partial hypotheses up to length t:

$$ \text{Score}(y_{1:t}) = \sum_{i=1}^{t} \log P(y_i | y_{

For a beam width B, the algorithm retains the top-B hypotheses ranked by their cumulative log-probability. This mitigates the risk of early errors propagating through greedy decoding.

Practical Implementation in NMT

Modern NMT systems like Transformer-based models implement beam search with additional refinements:

  • Length normalization: Adjusts scores by hypothesis length to prevent bias toward shorter outputs:
    $$ \text{Score}_{\text{norm}}(y_{1:t}) = \frac{1}{t^\alpha} \sum_{i=1}^{t} \log P(y_i | y_{ where α ∈ [0,1] controls the normalization strength.
  • End-of-sequence handling: Completed hypotheses are stored separately and removed from the active beam.
  • Diverse beam search: Partitions beams into groups to promote lexical diversity.

Performance Trade-offs

Increasing beam width improves translation quality (measured by BLEU) but with diminishing returns and higher computational cost. Empirical studies show:

Beam Width (B) BLEU Score Decoding Time (× baseline)
1 (greedy) 23.4 1.0
5 25.1 2.3
10 25.3 3.8

The optimal B typically ranges between 4–10 for production systems, balancing quality and latency.

Comparative Analysis with Sampling Methods

While beam search excels in deterministic scenarios, stochastic methods like nucleus sampling (top-p) often produce more natural text for open-ended generation. Hybrid approaches dynamically switch between beam search and sampling based on output entropy thresholds.

$$ \text{Switch if } H(y_t | y_{ \tau $$

where H is the conditional entropy and τ is a tunable threshold.

Case Study: Beam Search in Machine Translation – Text Generation Strategies: Greedy vs Beam Search – Tutorial Diagram
Diagram Description: The diagram would show the step-by-step expansion and pruning of beam hypotheses during decoding, comparing multiple paths versus greedy search's single path.

4. Performance Comparison on Standard Benchmarks

4.1 Performance Comparison on Standard Benchmarks

When evaluating text generation strategies, empirical performance on standardized benchmarks provides critical insights into the trade-offs between greedy search and beam search. Key metrics include perplexity, BLEU score, ROUGE-L, and human evaluation scores, measured across datasets like WMT (Machine Translation), CNN/Daily Mail (Summarization), and WikiText (Language Modeling).

Quantitative Metrics

Greedy search, which selects the token with the highest probability at each step, often achieves lower computational overhead but suffers from local optima. Beam search (with beam width B) explores multiple hypotheses, improving sequence likelihood but at the cost of increased latency. The likelihood of a generated sequence y given input x can be formalized as:

$$ P(y|x) = \prod_{t=1}^T P(y_t | y_{

For beam search, this becomes a search for the top-B sequences maximizing cumulative log-probability:

$$ \text{score}(y) = \sum_{t=1}^T \log P(y_t | y_{

Benchmark Results

On the WMT14 English-German translation task, beam search (B=5) outperforms greedy decoding by 2.1 BLEU points, but with 3× slower inference. However, greedy search achieves lower perplexity on WikiText-103 (Table 1), suggesting it may generalize better for open-ended generation where diversity matters.

Trade-offs in Summarization

For abstractive summarization (CNN/Daily Mail), beam search generates more factually consistent outputs (ROUGE-L: 38.2 vs. 35.7) but risks repetition with larger beams. Hybrid approaches like diverse beam search (Vijayakumar et al., 2018) mitigate this by enforcing diversity among hypotheses.

Computational Efficiency

The time complexity of greedy search is O(T · V), where V is vocabulary size. Beam search scales to O(T · B · V), with memory overhead for storing B sequences. For B=10, this increases latency by 4–8× compared to greedy search on GPU hardware (A100 benchmarks).

Case Study: Machine Translation

In Transformer-based models (Vaswani et al., 2017), beam search with length normalization (α=0.6) achieves optimal BLEU scores. However, greedy decoding remains preferred for real-time applications due to strict latency constraints, despite a 5–10% quality drop.

4.2 Computational Efficiency and Memory Usage

Greedy search and beam search exhibit fundamentally different computational behaviors due to their contrasting exploration strategies. Greedy search operates with constant memory O(1) per time step, maintaining only a single candidate sequence. The time complexity scales linearly with sequence length L as O(L·V), where V is vocabulary size, as it performs a simple argmax operation over logits at each step.

$$ C_{\text{greedy}} = L \cdot (V + d_{\text{model}}^2) $$

where dmodel represents the transformer's hidden dimension. Beam search with width k requires maintaining k active sequences, resulting in memory complexity O(kL). The time complexity becomes O(L·k·V) due to the top-k selection process:

$$ C_{\text{beam}} = L \cdot k \cdot (V \log V + d_{\text{model}}^2) $$

Memory Bandwidth Bottlenecks

Modern GPUs face significant memory bandwidth constraints when executing beam search. Each candidate sequence requires separate attention key-value caches in autoregressive transformers, creating k-fold memory pressure compared to greedy decoding. For a model with nlayers layers and cache size dhead, the KV cache memory consumption is:

$$ M_{\text{cache}} = 2 \cdot k \cdot L \cdot n_{\text{layers}} \cdot d_{\text{head}} \cdot \text{bytes}_{\text{precision}}} $$

Practical implementations often hit memory limits before compute limits - a 175B parameter model with k=8 and L=2048 can require over 80GB just for KV caches at FP16 precision.

Parallelization Trade-offs

Beam search enables two parallelization dimensions: intra-sequence (across timesteps) and inter-sequence (across beams). However, the irregular computation patterns of active beam pruning create workload imbalance. Modern frameworks like TensorRT-LLM implement:

These optimizations can reduce memory overhead by 30-50% while maintaining the same search quality.

Quantitative Comparison

Benchmarks on an A100 GPU with Llama-2-7B reveal stark differences:

Strategy Throughput (tok/s) Memory (GB) Latency (ms/tok)
Greedy 142 4.2 7.1
Beam (k=4) 38 16.8 26.3
Beam (k=8) 19 33.6 52.6

The quadratic growth in memory and linear decrease in throughput demonstrate the fundamental trade-off between exploration quality and computational cost.

When to Choose Greedy or Beam Search

The choice between greedy search and beam search depends on the trade-offs between computational efficiency, output quality, and task-specific requirements. Each strategy has distinct advantages and limitations that make them suitable for different scenarios.

Computational Efficiency vs. Output Quality

Greedy search is computationally efficient, requiring only a single forward pass per time step. At each step, it selects the token with the highest probability:

$$ w_t = \argmax_{w \in V} P(w | w_{1:t-1}, x) $$

where V is the vocabulary and x is the input context. This makes greedy search ideal for real-time applications where latency is critical, such as autocomplete systems or voice assistants. However, it often produces suboptimal sequences due to its myopic decision-making.

Beam search maintains k candidate sequences at each step, where k is the beam width. The probability of a partial sequence is computed as:

$$ P(w_{1:t} | x) = \prod_{i=1}^t P(w_i | w_{1:i-1}, x) $$

By exploring multiple hypotheses, beam search generally produces higher-quality outputs but requires O(k) more computation than greedy search. The choice of k significantly impacts performance—larger beams improve quality but increase latency and memory usage.

Task-Specific Considerations

Use greedy search when:

Use beam search when:

Practical Trade-offs

In machine translation, beam search (with k=5 to 10) is standard because it reduces fluency errors. For open-ended generation (e.g., story writing), smaller beams (k=2 to 5) balance quality and creativity. Greedy decoding suffices for constrained tasks like named entity recognition, where correctness depends more on input context than sequential decisions.

Recent hybrid approaches, such as adaptive beam search, dynamically adjust k based on uncertainty metrics. For example:

$$ k_t = \begin{cases} k_{\max} & \text{if } H(P_{t}) > \theta \\ 1 & \text{otherwise} \end{cases} $$

where H(Pt) is the entropy of the token distribution at step t, and θ is a threshold. This conserves resources during low-uncertainty steps while maintaining quality for ambiguous predictions.

5. Stochastic Beam Search and Temperature Sampling

5.1 Stochastic Beam Search and Temperature Sampling

Stochastic beam search introduces randomness into the traditional beam search algorithm by probabilistically selecting candidates at each decoding step. Unlike deterministic beam search, which retains the top-k highest-scoring sequences, stochastic beam search samples sequences according to their probability distribution, enabling more diverse outputs while maintaining coherence.

Mathematical Formulation

Given a sequence probability distribution P(yt | y<t, x) at step t, stochastic beam search applies the following steps:

$$ \text{Step 1: Compute logits } \mathbf{z}_t = f(y_{<t}, x) $$
$$ \text{Step 2: Apply temperature scaling } \mathbf{p}_t = \text{softmax}(\mathbf{z}_t / \tau) $$
$$ \text{Step 3: Sample } y_t \sim \text{Categorical}(\mathbf{p}_t) $$

Here, τ (temperature) controls the sharpness of the distribution. Lower values (τ < 1) amplify high-probability tokens, while higher values (τ > 1) flatten the distribution.

Temperature Sampling

Temperature sampling modifies the softmax output to control the trade-off between diversity and likelihood:

$$ p_i = \frac{\exp(z_i / \tau)}{\sum_j \exp(z_j / \tau)} $$

Key effects of temperature:

Implementation Considerations

Stochastic beam search requires careful handling of sequence probabilities during sampling. Unlike standard beam search, where scores are cumulative log-probabilities, stochastic variants often use:

$$ \text{Renormalized scores: } s_t = s_{t-1} + \log p(y_t | y_{<t}) + \eta $$

where η is a noise term (e.g., Gumbel noise for differentiable sampling). Practical implementations often combine temperature sampling with top-k or top-p (nucleus) filtering to avoid low-probability tokens.

Comparative Analysis

Empirical studies show stochastic beam search with temperature tuning achieves:

The method is particularly effective when combined with techniques like length normalization and repetition penalty, as it allows controlled exploration of the solution space without collapsing to high-likelihood but generic outputs.

Stochastic Beam Search and Temperature Sampling – Text Generation Strategies: Greedy vs Beam Search – Tutorial Diagram
Diagram Description: The diagram would show the step-by-step transformation of logits to sampled tokens via temperature scaling, contrasting different temperature effects on the probability distribution.

5.2 Combining Beam Search with Top-k or Top-p Sampling

Beam search, while effective for deterministic text generation, often suffers from lack of diversity and repetitive outputs. Integrating stochastic sampling methods like top-k or top-p (nucleus sampling) with beam search can mitigate these issues while retaining coherence. The hybrid approach leverages the exploratory nature of sampling while maintaining the structured search of beam decoding.

Mathematical Formulation

Given a beam width B, top-k restricts the sampling pool to the k most probable tokens at each step, while top-p dynamically truncates the distribution by selecting the smallest set of tokens whose cumulative probability exceeds p. The combined strategy modifies the beam search scoring function:

$$ P(y_t | y_{

where V(k) is the top-k vocabulary subset and V(p) is the nucleus subset.

Implementation Steps

  1. Beam Initialization: Start with B hypotheses (e.g., [BOS] tokens).
  2. Step-wise Expansion: For each hypothesis, generate next-token probabilities and apply top-k or top-p filtering.
  3. Hypothesis Pruning: Retain the top-B sequences based on log-probability scores.
  4. Termination: Stop when all beams reach [EOS] or max length.

Practical Considerations

  • Temperature Scaling: Adjust softmax temperature (τ) to control entropy:
    $$ P_{\tau}(y_t) = \frac{\exp(s(y_t)/\tau)}{\sum_j \exp(s(y_j)/\tau)} $$
  • Beam Diversity: Penalize length-normalized scores to avoid length bias or introduce diversity-promoting terms.
  • Dynamic Thresholds: Adaptive top-p (varying p per timestep) can balance exploration-exploitation.

Case Study: Machine Translation

In neural machine translation (NMT), hybrid decoding with B=5, k=40, and τ=0.7 improved BLEU scores by 1.2 points over pure beam search in low-resource settings (Edunov et al., 2018). The method reduced repetitions while preserving semantic accuracy.

Trade-offs

Strategy Pros Cons
Beam + top-k Controlled diversity, deterministic k Fixed k may exclude plausible tokens
Beam + top-p Adaptive vocabulary, dynamic cutoff Sensitive to p choice, computationally variable

Empirical studies suggest top-p generally outperforms top-k in open-ended generation tasks, while top-k is preferred for constrained outputs like code generation.

5.3 Recent Innovations in Decoding Strategies

Traditional decoding methods like greedy search and beam search have limitations in generating diverse and coherent text. Recent innovations address these shortcomings through probabilistic, constrained, and adaptive techniques.

Nucleus Sampling (Top-p Sampling)

Nucleus sampling dynamically truncates the probability distribution by selecting the smallest set of tokens whose cumulative probability exceeds a threshold p. This avoids both the determinism of greedy search and the repetition issues of beam search. The probability mass is redistributed among the selected tokens:

$$ P(x_i | x_{

where V(p) is the smallest set satisfying x∈V(p) P(x|x) ≥ p. This method produces more diverse outputs while maintaining coherence.

Contrastive Search

Contrastive search optimizes for both likelihood and dissimilarity with previous tokens. The scoring function combines a model's confidence and a degeneration penalty:

$$ s(x_t) = (1 - \alpha) \cdot \log P(x_t | x_{

where α controls the trade-off, and h(x) denotes token embeddings. This suppresses repetitive n-grams while preserving fluency.

Adaptive Beam Search

Dynamic beam width adjustment improves efficiency. The beam expands when candidate scores are close (σt < threshold) and contracts when predictions are confident:

$$ k_t = \begin{cases} k_{t-1} + \Delta & \text{if } \sigma_t < \tau \\ \max(1, k_{t-1} - \Delta) & \text{otherwise} \end{cases} $$

where σt is the score variance at step t, and τ is a tunable threshold.

Stochastic Beam Search

This method introduces randomness by sampling beam candidates without replacement using Gumbel-top-k tricks. The probability of selecting sequence si is:

$$ P(s_i) = \frac{\exp(\log P(s_i) / T + g_i)}{\sum_{j=1}^B \exp(\log P(s_j) / T + g_j)} $$

where gi are i.i.d. Gumbel noises, and T is a temperature parameter. This combines diversity with beam search's structured exploration.

Lookahead Decoding

Parallel verification of candidate prefixes speeds up decoding. For each beam entry, the algorithm:

  • Generates k continuations
  • Scores them using a lightweight auxiliary model
  • Selects the highest-scoring path without full sequential computation

This reduces latency by up to 2× while maintaining output quality.

Energy-Based Decoding

Recent work frames decoding as energy minimization, where the energy function E(x) combines:

  • Negative log-likelihood
  • Task-specific constraints (e.g., semantic similarity)
  • Discourse coherence metrics
$$ E(x) = -\lambda_1 \log P(x) + \lambda_2 \mathcal{L}_{\text{constraint}}(x) + \lambda_3 \mathcal{L}_{\text{discourse}}(x) $$

Sampling from the Gibbs distribution P(x) ∝ exp(-E(x)) yields outputs that balance fluency with controllable attributes.

6. Key Research Papers on Decoding Strategies

6.1 Key Research Papers on Decoding Strategies

6.2 Recommended Books and Online Courses

6.3 Open-source Implementations and Toolkits