02.5 Generation and Sampling

Understand LLMsLesson 5 of 1020,642 words11 parts
Module 02 · 0 of 9 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10

An LLM never writes a whole answer at once. It produces one token at a time, and each token is chosen from a probability distribution over its entire vocabulary. This lesson follows that process from the inside: how the generation loop runs, how raw scores become a chosen token, what every sampling setting (temperature, top-p, top-k, min-p, penalties, beam search, seeds) actually does, how and why generation stops, what logprobs tell you, how streaming works, and which of these controls OpenAI, Anthropic, Gemini and OpenRouter still let you touch in November 2026. Every core concept is demonstrated on a real model running on your own laptop.

What you'll learn

  • The autoregressive loop: predict a token, append it, repeat, with one forward pass per output token
  • Prefill vs decode, and why output tokens are slower and more expensive than input tokens; time to first token and tokens per second
  • How logits become a probability distribution, and how a sampler turns that distribution into a single token
  • Every common decoding strategy, each demonstrated on a local model: greedy, temperature, top-k, top-p, min-p, repetition / frequency / presence penalties, beam search and seeds
  • How generation stops (EOS tokens, max tokens, stop sequences) and how to read finish reasons on every provider, including what to do when output is truncated
  • What logprobs are and how to use them for confidence scores, classification, debugging and evaluation
  • A verified parameter support matrix for OpenAI and Anthropic (with Gemini and OpenRouter as optional columns), including the big 2026 change: most current frontier models no longer accept temperature at all
  • Why "temperature 0" isn't deterministic through APIs
  • Streaming, constrained decoding (how structured output works under the hood), recommended settings per task, and performance topics such as speculative decoding and batching

What you don't need

  • Any maths beyond "divide", "add up" and "pick the biggest". Every formula is explained in words.
  • A GPU. All local demos run on a laptop CPU with a 0.5-billion-parameter model.
  • API keys to follow along. The local demos are free. Provider samples need keys only if you want to run them yourself.

Setup

The local demos need Python 3.11+, PyTorch and Hugging Face Transformers. The first run downloads Qwen/Qwen2.5-0.5B, a small open base model of about 1 GB. One demo (4.2) also downloads its chat-tuned sibling, Qwen/Qwen2.5-0.5B-Instruct, of the same size:

bash
uv add torch transformers          # or: pip install torch transformers

First time? Create a project with uv init llm-basics && cd llm-basics, then run scripts with uv run python file.py.

The outputs in this lesson were produced with torch 2.15.0 and transformers 5.22.1 on a laptop CPU. With other versions or hardware, probabilities may differ in the last decimal place, and timings will differ a lot. Transformers 5.x is a recent major version, so a newer major release may rename things again; if a sample fails after an upgrade, check its changelog.

The provider samples use the official SDKs and read API keys from a .env file:

bash
uv add openai anthropic google-genai python-dotenv
# or, without uv: pip install openai anthropic google-genai python-dotenv
bash
# .env (never commit this file)
OPENAI_API_KEY=...
ANTHROPIC_API_KEY=...
GEMINI_API_KEY=...        # optional: only for the Gemini samples
OPENROUTER_API_KEY=...    # optional: only for the OpenRouter samples

What you must be able to do after this lesson#

  • Explain the autoregressive generation loop
  • Turn logits into a token with temperature, top-k and top-p
  • Choose a decoding strategy for a task
  • Configure stop conditions for a generation
  • Read logprobs to judge model confidence
  • Explain why outputs are not fully deterministic
  • Pick sampling settings for a task

Why this matters for an AI engineer#

Generation settings are the first knobs you meet in every LLM API, and the source of a surprising number of production bugs:

You'll hear... You'll understand it after...
"Output tokens cost five times as much as input tokens." 1.4 Why output tokens are slower and pricier
"Our time to first token is 800 ms, then it streams at 90 tokens a second." 1.5 Measuring speed: TTFT and tokens per second
"Set the temperature to 0 so it's deterministic." 3.3 Temperature and Part 7: Determinism
"Use top-p 0.9" / "Try min-p instead." 3.4–3.7 Truncation samplers
"The bot keeps repeating itself; add a frequency penalty." 3.8 Repetition, frequency and presence penalties
"We got a 400 error: temperature isn't supported on this model." Part 6: What each provider lets you control
"The JSON came back cut off halfway through." 4.6 Handling truncated output
"Use logprobs to get a confidence score." Part 5: Logprobs
"Stream the response so the UI feels fast." Part 8: Streaming
"Structured outputs guarantee valid JSON." Part 9: Constrained decoding
"That provider is faster because it uses speculative decoding." 11.1 Speculative decoding

Part 1: The autoregressive loop#

1.1 One token at a time#

In lesson 01 you saw that an LLM's final layer outputs one score for every token in its vocabulary, and softmax turns those scores into probabilities. That's the model's entire output from one forward pass: a probability distribution over the next token. Not a sentence, not a word list, just "here's how likely each possible next token is".

To get a full answer, something outside the network has to run a loop:

  1. Run the model on the text so far. It outputs a score for every possible next token.
  2. Choose one token from those scores. This step is called decoding or sampling, and the code that does it is the sampler.
  3. Append the chosen token to the text.
  4. Repeat from step 1 with the slightly longer text, until a stop condition is met.
flowchart LR
    A["Text so far<br/>(prompt + tokens generated)"] --> B["Forward pass<br/>through the model"]
    B --> C["Logits: one score per<br/>vocabulary token"]
    C --> D["Sampler picks<br/>one token"]
    D --> E{"Stop?<br/>EOS, stop sequence,<br/>max tokens"}
    E -- "no: append the token" --> A
    E -- "yes" --> F["Return the<br/>generated text"]

This is called autoregressive generation: "auto" (self) + "regressive" (predicting from previous values). Each new token is predicted from everything before it, including the tokens the model itself just generated.

Three consequences follow directly, and they shape everything else in this lesson:

  • One forward pass per output token. A 500-token answer means about 500 runs through the whole network, one after another. You can't compute token 300 before token 299 exists.
  • Every choice is final. Once a token is appended, the model must continue from it. It can't go back and edit. If the sampler picks a poor token early, every later token builds on that mistake. This is one root of hallucination (11.4).
  • The model and the sampler are separate. The model (the trained weights) only produces probabilities. The sampler (a few lines of ordinary code) decides which token to take. Parameters like temperature and top_p only affect the sampler. They don't change the model, its knowledge or its weights.

1.2 Prefill and decode#

The first step of the loop is different from all the others.

When a request arrives, the model must process the entire prompt before it can predict anything. Because every prompt token is already known, the model can process all of them in parallel in a single forward pass, as one big batch of matrix multiplications. This phase is called prefill. It produces the first output token, plus a stored set of intermediate results for every prompt token called the KV cache.

After that, the model is in the decode phase: one forward pass per new token, each one reusing the KV cache so that it only has to compute the new token's part. Decode steps are inherently sequential, because each one needs the token chosen by the previous one.

flowchart LR
    subgraph pre ["Prefill: once per request"]
        P["All prompt tokens<br/>processed together<br/>in ONE forward pass"] --> K["KV cache built<br/>+ first output token"]
    end
    subgraph dec ["Decode: once per output token"]
        D1["Forward pass<br/>for token 2"] --> D2["Forward pass<br/>for token 3"] --> D3["... one pass<br/>per token"]
    end
    K --> D1
Prefill Decode
Processes All prompt (input) tokens One new output token per step
How many forward passes One (or a few, for very long prompts) One per output token
Parallelism High: thousands of tokens at once None within a request: strictly one after another
Bottleneck Raw compute (arithmetic) Memory bandwidth: all the weights, plus the growing KV cache, are read from memory for every single token
Determines Time to first token Tokens per second while the answer streams

1.3 Try it: prefill vs decode on your laptop#

This script measures both phases directly. It times one prefill pass over prompts of different lengths, then times 20 decode steps that reuse the KV cache:

python
import time
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

torch.manual_seed(0)
model_name = "Qwen/Qwen2.5-0.5B"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name, dtype=torch.float32)   # full precision on CPU
model.eval()

text = "The history of the printing press is a story of ideas spreading faster than ever before. " * 60
for n_prompt in [10, 200, 1000]:
    ids = tokenizer(text, return_tensors="pt").input_ids[:, :n_prompt]
    with torch.no_grad():
        model(ids)                                     # warm-up run (not timed)

        # PREFILL: one forward pass over the whole prompt at once
        start = time.perf_counter()
        out = model(ids, use_cache=True)
        prefill = time.perf_counter() - start

        # DECODE: 20 forward passes, one new token each, reusing the KV cache
        past, next_id = out.past_key_values, out.logits[:, -1:].argmax(-1)
        start = time.perf_counter()
        for _ in range(20):
            out = model(next_id, past_key_values=past, use_cache=True)
            past, next_id = out.past_key_values, out.logits[:, -1:].argmax(-1)
        per_token = (time.perf_counter() - start) / 20

    print(f"prompt {n_prompt:5d} tokens | prefill {prefill*1000:7.1f} ms "
          f"({n_prompt/prefill:7.0f} tokens/s) | decode {per_token*1000:5.1f} ms/token "
          f"({1/per_token:4.0f} tokens/s)")
Output3 lines
prompt    10 tokens | prefill    73.0 ms (    137 tokens/s) | decode  29.1 ms/token (  34 tokens/s)
prompt   200 tokens | prefill   185.5 ms (   1078 tokens/s) | decode  30.5 ms/token (  33 tokens/s)
prompt  1000 tokens | prefill  1283.6 ms (    779 tokens/s) | decode  59.5 ms/token (  17 tokens/s)

Your timings will differ, but the pattern will be the same:

  • Prefill is fast per token. The 200- and 1,000-token prompts were processed at roughly 800–1,100 tokens per second, because all of their tokens went through the network together.
  • Decode is slow per token. Every output token cost about 30 ms or more, a rate of roughly 17–34 tokens per second. Per token, decoding was about 30–45 times more expensive than prefill on this machine.
  • Decode gets slower as the context grows (59.5 ms per token after a 1,000-token prompt, against about 30 ms after a short one), because each new token attends to every previous token, so there's more KV cache to read at every step. Lesson 07 covers what long contexts cost.
  • The 10-token row shows a fixed overhead: a tiny prompt can't keep the hardware busy, so its "tokens per second" figure is low. Don't read too much into it.

A data-centre GPU is vastly faster than a laptop CPU, but the ratio between prefill and decode holds there too.

1.4 Why output tokens are slower and pricier#

The prefill/decode split explains two facts you'll see on every provider's pricing page and in every latency graph.

Output tokens cost more than input tokens. As of November 2026, output tokens cost 5× the input price on every current OpenAI GPT-6 model and every current Claude model, and between 5× and about 8× on current Gemini models:

Model (as of November 2026) Input, per 1M tokens Output, per 1M tokens Ratio
OpenAI gpt-6-luna $0.10 $0.50 5×
Anthropic claude-haiku-5-5 (prompts up to 100k tokens) $0.10 $0.50 5×
Anthropic claude-sonnet-5-5 $2.00 $10.00 5×
Google gemini-3.5-flash-lite $0.30 $2.50 ~8.3×

Prices change often. Always check the official pricing pages (OpenAI, Anthropic, Gemini, and each model's page on OpenRouter). Lesson 09, Part 6 covers pricing structures in detail.

The reason is the hardware cost behind each kind of token. An input token is processed in a big parallel batch during prefill. An output token needs its own sequential forward pass, during which the expensive GPU is mostly waiting on memory.

Output length dominates latency. A useful approximation for how long a non-streaming request takes:

text
total time ≈ time to first token + (number of output tokens ÷ output tokens per second)

For example, with a 0.5-second time to first token and 80 output tokens per second:

Output length Total time
50 tokens (a short answer) 0.5 + 50 ÷ 80 ≈ 1.1 s
500 tokens (a long answer) 0.5 + 500 ÷ 80 ≈ 6.8 s
2,000 tokens (a report) 0.5 + 2,000 ÷ 80 ≈ 25.5 s

Doubling the prompt usually adds a fraction of a second. Doubling the answer doubles most of the wait.

1.5 Measuring speed: TTFT and tokens per second#

Engineers describe LLM speed with a small set of metrics:

Metric What it measures Dominated by
Time to first token (TTFT) From sending the request to receiving the first output token Network, queueing at the provider, prefill (so prompt length, and whether the start of the prompt was already cached: lesson 07, Part 7), and thinking time on reasoning models
Output tokens per second (TPS, OTPS) How fast tokens arrive once generation has started Decode speed: the model size, the hardware, how busy the server is
Time per output token (TPOT) or inter-token latency The gap between consecutive tokens: 1 ÷ TPS Same as TPS
End-to-end latency From request to the last token TTFT + output tokens × TPOT
Throughput Total tokens per second a server produces across all users Batching (11.2)

What this means for you as an engineer:

  • To make responses faster, make them shorter. Ask for concise output, cap the maximum output tokens, and avoid asking for things you'll throw away (for example "explain your answer" when you only parse the answer). Cutting output length is usually the single biggest latency and cost win.
  • Stream anything a human reads (Part 8). Streaming doesn't make generation finish sooner, but users start reading after the TTFT instead of after the whole answer.
  • Measure TTFT and TPS separately. A slow TTFT points to long prompts, queueing or thinking. Slow TPS points to a big model or a busy provider. They have different fixes.
  • Use prompt caching for long, repeated prompts. If many requests share the same long system prompt or documents, a cached prefix skips most of the prefill and cuts TTFT and input cost (lesson 07, Part 7).
  • Compute TPS from token counts, not stream events. A provider's stream event can carry several tokens, so counting events undercounts. Use the output token count from the final usage: TPS ≈ output tokens ÷ (total time − TTFT). On reasoning models, the hidden thinking tokens are generated before the first visible text, so measure visible-text TTFT separately from thinking time.
  • Watch out for reasoning models in latency-sensitive paths. Their thinking happens before the first visible token, so their TTFT can be seconds or more.

Part 2: From logits to a token#

2.1 Logits over the whole vocabulary#

At each step, the model's final layer outputs a logit (a raw score) for every token in its vocabulary (lesson 01, 3.6). The model we'll use has a vocabulary of 151,936 tokens (lesson 02 explains where vocabularies come from), so every single step produces 151,936 numbers. Softmax converts them into probabilities that add up to 1.

Two properties of softmax are worth remembering because every sampler builds on them:

  • Only the differences between logits matter. Adding the same number to every logit changes nothing. A token with a logit 1 higher than another is about 2.7 times as likely; 2 higher, about 7.4 times; 5 higher, about 148 times.
  • Every token gets a probability above zero. Even absurd tokens get a tiny share. With 150,000 tokens, those tiny shares add up, which is why samplers usually cut off the "long tail" (3.4–3.7).

2.2 Try it: see what the model wants to say next#

Let's look at the real distribution. This script runs one forward pass of a small open model and prints the ten most likely next tokens:

python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

model_name = "Qwen/Qwen2.5-0.5B"          # a small base model that runs on a laptop CPU
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name, dtype=torch.float32)   # full precision on CPU
model.eval()

def top_next_tokens(prompt: str, k: int = 10):
    inputs = tokenizer(prompt, return_tensors="pt")
    with torch.no_grad():
        logits = model(**inputs).logits          # shape: (1, prompt_length, vocab_size)
    next_logits = logits[0, -1]                  # only the LAST position predicts the next token
    probs = torch.softmax(next_logits, dim=-1)   # logits -> probabilities over the whole vocabulary
    top = torch.topk(probs, k)

    print(f"Prompt: {prompt!r}")
    print(f"Vocabulary size: {next_logits.shape[0]:,} candidate tokens")
    for p, token_id in zip(top.values, top.indices):
        token = tokenizer.decode(token_id)
        print(f"  {token!r:14} logit {next_logits[token_id]:6.2f}   prob {p:6.1%}")
    print(f"  Top-{k} total: {top.values.sum():.1%}\n")

top_next_tokens("The Eiffel Tower is in the city of")
top_next_tokens("I opened the fridge and grabbed a")
top_next_tokens("The capital of France is")
Output41 lines
Prompt: 'The Eiffel Tower is in the city of'
Vocabulary size: 151,936 candidate tokens
  ' Paris'       logit  16.60   prob  79.7%
  ' Le'          logit  12.86   prob   1.9%
  ' Mar'         logit  12.61   prob   1.5%
  ' E'           logit  12.07   prob   0.9%
  ' Lyon'        logit  11.84   prob   0.7%
  ' Str'         logit  11.82   prob   0.7%
  ' P'           logit  11.67   prob   0.6%
  ' Met'         logit  11.65   prob   0.6%
  ' Br'          logit  11.48   prob   0.5%
  ' B'           logit  11.44   prob   0.5%
  Top-10 total: 87.4%

Prompt: 'I opened the fridge and grabbed a'
Vocabulary size: 151,936 candidate tokens
  ' bottle'      logit  15.00   prob   9.4%
  ' can'         logit  14.50   prob   5.7%
  ' few'         logit  14.31   prob   4.7%
  ' box'         logit  14.18   prob   4.1%
  ' piece'       logit  14.13   prob   3.9%
  ' bag'         logit  14.11   prob   3.8%
  ' loaf'        logit  13.75   prob   2.7%
  ' handful'     logit  13.72   prob   2.6%
  ' bowl'        logit  13.52   prob   2.1%
  ' glass'       logit  13.48   prob   2.0%
  Top-10 total: 41.1%

Prompt: 'The capital of France is'
Vocabulary size: 151,936 candidate tokens
  ' Paris'       logit  17.84   prob  31.6%
  ' ______'      logit  16.83   prob  11.5%
  ' ____'        logit  16.24   prob   6.4%
  ' __'          logit  16.10   prob   5.5%
  ':\n'          logit  16.03   prob   5.1%
  ' located'     logit  15.67   prob   3.6%
  ' the'         logit  15.42   prob   2.8%
  '\n'           logit  15.29   prob   2.5%
  ' ('           logit  15.07   prob   2.0%
  ' .\n'         logit  15.02   prob   1.9%
  Top-10 total: 72.7%

Three very different distributions:

  • "The Eiffel Tower is in the city of" is a peaked distribution. The model puts 79.7% on " Paris". The next candidates (" Le", " Mar", " E", " Str") are the starts of other city names, such as "Le Havre" or "Marseille". This is what the model looks like when it "knows" the answer.
  • "I opened the fridge and grabbed a" is a flat distribution. Many continuations are reasonable, so the top token gets only 9.4%, and even the top ten together cover only 41%. The other 59% is spread across thousands of tokens.
  • "The capital of France is" is a surprise. " Paris" leads with only 31.6%, followed by ' ______' and ' ____': blanks. This is a base model (trained to continue raw text, without the chat post-training covered in lesson 06), and to it this sentence looks like the start of a school worksheet: "The capital of France is ______." The model isn't answering a question. It's predicting what text usually comes next on the internet. Chat models are post-trained so that this prompt behaves like a question.

What this means for you as an engineer:

  • The shape of the distribution predicts how much sampling settings matter. On peaked steps (a fact the model knows), almost any setting picks the same token. On flat steps (open-ended text), settings decide what you get.
  • Base and chat models behave differently on the same text. If a local or open model gives strange continuations, check whether you're using a base model or a chat model, and whether you applied the chat template (4.2).

2.3 Try it: a hand-written generation loop#

Here's the autoregressive loop from 1.1, written by hand in about ten lines. At each step it runs the model, converts the scores to probabilities, picks the most likely token, appends it and repeats:

python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

model_name = "Qwen/Qwen2.5-0.5B"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name, dtype=torch.float32)   # full precision on CPU
model.eval()

prompt = "The three primary colours are"
token_ids = tokenizer(prompt, return_tensors="pt").input_ids    # shape: (1, number_of_tokens)
print(f"Prompt has {token_ids.shape[1]} tokens")

for step in range(12):
    with torch.no_grad():
        logits = model(token_ids).logits[0, -1]     # 1. forward pass: scores for the next token
    probs = torch.softmax(logits, dim=-1)           # 2. scores -> probabilities
    next_id = torch.argmax(probs)                   # 3. pick one token (here: the most likely)
    token_ids = torch.cat([token_ids, next_id.view(1, 1)], dim=1)   # 4. append it and repeat
    print(f"step {step:2d}: chose {tokenizer.decode(next_id)!r:12} (p={probs[next_id]:.2f})")

print("\nFinal text:", tokenizer.decode(token_ids[0]))
Output15 lines
Prompt has 5 tokens
step  0: chose ' red'       (p=0.26)
step  1: chose ','          (p=0.97)
step  2: chose ' green'     (p=0.44)
step  3: chose ' and'       (p=0.63)
step  4: chose ' blue'      (p=0.75)
step  5: chose '.'          (p=0.63)
step  6: chose ' When'      (p=0.09)
step  7: chose ' these'     (p=0.17)
step  8: chose ' colours'   (p=0.67)
step  9: chose ' are'       (p=0.91)
step 10: chose ' mixed'     (p=0.42)
step 11: chose ' together'  (p=0.26)

Final text: The three primary colours are red, green and blue. When these colours are mixed together

Read the probabilities column. After "The three primary colours are", the model was only 26% sure about " red". Once " red" was chosen, "," was 97% certain. The " When" at step 6 was chosen with only 9% probability, simply because it happened to be the largest of many small options. Every output you've ever received from an LLM was built this way, one choice at a time.

2.4 The sampling pipeline#

The loop above always picked the single most likely token. Real samplers do more. Between the raw logits and the chosen token, there's a pipeline of small, independent steps, each of which you can usually switch on or off:

flowchart LR
    L["Raw logits<br/>(one per token)"] --> P["Adjust scores<br/>penalties, logit bias,<br/>constraint masks"]
    P --> T["Temperature<br/>divide by T"]
    T --> F["Truncate<br/>top-k, top-p, min-p"]
    F --> S["Softmax over<br/>the survivors"]
    S --> R["Random draw<br/>(seeded RNG)"]
    R --> O["Next token"]
  1. Adjust scores. Penalties for repetition (3.8), manual logit bias (11.3) and constraint masks for structured output (Part 9) add to or subtract from specific tokens' logits.
  2. Temperature (3.3) rescales all the logits to make the distribution sharper or flatter.
  3. Truncation (3.4–3.7) removes unlikely tokens entirely: top-k, top-p, min-p and others.
  4. Softmax and renormalize. The surviving tokens' probabilities are rescaled to add up to 1 again.
  5. Random draw. A random number picks one token, weighted by probability. The random number generator can be seeded for reproducibility (3.10).

Part 3: Decoding strategies#

3.1 Greedy decoding#

The simplest strategy is to always take the most likely token, exactly as the loop in 2.3 did. This is greedy decoding. It needs no randomness, so the same prompt always gives the same output (on the same hardware and software).

python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

model_name = "Qwen/Qwen2.5-0.5B"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name, dtype=torch.float32)   # full precision on CPU

inputs = tokenizer("My top tips for staying productive at work:", return_tensors="pt")
for attempt in range(2):
    out = model.generate(**inputs, do_sample=False, max_new_tokens=60)   # greedy decoding
    new_tokens = out[0, inputs.input_ids.shape[1]:]
    print(f"Run {attempt + 1}:", repr(tokenizer.decode(new_tokens)), "\n")
Output3 lines
Run 1: ' 1. Set a goal. 2. Take breaks. 3. Use a timer. 4. Use a planner. 5. Use a to-do list. 6. Use a calendar. 7. Use a to-do list. 8. Use a calendar. ' 

Run 2: ' 1. Set a goal. 2. Take breaks. 3. Use a timer. 4. Use a planner. 5. Use a to-do list. 6. Use a calendar. 7. Use a to-do list. 8. Use a calendar. '

Two things to notice:

  • Both runs are identical. Greedy decoding is deterministic on a single machine.
  • It falls into a loop. "6. Use a calendar. 7. Use a to-do list. 8. Use a calendar." Once the model has repeated a phrase, the repetition itself makes the phrase more likely next time, and greedy decoding always takes the most likely option. Small models get stuck like this easily, but large models can too, especially in long outputs.

Greedy decoding has another, subtler weakness: the most likely token at each step doesn't necessarily lead to the most likely or the best overall text. A token that looks slightly less likely now may open up a much better continuation. Greedy is also, by construction, the least varied possible output: researchers found that human-written text regularly uses words the model considers fairly unlikely, so always choosing the top token produces text that's blander and more repetitive than anything a person would write.

When greedy is a good choice: short, factual outputs with one right answer, such as classification labels, extraction of a single field or a yes/no decision. Most APIs approximate it with temperature=0 (where they still accept temperature, see Part 6).

3.2 Random sampling#

The opposite strategy is to draw a token at random, in proportion to its probability. If " bottle" has a 9.4% probability, it gets picked about 9.4% of the time. This is called pure sampling or ancestral sampling, and it's what "temperature 1 with no other settings" means.

Sampling fixes greedy's blandness and loops: the output varies from run to run, and a repeated phrase is no longer certain to repeat. But pure sampling has the opposite problem. With 150,000 tokens in the vocabulary, the "long tail" of individually unlikely tokens adds up to a large total probability. Over hundreds of steps, the sampler will eventually draw something absurd, and because every choice is final, the text then derails. The two tools for controlling this are temperature (reshape the distribution) and truncation (cut off the tail).

3.3 Temperature#

Temperature controls how adventurous the sampler is. Mathematically, it's one step: divide every logit by the temperature, then apply softmax.

In words:

  • Temperature 1 leaves the logits unchanged: you sample from the model's own distribution.
  • Temperature below 1 (for example 0.2) divides by a small number, which stretches the gaps between logits. Likely tokens become even more likely and unlikely ones fade away. The distribution becomes sharper, more predictable.
  • Temperature above 1 (for example 1.5) shrinks the gaps. The probabilities become more even, so unlikely tokens get picked more often. The distribution becomes flatter, more random.
  • Temperature approaching 0 gives the top token nearly all the probability, which is greedy decoding. Dividing by exactly 0 is impossible, so most APIs, and servers such as vLLM and llama.cpp, treat temperature=0 as a special case meaning "greedy". Hugging Face Transformers rejects it with an error instead; there you use do_sample=False, as this lesson's demos do.

Temperature never changes the order of the tokens: the most likely token stays the most likely at every temperature. It only changes how much more likely it is than the others.

Here's the real distribution from the fridge prompt at four temperatures:

python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

model_name = "Qwen/Qwen2.5-0.5B"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name, dtype=torch.float32)   # full precision on CPU

inputs = tokenizer("I opened the fridge and grabbed a", return_tensors="pt")
with torch.no_grad():
    logits = model(**inputs).logits[0, -1]

def tokens_to_cover(probs, share):
    """How many of the most likely tokens are needed to cover `share` of the probability?"""
    sorted_probs = torch.sort(probs, descending=True).values
    return int((torch.cumsum(sorted_probs, 0) < share).sum()) + 1

top_ids = torch.topk(logits, 5).indices                  # the 5 most likely tokens (same at every T)
print("token        " + "".join(f"{tokenizer.decode(i)!r:>10}" for i in top_ids))
for T in [0.2, 0.7, 1.0, 1.5]:
    probs = torch.softmax(logits / T, dim=-1)            # temperature: divide logits by T, then softmax
    row = "".join(f"{probs[i]:>10.1%}" for i in top_ids)
    print(f"T = {T:<4}    {row}   | tokens covering 90%: {tokens_to_cover(probs, 0.9):,}")
Output5 lines
token         ' bottle'    ' can'    ' few'    ' box'  ' piece'
T = 0.2          86.0%      7.1%      2.8%      1.4%      1.1%   | tokens covering 90%: 2
T = 0.7          20.2%      9.9%      7.6%      6.3%      5.8%   | tokens covering 90%: 33
T = 1.0           9.4%      5.7%      4.7%      4.1%      3.9%   | tokens covering 90%: 274
T = 1.5           2.5%      1.8%      1.6%      1.5%      1.4%   | tokens covering 90%: 5,670
  • At T = 0.2, " bottle" takes 86% of the probability, and just 2 tokens cover 90% of it. The sampler will almost always say " bottle".
  • At T = 1.0 (the model's own distribution), " bottle" has 9.4%, and you need 274 different tokens to cover 90% of the probability.
  • At T = 1.5, the top token drops to 2.5%, and 5,670 tokens are needed to cover 90%. Thousands of mostly nonsensical tokens are now realistic picks.

Now let's see what that does to actual text. The same prompt, sampled three times at each temperature, with the same random seed:

python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

model_name = "Qwen/Qwen2.5-0.5B"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name, dtype=torch.float32)   # full precision on CPU

inputs = tokenizer("A short name for a coffee shop run by robots:", return_tensors="pt")
for T in [0.2, 0.7, 1.0, 1.5]:
    torch.manual_seed(42)                                 # same seed for every temperature
    out = model.generate(**inputs, do_sample=True, temperature=T,
                         top_k=0, top_p=1.0,    # switch off Transformers' default top_k=50 so ONLY temperature acts
                         max_new_tokens=15, num_return_sequences=3)
    print(f"T = {T}")
    for seq in out:
        print("   ", repr(tokenizer.decode(seq[inputs.input_ids.shape[1]:], skip_special_tokens=True)))
Output16 lines
T = 0.2
    ' "The Coffee Robot". The coffee shop is located in the city of Coffee'
    ' A coffee shop run by robots is a coffee shop that is run by robots'
    ' "Robo-Cafe". The coffee shop is located in a small town'
T = 0.7
    ' "coffee shop powered by software".\nWhat is a short description of the following'
    ' A nice way to say that it works 24/7. The'
    ' Starbucks has its own collection of robots, and now the company is giving them'
T = 1.0
    ' "Zaru"\nWritten by:  Neil Hill.\n"Zaru'
    ' A nice breakfast with an olfactory explosion\n\n\nIn my previous post, I'
    ' Point Zero Cafe in Burlington, De, NC. I pivoted this Cafe'
T = 1.5
    ' Pep Sampoli Investigation So Coditian conducts commodity addicted footage interviews intensively following'
    ' Locker Shop Recipe Bread\tFilling quantities in favored amounts RANDOM lon mitan.gca'
    ' Point Zero.in injust heel rent沃尔沃 Dahlu sauna\n piv众多从缸'
  • T = 0.2 produces safe, repetitive answers ("The Coffee Robot", "Robo-Cafe"), and the three samples are similar to each other.
  • T = 0.7 and 1.0 produce more varied text, which wanders off topic more often. (This is a small base model, so its "creativity" quickly turns into rambling. Larger models stay coherent at higher temperatures.)
  • T = 1.5 has derailed into gibberish, including random Chinese characters ("沃尔沃", "众多从缸"). Once one absurd token is chosen, the next steps condition on it, and the text never recovers.

What this means for you:

  • Lower temperature when there's one right answer (extraction, classification, factual Q&A, code that must compile). Higher temperature when you want variety (brainstorming, creative writing, generating several different candidates).
  • Temperatures above about 1.2 rarely help on their own. If you want more variety without gibberish, combine a moderate temperature with a truncation sampler such as min-p (3.6), or generate several samples.
  • Temperature values aren't comparable across providers or models. The same number reshapes different distributions, and providers have used different ranges (Anthropic's was 0–1, while OpenAI and Gemini use 0–2). "0.7" on one model isn't "0.7" on another.
  • On many 2026 models you can't set it at all. See Part 6.

3.4 Top-k sampling#

Top-k is the simplest truncation rule: keep only the k most likely tokens, discard the rest, renormalize and sample. With top_k=40, the sampler can only ever choose among the 40 best candidates, so the absurd tail is gone. top_k=1 is greedy decoding.

Its weakness is that k is fixed, but the shape of the distribution isn't:

  • On a peaked step ("The Eiffel Tower is in the city of"), 40 tokens is far too many. It keeps " Lyon", " Mar" and dozens of other wrong answers as possible picks.
  • On a flat step ("I opened the fridge and grabbed a"), 40 tokens may be too few, cutting off perfectly good continuations.

The demo in 3.7 shows this with real numbers.

3.5 Top-p (nucleus) sampling#

Top-p, also called nucleus sampling, fixes top-k's rigidity. Instead of a fixed number of tokens, it keeps the smallest set of most-likely tokens whose probabilities add up to at least p. With top_p=0.9, the sampler sorts the tokens by probability and keeps adding them until the running total reaches 90%, then samples only from that set (the "nucleus").

Because it works on cumulative probability, the size of the set adapts automatically:

  • When the model is confident, a few tokens reach 90% and the set is small.
  • When many continuations are plausible, the set grows large.

top_p=1.0 disables it (every token is kept). Top-p was introduced in the 2019 paper The Curious Case of Neural Text Degeneration, which also documented greedy decoding's repetition loops, and it quickly became the most common truncation method in APIs.

Top-p still has a weakness: on a flat distribution, reaching 90% may require hundreds of tokens, many of them poor (as the demo shows). And at high temperature, the flattened distribution makes the nucleus enormous.

3.6 Min-p sampling#

Min-p takes a different approach: keep every token that is at least min_p times as likely as the single most likely token. With min_p=0.1, a token survives only if its probability is at least one-tenth of the top token's.

The threshold scales with the model's confidence:

  • If the top token has 80%, the cut-off is 8%. Almost everything except the top few tokens is removed.
  • If the top token has only 9%, the cut-off is 0.9%, so dozens of reasonable candidates survive.

Min-p was proposed in 2024 (Turning Up the Heat: Min-p Sampling for Creative and Coherent LLM Outputs, ICLR 2025). Its main claim is that it keeps text coherent even at higher temperatures, so you can get more variety without the gibberish. It's widely available in open-source inference tools (Hugging Face Transformers, vLLM, llama.cpp, which enables it by default at 0.05) and through OpenRouter, but not in OpenAI's, Anthropic's or Gemini's own APIs.

3.7 Comparing the truncation samplers#

This script implements all three rules in a few lines each and applies them to the peaked and the flat prompt:

python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

model_name = "Qwen/Qwen2.5-0.5B"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name, dtype=torch.float32)   # full precision on CPU

def next_token_probs(prompt):
    with torch.no_grad():
        logits = model(**tokenizer(prompt, return_tensors="pt")).logits[0, -1]
    return torch.softmax(logits, dim=-1)

def top_k_keep(probs, k):
    """Keep the k most likely tokens."""
    return torch.topk(probs, k).indices

def top_p_keep(probs, p):
    """Keep the smallest set of most-likely tokens whose probabilities add up to at least p."""
    sorted_probs, sorted_ids = torch.sort(probs, descending=True)
    cumulative = torch.cumsum(sorted_probs, 0)
    n_keep = int((cumulative < p).sum()) + 1      # include the token that crosses p
    return sorted_ids[:n_keep]

def min_p_keep(probs, min_p):
    """Keep every token at least min_p times as likely as the top token."""
    return torch.nonzero(probs >= min_p * probs.max()).flatten()

for prompt in ["The Eiffel Tower is in the city of", "I opened the fridge and grabbed a"]:
    probs = next_token_probs(prompt)
    print(f"{prompt!r}  (top token has p={probs.max():.0%})")
    for name, kept in [("top_k=40   ", top_k_keep(probs, 40)),
                       ("top_p=0.9  ", top_p_keep(probs, 0.9)),
                       ("min_p=0.1  ", min_p_keep(probs, 0.1))]:
        kept = kept[torch.argsort(probs[kept], descending=True)]
        preview = ", ".join(repr(tokenizer.decode(i)) for i in kept[:6])
        print(f"   {name} keeps {len(kept):3d} tokens ({probs[kept].sum():.0%} of prob): {preview}{', ...' if len(kept) > 6 else ''}")
    print()
Output9 lines
'The Eiffel Tower is in the city of'  (top token has p=80%)
   top_k=40    keeps  40 tokens (93% of prob): ' Paris', ' Le', ' Mar', ' E', ' Lyon', ' Str', ...
   top_p=0.9   keeps  17 tokens (90% of prob): ' Paris', ' Le', ' Mar', ' E', ' Lyon', ' Str', ...
   min_p=0.1   keeps   1 tokens (80% of prob): ' Paris'

'I opened the fridge and grabbed a'  (top token has p=9%)
   top_k=40    keeps  40 tokens (70% of prob): ' bottle', ' can', ' few', ' box', ' piece', ' bag', ...
   top_p=0.9   keeps 274 tokens (90% of prob): ' bottle', ' can', ' few', ' box', ' piece', ' bag', ...
   min_p=0.1   keeps  24 tokens (60% of prob): ' bottle', ' can', ' few', ' box', ' piece', ' bag', ...
Peaked step (" Paris" at 80%) Flat step (" bottle" at 9%)
top_k=40 Keeps 40 tokens, including dozens of wrong cities Keeps 40, cutting off 30% of the probability
top_p=0.9 Keeps 17 tokens: still plenty of wrong answers Keeps 274 tokens, deep into the unlikely tail
min_p=0.1 Keeps just 1 token: " Paris" Keeps 24 reasonable continuations

Min-p behaves the way you'd want on both: strict when the model is sure, permissive when many answers are fine. Top-p is too loose on the flat step, and top-k is wrong in both directions.

Method Rule Adapts to confidence? Typical values Where you'll find it
Top-k Keep the k most likely tokens ❌ 20–100 Open-source tools, OpenRouter, (formerly) Anthropic, older Gemini models
Top-p (nucleus) Keep the smallest set reaching cumulative probability p Partly 0.8–0.95 OpenAI (with reasoning off), OpenRouter, open-source tools, older Gemini/Claude models
Min-p Keep tokens at least min_p × the top probability ✅ 0.02–0.1 Open-source tools, OpenRouter

What this means for you as an engineer:

  • In closed APIs you'll meet top-p at most, and on many current models not even that (Part 6). Where knobs exist, tune temperature first and leave top-p at its default.
  • On open models (through OpenRouter or self-hosted), min-p 0.05–0.1 with a moderate temperature is a sensible starting point, and a model card's recommended settings are better still.
  • Don't stack top-k, top-p and min-p without measuring. Each one you add makes the combined behaviour harder to predict.

3.8 Repetition, frequency and presence penalties#

Penalties fight repetition by lowering the scores of tokens that have already appeared. There are three common kinds, and they behave differently:

Penalty How it works Grows with repeats? Range and default Offered by
Presence penalty Subtract a fixed amount from the logit of every token that has appeared at least once ❌ One flat penalty, however many times the token appeared −2.0 to 2.0, default 0 OpenAI Chat Completions, OpenRouter, older Gemini models
Frequency penalty Subtract an amount proportional to how many times the token has appeared ✅ Each repeat adds more penalty −2.0 to 2.0, default 0 OpenAI Chat Completions, OpenRouter, older Gemini models
Repetition penalty Divide a seen token's (positive) logit by the penalty, or multiply it if negative ❌ But it's scaled to the token's original score Above 0, default 1.0 (off); 1.05–1.3 typical Hugging Face, vLLM, llama.cpp, OpenRouter

OpenAI documents the presence and frequency penalties as a single formula. In words: new logit = old logit − (times the token appeared × frequency penalty) − (presence penalty, if it appeared at all). OpenAI suggests values of about 0.1 to 1 to reduce repetition somewhat, and up to 2 to suppress it strongly, warning that high values "can noticeably degrade the quality of samples". Negative values encourage repetition. The repetition penalty, introduced with the CTRL model in 2019, works by division instead, and implementations often apply it to tokens in the prompt as well as the output.

The demo below runs greedy decoding (so the only difference between runs is the penalty) on the prompt that looped in 3.1. It uses Transformers' built-in repetition penalty, and a ten-line implementation of OpenAI's frequency and presence formula:

python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, LogitsProcessor, LogitsProcessorList

model_name = "Qwen/Qwen2.5-0.5B"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name, dtype=torch.float32)   # full precision on CPU

class FrequencyPresencePenalty(LogitsProcessor):
    """OpenAI-style penalties, applied to tokens the model has generated so far."""
    def __init__(self, prompt_length, frequency=0.0, presence=0.0):
        self.prompt_length, self.frequency, self.presence = prompt_length, frequency, presence

    def __call__(self, input_ids, scores):
        generated = input_ids[:, self.prompt_length:]
        for row in range(scores.shape[0]):
            counts = torch.bincount(generated[row], minlength=scores.shape[1]).float()
            scores[row] -= self.frequency * counts            # grows with every repeat
            scores[row] -= self.presence * (counts > 0)       # flat, once a token has appeared
        return scores

inputs = tokenizer("My top tips for staying productive at work:", return_tensors="pt")
n = inputs.input_ids.shape[1]

settings = {
    "no penalty":               {},
    "repetition_penalty=1.3":   {"repetition_penalty": 1.3},
    "presence_penalty=1.0":     {"logits_processor": LogitsProcessorList([FrequencyPresencePenalty(n, presence=1.0)])},
    "frequency_penalty=1.0":    {"logits_processor": LogitsProcessorList([FrequencyPresencePenalty(n, frequency=1.0)])},
}
for name, extra in settings.items():
    out = model.generate(**inputs, do_sample=False, max_new_tokens=60, **extra)   # greedy, so only the penalty differs
    text = tokenizer.decode(out[0, n:])
    unique = len(set(out[0, n:].tolist()))
    print(f"[{name}]  ({unique} distinct tokens out of 60)\n{text!r}\n")
Output11 lines
[no penalty]  (22 distinct tokens out of 60)
' 1. Set a goal. 2. Take breaks. 3. Use a timer. 4. Use a planner. 5. Use a to-do list. 6. Use a calendar. 7. Use a to-do list. 8. Use a calendar. '

[repetition_penalty=1.3]  (58 distinct tokens out of 60)
" 1. Set a goal and stick to it.\n2. Take breaks when you need them, even if they're short ones like taking five minutes out of your day or doing some stretching exercises before lunchtime.\n\n3. Use technology wisely - use productivity apps that help with time management such as T"

[presence_penalty=1.0]  (39 distinct tokens out of 60)
" 1. Set a goal for the day and stick to it. 2. Take breaks when you need them. 3. Use your time wisely. 4. Don't be afraid to delegate tasks. 5. Stay organized. 6. Take breaks. 7. Be flexible"

[frequency_penalty=1.0]  (49 distinct tokens out of 60)
" 1. Set a goal for the day and stick to it. 2. Take breaks when you need them, even if it's just to stretch or walk around. 3. Use your time wisely by prioritizing tasks and delegating as needed.\n4. Stay organized by using tools like"
  • No penalty: the familiar loop, with only 22 distinct tokens out of 60.
  • Presence penalty 1.0: the model avoids reusing words it has already said, and the list becomes more varied, but it still drifts back to "Take breaks" at point 6, because the flat penalty doesn't grow.
  • Frequency penalty 1.0: longer, more specific items, with 49 distinct tokens.
  • Repetition penalty 1.3: 58 distinct tokens out of 60, and much longer, more detailed points.

What this means for you: if a modern chat model repeats itself, first check the cause, which is usually the prompt (it asked for a long list), the context (earlier repetitive output fed back into the conversation), or an overly low temperature. A penalty is a last resort, and many 2026 frontier models don't offer one anyway.

All the strategies so far choose one token at a time and never look ahead. Beam search keeps several candidate sequences alive at once:

  1. Keep the B best partial sequences (the beams; B is the beam width, often 4–5).
  2. At each step, extend every beam with its most likely next tokens.
  3. Score every extension by its total log probability (the sum of the logprobs of all its tokens, Part 5), and keep only the B best overall.
  4. When beams finish, return the best one. Because every extra token makes the total smaller, finished beams are usually compared after dividing by their length (a length penalty), so short sequences don't win unfairly.

This lets the search keep a sequence whose first token was only the second-best choice if it leads somewhere much more likely. It's deterministic, like greedy decoding.

python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

model_name = "Qwen/Qwen2.5-0.5B"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name, dtype=torch.float32)   # full precision on CPU

inputs = tokenizer("The most surprising thing about octopuses is", return_tensors="pt")
n = inputs.input_ids.shape[1]

greedy = model.generate(**inputs, do_sample=False, max_new_tokens=25,
                        output_scores=True, return_dict_in_generate=True)
greedy_ids = greedy.sequences[0, n:]
total = sum(torch.log_softmax(s[0], dim=-1)[t] for s, t in zip(greedy.scores, greedy_ids))
print(f"Greedy, average logprob per token {total / len(greedy_ids):.3f}:")   # same scale as beam scores below
print("   ", repr(tokenizer.decode(greedy_ids)))

beams = model.generate(**inputs, do_sample=False, num_beams=5, num_return_sequences=3,
                       max_new_tokens=25, output_scores=True, return_dict_in_generate=True)
print("Beam search (5 beams), top 3 beams. Score = total logprob / length (length_penalty=1.0):")
for seq, score in zip(beams.sequences, beams.sequences_scores):
    print(f"    score {score:.3f}", repr(tokenizer.decode(seq[n:], skip_special_tokens=True)))
Output6 lines
Greedy, average logprob per token -1.259:
    ' that they are the only animals that can swim backwards. This is because they have a special organ called the mantle that is located'
Beam search (5 beams), top 3 beams. Score = total logprob / length (length_penalty=1.0):
    score -0.881 ' that they are the most intelligent animals on the planet. They have the most complex brains of any animal on the planet, and'
    score -0.906 ' that they are the most intelligent animals on the planet. They have the most complex brains of any animal on the planet. They'
    score -0.957 ' that they are the most intelligent animals on the planet. They have the most complex brains of any animal on the planet and they'

Transformers reports each beam's score as its total logprob divided by its length (length_penalty=1.0), so these are average logprobs per token, and the script computes greedy's average the same way. Beam search found a sequence the model considers more probable per token than greedy's (−0.881 against −1.259). (Neither is a reliable fact: greedy decoding's "the only animals that can swim backwards" and beam search's "the most intelligent animals on the planet" are both the kind of confident claim 11.4 warns about.) Now look at the three best beams: they're almost identical, differing only in the last token. That's typical. Beam search finds variations of one high-probability answer, not genuinely different answers.

Why chat models and APIs rarely use beam search:

  • Bland, repetitive text. For open-ended writing, the highest-probability sequence is often generic or repetitive. Research on text degeneration (the top-p paper from 3.5) showed that maximizing probability is the wrong goal for natural-sounding text.
  • Cost. B beams cost roughly B times the compute and memory of one.
  • No streaming. You can't show tokens to the user until you know which beam wins, and that's only clear at the end.
  • Modern chat models are already sharply peaked after post-training (lesson 06), so beam search adds little over greedy decoding.

None of OpenAI, Anthropic, Gemini or OpenRouter offers beam search. It's still used where there really is one correct output and the outputs are short: machine translation, speech recognition (Whisper can use it), and some constrained generation tasks. If you run models yourself, it's one num_beams argument away.

3.10 Seeds#

Sampling uses a pseudo-random number generator: an algorithm that produces numbers that look random but are completely determined by a starting value called the seed. Fix the seed, and you get exactly the same "random" choices again.

python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

model_name = "Qwen/Qwen2.5-0.5B"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name, dtype=torch.float32)   # full precision on CPU
inputs = tokenizer("Once upon a time, in a city of glass,", return_tensors="pt")
n = inputs.input_ids.shape[1]

def sample(seed):
    torch.manual_seed(seed)             # fixes the random numbers used to pick tokens
    out = model.generate(**inputs, do_sample=True, temperature=1.0, top_k=0, top_p=0.95,
                         max_new_tokens=15)          # top_k=0 switches off Transformers' default top_k=50
    return tokenizer.decode(out[0, n:])

for seed in [1, 1, 2]:
    print(f"seed {seed}: {sample(seed)!r}")
Output3 lines
seed 1: ' someone made a great statue of the City God. It was adorned with brightly'
seed 1: ' someone made a great statue of the City God. It was adorned with brightly'
seed 2: ' lived a pirate. He wished to hunt down the finest treasure of the city'

Seed 1 twice gives the same story, word for word. Seed 2 gives a different one. Locally, on one machine with the same software, a seed makes sampling fully reproducible, which is invaluable for debugging and for tests.

Through provider APIs it's a different story. Even with a seed, outputs can vary, because the model's probabilities themselves can differ slightly from run to run. Part 7 explains why, and which providers still accept a seed.

3.11 Other samplers you may meet#

Open-source inference tools offer many more samplers. You don't need them for API work, but you'll see the names in model cards, OpenRouter's parameter list and local tools:

Sampler Idea in one line Where you'll see it
Typical sampling (typical_p) Keep tokens whose "surprise" is close to the average surprise at this step, rather than simply the most likely ones Transformers, llama.cpp
Epsilon / eta cutoff Drop tokens below a fixed probability floor (epsilon) or a floor that depends on how uncertain the step is (eta) Transformers
Top-a Keep tokens above a threshold based on the square of the top token's probability: "a dynamic top-p" OpenRouter
Top-nσ Keep tokens whose logit is within n standard deviations of the top logit llama.cpp
Mirostat Adjust truncation on the fly to keep the text's average "surprise" at a target level llama.cpp
DRY ("don't repeat yourself") Penalize tokens that would extend a sequence already seen earlier in the text, targeting repeated phrases rather than single tokens llama.cpp and other local tools
XTC ("exclude top choices") Sometimes remove the most likely tokens to force more creative choices llama.cpp and other local tools

Part 4: Stopping#

4.1 How generation ends#

The loop in Part 1 has no natural end. Something has to tell it to stop. There are four common reasons:

Stop condition Who decides Is the output complete?
End-of-sequence (EOS) token The model: it generates a special "I'm done" token ✅ Yes, the model finished
Stop sequence You: generation halts when a string you specified appears ✅ Usually, by your own definition
Maximum output tokens You (or the model's hard limit): a cap on generated tokens ❌ Probably not. The model was cut off
Context window full The model's maximum total length (input + output) ❌ No

Providers add their own reasons on top (a tool call, a safety filter, a refusal), which you'll see in 4.5.

4.2 End-of-sequence tokens#

A model's vocabulary contains special tokens that never appear in normal text, including one or more end-of-sequence (EOS) tokens. During training, documents and example conversations ended with one, so the model learned to generate it when a text or an answer is complete. The generation code watches for it and stops the loop when it appears. The EOS token itself is never shown to you.

Chat models also wrap each message in special tokens that mark who is speaking. This demo sends the same chat-formatted prompt to the chat-tuned model and to the base model, and shows what each generates and why it stopped:

python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

messages = [{"role": "user", "content": "Name one planet. Answer in one word."}]

for model_name in ["Qwen/Qwen2.5-0.5B-Instruct", "Qwen/Qwen2.5-0.5B"]:     # chat-tuned vs base model
    tokenizer = AutoTokenizer.from_pretrained(model_name)
    model = AutoModelForCausalLM.from_pretrained(model_name, dtype=torch.float32)   # full precision on CPU
    prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
    if model_name.endswith("Instruct"):
        print("End of what the model actually receives:\n" + "\n".join(prompt.splitlines()[-2:]) + "\n")

    inputs = tokenizer(prompt, return_tensors="pt")
    out = model.generate(**inputs, do_sample=False, max_new_tokens=30)
    new_ids = out[0, inputs.input_ids.shape[1]:].tolist()

    stop_ids = model.generation_config.eos_token_id          # the token id(s) that end generation
    stop_ids = stop_ids if isinstance(stop_ids, list) else [stop_ids]
    finish = "stop (EOS token)" if new_ids[-1] in stop_ids else "length (hit max_new_tokens)"
    print(f"[{model_name}] stops on {[tokenizer.decode(i) for i in stop_ids]}")
    print(f"   {len(new_ids)} tokens, finish: {finish}")
    print("   tokens:", [tokenizer.decode(i) for i in new_ids[:12]], "..." if len(new_ids) > 12 else "", "\n")
Output11 lines
End of what the model actually receives:
Name one planet. Answer in one word.<|im_end|>
<|im_start|>assistant

[Qwen/Qwen2.5-0.5B-Instruct] stops on ['<|im_end|>', '<|endoftext|>']
   2 tokens, finish: stop (EOS token)
   tokens: ['Earth', '<|im_end|>']  

[Qwen/Qwen2.5-0.5B] stops on ['<|endoftext|>']
   30 tokens, finish: length (hit max_new_tokens)
   tokens: ['The', ' word', ' is', ' "', 'Earth', '".', 'coholic', '\n', ' Comey', '\n', 'You', ' are'] ...
  • The chat template turned one user message into a structured token sequence. Each message ends with an <|im_end|> marker token, and the prompt ends with <|im_start|>assistant so that the model's next tokens are the assistant's reply. (The demo prints only the last two lines. The full rendering, including a default system message this template adds on its own, is in lesson 02, 4.3.)
  • The chat model answered "Earth" and then generated <|im_end|>, its end-of-turn token. That token is listed in its generation configuration as a stop token, so generation ended after 2 tokens with a natural "stop". (This model's configuration also applies a repetition penalty of 1.1 even in greedy mode, see 6.3; it makes no difference to a two-token answer.)
  • The base model, given exactly the same input, never stopped. It wasn't post-trained on conversations, so it doesn't know that an assistant turn should end with <|im_end|>, and its configuration only stops on <|endoftext|> (end of document). It answered, then drifted into unrelated text ("coholic", " Comey", and the start of a copy of the template's default system prompt) until it hit the 30-token cap: finish reason "length".

Two practical lessons: a model stops cleanly only if it was trained to produce the stop token and the generation code is configured to watch for it; and a finish reason of "length" usually means the model was cut off, not that it finished.

4.3 Maximum output tokens#

Every API lets you cap the number of generated tokens, and Anthropic's Messages API requires you to. The parameter names differ:

Provider Parameter Notes
OpenAI Chat Completions max_completion_tokens The older max_tokens is deprecated and doesn't work with o-series reasoning models
OpenAI Responses max_output_tokens Minimum 16
Anthropic max_tokens Required on every request. Up to 128K on current models (as of November 2026)
Gemini max_output_tokens (maxOutputTokens in REST) Default and maximum vary by model
OpenRouter max_tokens Up to the context length minus the prompt length

Four things to understand about this limit:

  • It's a hard cut-off, not a length instruction. The model doesn't know the limit exists, so it doesn't plan a shorter answer. It simply gets stopped mid-sentence (or mid-JSON) when it hits the number. To get shorter answers, ask for them in the prompt ("in two sentences"), or use a verbosity control where offered (6.4). Use the token limit as a safety net against runaway costs and loops.
  • It includes reasoning tokens. On reasoning models, thinking counts against the same limit on OpenAI, Anthropic and Gemini. Set it too low and the model can spend the whole budget thinking and return an empty visible answer, which you still pay for. OpenAI's docs suggest reserving at least 25,000 tokens for reasoning and output when you start experimenting with its reasoning models.
  • Models have their own maximum. Even if you ask for more, a model can't generate past its own output limit or its context window (lesson 07).
  • Long outputs may need streaming. For example, Anthropic's Python SDK requires streaming when max_tokens is above 21,333, so that long requests don't hit network timeouts, and Gemini 4 Argon's default cap is 65,536 output tokens, while long decode can raise it towards the full window (in hops of up to 65,536 tokens, or 32,768 for a non-streaming hop) (as of November 2026; see lesson 07, 2.3).

4.4 Stop sequences#

A stop sequence is a string that ends generation as soon as the model produces it. It's useful when the model would otherwise keep going past the part you want, for example a base model continuing a Q&A pattern:

python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

model_name = "Qwen/Qwen2.5-0.5B"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name, dtype=torch.float32)   # full precision on CPU

prompt = "Q: What is the capital of Japan?\nA: Tokyo\nQ: What is the capital of Italy?\nA:"
inputs = tokenizer(prompt, return_tensors="pt")
n = inputs.input_ids.shape[1]

def finish_reason(new_ids, max_new_tokens):
    if new_ids and new_ids[-1] == tokenizer.eos_token_id:
        return "stop (EOS token)"
    return "length (hit max_new_tokens)" if len(new_ids) >= max_new_tokens else "stop (stop sequence)"

for label, extra in [("max_new_tokens only", {}),
                     ("with stop sequence '\\nQ:'", {"stop_strings": ["\nQ:"], "tokenizer": tokenizer})]:
    out = model.generate(**inputs, do_sample=False, max_new_tokens=30, **extra)
    new_ids = out[0, n:].tolist()
    print(f"[{label}] {len(new_ids)} tokens, finish: {finish_reason(new_ids, 30)}")
    text = tokenizer.decode(new_ids)
    if "stop_strings" in extra:
        print("   raw output:", repr(text))
        text = text.split("\nQ:")[0]          # APIs strip the stop sequence for you; locally we do it ourselves
    print("   final text:", repr(text))
Output5 lines
[max_new_tokens only] 30 tokens, finish: length (hit max_new_tokens)
   final text: ' Rome\nQ: What is the capital of France?\nA: Paris\nQ: What is the capital of Germany?\nA: Berlin\nQ:'
[with stop sequence '\nQ:'] 4 tokens, finish: stop (stop sequence)
   raw output: ' Rome\nQ:'
   final text: ' Rome'

Without a stop sequence, the base model answered "Rome", then carried on inventing more questions and answers until it hit the 30-token cap (so the finish reason is "length"). With "\nQ:" as a stop sequence, it stopped after 4 tokens, and the finish reason is "stop". Locally, Transformers leaves the stop string in the raw output and we cut it off ourselves. APIs remove the stop sequence for you: OpenAI and Gemini both document that the returned text doesn't contain it, and Anthropic reports which sequence fired in a separate stop_sequence field.

Provider support (as of November 2026):

Provider Parameter Limit
OpenAI Chat Completions stop Up to 4 sequences. Not supported on the o3 and o4-mini reasoning models
OpenAI Responses Not available —
Anthropic stop_sequences No maximum documented
Gemini stop_sequences Up to 5
OpenRouter stop Passed to the provider

4.5 Finish reasons per provider#

Every API tells you why generation stopped. This field is the first thing to check on every response, because it's the only reliable way to know whether you got a complete answer.

What happened OpenAI Chat Completions finish_reason OpenAI Responses Anthropic stop_reason Gemini finish_reason OpenRouter finish_reason
Natural end (EOS) stop status: "completed" end_turn STOP stop
Hit a stop sequence stop (no stop sequences) stop_sequence (+ stop_sequence field) STOP stop
Hit max output tokens length status: "incomplete", incomplete_details.reason: "max_output_tokens" max_tokens MAX_TOKENS length
Context window full length incomplete / max_output_tokens model_context_window_exceeded MAX_TOKENS length
Model called a tool tool_calls (function_call is deprecated) A function_call output item tool_use STOP, with a function_call part in the content (the finish reason alone doesn't signal it) tool_calls
Safety / content filter content_filter incomplete, reason content_filter refusal (+ stop_details) SAFETY, PROHIBITED_CONTENT, BLOCKLIST, SPII, RECITATION... content_filter
Server-tool loop hit its iteration limit — — pause_turn (send the response back to continue) — —
Error — status: "failed" — (an error event or HTTP error) OTHER, MALFORMED_FUNCTION_CALL... error

Notes on each provider (as of November 2026):

  • OpenAI has two APIs. Chat Completions puts finish_reason on each choice. The newer Responses API uses the response's status (completed, incomplete, failed, cancelled, queued, in_progress) plus incomplete_details.reason (max_output_tokens, content_filter, max_messages or steered). A Responses call can hit its limit before any visible text is produced if the model spent the budget on reasoning.
  • Anthropic's complete list is end_turn, max_tokens, stop_sequence, tool_use, pause_turn, refusal and model_context_window_exceeded. A refusal arrives as a normal HTTP 200 response, not an error. Its new stop_details field gives a category.
  • Gemini's FinishReason enum is long. Besides STOP and MAX_TOKENS, it includes safety reasons (SAFETY, PROHIBITED_CONTENT, BLOCKLIST, SPII), RECITATION (output too similar to training data), LANGUAGE, tool-related reasons (MALFORMED_FUNCTION_CALL, UNEXPECTED_TOOL_CALL, TOO_MANY_TOOL_CALLS), image-generation reasons, and a new CONTINUATION for long outputs that continue in a follow-up request. Note that Gemini uses STOP both for a natural end and for a stop sequence.
  • OpenRouter normalizes every model's reason to one of stop, length, tool_calls, content_filter or error, and passes the provider's original value in native_finish_reason. A stream can also end with finish_reason: "error" after a 200 OK, so check it even when the HTTP status looked fine.

Here's how you read the finish reason on each provider, using the same small request. Anthropic and Gemini have no sampling knobs in these samples, for reasons explained in Part 6:

OpenAI (Chat Completions, three samples in one request with n=3):

python
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()                 # reads OPENAI_API_KEY from your .env file
client = OpenAI()

response = client.chat.completions.create(
    model="gpt-6-luna",
    reasoning_effort="none",  # GPT-6 models accept temperature/top_p only with reasoning off
    messages=[{"role": "user", "content": "Suggest a name for a coffee shop run by robots. Reply with the name only."}],
    temperature=1.2,          # 0-2, default 1
    n=3,                      # three samples in one request (you pay for all three); n with GPT-6 isn't documented either way
    max_completion_tokens=20, # cap on generated tokens (includes reasoning tokens)
)
for choice in response.choices:
    print(choice.index, choice.finish_reason, repr(choice.message.content))
print("output tokens billed:", response.usage.completion_tokens)
Example output · illustrative4 lines
0 stop 'Byte & Brew'
1 stop 'Circuit Café'
2 stop 'The Daily Grind Protocol'
output tokens billed: 19

Anthropic:

python
import anthropic
from dotenv import load_dotenv

load_dotenv()                 # reads ANTHROPIC_API_KEY
client = anthropic.Anthropic()

response = client.messages.create(
    model="claude-haiku-5-5",
    max_tokens=200,           # required on every request
    stop_sequences=["\n\n"],  # stop at the first blank line
    # No temperature/top_p/top_k: current Claude models reject them with a 400 error
    messages=[{"role": "user", "content": "Suggest three names for a coffee shop run by robots, one per line."}],
)
text = "".join(block.text for block in response.content if block.type == "text")
print(repr(text))
print("stop_reason:", response.stop_reason, "| stop_sequence:", repr(response.stop_sequence))
print("tokens:", response.usage.input_tokens, "in /", response.usage.output_tokens, "out")
Example output · illustrative3 lines
'Byte & Brew\nCircuit Roasters\nThe Servo Café'
stop_reason: end_turn | stop_sequence: None
tokens: 24 in / 21 out

Gemini:

python
from dotenv import load_dotenv
from google import genai
from google.genai import types

load_dotenv()                 # reads GEMINI_API_KEY
client = genai.Client()

response = client.models.generate_content(
    model="gemini-3.5-flash-lite",
    contents="Suggest three names for a coffee shop run by robots, one per line.",
    config=types.GenerateContentConfig(
        max_output_tokens=200,    # includes thinking tokens
        stop_sequences=["\n\n"],  # up to 5; the stop sequence is not included in the output
        # temperature/top_p/top_k are silently ignored on Gemini 3.5 Flash-Lite, 3.6 Flash and newer
    ),
)
print(repr(response.text))
print("finish_reason:", response.candidates[0].finish_reason)
usage = response.usage_metadata
print("tokens:", usage.prompt_token_count, "in /", usage.candidates_token_count, "out /",
      usage.thoughts_token_count, "thinking")
Example output · illustrative3 lines
'Byte & Bean\nThe Circuit Café\nRoboRoast'
finish_reason: FinishReason.STOP
tokens: 14 in / 15 out / None thinking

OpenRouter (an open-weight model, which accepts the full set of sampling parameters):

python
import os
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()                 # reads OPENROUTER_API_KEY
client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=os.environ["OPENROUTER_API_KEY"])

response = client.chat.completions.create(
    model="meta-llama/llama-3.3-70b-instruct",   # open-weight models expose the full sampling toolbox
    messages=[{"role": "user", "content": "Suggest three names for a coffee shop run by robots, one per line."}],
    temperature=1.0,
    max_tokens=60,
    stop=["\n\n"],
    seed=42,
    extra_body={
        "min_p": 0.05,                            # OpenRouter-specific parameters go in extra_body
        "repetition_penalty": 1.1,
        "provider": {"require_parameters": True}, # only route to providers that support every parameter
    },
)
choice = response.choices[0]
print(repr(choice.message.content))
print("finish_reason:", choice.finish_reason, "| native:", getattr(choice, "native_finish_reason", None))
Example output · illustrative2 lines
'1. Byte & Brew\n2. Circuit Café\n3. Gears & Grounds'
finish_reason: stop | native: stop

4.6 Handling truncated output#

A response that stopped because of the token limit is a partial response. Treating it as complete is one of the most common LLM bugs in production: a summary missing its conclusion, a list missing items, or, most often, JSON that fails to parse because the closing braces were never generated.

flowchart TD
    R["Response received"] --> F{"Finish reason?"}
    F -- "natural end<br/>(stop, end_turn, STOP)" --> OK["Use the output<br/>(still validate it)"]
    F -- "stop sequence" --> SS["Expected cut-off:<br/>use the output"]
    F -- "length / max tokens" --> TR["Truncated: never treat as complete.<br/>Raise the limit, continue,<br/>or ask for less"]
    F -- "tool call" --> TC["Run the tool,<br/>send the result back"]
    F -- "safety / refusal /<br/>content filter" --> SF["Handle as a refusal:<br/>log it, show a fallback"]
    F -- "error / other" --> ER["Retry or fail<br/>gracefully"]

What to do when the finish reason says the output was truncated:

  1. Always check the finish reason before using the output. Treat anything other than a natural stop (or your own stop sequence) as needing special handling. Log finish reasons in production so that you notice when truncation starts happening.
  2. Raise the limit if the task genuinely needs a longer answer, especially on reasoning models, where thinking may have used up the budget.
  3. Continue the answer: send the partial output back and ask the model to carry on. Many current models no longer support assistant prefill (starting the assistant's message for it; not to be confused with the prefill phase in 1.2): Anthropic rejects it on Claude 4.6 and later, and Gemini on 3.6 Flash, 3.5 Flash-Lite and later. So put the partial answer back as an assistant message and then add a user message asking it to continue.
  4. Ask for less: request a shorter format, fewer items, or split the task into several calls. A continuation can repeat or overlap the last few words of the previous part, so always re-validate joined text, especially JSON.
  5. Never auto-repair truncated JSON by guessing the missing closing brackets. A truncated object is missing data, not just punctuation. Retry instead.

A sketch of both patterns. Note that the Anthropic half treats only end_turn and stop_sequence as complete, raises on refusal and on anything unexpected, and continues only on the two truncation reasons:

python
import anthropic
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()

# --- OpenAI Responses API: detect truncation, retry with a bigger budget ---
openai_client = OpenAI()

def ask_openai(prompt: str, budget: int = 500, max_budget: int = 4000) -> str:
    while True:
        response = openai_client.responses.create(model="gpt-6-luna", input=prompt, max_output_tokens=budget)
        if response.status == "completed":
            return response.output_text
        if response.status == "incomplete" and response.incomplete_details.reason == "max_output_tokens":
            if budget >= max_budget:
                raise RuntimeError("Still truncated at the maximum budget; ask for a shorter answer instead")
            budget *= 2                       # reasoning tokens may have used the budget: try again with more
            continue
        raise RuntimeError(f"Unusable response: {response.status} {response.incomplete_details}")

# --- Anthropic: continue a truncated answer ---
claude = anthropic.Anthropic()

def ask_claude(prompt: str, max_rounds: int = 3) -> str:
    messages = [{"role": "user", "content": prompt}]
    parts = []
    for _ in range(max_rounds):
        response = claude.messages.create(model="claude-haiku-5-5", max_tokens=1000, messages=messages)
        text = "".join(block.text for block in response.content if block.type == "text")
        parts.append(text)
        if response.stop_reason in ("end_turn", "stop_sequence"):
            return "".join(parts)            # complete (re-validate joined text, e.g. JSON: a continuation can overlap)
        if response.stop_reason == "refusal":
            raise RuntimeError(f"Refused: {response.stop_details}")
        if response.stop_reason not in ("max_tokens", "model_context_window_exceeded"):
            raise RuntimeError(f"Unexpected stop_reason: {response.stop_reason}")   # e.g. tool_use, pause_turn
        # Truncated. Prefill is not allowed on current models, so put the partial answer back and ask to continue
        messages += [{"role": "assistant", "content": text},
                     {"role": "user", "content": "Please continue from where you left off."}]
    raise RuntimeError("Answer still incomplete; ask for something shorter or split the task")

print(ask_openai("List ten uses for a paperclip, one line each."))
print(ask_claude("List ten uses for a paperclip, one line each."))

4.7 What a tool call really is#

The finish-reason table in 4.5 has a row for "Model called a tool". It's worth being precise about what that means, because it's the mechanism behind every agent. The model never runs anything. A tool call (also called a function call) is just more generated text: the model writes a structured request, such as the name get_weather plus the JSON arguments {"city": "Paris"}, and then stops. The response tells you so: a tool_calls finish reason on OpenAI Chat Completions and OpenRouter, a function_call output item on the Responses API, a tool_use stop reason on Anthropic, and a function_call part on Gemini (whose finish reason stays STOP).

Everything else is your code:

  1. You send the request with tool definitions (names, descriptions and JSON schemas). They're rendered into the prompt as tokens (lesson 02, 4.4).
  2. The model's reply ends with a tool call instead of an answer. You check the finish reason, validate the arguments and run the function yourself.
  3. You append the model's tool call and a new tool-result message containing the function's output to the conversation, and send the whole history again as a new request.
  4. The model reads the result like any other input and either answers or asks for another tool. The loop repeats until it finishes with a natural end.
sequenceDiagram
    participant App as Your code
    participant API as Model API
    App->>API: Request 1: messages + tool definitions
    Note over API: The model writes a structured request,<br/>e.g. get_weather(city="Paris"), and stops
    API-->>App: Finish reason: tool call (tool_calls / tool_use)
    Note over App: Your code runs get_weather("Paris")<br/>(validate the arguments first)
    App->>API: Request 2: same history + the tool call<br/>+ a new tool-result message
    Note over API: The model reads the result as input tokens<br/>and continues
    API-->>App: Finish reason: natural end (stop / end_turn)<br/>"It's 18 °C and sunny in Paris."

What this means for you:

  • Each round trip is a full new request. The model is stateless (lesson 07, Part 3), so the history, the tool definitions and every earlier tool result are sent, and billed as input tokens, again on every step. Large tool results are the fastest-growing item in an agent's context (lesson 07, 1.3).
  • The model can ask for the wrong thing. It can invent a tool, pass a malformed or made-up argument, or misread a result. That's why you validate before running and cap the number of steps (lesson 10, Part 18).
  • Reasoning models must get their reasoning back inside a tool loop, unchanged (lesson 08, 8.2).

Tool definitions, parallel calls, forced tool choice and agent design are covered in depth in Module 08A.


Part 5: Logprobs: seeing the model's confidence#

5.1 What logprobs are#

A logprob (log probability) is the natural logarithm of the probability the model gave a token. APIs return logprobs instead of plain probabilities for two practical reasons: tiny probabilities such as 0.000000001 are awkward to store and compare, and the probability of a whole sequence is the product of its tokens' probabilities, which becomes a simple sum in log form.

You don't need to compute logarithms. Learn to read them:

Logprob Probability Meaning
0 100% Certain
−0.01 99% Near certain
−0.1 90% Confident
−0.69 50% Coin flip
−1 37% Unsure
−2.3 10% Unlikely
−4.6 1% Very unlikely

To convert back: probability = e^logprob, which is math.exp(logprob) in Python. Logprobs are always 0 or negative, and closer to 0 means more confident.

APIs that support logprobs typically return, for each generated token, its own logprob plus the top alternatives at that position (for example the 5 most likely tokens and their logprobs). You may notice that cross-entropy loss from lesson 01, 5.1 is just a negative logprob: training lowers exactly this number for the correct next token.

5.2 Try it: logprobs on a local model#

python
import math
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

model_name = "Qwen/Qwen2.5-0.5B"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name, dtype=torch.float32)   # full precision on CPU

inputs = tokenizer("Albert Einstein was born in the city of", return_tensors="pt")
n = inputs.input_ids.shape[1]
out = model.generate(**inputs, do_sample=False, max_new_tokens=10,
                     output_scores=True, return_dict_in_generate=True)

print(f"{'token':>10} {'logprob':>8} {'prob':>7}   top alternatives")
total = 0.0
for step, token_id in enumerate(out.sequences[0, n:]):
    logprobs = torch.log_softmax(out.scores[step][0], dim=-1)     # log of each token's probability
    lp = logprobs[token_id].item()
    total += lp
    alts = torch.topk(logprobs, 3)
    alt_text = ", ".join(f"{tokenizer.decode(i)!r} {math.exp(v):.0%}" for v, i in zip(alts.values, alts.indices))
    print(f"{tokenizer.decode(token_id)!r:>10} {lp:8.3f} {math.exp(lp):7.1%}   {alt_text}")

print(f"\nSum of logprobs: {total:.3f} -> probability of this whole sequence: {math.exp(total):.1%}")
Output13 lines
     token  logprob    prob   top alternatives
     ' Ul'   -1.051   35.0%   ' Ul' 35%, ' Bern' 13%, ' Ber' 9%
       'm'   -0.015   98.6%   'm' 99%, 'rich' 0%, 'men' 0%
       ','   -0.448   63.9%   ',' 64%, ' in' 20%, ' on' 3%
' Germany'   -0.570   56.6%   ' Germany' 57%, ' in' 11%, ' Bav' 5%
       ','   -0.922   39.8%   ',' 40%, '.' 24%, ' on' 13%
     ' on'   -0.850   42.8%   ' on' 43%, ' in' 29%, ' and' 6%
  ' March'   -0.575   56.3%   ' March' 56%, ' ' 15%, ' April' 11%
       ' '   -0.006   99.4%   ' ' 99%, ' the' 0%, ',' 0%
       '1'   -0.008   99.2%   '1' 99%, '2' 0%, '3' 0%
       '4'   -0.001   99.9%   '4' 100%, '5' 0%, '1' 0%

Sum of logprobs: -4.445 -> probability of this whole sequence: 1.2%

This is a lot of insight from one short sentence:

  • The key fact was the least certain token. " Ul" (the start of "Ulm", Einstein's actual birthplace) got only 35%, with " Bern" (13%) and " Ber" (9%, the start of "Berlin") as alternatives. The model "knew" the answer only weakly. Run this with sampling instead of greedy decoding and about two times in three it would have started a different answer.
  • Once committed, it was confident. After " Ul", the "m" was 98.6% certain: the model was completing a word, not choosing a fact.
  • Grammar tokens vary in confidence for harmless reasons. "," at 39.8% versus "." at 24% is a style choice, not a factual one.
  • The whole sequence had a probability of 1.2%: the sum of the logprobs (−4.445) converted back. Beam search maximizes this number, usually divided by the length (3.9).

5.3 What logprobs are useful for#

Use How Watch out for
Confidence estimation Look at the logprob of the key token (the label, the number, the entity). Low → route to a human, add a warning, or retry with more context Confidence is about the model's uncertainty, not truth. Models can be confidently wrong (see 11.4)
Classification Ask for a one-token answer and read the probabilities of each label from the top alternatives, instead of parsing text. You get a score for every class from one call Labels must be distinguishable by their first token. Probabilities from chat models are often poorly calibrated (a reported 90% isn't right 90% of the time)
Uncertainty from the alternatives (entropy) Look at how spread out the top alternatives are, not just the chosen token. One dominant alternative = certain; many similar ones = uncertain. Entropy is the standard single-number measure of that spread Only the top 5–20 alternatives are returned, so it's an approximation
Highlighting uncertain spans Colour or flag tokens with low logprobs in a UI, so reviewers know where to look Low-probability tokens are often just style choices
Debugging prompts See which alternatives the model was torn between at a surprising token —
Evaluation and scoring Score how likely a model finds a given text: the average negative logprob per token underlies perplexity, a standard measure of how well a model predicts text Needs logprobs for given text, which most chat APIs don't provide (they only return logprobs for text they generate)
Autocomplete and ranking Rank candidate completions by total or average logprob Longer texts always have lower totals, so compare averages

Logprob classification is the most practical of these. Here it is on our local base model, using a short few-shot prompt (two labelled examples) so that the next token after "Sentiment:" is naturally a label:

python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

model_name = "Qwen/Qwen2.5-0.5B"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name, dtype=torch.float32)   # full precision on CPU

labels = [" positive", " negative"]
label_ids = [tokenizer.encode(label)[0] for label in labels]   # first token of each label

examples = ("Review: Great value, works perfectly.\nSentiment: positive\n\n"
            "Review: Stopped working after a week.\nSentiment: negative\n\n")

def classify(review: str):
    prompt = examples + f"Review: {review}\nSentiment:"
    with torch.no_grad():
        logits = model(**tokenizer(prompt, return_tensors="pt")).logits[0, -1]
    probs = torch.softmax(logits, dim=-1)
    label_probs = probs[label_ids]
    on_labels = label_probs.sum()                 # how much probability landed on our two labels
    normalized = label_probs / on_labels          # renormalize over just the labels
    best = int(torch.argmax(normalized))
    return labels[best].strip(), normalized[best].item(), on_labels.item()

for review in ["Absolutely loved it, would buy again!",
               "Broke after two days. Waste of money.",
               "It arrived on time. The colour is fine, I guess."]:
    label, confidence, coverage = classify(review)
    print(f"{label:8} confidence {confidence:6.1%}  (label tokens got {coverage:.0%} of all probability)  | {review}")
Output3 lines
positive confidence  97.6%  (label tokens got 94% of all probability)  | Absolutely loved it, would buy again!
negative confidence  99.6%  (label tokens got 96% of all probability)  | Broke after two days. Waste of money.
positive confidence  80.1%  (label tokens got 59% of all probability)  | It arrived on time. The colour is fine, I guess.
  • The clear-cut reviews get 97.6% and 99.6%, and almost all of the model's probability (94–96%) lands on one of the two label tokens. The model is confident and on-task.
  • The lukewarm review ("fine, I guess") comes out positive at only 80.1%, and just 59% of the probability lands on either label. Most of the rest went to tokens we didn't offer: a separate check shows " neutral" at 30% and " mixed" at 4%. That's the model telling you that neither label fits well. Both numbers are useful signals: a low label confidence or a low label coverage is a good reason to send an item for human review.
  • One forward pass per review, no text parsing, and a score for every class. With API models, you'd request the first output token with top_logprobs and read the same numbers (5.4).

5.4 Logprobs from providers#

As of November 2026, logprob support has narrowed sharply as providers moved to reasoning models:

Provider Logprobs? How
OpenAI ✅ With conditions Chat Completions: logprobs=True, top_logprobs 0–20. Responses: include=["message.output_text.logprobs"] and top_logprobs. On GPT-6 models, only with reasoning effort none (available on gpt-6-luna, gpt-6.1-terra and the earlier gpt-6-sol, not on gpt-6-astra or gpt-6.1-sol)
Anthropic ❌ Not offered by the Messages API. Its OpenAI-compatible endpoint ignores logprobs and always returns them empty
Gemini ⚠️ Check per model response_logprobs=True and logprobs (up to 20) in the config, returned in candidate.logprobs_result. Google's Vertex AI docs mark these parameters as deprecated for Gemini 3.x models, so verify that your model still returns them
OpenRouter ✅ Where the provider supports it logprobs=True, top_logprobs 0–20. Supported by many open-weight models and some OpenAI models, not by Claude or current Gemini models. Add provider: {"require_parameters": true} so the request is only routed to providers that actually support it

To check what an OpenRouter model supports, look at its supported_parameters list on its model page or in the models API (https://openrouter.ai/api/v1/models).

OpenAI:

python
import math
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
client = OpenAI()

review = "It arrived on time. The colour is fine, I guess."
response = client.chat.completions.create(
    model="gpt-6-luna",
    reasoning_effort="none",       # logprobs are only available with reasoning off
    messages=[{"role": "user", "content":
               f"Classify the sentiment of this review. Answer with one word: positive, negative or neutral.\n\n{review}"}],
    max_completion_tokens=1,       # we only need the first token
    logprobs=True,
    top_logprobs=5,                # 0-20 alternatives per position
)
first = response.choices[0].logprobs.content[0]
print("chosen:", repr(first.token), f"{math.exp(first.logprob):.1%}")
for alt in first.top_logprobs:
    print(f"   {alt.token!r:12} {math.exp(alt.logprob):6.1%}")
Example output · illustrative6 lines
chosen: 'neutral' 71.2%
   'neutral'     71.2%
   'positive'    27.9%
   'Neutral'      0.5%
   'negative'     0.3%
   'pos'          0.0%

Anthropic: there's no equivalent. Alternatives when you need a confidence signal from a model without logprobs: ask for a confidence field in a structured output (useful, but it's the model's self-report, not a measured probability), sample several answers and measure how often they agree, or use a separate model or classifier that does expose probabilities.

Gemini:

python
import math
from dotenv import load_dotenv
from google import genai
from google.genai import types

load_dotenv()
client = genai.Client()

review = "It arrived on time. The colour is fine, I guess."
response = client.models.generate_content(
    model="gemini-3.5-flash-lite",   # check that your model still supports logprobs (see the warning below)
    contents=f"Classify the sentiment of this review. Answer with one word: positive, negative or neutral.\n\n{review}",
    config=types.GenerateContentConfig(response_logprobs=True, logprobs=5, max_output_tokens=5),
)
result = response.candidates[0].logprobs_result
chosen = result.chosen_candidates[0]
print("chosen:", repr(chosen.token), f"{math.exp(chosen.log_probability):.1%}")
for alt in result.top_candidates[0].candidates:
    print(f"   {alt.token!r:12} {math.exp(alt.log_probability):6.1%}")
Example output · illustrative6 lines
chosen: 'neutral' 68.4%
   'neutral'     68.4%
   'positive'    30.1%
   'Neutral'      0.9%
   'negative'     0.4%
   'mixed'        0.1%

OpenRouter:

python
import math
import os
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=os.environ["OPENROUTER_API_KEY"])

review = "It arrived on time. The colour is fine, I guess."
response = client.chat.completions.create(
    model="meta-llama/llama-3.3-70b-instruct",
    messages=[{"role": "user", "content":
               f"Classify the sentiment of this review. Answer with one word: positive, negative or neutral.\n\n{review}"}],
    max_tokens=1,
    logprobs=True,
    top_logprobs=5,
    extra_body={"provider": {"require_parameters": True}},   # skip providers that would silently drop logprobs
)
for alt in response.choices[0].logprobs.content[0].top_logprobs:
    print(f"   {alt.token!r:12} {math.exp(alt.logprob):6.1%}")
Example output · illustrative5 lines
   'neutral'     64.0%
   'positive'    33.8%
   'Neutral'      1.1%
   'negative'     0.6%
   'Positive'     0.2%

Part 6: What each provider lets you control#

Reference

6.1 The big shift: frontier models are dropping sampling knobs#

If you learned LLM APIs before 2026, this is the most important update in the lesson. Most current frontier models no longer let you set temperature, top-p or top-k. As of November 2026:

  • OpenAI GPT-6 models are all reasoning models. temperature, top_p and logprobs are only accepted when reasoning effort is set to none. That setting exists on gpt-6-luna, gpt-6.1-terra and the earlier gpt-6-sol, but not on gpt-6-astra or gpt-6.1-sol. (Strictly, OpenAI's GPT-6 guide says to remove these parameters whenever reasoning effort isn't none; that they work at none follows the rule GPT-5.2's guide stated explicitly.)
  • Anthropic removed temperature, top_p and top_k. On Claude Opus 5.5, Sonnet 5.5, Haiku 5.5 and other recent models, sending a non-default value returns a 400 error, and from API version 2026-10-21 sending them at all is an error on every model. The current Python SDK no longer has these arguments. Anthropic's guidance is to "use prompting to guide the model's behavior instead".
  • Google deprecated temperature, top_p and top_k starting with Gemini 3.6 Flash and Gemini 3.5 Flash-Lite. They're silently ignored on those and newer models, with HTTP 400 errors announced for a future generation. For earlier Gemini 3 models, Google's Gemini 3 guidance recommended keeping temperature at its default of 1.0 and warned that lower values could cause "looping or degraded performance" (this wording isn't repeated on the current model pages, so treat it as launch-time advice). candidate_count is unsupported on Gemini 3 and later.
  • OpenRouter passes parameters through to whatever the underlying model supports. Open-weight models (Llama, DeepSeek, Qwen, Mistral) still expose the full toolbox, including top-k, min-p and repetition penalty.

Why did this happen? The providers' stated reasons are that their reasoning models are optimized for the default sampling settings, and that you should steer behaviour through prompts, reasoning effort, verbosity controls and structured outputs instead. A plausible technical reason, consistent with the greedy-decoding loops you saw in 3.1, is that long reasoning chains are prone to repetition at low temperatures. Whatever the reason, the practical consequence is clear: on frontier closed models, the sampler is no longer yours to tune.

6.2 The parameter support matrix#

Verified against official documentation in November 2026. "Removed" and "ignored" refer to the current model generations described in 6.1.

Parameter OpenAI (Chat Completions / Responses) Anthropic (Messages) Gemini (generate_content, optional) OpenRouter (optional)
temperature 0–2, default 1. GPT-6: only with reasoning effort none ❌ Removed (was 0–1, default 1) 0–2, default varies by model. Ignored on 3.6 Flash, 3.5 Flash-Lite and newer 0–2. If omitted, the provider's default applies
top_p 0–1, default 1. Same restriction as temperature ❌ Removed. Under API version 2026-10-21, sending it is a 400 even at its default value, so don't assume top_p=1 is safe: omit it 0–1. Ignored on newer models 0–1
top_k ❌ Not offered ❌ Removed top_k, where the model allows it. Ignored on newer models ✅ Where supported (not on OpenAI models)
min_p ❌ ❌ ❌ ✅ 0–1, where supported
repetition_penalty ❌ ❌ ❌ ✅ 0–2, default 1, where supported
frequency / presence penalty −2 to 2, default 0 (Chat Completions only) ❌ Documented, but Vertex AI says custom values return an error on 3.6 Flash and later −2 to 2, where supported
seed Chat Completions only, best effort (labelled Beta in OpenAI's reference) ❌ seed, best effort ✅ Best effort
stop sequences stop, up to 4 (Chat Completions only) stop_sequences stop_sequences, up to 5 stop
max output tokens max_completion_tokens / max_output_tokens (include reasoning) max_tokens, required max_output_tokens (includes thinking) max_tokens
logprobs logprobs + top_logprobs (0–20) / include + top_logprobs; reasoning effort none only ❌ response_logprobs + logprobs (0–20); deprecated for Gemini 3.x on Vertex AI logprobs + top_logprobs (0–20), where supported
n / multiple candidates n 1–128 (Chat Completions only); billed for every choice ❌ (make separate calls) candidate_count; unsupported on Gemini 3+ ❌ Not documented
logit bias logit_bias, −100 to 100 per token ID (Chat Completions only) ❌ ❌ ✅ Where supported (mainly OpenAI and open-weight models)
What replaces the knobs reasoning_effort, verbosity output_config.effort, structured outputs, prompting thinking_level, system instructions, structured output reasoning, verbosity (passed through)

How to keep this table current yourself:

  • OpenAI: the API reference for Chat Completions and Responses, plus each model's page and the "latest model" migration guide.
  • Anthropic: the Messages API reference and each model's migration guide.
  • Gemini: the API reference (each field notes which models ignore it) and the "what's new" page for each model generation.
  • OpenRouter: the parameters page and each model's supported_parameters list.

6.3 Cross-provider gotchas#

  • "Silently ignored" is the dangerous case. Gemini ignores sampling parameters on newer models, and OpenRouter ignores any parameter the chosen provider doesn't support. Your code runs, your "temperature 0.2" does nothing, and nothing tells you. On OpenRouter, set provider: {"require_parameters": true} when a parameter matters, so the request only goes to providers that honour it.
  • Errors after an upgrade. Code that sent temperature=0 for years now fails with a 400 on current Claude models. When you move to a new model, read its migration guide and remove parameters it no longer accepts. Your evals (Module 10A) will tell you whether the behaviour you relied on survived.
  • The same name, different behaviour. Temperature ranges, defaults and sampler order differ between providers and inference servers (2.4). Re-tune when you switch.
  • Defaults are model-specific. Open-weight models ship a recommended configuration in their generation_config.json (the model card usually lists recommended settings too), and provider defaults vary. If you don't set a parameter, you get someone else's choice, which is usually a good one. The demo below shows this for our two local models.
  • Reasoning models change the rules. See lesson 08, Part 3 for the controls that replace sampling on reasoning models (reasoning effort, thinking budgets and levels), and 6.4 for verbosity.

Here are the defaults shipped with the two local models used in this lesson. GenerationConfig.from_pretrained reads only the small generation_config.json file, so this runs instantly:

python
from transformers import GenerationConfig

for model_name in ["Qwen/Qwen2.5-0.5B", "Qwen/Qwen2.5-0.5B-Instruct"]:
    config = GenerationConfig.from_pretrained(model_name)    # reads the model's generation_config.json
    print(model_name)
    for key in ["do_sample", "temperature", "top_p", "top_k", "repetition_penalty", "eos_token_id"]:
        print(f"   {key:20} {getattr(config, key)}")
Output14 lines
Qwen/Qwen2.5-0.5B
   do_sample            False
   temperature          None
   top_p                None
   top_k                None
   repetition_penalty   None
   eos_token_id         151643
Qwen/Qwen2.5-0.5B-Instruct
   do_sample            True
   temperature          0.7
   top_p                0.8
   top_k                20
   repetition_penalty   1.1
   eos_token_id         [151645, 151643]
  • The base model sets almost nothing. None means Transformers' own fallbacks apply: temperature 1.0, top-p 1.0, repetition penalty 1.0 and top-k 50 (used whenever sampling is on).
  • The chat model ships its authors' recommended settings: sampling on, temperature 0.7, top-p 0.8, top-k 20 and a repetition penalty of 1.1. Calling generate() without arguments samples with all of these.
  • Some defaults survive even when you switch sampling off. The EOS demo in 4.2 used do_sample=False on the chat model, so temperature, top-p and top-k were ignored, but the repetition penalty of 1.1 still applied, because penalties are part of the pipeline even in greedy decoding (2.4).

Providers work the same way, except that you can't print their defaults: always assume a default you didn't set is in effect.

6.4 Verbosity: the length control that replaces tuning#

On models without sampling knobs, the main setting that shapes the answer (rather than the thinking behind it) is verbosity: a hint about how long and detailed the reply should be. Unlike the maximum-output-tokens limit (4.3), which simply cuts the answer off, verbosity changes what the model writes, so a low answer is complete, just shorter.

Provider Setting Values (as of November 2026)
OpenAI Responses API text={"verbosity": ...} "low", "medium" (the default), "high"
OpenAI Chat Completions verbosity (top-level) The same three values
Anthropic ❌ No verbosity parameter. Ask for the length you want in the prompt. output_config.effort controls how much work the model does, not how long the answer is —
Gemini ❌ No verbosity parameter. Ask in the prompt or system instruction —
OpenRouter verbosity, passed through to the provider low, medium (default), high, plus xhigh and max. For Anthropic models, OpenRouter maps it to output_config.effort
python
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()                      # reads OPENAI_API_KEY from .env
client = OpenAI()

for verbosity in ["low", "high"]:
    response = client.responses.create(
        model="gpt-6-luna",
        input="What is a context window? Answer for a new developer.",
        text={"verbosity": verbosity},        # Chat Completions: verbosity=verbosity
    )
    words = len(response.output_text.split())
    print(f"{verbosity:5} {words:4} words, {response.usage.output_tokens} output tokens")
Example output · illustrative2 lines
low     41 words, 168 output tokens
high   236 words, 512 output tokens

Three things to know:

  • It's a hint, not a limit. Keep a maximum-output-tokens setting as the safety net (4.3), and check the finish reason (4.5).
  • Explicit instructions still work and combine with it. "Answer in two sentences" in the prompt is more precise than low, and it's the only option on Anthropic and Gemini.
  • On OpenRouter, the same word means different things. For OpenAI models verbosity sets answer length. For Anthropic models it changes reasoning effort, which affects cost, latency and quality, not just length. Set it deliberately per model.

Part 7: Determinism and reproducibility#

7.1 Why "temperature 0" isn't deterministic through APIs#

On your laptop, greedy decoding gave identical output twice (3.1), and a fixed seed reproduced a sampled story exactly (3.10). Through provider APIs, the same request can return different outputs even at temperature 0, and every provider says so: Anthropic's documentation states that "even with temperature set to 0, the results will not be fully deterministic", OpenAI's says its seed gives only "best effort" determinism, and Google's says the same for Gemini's seed.

Lesson 01, 7.5 introduced the cause: tiny numerical differences. Here's the full chain:

  1. Floating-point arithmetic isn't associative. With computer numbers, (a + b) + c doesn't always equal a + (b + c), because each addition rounds its result.
  2. The order of additions depends on how the work is split up. GPU code splits big sums across many parallel units and combines the pieces. How it splits them can depend on the shape of the work, in particular the batch size: how many requests are being processed together.
  3. Batch size depends on server load. Your request is batched with other users' requests (11.2), and how many there are changes from moment to moment.
  4. So your logits differ very slightly between runs, depending on who else was using the server at that moment.
  5. Usually this changes nothing, but occasionally it flips a choice. When two tokens are almost tied, a difference in the fifth decimal place changes which one is "most likely". And because generation is autoregressive, one flipped token changes everything after it.

Both effects are visible on a laptop:

python
import numpy as np
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

# 1. Floating-point addition is not associative: the ORDER of a sum changes the result
a, b, c = np.float32(0.1), np.float32(1e8), np.float32(-1e8)
print("(0.1 + 1e8) - 1e8 =", (a + b) + c)
print("0.1 + (1e8 - 1e8) =", a + (b + c))

# 2. The same prompt alone vs inside a batch with a longer prompt
model_name = "Qwen/Qwen2.5-0.5B"
tokenizer = AutoTokenizer.from_pretrained(model_name)
tokenizer.padding_side = "left"
model = AutoModelForCausalLM.from_pretrained(model_name, dtype=torch.float32)   # full precision on CPU

prompt = "The weather today is"
other = "Write a long and detailed essay about the history of the Roman Empire, covering"
with torch.no_grad():
    alone = model(**tokenizer([prompt], return_tensors="pt")).logits[0, -1]
    batch = tokenizer([prompt, other], return_tensors="pt", padding=True)
    position_ids = (batch.attention_mask.cumsum(-1) - 1).clamp(min=0)   # same positions as when alone
    batched = model(**batch, position_ids=position_ids).logits[0, -1]

print("\nMax difference in logits, alone vs batched:", (alone - batched).abs().max().item())
print("Same top token?", alone.argmax().item() == batched.argmax().item())
Output5 lines
(0.1 + 1e8) - 1e8 = 0.0
0.1 + (1e8 - 1e8) = 0.1

Max difference in logits, alone vs batched: 5.626678466796875e-05
Same top token? True

The first two lines show non-associativity: adding 0.1 to 100,000,000 in 32-bit floating point loses the 0.1 entirely, so the order of the additions decides whether the answer is 0.0 or 0.1. The last two lines show the batching effect on a real model: the same prompt gives slightly different logits (here by about 0.00006) when it's processed alongside another prompt. The script passes the same token positions in both cases, so the difference comes from the batch itself: batching means padding the short prompt to the long one's length, which changes the shapes of the matrix operations and therefore the order of the additions, the same mechanism providers face. The top token didn't change this time, but on a near-tie it would.

7.2 Seeds and system fingerprints#

As of November 2026:

Provider Seed Backend-change indicator
OpenAI seed in Chat Completions: "best effort", "determinism is not guaranteed". The API reference labels it Beta. Not available in the Responses API system_fingerprint identifies the backend configuration, so you can tell when a change might affect determinism (OpenAI's Node SDK typings mark the field deprecated, so don't build on it)
Anthropic ❌ Not offered ❌
Gemini seed: the SDK says "the model makes a best effort to provide the same response for repeated requests". Vertex AI adds that deterministic output "isn't guaranteed" ❌
OpenRouter seed, passed to the provider: "Determinism is not guaranteed for some models" ❌

Note that on the many models where temperature is fixed (6.1), you can't even ask for greedy decoding: every call samples.

7.3 What to do about non-determinism#

Design for variation instead of fighting it:

  • Don't promise users identical answers. If you need the same output for the same input (for example a cached product description), store the output and serve the stored copy. A response cache like this is cheaper and fully deterministic (Module 11B); it's your own application's cache, not provider prompt caching.
  • Pin the model version: use a pinned snapshot ID rather than a "latest" alias, so the model doesn't change under you (lesson 09, 8.3 covers how each provider names snapshots).
  • Log everything needed to investigate: model ID, every parameter, the full prompt, the output and the finish reason.
  • Test with multiple runs. One passing run proves little. Run evaluation cases several times and track the pass rate (Module 10A).
  • Use structure to reduce variation where it matters: structured outputs (Part 9), explicit rules in the system prompt, and enumerated options make outputs far more consistent than any sampling setting.
  • Turn variation into a tool. Sample several answers and compare them: agreement suggests confidence, and disagreement flags questions worth a second look (11.4).

Part 8: Streaming#

Deep-dive

8.1 What streaming is#

Without streaming, the API waits until generation finishes and then returns the whole response at once. With streaming, it sends each piece of text as soon as it's generated, over a single long-lived HTTP connection, usually using server-sent events (SSE): a simple format where the server writes a series of small data: {...} messages into the response.

sequenceDiagram
    participant App as Your app
    participant API as Provider API
    participant M as Model
    App->>API: request with stream=true
    API->>M: prefill the prompt
    M-->>API: token 1
    API-->>App: event: "The"
    M-->>API: token 2
    API-->>App: event: " CPU"
    Note over App,API: ...one small event per token or group of tokens...
    M-->>API: end of sequence
    API-->>App: final event: finish reason + usage

Because the model generates one token at a time anyway (Part 1), streaming costs the provider nothing extra. You pay the same per token.

Why products stream:

  • Perceived speed. The user starts reading after the time to first token instead of waiting for the full answer. For a 500-token answer at 80 tokens per second, that's the difference between seeing text after about half a second and staring at a spinner for over six seconds (1.4).
  • Early cancellation. A user (or your code) can stop a response that's clearly going wrong and avoid generating the rest. OpenRouter notes that for supported providers, aborting the connection stops processing and billing immediately.
  • Long outputs. Long non-streaming requests risk HTTP timeouts. As noted in 4.3, some SDKs and models require or favour streaming for large outputs.
  • Progressive processing. Agents and pipelines can start acting on early parts of the output, for example speaking a sentence aloud in a voice app while the rest is still being generated (Module 09).

What streaming makes harder:

  • Partial structured output. Half a JSON object isn't valid JSON. You must buffer it, or use a streaming JSON parser, before you can act on it.
  • Moderation and validation. You can only validate a complete answer. If you show text as it arrives, you've already shown it before you could check it (Module 12).
  • Errors mid-stream. Once the server has sent 200 OK, an error can only arrive as an event inside the stream. Your code must handle a stream that stops early, and check the final event's finish reason.
  • Usage and finish reason arrive at the end, in the last event or chunk, so token accounting must wait for it.

8.2 Try it: stream from a local model#

Transformers can stream too. TextIteratorStreamer hands you text pieces as generate() produces them in a background thread, which lets us measure TTFT and tokens per second directly:

python
import time
from threading import Thread
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer

model_name = "Qwen/Qwen2.5-0.5B"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name, dtype=torch.float32)   # full precision on CPU

inputs = tokenizer("A CPU (central processing unit) is", return_tensors="pt")

streamer = TextIteratorStreamer(tokenizer, skip_prompt=True, skip_special_tokens=True)
start = time.perf_counter()
# generate() runs in a background thread and pushes text into the streamer as tokens are produced
Thread(target=model.generate, kwargs=dict(**inputs, streamer=streamer, do_sample=False, max_new_tokens=60)).start()

first_token_at, pieces = None, []
for piece in streamer:                       # each piece arrives as soon as it's generated
    if first_token_at is None and piece:
        first_token_at = time.perf_counter() - start
    pieces.append(piece)
    print(piece, end="", flush=True)
total = time.perf_counter() - start

n_out = len(tokenizer("".join(pieces)).input_ids)
print(f"\n\nTime to first token: {first_token_at:.2f} s | total: {total:.2f} s | "
      f"{n_out} tokens -> {n_out / (total - first_token_at):.0f} tokens/s after the first")
Output3 lines
 a device that performs arithmetic and logical operations on data. The CPU is the core of a computer, and it is the brain of the computer. The CPU is the most important component of a computer. The CPU is the brain of the computer. The CPU is the most important component of a computer.

Time to first token: 0.17 s | total: 1.94 s | 60 tokens -> 34 tokens/s after the first

The first text arrived after 0.17 seconds, and the rest streamed at about 34 tokens per second, the same decode speed you measured in 1.3. Without streaming, you'd have stared at nothing for nearly two seconds and then received everything at once. (The repetitive text is greedy decoding on a small base model again, see 3.1.)

8.3 Streaming with each provider#

A minimal streaming call for each provider. Deep API usage, including async streaming and error handling, is covered in Module 03.

OpenAI (Responses API). The stream is a sequence of typed events; text arrives in response.output_text.delta events, and the final event (response.completed, or response.incomplete / response.failed if something went wrong) carries the status and usage. This sample also measures TTFT and computes tokens per second from the final usage rather than by counting events:

python
import time
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
client = OpenAI()

start = time.perf_counter()
first_token_at, final = None, None
stream = client.responses.create(
    model="gpt-6-luna",
    reasoning={"effort": "none"},   # no hidden thinking, so TTFT and TPS measure only visible text
    input="Explain what a CPU does in three sentences.",
    stream=True,
)
for event in stream:
    if event.type == "response.output_text.delta":      # a new piece of text
        if first_token_at is None:
            first_token_at = time.perf_counter() - start
        print(event.delta, end="", flush=True)
    elif event.type in ("response.completed", "response.incomplete", "response.failed"):
        final = event.response                          # the last event carries status and usage
    elif event.type == "error":
        raise RuntimeError(f"Stream error: {event}")
total = time.perf_counter() - start

print(f"\n\nstatus: {final.status} | incomplete: {final.incomplete_details}")
if final.usage and first_token_at is not None:
    usage = final.usage
    # TPS from the final usage, not by counting events (one event can carry several tokens)
    print(f"TTFT {first_token_at:.2f} s | total {total:.2f} s | {usage.output_tokens} output tokens "
          f"(incl. {usage.output_tokens_details.reasoning_tokens} reasoning) -> "
          f"{usage.output_tokens / (total - first_token_at):.0f} tokens/s")
Example output · illustrative4 lines
A CPU (central processing unit) is the part of a computer that carries out instructions...

status: completed | incomplete: None
TTFT 0.41 s | total 1.32 s | 74 output tokens (incl. 0 reasoning) -> 81 tokens/s

In Chat Completions, you'd pass stream=True and read chunk.choices[0].delta.content from each chunk instead; add stream_options={"include_usage": True} to get usage in a final chunk (whose choices list is empty).

Anthropic. The SDK's messages.stream() helper gives you text_stream (just the text) and get_final_message() (the complete message, with stop_reason and usage). Under the hood the events are message_start, content_block_start, content_block_delta, content_block_stop, message_delta (which carries the stop reason and cumulative usage) and message_stop, plus occasional ping events:

python
import anthropic
from dotenv import load_dotenv

load_dotenv()
client = anthropic.Anthropic()

with client.messages.stream(
    model="claude-haiku-5-5",
    max_tokens=500,
    messages=[{"role": "user", "content": "Explain what a CPU does in three sentences."}],
) as stream:
    for text in stream.text_stream:          # yields only the text pieces, as they arrive
        print(text, end="", flush=True)
    final = stream.get_final_message()       # the complete Message, once the stream ends

print(f"\n\nstop_reason: {final.stop_reason} | output tokens: {final.usage.output_tokens}")
Example output · illustrative3 lines
A CPU, or central processing unit, is the component that executes a computer's instructions...

stop_reason: end_turn | output tokens: 81

Gemini. Each chunk carries a piece of text; the last one also carries the finish reason and usage:

python
from dotenv import load_dotenv
from google import genai

load_dotenv()
client = genai.Client()

last = None
for chunk in client.models.generate_content_stream(
    model="gemini-3.5-flash-lite",
    contents="Explain what a CPU does in three sentences.",
):
    if chunk.text:                           # some chunks carry no text (e.g. only metadata)
        print(chunk.text, end="", flush=True)
    last = chunk                             # the final chunk carries the finish reason and usage

print(f"\n\nfinish_reason: {last.candidates[0].finish_reason} | "
      f"output tokens: {last.usage_metadata.candidates_token_count}")
Example output · illustrative3 lines
A CPU (Central Processing Unit) is the primary component of a computer that executes instructions...

finish_reason: FinishReason.STOP | output tokens: 79

OpenRouter uses the OpenAI Chat Completions format. It also sends occasional : OPENROUTER PROCESSING comment lines to keep the connection alive (the SDK ignores them), and the final chunk carries the usage:

python
import os
from dotenv import load_dotenv
from openai import OpenAI

load_dotenv()
client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=os.environ["OPENROUTER_API_KEY"])

stream = client.chat.completions.create(
    model="meta-llama/llama-3.3-70b-instruct",
    messages=[{"role": "user", "content": "Explain what a CPU does in three sentences."}],
    stream=True,
)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
    if chunk.usage:                          # OpenRouter sends usage in the last chunk
        print(f"\n\nfinish: {chunk.choices[0].finish_reason} | output tokens: {chunk.usage.completion_tokens}")
Example output · illustrative3 lines
A CPU, or Central Processing Unit, is the primary component of a computer that performs most of the processing...

finish: stop | output tokens: 78

Part 9: Constrained decoding and structured output#

Deep-dive

9.1 The idea: mask the tokens you don't allow#

Asking a model nicely to "respond only with JSON" usually works, but "usually" isn't good enough when your code parses the result. Constrained decoding makes invalid output impossible by intervening in the sampling pipeline (2.4):

  1. Before each token is chosen, work out which tokens are legal at this point, according to a set of rules (a JSON schema, a grammar, a list of allowed values).
  2. Set the logit of every illegal token to minus infinity, so its probability after softmax is exactly zero.
  3. Sample as usual from whatever is left.
flowchart LR
    G["Grammar or JSON schema<br/>+ text generated so far"] --> V["Which tokens can<br/>legally come next?"]
    L["Model logits"] --> M["Mask: illegal tokens<br/>set to minus infinity"]
    V --> M
    M --> S["Sample from the<br/>legal tokens only"]
    S --> U["Update the grammar state"]
    U --> G

Here's the simplest possible version: an answer that may contain only digits.

python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, LogitsProcessor, LogitsProcessorList

model_name = "Qwen/Qwen2.5-0.5B"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name, dtype=torch.float32)   # full precision on CPU

class AllowOnly(LogitsProcessor):
    """Constrained decoding: set every token NOT in the allowed list to -infinity."""
    def __init__(self, allowed_ids):
        self.allowed_ids = torch.tensor(allowed_ids)

    def __call__(self, input_ids, scores):
        mask = torch.full_like(scores, float("-inf"))
        mask[:, self.allowed_ids] = 0.0          # allowed tokens keep their score
        return scores + mask                     # banned tokens get probability 0 after softmax

# Allowed: tokens made only of digits, plus the end-of-text token
digit_ids = [i for i in range(len(tokenizer)) if tokenizer.decode(i).isdigit()]
allowed = digit_ids + [tokenizer.eos_token_id]
print(f"Allowed tokens: {len(allowed)} out of {len(tokenizer):,}")

prompt = "Question: Sarah was born in 1990. How old was she in 2024?\nAnswer: "   # trailing space: the next token is then a digit
inputs = tokenizer(prompt, return_tensors="pt")
n = inputs.input_ids.shape[1]

free = model.generate(**inputs, do_sample=False, max_new_tokens=25)
print("Unconstrained:", repr(tokenizer.decode(free[0, n:])))

forced = model.generate(**inputs, do_sample=False, max_new_tokens=4,
                        logits_processor=LogitsProcessorList([AllowOnly(allowed)]))
print("Digits only:  ", repr(tokenizer.decode(forced[0, n:])))
Output3 lines
Allowed tokens: 29 out of 151,665
Unconstrained: '2024 - 1990 = 34 years\n34 years = 34 x '
Digits only:   '2024'

Of the tokenizer's 151,665 tokens, only 29 are allowed: the digit tokens and the end-of-text token. (The model's output layer has 151,936 slots, slightly more than the tokenizer's real tokens, because vocabulary sizes are often padded to a round multiple for efficiency.) The result is a perfect illustration of both the power and the danger of constraints:

  • The constraint worked. The output contains only digits, exactly as the rules required. The model could not have produced anything else.
  • The answer is wrong. Unconstrained, the model wanted to show its working: "2024 - 1990 = 34". Forced to produce digits only, it started the same way, with "2024", and the token limit ended it there. The constraint guaranteed the format, not the content, and by blocking the model's natural path it made the answer worse.

(The prompt deliberately ends with a space so that the next token is a digit. Lesson 02, 12.3 explains why trailing spaces are usually best avoided; here it keeps the demo to digit tokens.)

Production structured-output systems are much smarter than this ten-line filter, but the same trade-off applies, which is why 9.3 recommends giving the model room to think inside the structure.

9.2 From a digit filter to JSON schemas#

Real structured output uses the same masking idea with much richer rules. The JSON schema (or a grammar) is compiled into a state machine that tracks where you are in the structure. After {"age": , only tokens that can start a number are legal. Inside a string, almost anything is legal except an unescaped quote. After the last required field, only } is legal. At every step, the sampler masks everything the structure doesn't allow.

The providers document this directly (as of November 2026):

  • Anthropic says its structured outputs "guarantee schema-compliant responses through constrained decoding" and use "constrained sampling with compiled grammar artifacts". The first request with a new schema takes longer while the grammar is compiled, and compiled grammars are cached for 24 hours. Use output_config.format with a JSON schema, or strict: true on tool definitions.
  • OpenAI's Structured Outputs (response_format with "strict": true in Chat Completions, text.format in Responses) "ensures the model will always generate responses that adhere to your supplied JSON Schema", with extra latency on the first request with each schema. OpenAI also lets custom tools constrain their input with a context-free grammar written in Lark syntax or a regex, noting that "model sampling is constrained using LLGuidance" (an open-source constrained-decoding library).
  • Gemini refers to "constrained decoding" in its structured output documentation (response_mime_type="application/json" plus a schema) and notes some schema keywords, such as minLength, that it doesn't enforce during constrained decoding.
  • Open-source servers such as vLLM and llama.cpp support JSON schemas and grammars too, through libraries such as Outlines, XGrammar and LLGuidance, and llama.cpp's own GBNF grammars.

9.3 What constrained decoding can't do#

  • It guarantees structure, not truth. The JSON will parse and match the schema, but the values can still be wrong or invented. Google's documentation says it plainly: structured output "does not guarantee the values are semantically correct".
  • Truncation still breaks it. If the model hits max_tokens mid-object, you get incomplete JSON. Check the finish reason (4.6).
  • Refusals can bypass the schema. Anthropic notes that a refusal may produce output that doesn't match the schema.
  • Constraints can hurt quality when they fight the model. If the most natural continuation is illegal, the model is forced down a lower-probability path, as the digit demo showed. Keep schemas natural (sensible field names, a free-text reasoning field before the answer field if the model needs to think, and a way to say "unknown").
  • Schema features are limited. Each provider supports a subset of JSON Schema (for example, Anthropic doesn't support recursive schemas or numeric minimum/maximum). Check the docs for your provider.

Full structured-output usage, including Pydantic models and validation, is covered in Module 03.


10.1 Starting points#

These are starting points for models that accept sampling parameters (open-weight models, older or non-reasoning models, GPT-6 with reasoning effort none). For models that don't, use the right-hand column. Then measure on your own task (10.4).

Task Sampling starting point (where knobs exist) On models without sampling knobs Also
Extraction, classification, routing Temperature 0 (or the lowest allowed) Structured outputs with an enum or schema; low reasoning effort for simple tasks Logprobs for a confidence score, where available. No penalties
Structured data / JSON Temperature 0–0.3 Structured outputs No penalties. Check the finish reason
Coding Temperature 0–0.3 for one answer; 0.6–1.0 when generating several candidates to test The model's defaults; adjust reasoning effort No penalties (code repeats tokens legitimately). Validate with tests and linters
Factual Q&A, RAG answers Temperature 0–0.3 Defaults plus a clear system prompt and grounding (Module 07) Lower temperature removes errors caused by sampling unlikely tokens, not the model's own confident errors (11.4)
General chat assistant The provider's or model's default (often 0.7–1.0) Defaults Steer tone through the prompt
Creative writing Temperature 0.8–1.1, optionally min-p 0.05–0.1 (open models) Defaults; ask for a style explicitly; vary the prompt A small presence or frequency penalty (0.1–0.5) for long prose
Brainstorming, generating variations Temperature 0.9–1.2, n > 1 where available Several calls, or ask for N distinct ideas in one response Deduplicate the results
LLM-as-judge (a second model that grades outputs against a rubric; Module 10A), grading Temperature 0 Defaults plus a strict rubric and structured output Run several times and aggregate (Module 10A)
Self-consistency / best-of-N Temperature 0.7–1.0 (you need diversity) Several calls Majority vote or a verifier picks the winner

10.2 Change temperature or top_p, not both#

OpenAI's documentation has long recommended "altering this or top_p but not both", and Anthropic's older documentation said the same (before it removed both parameters). The reasons:

  • They act on the same thing. Both reshape the same distribution, one by rescaling it and one by truncating it, and their effects interact. In Transformers' order, a higher temperature flattens the distribution so top-p keeps more tokens, partly cancelling a lower top-p. Two knobs that partly undo each other are hard to reason about.
  • Tuning is experimental. With one knob, you can run a small sweep and see the effect. With two, the number of combinations multiplies and the results are much harder to interpret.
  • Defaults are usually tuned together. Leaving one at its default keeps you close to settings the provider or model author tested.

Some combinations are fine and common in open-source setups (for example temperature plus min-p), but in provider APIs, change one, keep the other at its default. Anthropic went further: on Claude 4.7 and later models, a request that included both temperature and top_p was rejected even at their default values, and API version 2026-10-21 then removed both parameters entirely.

10.3 When to leave the defaults#

Leave sampling settings alone when:

  • The model doesn't accept them, or ignores them (6.1). Remove them rather than sending values that do nothing.
  • You're using a reasoning model. Providers tune their reasoning models for the default settings, and some warn that changes can cause looping or degraded reasoning. Use reasoning effort and prompting instead (lesson 08).
  • You have no way to measure the effect. Without an evaluation set, changing temperature is guesswork. Defaults were chosen by people who tested them.
  • The real problem is elsewhere. Wrong answers, ignored instructions, wrong format and repetition are usually prompt, context or model-choice problems. Fix those first (Module 04).

10.4 Tune with evaluations, not intuition#

If you do tune sampling, treat it like any other change to an AI feature:

  1. Build a small evaluation set of real inputs with known good outputs or a scoring rubric (Module 10A).
  2. Change one parameter at a time, over a few values (for example temperature 0, 0.3, 0.7, 1.0).
  3. Run each setting several times, because sampling is random.
  4. Compare quality, consistency, cost and latency, and pick the simplest setting that works.
  5. Record the chosen settings next to the prompt in version control, and re-test when you change models.

Part 11: Going deeper: speed, control and hallucination#

Deep-dive

11.1 Speculative decoding: why some providers are faster#

Decode is slow because every token needs its own sequential forward pass through a big model, and that pass is limited by memory bandwidth, not compute (1.2). Speculative decoding exploits the spare compute:

  1. A cheap drafter guesses the next several tokens. It could be a much smaller model, extra prediction heads on the main model, or simply text copied from the prompt.
  2. The big model checks all the guesses in a single forward pass, which costs about the same as generating one token, because verification works like prefill: all positions are processed in parallel.
  3. Every guess the big model agrees with is accepted. At the first disagreement, the big model's own choice is used instead, and drafting starts again from there.
flowchart LR
    Dr["Cheap drafter guesses<br/>the next 5 tokens"] --> V["Big model checks all 5<br/>in ONE forward pass"]
    V --> A{"How many<br/>guesses match?"}
    A -- "first 3 accepted" --> K["Keep 3 tokens<br/>+ 1 correction from<br/>the big model"]
    K --> Dr

If the drafter is usually right, the big model produces several tokens per forward pass instead of one. The clever part: with the right acceptance rule, the output follows exactly the same distribution as the big model alone, so quality is unchanged. Only speed improves. With greedy decoding the rule is simple: keep a guess if it's the big model's top token. With sampling, each guess is accepted with probability equal to the big model's probability for it divided by the drafter's (capped at 1), and on a rejection a replacement token is sampled from a corrected distribution. This is what keeps the output distribution exact.

Drafters you'll see named in model cards and serving tools: small draft models from the same family, extra prediction heads trained on the big model (Medusa, EAGLE), and multi-token prediction (MTP) layers built into some models during training.

It works best when the output is predictable (code edits, reformatting, copying from the prompt, boilerplate) and when the server isn't already busy: under large batches, the GPU is closer to compute-bound (11.2), so there's less spare compute for verifying guesses and the speed-up shrinks. Here's the simplest variant, prompt lookup decoding, where the "drafter" just looks for the current text in the prompt and proposes whatever followed it there:

python
import time
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

model_name = "Qwen/Qwen2.5-0.5B"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name, dtype=torch.float32)   # full precision on CPU

code = '''def total_price(items):
    total = 0
    for item in items:
        total += item["price"] * item["quantity"]
    return total
'''
prompt = f"Original code:\n```python\n{code}```\n\nThe same code with `total` renamed to `subtotal`:\n```python\n"
inputs = tokenizer(prompt, return_tensors="pt")
n = inputs.input_ids.shape[1]
outputs = []

for label, extra in [("normal decoding", {}),
                     ("prompt lookup (speculative)", {"prompt_lookup_num_tokens": 10})]:
    model.generate(**inputs, max_new_tokens=5, do_sample=False, **extra)    # warm-up
    start = time.perf_counter()
    out = model.generate(**inputs, max_new_tokens=50, do_sample=False, **extra)
    elapsed = time.perf_counter() - start
    new = out[0, n:]
    print(f"{label:28} {len(new)} tokens in {elapsed:.2f} s -> {len(new)/elapsed:5.1f} tokens/s")
    outputs.append(tokenizer.decode(new))
print("\nIdentical output both ways?", outputs[0] == outputs[1])
print(outputs[1].split("```")[0])            # show just the code part
Output9 lines
normal decoding              50 tokens in 1.58 s ->  31.6 tokens/s
prompt lookup (speculative)  50 tokens in 0.65 s ->  76.4 tokens/s

Identical output both ways? True
def total_price(items):
    subtotal = 0
    for item in items:
        subtotal += item["price"] * item["quantity"]
    return subtotal

Same model, same greedy decoding, identical output, and about 2.4× faster. The renamed code is almost entirely a copy of the prompt, so the drafted tokens were usually right, and each forward pass of the model confirmed several tokens at once instead of producing one. On creative text that doesn't repeat the prompt, prompt lookup finds nothing to propose and gives no speed-up (try it in the exercises).

What you'll see from providers:

  • OpenAI's Predicted Outputs (prediction in Chat Completions) let you supply text you expect the output to largely repeat, such as a file you're asking the model to edit, and "if generated tokens would match this content, the entire model response can be returned much more quickly". OpenAI doesn't call this speculative decoding, but it works on the same principle, with your text as the draft. Rejected predicted tokens are still billed, and it has restrictions (no n > 1, logprobs, penalties or tools). Check which current models support it.
  • Anthropic's fast mode (speed: "fast") "delivers up to 2.5x higher output tokens per second at premium pricing" on supported Opus models, running "the same model with a faster inference configuration". It was still labelled a research preview in Anthropic's docs in November 2026, so check the current model list, price multiplier and any beta header on the fast mode page before relying on it. Anthropic doesn't document how it works internally. Note that the benefit is in output tokens per second, not TTFT.
  • Different OpenRouter providers serve the same open model at very different speeds, partly because of techniques like this, plus hardware and quantization differences. OpenRouter lets you sort providers by throughput (the :nitro model suffix, or provider.sort).

11.2 Batching: throughput vs latency#

Because decode leaves the GPU's arithmetic units mostly idle (1.2), serving one request at a time wastes the hardware. Inference servers therefore batch many users' requests together: one forward pass reads the weights once and produces the next token for every request in the batch. Modern servers use continuous batching, adding and removing requests from the running batch at every step instead of waiting for a whole batch to finish.

This creates a trade-off you'll meet as soon as you choose providers or host models:

Small batches Large batches
Speed for each user (latency, TPS) ✅ Faster ❌ Slower, but only gradually at first: while decode is memory-bound, a step for 32 requests takes not much longer than a step for one
Total tokens per second per GPU (throughput) ❌ Lower ✅ Much higher
Cost per token ❌ Higher ✅ Lower

Up to a point, batching is almost free throughput: the weights are read once per step whatever the batch size. Only when batches grow large enough to make the GPU compute-bound does each user's speed drop noticeably. Providers choose a batch size that balances the two.

Consequences for you:

  • Speed varies with load. The same provider can be noticeably slower at peak times, because batches are bigger. Measure TTFT and TPS over time, not once.
  • Batch APIs are cheaper. When you don't need an immediate answer (nightly jobs, bulk classification), batch APIs let providers schedule your work into full batches. As of November 2026, Anthropic's Message Batches API costs 50% of standard prices, and Gemini's batch prices are also half the standard ones for the models checked. Check each provider's pricing page for current discounts (Module 11B).
  • Priority tiers buy latency. Several providers sell higher-priority or faster serving at a higher price, effectively smaller or prioritized batches.
  • Batching is why API output isn't deterministic (7.1).

11.3 Logit bias#

Logit bias lets you add a fixed amount to specific tokens' logits before sampling: a large positive value forces a token, a large negative value bans it. In OpenAI's Chat Completions, logit_bias maps token IDs (from the model's tokenizer, lesson 02) to values from −100 to 100. OpenAI's docs say values between −1 and 1 nudge the likelihood, while −100 or 100 "should result in a ban or exclusive selection". OpenRouter passes it through to models that support it. Anthropic and Gemini don't offer it.

Here's a ban on a local model:

python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

model_name = "Qwen/Qwen2.5-0.5B"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name, dtype=torch.float32)   # full precision on CPU

inputs = tokenizer("The Eiffel Tower is in the city of", return_tensors="pt")
n = inputs.input_ids.shape[1]
paris = tokenizer.encode(" Paris")                       # the token id(s) for " Paris"
print("' Paris' is token id", paris)

for label, bias in [("no bias", None),
                    ("bias -100 on ' Paris'", {tuple(paris): -100.0})]:
    out = model.generate(**inputs, do_sample=False, max_new_tokens=8, sequence_bias=bias)
    print(f"[{label}] {tokenizer.decode(out[0, n:])!r}")
Output3 lines
' Paris' is token id [12095]
[no bias] ' Paris, France. The tower is '
[bias -100 on ' Paris'] ' Le Havre, France. The tower'

With " Paris" banned, the model didn't refuse or hedge. It confidently produced the next most likely city, Le Havre, which is wrong, and continued the sentence as if nothing had happened. That's the lesson of logit bias:

  • It works on tokens, not words or meanings. Banning " Paris" doesn't ban "Paris" without a space, "PARIS" or "Par" + "is". To reliably suppress a word you'd have to find every token sequence that can spell it.
  • The model routes around it, often by producing something worse, as here.
  • It's best for narrow, mechanical jobs: forcing a choice between a few single-token labels (bias them up), or suppressing a specific token that keeps appearing. For "only output one of these labels", structured outputs with an enum are now the more robust tool (Part 9).

11.4 Sampling and hallucination#

Sampling interacts with hallucination (lesson 10) in three ways:

1. Sampling can pick a wrong token, and the model then commits to it. In 5.2, "Ulm" had only 35% probability. At temperature 1, the model would start a different answer about two times in three, and then fluently continue as if that were true. Higher temperatures and loose truncation make this more likely.

2. But greedy decoding doesn't prevent hallucination. The model can be confidently wrong:

python
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

model_name = "Qwen/Qwen2.5-0.5B"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name, dtype=torch.float32)   # full precision on CPU

inputs = tokenizer("The Eiffel Tower was completed in 1889 and", return_tensors="pt")
n = inputs.input_ids.shape[1]
out = model.generate(**inputs, do_sample=False, max_new_tokens=11,     # greedy: always the top token
                     output_scores=True, return_dict_in_generate=True)

print("Greedy output:", repr(tokenizer.decode(out.sequences[0, n:])))
for step, token_id in enumerate(out.sequences[0, n:]):
    p = torch.softmax(out.scores[step][0], dim=-1)[token_id].item()
    print(f"   {tokenizer.decode(token_id)!r:14} p={p:.0%}")
Output12 lines
Greedy output: ' is the tallest man-made structure in the world. It'
   ' is'          p=24%
   ' the'         p=18%
   ' tallest'     p=71%
   ' man'         p=43%
   '-made'        p=93%
   ' structure'   p=90%
   ' in'          p=91%
   ' the'         p=97%
   ' world'       p=97%
   '.'            p=59%
   ' It'          p=29%

Greedy decoding stated that the Eiffel Tower "is the tallest man-made structure in the world", which hasn't been true since 1930, with " tallest" at 71% and most of the rest of the phrase at over 90%. The most likely continuation is the one that sounds most like the model's training text, not the one that's true. Lowering the temperature removes errors caused by sampling unlikely tokens (point 1), but it can't fix errors the model itself believes: the most likely continuation can be false. The logit-bias demo in 11.3 showed the same thing from another angle.

3. Sampling variation can help you detect hallucinations. If you ask the same factual question several times with sampling on, a model that "knows" the answer tends to give the same one each time, while a model that's guessing tends to give different answers. Comparing several samples for consistency (the idea behind methods such as SelfCheckGPT, and the same sampling trick that self-consistency voting uses to improve answers; see lesson 08, 11.1) is a practical hallucination signal that works even with models that don't expose logprobs. Low logprobs on key tokens are a similar signal where logprobs are available (5.3).

What actually reduces hallucination is mostly outside the sampler: grounding answers in retrieved documents (Module 07), tools (Module 08A), letting the model say "I don't know", and evaluation (Module 10A).


Common misconceptions#

Misconception Reality
"The model writes the whole answer at once." It generates one token per forward pass, each conditioned on everything before it, including its own earlier tokens (Part 1).
"Temperature makes the model smarter or more creative." Temperature only reshapes the probability distribution the sampler draws from. It doesn't change the model's knowledge or ability. High values mostly add randomness (3.3).
"Temperature 0 gives perfectly reproducible output." It's greedy decoding, but API outputs still vary because of batching and floating-point effects. On many current models you can't even set it (Part 7).
"Temperature 0 prevents hallucinations." Temperature 0 removes sampling-induced mistakes, not the model's own confident errors: the most likely continuation can be false (11.4).
"max_tokens tells the model how long to make its answer." It's a hard cut-off the model doesn't know about. The answer is truncated mid-sentence. Ask for length in the prompt (4.3).
"If the API returned 200 OK, the answer is complete." Check the finish reason. length, max_tokens, MAX_TOKENS or incomplete means truncated (4.5).
"Input and output tokens cost the same." Output tokens typically cost about 5× more, and reasoning tokens are billed as output (1.4).
"A frequency penalty fixes repetition safely." Penalties act on individual tokens and damage JSON, code and lists. Fix the prompt first (3.8).
"Logprobs tell you whether an answer is true." They tell you how confident the model was, and chat models are often overconfident (5.3).
"Structured outputs guarantee correct data." They guarantee the structure. The values can still be wrong (9.3).
"Streaming makes generation faster." Total time is the same. Streaming improves perceived speed by showing text after the time to first token (Part 8).
"Every provider supports temperature and top_p." As of November 2026, current Claude models reject them, newer Gemini models ignore them, and GPT-6 models accept them only with reasoning off (6.1).

Key takeaways#

  • An LLM outputs one probability distribution per forward pass. A separate sampler picks a token, the token is appended, and the loop repeats: autoregressive generation. Every choice is final.
  • Prefill processes the whole prompt in parallel and sets the time to first token. Decode generates one token per sequential, memory-bound pass and sets tokens per second. That's why output tokens are slower and cost about 5× more than input tokens, and why shorter outputs are the biggest latency and cost lever.
  • Greedy decoding takes the top token: deterministic locally, but prone to loops and bland text. Sampling draws at random in proportion to probability.
  • Temperature divides logits before softmax: below 1 sharpens, above 1 flattens, and 0 means greedy. Top-k, top-p and min-p cut off the unlikely tail. Min-p adapts best to the model's confidence.
  • Presence, frequency and repetition penalties push down tokens already used. They work on tokens, not ideas, so they harm JSON and code.
  • Beam search keeps several candidate sequences, but produces bland text, costs more and can't stream, so chat APIs don't offer it. Seeds make local sampling reproducible.
  • Generation stops at an EOS token, a stop sequence, max output tokens or the context limit. Always check the finish reason: truncated output (length, max_tokens, MAX_TOKENS, incomplete) is not a complete answer.
  • Logprobs show the model's confidence per token and enable cheap classification and uncertainty flags, but confidence isn't truth, and only OpenAI (reasoning off), OpenRouter (some models) and possibly some Gemini models expose them.
  • As of November 2026, frontier closed models have largely removed sampling controls. Claude rejects temperature/top_p/top_k, newer Gemini models ignore them, and GPT-6 allows them only with reasoning effort none. Open-weight models (for example through OpenRouter) still expose everything.
  • API output isn't deterministic even at temperature 0, mainly because of batching. Cache outputs you need to repeat, pin model versions and test over several runs.
  • Streaming sends tokens as they're generated, improving perceived latency at the cost of handling partial output and mid-stream errors.
  • Constrained decoding masks illegal tokens so output always matches a schema or grammar. It's how structured outputs work, and it guarantees structure, not correctness.
  • Change temperature or top_p, not both, leave defaults alone unless you can measure the effect, and tune with evaluations.

Terms introduced in this lesson#

Term One-line definition
Autoregressive generation Producing text one token at a time, each predicted from all the previous tokens, including generated ones
Decoding / sampling Choosing the next token from the model's probability distribution
Sampler The code that turns logits into a chosen token (temperature, truncation, penalties, random draw)
Prefill Processing the whole prompt in one parallel forward pass before generating
Decode (phase) Generating output tokens one sequential forward pass at a time
KV cache Stored intermediate results for earlier tokens, so each decode step only computes the new token (introduced in lesson 04)
Time to first token (TTFT) Time from sending a request to receiving the first output token
Tokens per second (TPS / OTPS) How fast output tokens are generated once generation has started
Throughput Total tokens a server produces per second across all users
Greedy decoding Always choosing the single most likely token
Pure (ancestral) sampling Drawing a token at random in proportion to its probability
Temperature A setting that divides logits before softmax, making the distribution sharper (below 1) or flatter (above 1)
Top-k sampling Sampling only from the k most likely tokens
Top-p (nucleus) sampling Sampling from the smallest set of tokens whose probabilities add up to p
Min-p sampling Sampling only from tokens at least min_p times as likely as the top token
Presence penalty A flat logit reduction for every token that has already appeared
Frequency penalty A logit reduction proportional to how many times a token has appeared
Repetition penalty A multiplicative penalty on the scores of tokens already seen
Beam search Decoding that keeps several best partial sequences and returns the most probable complete one
Seed The starting value of a random number generator; the same seed reproduces the same random choices
EOS token A special end-of-sequence token the model generates to signal that it's finished
Stop sequence A string that ends generation when the model produces it
Max output tokens A hard cap on the number of generated tokens (including reasoning tokens)
Verbosity (parameter) A request setting (low, medium, high) that asks the model for shorter or longer answers, offered by OpenAI and passed through by OpenRouter
Finish reason / stop reason The field telling you why generation stopped
Tool call (function call) A structured request the model writes (a tool name plus JSON arguments) before stopping; your code runs the tool and sends the result back as a new message (4.7)
Logprob The natural log of the probability the model gave a token; 0 is certain, more negative is less likely
Calibration How well a model's stated probabilities match how often it's actually right
Streaming / SSE Sending output to the client piece by piece as it's generated, usually as server-sent events
Constrained decoding Masking illegal tokens during sampling so output must follow a schema or grammar
Logit bias A fixed amount added to specific tokens' logits to encourage or ban them
Speculative decoding A drafter guesses several tokens and the big model verifies them in one pass, speeding up decoding without changing the output distribution
Continuous batching Serving many requests together, adding and removing them from the batch at every step
Best-of-N Generating several samples and picking one with a scorer, test suite or verifier
Self-consistency (preview; defined in lesson 08) Sampling several reasoning paths and taking a majority vote over their final answers
Entropy A single number measuring how spread out a probability distribution is: high entropy means uncertain

All terms are also collected in the glossary.


Exercises#

Run the code from this lesson and experiment:

  1. Next-token distributions (2.2): find a prompt where the top token has more than 95% probability, and one where it has less than 2%. What kinds of text produce each?
  2. Temperature (3.3): add T = 0.05 and T = 3.0 to the temperature demo. How many tokens cover 90% of the probability at each? Then run the coffee-shop sampling demo at T = 0.05. How do the three samples compare with greedy decoding?
  3. Truncation (3.7): change min_p to 0.05 and 0.2, and top_p to 0.5. Which setting keeps " Paris" alone on the peaked prompt while still allowing at least 10 options on the flat one?
  4. Penalties (3.8): run the penalty demo with presence_penalty=-1.0. What happens, and why? Then try a frequency penalty of 2.0 and look for broken words or formatting.
  5. Stop sequences (4.4): change the stop sequence to "\n". What does the output become, and when would that be useful?
  6. Logprob classification (5.3): add a " neutral" label to the classifier, plus a neutral example to the few-shot prompt. Check that each label's first token is different. Which review moves to neutral, and how much of the probability now lands on the three labels?
  7. Constrained decoding (9.1): change the allowed tokens so that the answer must be either "yes" or "no" (hint: find the token IDs for "yes" and "no"). Ask the model a yes/no question.
  8. Speculative decoding (11.1): in the prompt-lookup demo, replace the code-editing request with "Write a haiku about the sea". Does prompt lookup still speed things up? Why not?
  9. Provider matrix (6.2): pick a model on OpenRouter and look up its supported_parameters in https://openrouter.ai/api/v1/models. Which sampling parameters from this lesson does it support?
  10. Truncation handling (4.6): write a function that takes any provider's response object and returns "complete", "truncated", "refused" or "tool_call", using the finish-reason table.
Hints and what you should see
  1. Near-certain steps are facts with one famous completion ("The Eiffel Tower is in the city of") or the middle of a word. Flat steps are open starts such as "I opened the fridge and grabbed a" or "My favourite thing about". Only the prompts' shape matters; exact percentages depend on the model.
  2. At T = 0.05 expect 1 token to cover 90% (it is effectively greedy), and at T = 3.0 expect far more than the 5,670 you saw at T = 1.5, because the distribution is almost flat. The three T = 0.05 coffee-shop samples should be near-identical to each other and close to the greedy output.
  3. On the peaked prompt the runner-up (" Le") has only 1.9%, so min_p 0.05, 0.1 and 0.2 and top_p 0.5 all keep " Paris" alone. On the flat prompt the top ten tokens cover only 41%, so every one of these settings keeps at least ten options. The settings differ most on a prompt of medium confidence, so test a third prompt of your own to see where each rule starts to cut.
  4. A negative presence penalty rewards tokens that have already appeared, so expect the same loop or a worse one, with about 22 distinct tokens or fewer (the exact text depends on your run). A frequency penalty of 2.0 pushes the model away from even the tokens it needs (digits, "." and common words), so look for odd synonyms, broken list numbering or half-words.
  5. The output stops at the first line break, so you get just the answer, for example Rome. That is useful for single-line answers in few-shot prompts and for line-oriented formats.
  6. Add an example such as Review: It's fine, nothing special.\nSentiment: neutral to examples, and extend labels and label_ids. The lukewarm review ("The colour is fine, I guess") is the one most likely to move to neutral, and the share of probability that lands on the label tokens should rise above the 59% you saw with two labels (your exact numbers will differ; the separate check in 5.3 found " neutral" at about 30% before you added the example).
  7. Use tokenizer.encode(" yes") and tokenizer.encode(" no") (note the leading space) and print the results. If a label is more than one token, allow only its first token, as in 5.3. End the prompt with Answer (yes or no): so the next token is a label.
  8. Expect little or no speed-up: a haiku does not repeat the prompt, so prompt lookup finds nothing to draft and every step costs one normal forward pass. The output is still identical to normal decoding, which is the guarantee speculative decoding gives.
  9. There is no single right answer. Open-weight chat models usually list top_k, min_p and repetition_penalty; Claude and recent Gemini models list none of them, which is the point of 6.1.
  10. A sketch: map OpenAI finish_reason stop to complete, length to truncated, content_filter to refused and tool_calls to tool_call; Anthropic end_turn/stop_sequence, max_tokens/model_context_window_exceeded, refusal, tool_use; Gemini STOP (check for a function_call part first), MAX_TOKENS, the safety reasons. Return a separate value for anything you do not recognise instead of guessing.

Check yourself#

  1. Why does generating a 1,000-token answer take much longer than reading a 1,000-token prompt?
  2. What's the difference between the model and the sampler? Which one does temperature affect?
  3. What does temperature do mathematically, in words? What happens at T = 0.2 and at T = 1.5?
  4. A model's next-token distribution has one token at 85%. How many tokens would min_p=0.1 keep, roughly, and why?
  5. Why can top-k be "wrong in both directions"?
  6. What's the difference between a presence penalty and a frequency penalty? Why shouldn't you use either for JSON output?
  7. Why don't chat APIs offer beam search?
  8. Name four reasons generation can stop, and say which of them mean the answer may be incomplete.
  9. Your Claude request returns stop_reason: "max_tokens", and the JSON in it won't parse. What happened, and what should your code do?
  10. A token has a logprob of −0.1, and another has −2.3. Roughly what probabilities are these?
  11. How can you use logprobs to classify a review as positive or negative with one API call?
  12. Your team's code sends temperature=0 to claude-sonnet-5-5 and gets a 400 error. Why, and what should you do instead?
  13. Why can two identical temperature-0 requests to an API return different answers?
  14. What does streaming improve, and what does it make harder?
  15. How does constrained decoding guarantee valid JSON, and what doesn't it guarantee?
  16. Why can speculative decoding make generation faster without changing the output?

Further resources#


← 02.4 — Attention and Transformers | Module 02 overview | 02.6 — How LLMs Are Trained →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close