30 Mins

5. Text Generation & Decoding Strategies

Autoregressive Generation and Deterministic Decoding

At the core of modern Large Language Models lies the autoregressive property: the probability of the next token is conditioned on the sequence of all previously generated tokens. Mathematically, this is expressed as p(x_t | x_{

Greedy Search is the most straightforward approach, where the model consistently selects the token with the highest probability at each step (argmax). While computationally efficient, this approach is notoriously prone to local optima, often leading to repetitive, generic, or loops in generated text. Beam Search mitigates this by maintaining 'k' most likely partial sequences at each step, exploring a broader search space, although it can still struggle with the 'degeneration' problem where it prefers shorter or overly probable sequences.

Operator Note: Beam search length penalty is often used to counteract the bias where the model assigns higher log-probabilities to shorter sequences by artificially inflating scores of longer completions.
Python 3
import torch
import torch.nn.functional as F

# Simulate logits for a vocabulary of 5 tokens
logits = torch.tensor([2.0, 0.5, 0.1, 5.0, 1.2])

# Greedy Search: selecting the argmax index
greedy_token = torch.argmax(logits).item()

# Beam Search logic (simplified): Selecting top 2
probs = F.softmax(logits, dim=-1)
beam_tokens = torch.topk(probs, 2).indices.tolist()

print(f"Greedy: {greedy_token}, Beam: {beam_tokens}")

Injecting Diversity: Sampling and Temperature

To move beyond deterministic outputs, we introduce stochastic sampling. Temperature scaling modulates the softmax distribution: dividing logits by a temperature 'T' before exponentiation. A T < 1 sharpens the distribution, making the model more confident and conservative, while T > 1 flattens it, increasing the probability of picking lower-ranked 'tail' tokens, which creates more diverse and creative output.

However, pure random sampling often selects extremely unlikely tokens, leading to nonsensical text. To solve this, we use Top-K and Top-P (Nucleus) sampling. Top-K truncates the distribution to the K most likely candidates. Top-P (Nucleus) is more dynamic: it considers the smallest set of tokens whose cumulative probability mass exceeds threshold 'p'. This allows the model to adaptively expand its selection pool based on its own confidence level.

Operator Note: Combining Top-K and Top-P is a common industry standard; usually, Top-K acts as a hard filter to remove noise, while Top-P acts as the semantic throttle for creativity.
Python 3
import torch

def apply_temperature(logits, t=1.0):
    return logits / t

# Top-P Sampling implementation snippet
def top_p_filter(logits, p=0.9):
    sorted_logits, sorted_indices = torch.sort(logits, descending=True)
    cumulative_probs = torch.cumsum(torch.softmax(sorted_logits, dim=-1), dim=-1)
    sorted_indices_to_remove = cumulative_probs > p
    # Shift indices to keep at least one token
    sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
    sorted_indices_to_remove[..., 0] = 0
    indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
    logits[indices_to_remove] = float('-inf')
    return logits

Knowledge Check

Ready to test your understanding of 5. Text Generation & Decoding Strategies?

Back