Decoding: Greedy, Beam Search, Sampling & Structured Output

Generative & Agentic AI · Working with LLMs · Intermediate · 20 min

Explain how an LLM turns next-token scores into text: greedy, beam search, temperature, top-k, top-p, min-p, penalties, stop sequences and constrained decoding for reliable JSON, and implement beam search.

A hiker at a fork in the trail every few steps. Greedy takes whichever path looks best right now. Beam search sends a few scouts down the most promising paths and keeps only the best scouts at each fork. Sampling rolls weighted dice.

The idea in everyday words

Planning a road trip with a sat-nav. Picking the fastest road at every junction (greedy) can lead you onto a road that ends in a traffic jam. Keeping the three best routes so far and extending each one (beam search) finds a better overall trip. If you want a surprising scenic route, you let chance pick among the good roads (sampling).

One token at a time, from scores to a choice

At every step the model outputs a logit (a raw score) for every token in its vocabulary. Softmax turns those scores into probabilities that add up to 1. Then a decoding strategy picks one token, appends it, and the whole thing repeats.

So the model does not "write an answer". It writes one token, then the next, then the next, and the decoding strategy decides how each one is chosen. Two families:

Family How it picks Good for
Search (greedy, beam) the most likely token or sequence translation, short exact outputs, speech-to-text
Sampling (temperature, top-k, top-p, min-p) a weighted random pick chat, creative writing, varied answers

A quick reminder of the sampling dials from the in-context learning lesson: temperature divides logits before softmax (below 1 sharpens, above 1 flattens), top-k keeps the k most likely tokens, and top-p keeps the smallest top group whose probabilities add up to p.

Greedy vs beam search

Greedy decoding takes the single most likely token at every step. It is fast and simple, but it can be short-sighted: a token that looks best now can lead to a worse sentence overall.

Beam search keeps the width (also called beam size) best partial sequences at every step:

  1. Grow every kept sequence by every possible next token.
  2. Score each candidate by its total log-probability (adding logs = multiplying probabilities).
  3. Keep the best width candidates, drop the rest. Repeat.

Tiny example, with scores = log-probability × 10 (higher is better):

Path Step 1 Step 2 Total
The nice woman -7 -9 -16
The dog has -9 -1 -10

Greedy grabs "nice" (-7 beats -9) and ends at -16. Beam search with width 2 keeps "dog" alive and finds "The dog has" at -10.

Know the limits (interviewers ask):

  • Beam search is not guaranteed optimal: a path pruned early is never revisited.
  • Long sequences add more negative scores, so beam search favours short answers. A length penalty (divide the score by length to some power) fixes that.
  • For open-ended chat it tends to produce bland, repetitive text, which is why chat LLMs sample instead. Beam search is still common in translation and speech recognition.

More sampling controls: min-p and penalties

Beyond temperature, top-k and top-p:

  • min-p: keep tokens whose probability is at least min_p × (top token's probability). When the model is confident, almost everything else is cut; when it is unsure, many tokens survive. Popular in open-source servers.
  • Repetition penalty: make tokens that already appeared less likely, to stop loops like "very very very".
  • Frequency penalty: subtract more the more often a token has appeared. Presence penalty: subtract a fixed amount once a token has appeared at all. (These are OpenAI-style names; other providers differ.)
  • Max tokens and stop sequences: not about randomness, but they decide when decoding ends. The API's stop reason tells you which one fired, so check it: an answer cut off by max tokens is incomplete.
probs = {"blue": 60, "clear": 25, "grey": 10, "pizza": 5}
min_p = 0.2
top = max(probs.values())
print([t for t, p in probs.items() if p >= min_p * top])

Temperature 0 is not a determinism guarantee. In practice the same prompt can still produce different outputs, because GPU maths can add numbers in a slightly different order depending on how requests are batched together, and a tiny difference can flip a near-tie. Design systems that tolerate small variations: validate outputs, do not compare them byte for byte.

Structured output: constrain the decoder

Asking "please reply in JSON" works most of the time. Production systems need every time. Constrained decoding enforces it at the token level: at each step, any token that would break the required format (a JSON schema, a regular expression, a grammar) gets its probability set to zero before the pick. The model can only produce valid output.

logits = {"Sure": 2.5, "{": 1.9, "Here": 1.2}
allowed = {"{"}           # a JSON object must start with {
masked = {t: (l if t in allowed else float("-inf")) for t, l in logits.items()}
print(max(logits, key=logits.get), "->", max(masked, key=masked.get))

On AWS (Amazon Bedrock):

  • The Converse API takes the common dials in inferenceConfig: maxTokens, temperature, topP, stopSequences. Model-specific extras (like top_k for Anthropic Claude) go in additionalModelRequestFields.
  • For reliable JSON, define a tool in toolConfig whose inputSchema is your JSON schema and force it with toolChoice; the model's tool call input is your structured output. Some models also offer a native JSON schema / structured output mode: check the model's page in the Bedrock docs.
  • Always validate the result (for example with a JSON schema validator in your Lambda) and retry or fall back if it fails.

Open-source equivalent: vLLM and SGLang support guided decoding with JSON schemas or grammars, and llama.cpp uses GBNF grammars. OpenAI and Anthropic APIs offer structured output modes too.

Step by step

  1. Start:

    Width = 2. One beam: "The" with total score 0. Scores are log-probability × 10, so closer to 0 is better.

  2. Grow step 1:

    "The" can continue with nice (-7), dog (-9) or car (-23). Three candidates: The nice -7, The dog -9, The car -23.

  3. Prune to 2:

    Keep the best 2 by total: The nice (-7) and The dog (-9). "car" is dropped for good.

  4. Grow step 2:

    nice → woman -9, house -12, guy -12. dog → has -1, runs -30, and -30. Totals: nice woman -16, nice house -19, nice guy -19, dog has -10, dog runs -39, dog and -39.

  5. Prune again:

    Sort by total and keep 2: The dog has (-10) and The nice woman (-16).

  6. Compare with greedy:

    Answer: "The dog has" at -10 (about 37% likely). Greedy took "nice" first and ended at -16 (about 20%). Looking one step ahead paid off.

Code example

import math

def softmax(logits, T=1.0):
    exps = {tok: math.exp(l / T) for tok, l in logits.items()}
    total = sum(exps.values())
    return {tok: e / total for tok, e in exps.items()}

logits = {"blue": 3.0, "clear": 2.2, "grey": 1.4, "falling": 0.3, "pizza": -1.5}

for T in [0.5, 1.0, 1.5]:
    probs = softmax(logits, T)
    print("T =", T, ":", ", ".join(f"{t} {round(100 * p)}%" for t, p in probs.items()))

probs = softmax(logits)
print("greedy picks:", max(probs, key=probs.get))
top = max(probs.values())
print("min-p 0.1 keeps:", [t for t, p in probs.items() if p >= 0.1 * top])

# Constrained decoding: mask every token that would break the required JSON.
wanted = {"Sure": 2.5, "{": 1.9, "Here": 1.2, '"': 0.4}
allowed = {"{"}
masked = {t: (l if t in allowed else float("-inf")) for t, l in wanted.items()}
print("unconstrained:", max(wanted, key=wanted.get), "| constrained:", max(masked, key=masked.get))

Complexity

  • Time: Beam search: O(steps × width × branches × log(width × branches)) for expanding and sorting the candidates each step. Greedy is the width = 1 case.
  • Space: O(width × steps) to hold the kept sequences (plus the candidate list each step).

Interview tips

  • "Greedy vs beam search vs sampling: when would you use each?" Beam for short, exact outputs like translation; sampling for chat and creative text; greedy or low temperature for extraction.

  • Be ready to code beam search: expand all beams, score by cumulative log-probability, sort globally, keep width. Mention length normalisation and that it is not guaranteed optimal.

  • Explain why temperature 0 can still give different outputs in production (batching changes floating point order, near-ties flip), and how you design around it (validation, tolerant comparisons, caching answers you must repeat).

  • "How do you guarantee valid JSON from an LLM?" Constrained or structured decoding with a schema (or forcing a tool with an input schema on Bedrock), then validate and retry, never prompt-only.

  • Know min-p, top-p, top-k and the repetition, frequency and presence penalties well enough to say which problem each one solves.

Challenge: Beam Search Decoder

Write beam_search(graph, start, width, steps) and return [best_tokens, total_score].

  • graph maps a token to its possible next tokens: {"The": [["nice", -7], ["dog", -9]], ...}. Scores are log-probabilities × 10 (integers, 0 or below). A sequence's score is the sum of its step scores.
  • Start with one beam: [[start], 0]. Repeat steps times:
    • Grow every beam by every option for its last token. A beam whose last token is missing from graph (or has an empty list) is finished: keep it unchanged as a candidate.
    • Sort all candidates together by total score, highest first. Ties: the smaller sequence when its tokens are joined with single spaces.
    • Keep the first width candidates.
  • Return the best beam (tokens and score).

Example:

g = {"The": [["nice", -7], ["dog", -9], ["car", -23]],
     "nice": [["woman", -9], ["house", -12], ["guy", -12]],
     "dog": [["has", -1], ["runs", -30], ["and", -30]]}
beam_search(g, "The", 1, 2)  →  [["The", "nice", "woman"], -16]
beam_search(g, "The", 2, 2)  →  [["The", "dog", "has"], -10]

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Working with LLMs

Previous: In-Context Learning & Inference Parameters · Next: Building With LLM APIs