Unit 5 of 9

Generation is a loop, not one pass

  • 50 min
  • Reading, walkthrough, and knowledge check

What you’ll learn

  • Turn a model’s logits into next-token probabilities with softmax, and pick the greedy token.
  • Predict, with numbers, how temperature, top-k, and top-p reshape the distribution, and explain why temperature 0 means greedy selection.
  • Explain what a random seed guarantees and why a busy server can still answer the same request differently.
  • Configure end tokens, stop strings, and token limits, and tell from the finish reason which one ended a response.
  • Stream text without broken characters or leaked stop strings.

One forward pass, one next token

Send Llama 3.1 8B Instruct the prompt “Write a haiku about the sea” three times and you may get three different poems. Ask for a long answer and it may stop in the middle of a sentence. Stream the reply to a browser and an emoji may arrive as two question-mark boxes. None of these are model bugs. They come from the loop that wraps the model.

A forward pass through the model produces one thing you can use: a score for every possible next token. To write a 200-token answer, the engine runs the model 200 times, picks one token after each pass, and feeds it back in. The rules for picking (sampling), for ending (stop conditions), and for sending text to the user (streaming) belong to the inference engine, not the model.

By the end of this lesson you will be able to compute next-token probabilities by hand, predict what temperature, top-k, and top-p do to them, explain when outputs repeat and when they do not, and stream text safely.

The generation loop

Generation is autoregressive: each new token depends on every token before it, so token 3 cannot be chosen until tokens 1 and 2 exist. Each pass is highly parallel inside, but the passes themselves run one after another.

Token IDsprompt, then prompt + outputForward passevery layer, onceLogitslast position: 128,256 scoresChoose a tokengreedy or sampledStop checkend token, stop string, limitFinishreturn a finish reasonAppend and streamthe token becomes inputstopcontinuenext pass
The generation loop. Each pass yields one distribution over the vocabulary; the engine picks a token, checks the stop rules, and either finishes or feeds the token back in.

The model’s output has one row of scores, called logits, for every position it processed. Only the last row predicts something new: row i scores the token that should follow position i, so for the positions inside the prompt it only restates what is already there. For Llama 3.1 8B, the last row holds 128,256 logits, one per vocabulary entry.

The first output token comes from the prefill pass over the whole prompt. Every later token needs one decode pass. So an answer of N tokens costs 1 prefill and N − 1 decode passes, and N sampling decisions. In this lesson each pass conceptually sees the whole sequence so far; the KV cache lesson shows how engines avoid recomputing the earlier positions.

How LLMs work · Watch on YouTube

From logits to probabilities, and the greedy choice

Logits are raw scores: any real number, higher meaning more likely. Softmax turns them into probabilities: exponentiate each logit, then divide by the total, so every value is positive and they sum to 1.

To keep the arithmetic short, pretend the model’s vocabulary has only four tokens and it has just read “The sky is”. The token IDs are Llama 3.1’s, ␣ marks the leading space that is part of each token, and the logits are illustrative.

Softmax over four candidates (illustrative logits)

  1. Logits for ␣blue (6437), ␣clear (2867), ␣dark (6453), ␣falling (16054)2.0, 0.9, 0.6, −0.5
  2. Exponentiatee^2.0 = 7.39, e^0.9 = 2.46, e^0.6 = 1.82, e^−0.5 = 0.61
  3. Total7.39 + 2.46 + 1.82 + 0.61 = 12.28
  4. Divide each by the total0.60, 0.20, 0.15, 0.05

Result␣blue is the most likely next token, with probability 0.60

Greedy decoding always takes the highest-probability token, here ␣blue. It needs no randomness, so the same logits always give the same token. It is the right choice for tasks with one correct answer, such as extraction or classification. For open-ended writing it tends to repeat itself, because it never takes the second-best path.

Real engines subtract the largest logit from every logit before exponentiating. Shifting all logits by the same amount does not change the probabilities, because the shift cancels in the division, but it keeps e^x from overflowing when logits are large.

Temperature, top-k, and top-p

Sampling draws a token at random according to the probabilities, so ␣blue appears about 60% of the time and ␣falling about 5%. Three settings reshape the distribution before the draw.

Temperature divides every logit by a number T before the softmax. T below 1 stretches the gaps between logits, so the top token gets more of the probability. T above 1 shrinks the gaps and spreads probability toward the tail. T = 1 leaves the distribution as the model produced it.

0%25%50%75%100%T = 0.5T = 0.5: blue, 84.9%blueT = 0.5: clear, 9.4%clearT = 0.5: dark, 5.2%T = 0.5: falling, 0.6%100%T = 1T = 1: blue, 60.2%blueT = 1: clear, 20%clearT = 1: dark, 14.8%darkT = 1: falling, 4.9%100%T = 2T = 2: blue, 42.4%blueT = 2: clear, 24.5%clearT = 2: dark, 21%darkT = 2: falling, 12.1%falling100%bluecleardarkfallingIllustrative values, not measurements.
The same four logits at three temperatures. Lower temperature concentrates probability on ␣blue; higher temperature spreads it across the other tokens.

Temperature 0.5 on the same logits

  1. Divide the logits by 0.54.0, 1.8, 1.2, −1.0
  2. Exponentiate54.60, 6.05, 3.32, 0.37 (total 64.34)
  3. Divide by the total0.85, 0.09, 0.05, 0.01

Result␣blue rises from 0.60 to 0.85

Now push T toward 0. At T = 0.1 the logits become 20, 9, 6, and −5, and ␣blue’s probability is above 0.9999. In the limit, all probability sits on the top token, which is exactly greedy decoding. Dividing by zero is undefined, so engines treat temperature 0 as a request for greedy selection. vLLM switches to greedy below a temperature of 0.00001. Transformers rejects temperature 0 when sampling is on and asks you to set do_sample=False instead.

Top-k keeps only the k most likely tokens, sets the rest to zero, and renormalizes. Top-p, also called nucleus sampling, sorts tokens by probability and keeps the smallest set whose probabilities add up to at least p, including the token that crosses p. Top-p adapts to the shape of the distribution: when the model is confident it keeps few tokens, and when it is unsure it keeps many.

Top-k and top-p on the T = 1 probabilities 0.60, 0.20, 0.15, 0.05

  1. Top-k with k = 2: keep ␣blue and ␣clear0.60 + 0.20 = 0.80
  2. Renormalize0.60 / 0.80 = 0.75 and 0.20 / 0.80 = 0.25
  3. Top-p with p = 0.9: running totals0.60, then 0.80, then 0.95, which crosses 0.9
  4. Keep the first three and renormalize by 0.950.63, 0.21, 0.16

ResultEither filter removes ␣falling; top-p keeps ␣dark as well

Order matters. vLLM applies penalties first, then temperature, then min-p (which drops tokens less likely than a set fraction of the top token’s probability), then top-k and top-p, then draws. Because top-p runs after temperature, the same p keeps a different number of tokens at each temperature.

Engines also offer repetition penalties, which lower the logits of tokens the request has already used. A frequency penalty of 0.5 subtracts 0.5 for each earlier use, so a logit of 2.0 for a token used three times drops to 0.5. A presence penalty subtracts once for any earlier use. A repetition penalty of 1.2 divides positive logits by 1.2 and multiplies negative ones by 1.2, so 2.0 becomes 1.67 and −0.5 becomes −0.6.

Seeds, and why the same request can give different answers

A sampler draws from a pseudo-random number generator. A seed sets that generator’s starting state, so the same seed with the same probabilities produces the same sequence of draws. Seeding makes sampling repeatable; it does not make it less random.

Two details trip people up. A generator is a stream: each draw consumes it, so calling generate twice on the same seeded generator gives two different completions, and the second depends on the first. And re-seeding before every token repeats the same random number at every step, which quietly biases every choice the same way.

Greedy decoding needs no random numbers, yet a busy server can still return different greedy answers to the same request. The logits themselves can change: GPU kernels add numbers in an order that depends on the batch size and on which other requests share the batch, and floating-point addition gives slightly different results in different orders. When two tokens are nearly tied, a difference in the last bits flips the choice, and every later token follows the new path.

vLLM 0.28.0 states this plainly: it does not guarantee reproducible results by default, for the sake of performance. Its batch-invariant mode (VLLM_BATCH_INVARIANT=1, on NVIDIA GPUs of compute capability 8.0 or higher) makes outputs independent of batch size and order at some cost in speed, and even then reproducibility holds only on the same hardware and the same vLLM version.

Stop conditions: end tokens, stop strings, and limits

A model never decides to stop on its own. It emits tokens, and the engine ends the loop when one of these rules fires:

  • An end token. Chat models end a turn with a special token. Llama 3.1 8B Instruct’s generation_config.json lists three: 128001 (<|end_of_text|>), 128008 (<|eom_id|>), and 128009 (<|eot_id|>, the end of a turn). The engine stops when the model produces any of them and does not show them as text.
  • A stop string. The application asks to stop at text such as "\n\nUser:". Stop strings are matched on the decoded text, so they can span several tokens. vLLM leaves the stop string out of the output unless you set include_stop_str_in_output.
  • A token limit. max_tokens caps the number of generated tokens. Generation also stops when prompt plus output reaches the model’s context window.
  • Cancellation or an error. A client that disconnects should abort the request, and every exit path must free its memory and close the stream.

OpenAI-compatible servers report which rule fired as a finish reason. In vLLM, stop means an end token or a stop string, and length means max_tokens was used up or the context window was reached. A reply that ends mid-sentence with length is not a model failure; the limit was too small.

Stream text without broken characters or leaked stop strings

Streaming sends each token’s text to the client as soon as it is chosen. Two things make that harder than printing each token.

First, tokens are pieces of bytes, not characters. Llama 3.1’s tokenizer is byte-level: common characters have their own tokens, but a character that takes several bytes in UTF-8 can be split across tokens. In “Café ☕”, token 26182 holds a space plus the first two of the emoji’s three bytes, and token 243 holds the last byte. Decode each token on its own and the emoji becomes two replacement characters (�).

Token bytesC34af2642C3 A997820 E2 982618295243Decode eachCafé␣ ��IncrementalCafé␣☕holds E2 98broken charactercompleted character
Llama 3.1’s tokens for “Café ☕”. Decoding each token alone breaks the emoji; an incremental decoder holds the incomplete bytes until the next token completes the character.

The fix is an incremental decoder: keep bytes that do not yet form a whole character and release them when the rest arrives. The Hugging Face tokenizers library does this in DecodeStream, which vLLM uses; it holds back output while the decoded text ends in an incomplete character.

Second, stop strings arrive in pieces too. If the stop string is “\n\nUser:” and the model has produced “\n\nUs” so far, you cannot send those characters yet: the next token might complete the stop string, and then the client would already have text it should never see. Hold back any tail of the text that could still grow into a stop string, and release it as soon as it cannot.

stream_safely.py
import codecs

# Byte pieces of Llama 3.1's tokens for "Café ☕" (IDs 34, 2642, 978, 26182, 243).
pieces = [b"C", b"af", b"\xc3\xa9", b" \xe2\x98", b"\x95"]
naive = [piece.decode("utf-8", errors="replace") for piece in pieces]
print("decode each token:", naive, "->", "".join(naive))
decoder = codecs.getincrementaldecoder("utf-8")()
safe = [decoder.decode(piece) for piece in pieces]
print("incremental:      ", safe, "->", "".join(safe))


def pending_stop(text, stop):
    """Length of the longest tail of text that could still grow into stop."""
    for size in range(min(len(stop) - 1, len(text)), 0, -1):
        if stop.startswith(text[-size:]):
            return size
    return 0


stop = "\n\nUser:"
text, sent = "", 0
for chunk in ["The answer is 42.", "\n\n", "Usually", " yes.", "\n\n", "User", ":"]:
    text += chunk
    if stop in text:
        end = text.index(stop)
        print(f"{chunk!r:>20} -> send {text[sent:end]!r}, then stop")
        break
    safe_end = len(text) - pending_stop(text, stop)
    print(f"{chunk!r:>20} -> send {text[sent:safe_end]!r}, hold {text[safe_end:]!r}")
    sent = safe_end
You should see
decode each token: ['C', 'af', 'é', ' �', '�'] -> Café ��
incremental:       ['C', 'af', 'é', ' ', '☕'] -> Café ☕
 'The answer is 42.' -> send 'The answer is 42.', hold ''
              '\n\n' -> send '', hold '\n\n'
           'Usually' -> send '\n\nUsually', hold ''
             ' yes.' -> send ' yes.', hold ''
              '\n\n' -> send '', hold '\n\n'
              'User' -> send '', hold '\n\nUser'
                 ':' -> send '', then stop

Read the output from the top. Decoding each token separately shows two � characters; the incremental decoder returns an empty string for the incomplete bytes and then the whole ☕. In the stop-string run, “\n\n” is held because it could start “\n\nUser:”. When “Usually” arrives it cannot, so the held text is released. The second “\n\n” and “User” are held, the “:” completes the stop string, and the client never sees any of it.

vLLM uses a simpler rule with the same guarantee: while a request runs, it holds back the last (length of the longest stop string − 1) characters, and releases them when the request finishes.

Try it: sampling by hand and a whole generation loop

The script below reproduces every number in this lesson’s sampling examples and then draws 10,000 samples to show that the random choices follow the probabilities. You need Python 3.9 or later and NumPy.

sampling_by_hand.py
import numpy as np

tokens = [" blue", " clear", " dark", " falling"]
logits = np.array([2.0, 0.9, 0.6, -0.5])


def probabilities(z, temperature=1.0):
    z = (z - z.max()) / temperature  # the shift changes nothing but avoids overflow
    e = np.exp(z)
    return e / e.sum()


def top_p_keep(p, top_p):
    order = np.argsort(-p)
    before = np.cumsum(p[order]) - p[order]  # mass ranked above each token
    return order[before < top_p]              # keeps the token that crosses top_p


np.set_printoptions(precision=3, suppress=True)
print("greedy pick:", repr(tokens[int(np.argmax(logits))]))
for t in (0.5, 1.0, 2.0):
    print(f"T={t}:", probabilities(logits, t))
p = probabilities(logits)
top2 = np.argsort(-p)[:2]
print("top-k=2 keeps:", [tokens[i] for i in top2], p[top2] / p[top2].sum())
kept = top_p_keep(p, 0.9)
print("top-p=0.9 keeps:", [tokens[i] for i in kept], p[kept] / p[kept].sum())

rng = np.random.default_rng(42)
draws = rng.choice(len(tokens), size=10_000, p=p)
print("share of 10,000 draws:", np.bincount(draws, minlength=4) / 10_000)
print("seed 7 twice:", np.random.default_rng(7).choice(4, 5, p=p),
      np.random.default_rng(7).choice(4, 5, p=p))
You should see
greedy pick: ' blue'
T=0.5: [0.849 0.094 0.052 0.006]
T=1.0: [0.602 0.2   0.148 0.049]
T=2.0: [0.424 0.244 0.21  0.121]
top-k=2 keeps: [' blue', ' clear'] [0.75 0.25]
top-p=0.9 keeps: [' blue', ' clear', ' dark'] [0.633 0.211 0.156]
share of 10,000 draws: [0.607 0.2   0.143 0.049]
seed 7 twice: [1 2 1 0 0] [1 2 1 0 0]

The three temperature rows match the figure. The 10,000 draws land close to 0.60, 0.20, 0.15, and 0.05, but not exactly: that gap is sampling noise, and it shrinks as you draw more. The last line shows two generators created with seed 7 producing identical draws. If your draw shares differ from these by more than about 0.01, check that you seeded with 42.

The second script puts the whole loop together. A lookup table stands in for the model: it returns next-token logits that depend only on the last token, which is enough to exercise everything the engine owns. The loop calls the model, chooses a token with temperature and top-p, stops on the end token or on max_tokens, and returns the text with a finish reason:

generation_loop.py
import numpy as np

vocab = ["<end>", "The", " sky", " sea", " is", " blue", " calm", " grey", "."]
END = 0
# A stand-in for the model: next-token logits that depend only on the last token.
table = np.full((len(vocab), len(vocab)), -4.0)
for prev, nxt, score in [(1, 2, 3.0), (1, 3, 2.0), (2, 4, 4.0), (3, 4, 4.0),
                         (4, 5, 2.0), (4, 6, 1.2), (4, 7, 0.8), (5, 8, 3.0),
                         (6, 8, 3.0), (7, 8, 3.0), (8, 0, 4.0)]:
    table[prev, nxt] = score


def model(ids):  # one forward pass: scores for the next token only
    return table[ids[-1]]


def choose(logits, temperature, top_p, rng):
    if temperature == 0:
        return int(np.argmax(logits))  # greedy
    z = (logits - logits.max()) / temperature
    p = np.exp(z) / np.exp(z).sum()
    order = np.argsort(-p)
    keep = order[np.cumsum(p[order]) - p[order] < top_p]
    return int(rng.choice(keep, p=p[keep] / p[keep].sum()))


def generate(prompt, max_tokens, temperature=0.0, top_p=1.0, rng=None):
    ids = list(prompt)
    for _ in range(max_tokens):
        token = choose(model(ids), temperature, top_p, rng)
        if token == END:  # stop on the end token; never show it
            return "".join(vocab[i] for i in ids), "stop"
        ids.append(token)
    return "".join(vocab[i] for i in ids), "length"


print("greedy:        ", generate([1], max_tokens=10))
print("greedy, max 2: ", generate([1], max_tokens=2))
rng = np.random.default_rng(3)  # seed once per request, not once per token
for run in range(4):  # the stream advances, so each run can differ
    print(f"T=1.0 run {run}:", generate([1], 10, 1.0, 0.95, rng))
print("reseeded run 0:", generate([1], 10, 1.0, 0.95, np.random.default_rng(3)))
You should see
greedy:         ('The sky is blue.', 'stop')
greedy, max 2:  ('The sky is', 'length')
T=1.0 run 0: ('The sky is calm.', 'stop')
T=1.0 run 1: ('The sky is blue.', 'stop')
T=1.0 run 2: ('The sky is blue.', 'stop')
T=1.0 run 3: ('The sea is calm.', 'stop')
reseeded run 0: ('The sky is calm.', 'stop')

Greedy decoding follows the highest score at every step and always writes “The sky is blue.”, then stops with stop because the model produced the end token, which never appears in the text. With max_tokens=2 the same loop is cut off after two new tokens and reports length. The sampled runs share one generator seeded once, so its random stream advances and the runs differ: after “ is” the loop picks “ blue” about 57% of the time and “ calm” about 26%. Top-p at 0.95 removes the near-zero tokens before each draw, so no run ever wanders into a word the table scores at −4. A new generator with the same seed repeats run 0 exactly.

Common mistakes

Symptoms you may see, their usual cause, and the fix
SymptomLikely causeFix
The first generated token ignores most of the promptThe token was chosen from the logits of an early position instead of the last.Use the last position: logits[:, -1, :].
A division-by-zero error or NaN at temperature 0The code divided by the temperature without special-casing 0.Treat temperature 0 as greedy: take the argmax.
Sampling keeps too few tokens, sometimes noneTop-p dropped the token that crosses p, or ran on logits instead of probabilities.Softmax first, then keep tokens until the running total reaches p, including the one that crosses it.
The same odd word keeps appearingThe random generator is re-seeded before every token.Seed once per request and let the stream advance.
Replies stop at exactly 16 tokens in vLLM’s offline APISamplingParams defaults max_tokens to 16.Set max_tokens for every request.
The model writes past the end of its turnThe end-of-turn token (128009 for Llama 3.1 Instruct) is not in the stop list.Use the end tokens from generation_config.json.
Users see � in streamed textEach token was decoded on its own.Use an incremental decoder that holds incomplete characters.
Part of a stop string flashes on screen, then the stream endsText was sent before the stop check could see the whole stop string.Hold back any tail that could still become a stop string.

How real engines sample and stop

  • Per-request settings, one batch. vLLM’s sampler takes the logits of every request in the batch at once, converts them to FP32, and applies each request’s own penalties, temperature, top-k, top-p, and min-p. A request with a seed draws from its own generator, so its draw does not depend on its neighbors, though its logits still can.
  • Parameter conventions. In vLLM 0.28.0, temperature=0 means greedy, top_k=0 (or −1) and top_p=1 turn those filters off, and max_tokens defaults to 16 in SamplingParams. In Transformers, greedy is do_sample=False, and the documented default top_k is 50 when the model’s generation config does not set one.
  • Defaults from the model. Llama 3.1 8B Instruct’s generation_config.json sets sampling on, with temperature 0.6 and top-p 0.9. vLLM loads that file by default (--generation-config auto), so a chat request that omits temperature samples at 0.6. Pass --generation-config vllm to use vLLM’s neutral defaults instead.
  • Stop handling. vLLM checks end tokens on token IDs, matches stop strings on the incrementally decoded text, and reports stop or length as the finish reason.

When outputs surprise you, log the effective sampling parameters of the request, not the ones you meant to send, along with the finish reason and the number of generated tokens. Check for a changed default, a missing end token, or a small token limit before you suspect the model.

Go deeperWhy the order of additions changes results

Floating-point numbers keep a fixed number of significant bits, so a large and a small number added together lose the small one. The result then depends on the order of the additions. In FP32:

addition_order.py
import numpy as np

values = np.array([1e8, 1.0, -1e8, 1.0], dtype=np.float32)
print("left to right:", (values[0] + values[1]) + values[2] + values[3])
print("pairs first:  ", (values[0] + values[2]) + (values[1] + values[3]))
You should see
left to right: 1.0
pairs first:   2.0

Adding 1 to 100,000,000 in FP32 rounds back to 100,000,000, so the first order loses one of the 1s. A matrix multiplication sums thousands of products, and GPU kernels choose how to split those sums based on the matrix shapes, which include the batch size. Different splits give logits that differ in the last bits, and a near-tie between two tokens can then go either way. Batch-invariant kernels fix the split so it no longer depends on the batch, which is why they cost some speed.

Cheat sheet

  • One forward pass gives one distribution; an N-token answer needs N passes and N choices.
  • Use the logits of the last position. Softmax: exponentiate, divide by the total. Only differences between logits matter.
  • Greedy takes the argmax. Temperature 0 is the conventional way to ask for it; in Transformers use do_sample=False.
  • Temperature divides logits by T: below 1 sharpens, above 1 flattens. Top-k keeps k tokens; top-p keeps the smallest set reaching p.
  • vLLM order: penalties, temperature, min-p, top-k and top-p, then the draw.
  • A seed makes draws repeatable, not the logits. Busy servers are not reproducible by default.
  • Stop on the model’s end tokens, stop strings, and max_tokens; read the finish reason.
  • Stream with an incremental decoder and hold back any possible start of a stop string.

Walkthrough

Follow one decode step from logits to a streamed token

Request traceReady

Knowledge check

What does temperature 0 conventionally request?

Choose one answer

Sources and further reading

Finished this unit?