# Greedy vs Beam Search vs Sampling

> The three ways a model picks its next word, when each one fits, and what each one costs, explained simply for your AI interview.

**In short:** Greedy search always takes the single most likely next word. Beam search keeps several candidate sentences alive and returns the one with the highest overall score. Sampling draws the next word at random, weighted by how likely each one is, which gives more varied text.

AI and LLM interview question Q013, LLM fundamentals. Intermediate, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/greedy-vs-beam-search-vs-sampling

## Say it in 30 seconds

When an AI model writes, it picks one word at a time. Greedy search always picks the single most likely word. Beam search keeps a few candidate sentences going and picks the best whole one, which suits tasks like transcribing audio. Sampling picks at random, weighted by likelihood, so it's varied but less predictable. For facts from a recording I'd use beam, and for drafts I'd sample. Any amount gets checked against the audio or billing data.

## Say it in 2 minutes

A language model writes one token at a time, and it needs a rule for each pick. That rule is the decoding strategy, and it changes the output even when the model stays the same.

Greedy search is the simplest. It takes the top-scoring token at every step, so it's fast and steady, but it can lock in an early choice that leads to a worse sentence, and on long answers it tends to repeat itself. Beam search keeps several candidate sentences alive at once and returns the one with the highest overall score. It costs more work, and it suits tasks where the input decides the answer, like speech recognition.

Sampling draws each token at random, weighted by its probability. That gives varied wording, which suits a support bot's drafts, but the same prompt can give a different answer each run. Temperature is the dial that makes sampling sharper or flatter.

In a real project I'd match the strategy to the task. A call transcription needs beam or greedy, with amounts checked against the audio. A reply drafter can sample, but the refund amount must come from billing code, which the model never sets. Naming the risk first, then the setting, is what interviewers listen for.

## What are the three ways a model picks a word, in plain words?

A language model writes one small piece of text at a time, called a token. At each step it gives every possible next token a score, which is roughly how likely it is to come next. Decoding is the rule that picks one of those tokens, and the rule you choose changes what comes out.

Picture a call centre agent with a script. Read the top reply every time, and every call sounds the same. Read several full replies side by side, then choose the best whole one. Or draw one reply at random, favouring the common ones. Those three habits are greedy, beam and sampling.

In an AI product the same choice decides whether a transcript of a customer's call gets a dollar amount right, and whether a drafted reply sounds natural.

- **Token:** A small piece of text, often a word or part of one, that the model writes one at a time.
- **Decoding:** The rule that turns the model's scores into the next token it writes.
- **Probability:** How likely the model thinks a token is to come next, from 0 to 1.
- **Beam:** One of several full candidate sentences that beam search keeps alive while it writes.
- **Temperature:** A setting that makes sampling more random when higher and more predictable when lower.

## How does each strategy pick the next word?

- **Greedy: Top pick at each step.** Takes the single most likely token every time. Fast and steady, but it can lock in an early mistake.
- **Beam: Several candidates at once.** Keeps a few full candidates alive, then returns the highest overall score. More work, and better where the input decides the answer.
- **Sampling: A weighted draw.** Picks a token at random, weighted by likelihood. Varied wording, but a different answer can come each run.

Greedy search is the simplest of the three. Hugging Face's Transformers library, an open-source toolkit, makes it the default decoding strategy. Its guide says greedy search suits short outputs where creativity is not a priority, and that it breaks down on longer text, because it begins to repeat itself.

Beam search keeps several candidates, called beams, alive at each step. At the end it returns the one with the highest overall probability. It can pick a sentence whose first words were less likely but which scores better in total. Hugging Face says beam search is best suited to input-grounded tasks, like describing an image or recognising speech, where the input sets the right output.

In that library you switch beam search on with a number of beams. At one beam it is the same as greedy search.

Sampling does the opposite of the top pick. It chooses a token at random, weighted by its probability, so any token with some chance can be picked. Hugging Face says this reduces repetition and can give more creative and varied output.

*Diagram, Three ways to pick the next word: The model scores every possible next token. Each strategy turns those scores into a pick, and the box to its right shows what that pick tends to lead to. Blue is the main path, orange a known problem, green the highest-scoring result, which is not always the true one.*
1. Greedy takes the single top token at each step.
2. Beam keeps several full candidates alive while it writes.
3. Sampling draws a token at random, weighted by its odds.
4. An early pick can lock in and push the text into repeats.
5. The best whole candidate wins, at more compute.
6. Each run can differ, so checks matter more.

In 2019 Ari Holtzman and co-authors showed that the decoding choice alone changes the quality of machine text, even with the same model. Their finding was that using likelihood as the decoding goal gives text that is bland and strangely repetitive.

> "using likelihood as a decoding objective leads to text that is bland and strangely repetitive" (Holtzman et al., 2019)
>
> "most state-of-the-art results on language generation tasks are attained using beam search despite its overwhelmingly high search error rate." (Meister et al., 2020)

In 2020 Meister and co-authors added a useful twist. Beam search often misses the highest-scoring sentence, yet most state-of-the-art results on language generation tasks came from beam search. So beam is a practical choice with known limits.

## Why can greedy search miss the better answer?

Here is a simplified, made-up example. A speech model transcribes a call to a bank's dispute team, and the audio is unclear on one amount. The model's options are below. The code further down compares only the first two words, which is enough to show the idea.

1. **Step 1: the first word:** The audio could be fifty (60%) or fifteen (40%).
2. **Step 2: the word after it:** After fifty, dollars is the top next word at 30% (made-up numbers). After fifteen, dollars is 90%.
3. **Greedy keeps one start:** It takes fifty, then dollars: 0.6 × 0.3 = 0.18 in total.
4. **Beam keeps both starts:** It scores each full pair and picks fifteen dollars: 0.4 × 0.9 = 0.36, the higher total.

Beam found the higher-scoring sentence, but it only knows what the model thinks is likely. If the caller really said fifty, beam is confidently wrong. That is why amounts need a check against the recording.

```python
# A made-up call-transcript example: one word the speech model is unsure of.
# Step 1: the audio could be "fifty" (60%) or "fifteen" (40%).
# Step 2: the chance "dollars" comes next, given that first word.
FIRST = {"fifty": 0.6, "fifteen": 0.4}
NEXT = {"fifty": 0.3, "fifteen": 0.9}

def greedy():
    # Keep only the single best first word, then move on.
    word = max(FIRST, key=FIRST.get)
    return word, round(FIRST[word] * NEXT[word], 2)

def beam(width=2):
    # Keep the best few first words, then score each full pair.
    kept = sorted(FIRST, key=FIRST.get, reverse=True)[:width]
    pairs = [(w, round(FIRST[w] * NEXT[w], 2)) for w in kept]
    return max(pairs, key=lambda pair: pair[1])

import random
rng = random.Random(7)  # fixed seed, so every run prints the same picks
picks = [rng.choices(list(FIRST), weights=list(FIRST.values()))[0] for _ in range(6)]

print("greedy:", greedy())
print("beam:", beam())
print("sampling, 6 runs:", picks)
```

Output:

```text
greedy: ('fifty', 0.18)
beam: ('fifteen', 0.36)
sampling, 6 runs: ['fifty', 'fifty', 'fifteen', 'fifty', 'fifty', 'fifty']
```

Run it and you see greedy's 0.18 against beam's 0.36. The sampling line gave a mix of answers, because its picks are random, weighted by the odds. A fixed seed, the starting number for the random draws, makes this run repeat exactly.

## Where do temperature and top-k fit?

Sampling has dials. Temperature sets how random a draw is. Google's guide says temperature controls the degree of randomness in token selection, and that a temperature of 0 means the highest-probability tokens are always selected.

So temperature 0 acts much like greedy search. Anthropic's glossary warns that on APIs, even at temperature 0, results are not fully deterministic. Google's guide says responses at temperature 0 are mostly deterministic (the same input gives the same output), but a small amount of variation is still possible. Don't promise a client exact repeats.

Top-k and top-p cut the list of candidates before the draw. Top-k keeps only the k most likely tokens, a number you set. Top-p keeps the most likely tokens until their odds add up to p. Google notes that a top-K of 1 is the same as greedy decoding. The answers on top-k and top-p cover both in full.

> **Tip:** Asked to name the setting for a steady answer: say temperature near 0, then add a check, because it is still not guaranteed.

### How would you pick a strategy for two real features?

Take two features at a mid-size bank. One is a call transcriber that writes down what the customer said. The other is a reply drafter that writes answers to refund requests. Same model, different strategy.

- **Call transcriber: Beam or greedy, then check.** The recording has one right answer, so aim for the highest-scoring transcript. Check every amount and date against the audio.
- **Reply drafter: Sample, but fix the amount.** Varied wording reads more naturally. The refund amount comes from billing code, never from the random draw.

Name which feature needs one right answer and which needs variety. That one split shows an interviewer you weigh risk before you touch a setting.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] Greedy takes the top token at each step: fast, but it can repeat and lock in early errors.
- [ ] Beam keeps several candidates and returns the highest overall score: more work, good for input-grounded tasks.
- [ ] Sampling draws at random by weight: varied, but it can differ each run.
- [ ] Temperature, top-k and top-p are settings you tune when sampling.
- [ ] Beam finds the best it can, which is not always the true answer, so facts still need checks.

**Common traps**

- Trap: "Beam search always gives the right answer." Better: It returns the highest-scoring sequence the model can find, which may not be the true one. Check the facts.
- Trap: "Temperature 0 makes the output identical every time." Better: Almost. Google says responses are mostly deterministic, and API results can still differ, so don't rely on exact repeats.
- Trap: "Sampling is more creative, so use it everywhere." Better: Use it for drafts and variety. Never for a number, a date or a fee, which need one right answer.

## Can you spot the risk?

**Spot the risk:** A call summariser writes dollar amounts into case notes. Which setting is the risk?

A. generate(audio, num_beams=4, do_sample=False)
B. generate(audio, do_sample=True, temperature=1.2)
C. generate(audio, num_beams=1)
D. generate(audio, max_new_tokens=256)

**Answer:** B. Random draws at a high temperature can pick a different amount on each run. Use beam or greedy for facts, then check amounts against the recording.

**Quick check:** A support bot drafts replies to refund requests. Which setup fits both the wording and the amount?

A. Greedy search for the wording; the model picks the amount
B. Sampling for the wording; billing code sets the amount
C. Beam search for the wording; the model picks the amount
D. Temperature 0 for everything; the model checks its own maths

**Answer:** B. Sampling gives the varied wording. Billing code sets the amount, because a model can't be trusted to repeat a number exactly, whichever strategy it uses.

## Can you answer these from memory?

**Flash cards**

- **What is greedy search?** Always the single most likely next token. Fast, but it can repeat and lock in early errors.
- **What is beam search?** Keeps several full candidates alive and returns the highest overall score. More work.
- **What is sampling?** A random draw, weighted by likelihood. Varied wording, but a different answer can come each run.
- **Which suits facts from a recording?** Beam or greedy, then check every amount against the audio.
- **What does temperature do?** Sets how random sampling is. At 0 it is close to greedy: mostly repeatable, but not exact.
- **Is greedy the default in Transformers?** Yes. Hugging Face's library makes greedy search its default decoding strategy.

## Likely follow-up questions

- Q010 What does temperature control? https://designervenkat.online/interview/ai/what-does-temperature-control
- Q011 What is top-k sampling? https://designervenkat.online/interview/ai/what-is-top-k-sampling
- Q012 What is top-p (nucleus) sampling? https://designervenkat.online/interview/ai/what-is-top-p-nucleus-sampling
- Q014 Why can one prompt give different answers? https://designervenkat.online/interview/ai/why-can-one-prompt-give-different-answers
- Q023 What is a hallucination, and why does it happen? https://designervenkat.online/interview/ai/what-is-an-ai-hallucination
- Q146 How do you pick top-k? https://designervenkat.online/interview/ai/how-do-you-pick-top-k

## Learn it in depth

- [Sampling Parameters](https://designervenkat.online/learn/ai-engineering/sampling-parameters)
