Suryanand/ Bootcamp
suryanand.com ↗Let's talk
← FoundationsAI guideBeginner#foundations#sampling#decoding#llm-basics
Frame · ai-engineering / foundations / 02-how-llms-generate-text.mdGuide 002 / 103

How LLMs generate text

A large language model does one thing: given a sequence of tokens, it produces a score for every token in its vocabulary describing how likely each one is to come next. Everything else, chat, code, tool calls, reasoning, is that single step run in a loop. Once you understand the loop and the knobs that control which token gets picked, a lot of "weird model behavior" stops being mysterious.

Why it matters

Generation mechanics explain practical things you will hit in week one. Why the same prompt gives different answers on each run. Why output tokens are slower and pricier than input tokens. Why a model can confidently produce a plausible but wrong fact (the probable next token is not the true next token). Why setting temperature to 0 still does not guarantee identical outputs across runs. And why some newer models reject sampling parameters entirely.

How it works

The input text is split into tokens (see tokenization), each mapped to an integer id. The model, a transformer, processes the whole sequence and outputs a vector of logits at the final position: one raw score per vocabulary entry. A softmax turns logits into probabilities. A sampler picks one token from that distribution, the token is appended to the sequence, and the loop runs again. It stops when the model emits a stop token, hits a stop sequence you supplied, or reaches the max_tokens limit.

Rendering diagram…

Two phases have very different performance profiles. The prefill phase processes all input tokens in parallel, so it is relatively fast per token. The decode phase generates output tokens one at a time, each requiring a forward pass, which is why output tokens dominate latency and are priced higher by every major provider. Servers cache the attention keys and values from earlier positions (the KV cache) so each new token does not recompute the whole prefix.

The sampling knobs

  • Temperature divides the logits before the softmax. Below 1 it sharpens the distribution toward the top token, above 1 it flattens it. Temperature near 0 approaches greedy decoding: always pick the most likely token.
  • Top-k keeps only the k most likely tokens and renormalizes. It is a blunt cap on how far down the tail the sampler can reach.
  • Top-p (nucleus sampling) keeps the smallest set of tokens whose cumulative probability reaches p. When the model is confident, that set is tiny; when it is uncertain, the set grows. This adaptivity is why Holtzman et al. proposed it as an alternative to fixed top-k.

The practical rule: change one knob at a time, and usually only temperature. Provider support varies in 2026. OpenAI's reasoning model families reject temperature with an error, and developers report that recent Claude models return a 400 if you set both temperature and top_p, with the newest ones only accepting defaults. Check your model's docs, and if your client library sends default values for every parameter, turn that off.

Why temperature 0 is not deterministic

Even greedy decoding can vary between runs. Batched inference on GPUs uses floating point operations whose order depends on what else is in the batch, so tiny numeric differences can flip a near-tie between two tokens, and once one token differs, the rest of the sequence diverges. Treat outputs as samples from a distribution and design your evals accordingly.

Reference architecture

Here is what a single streaming request looks like from the server's point of view, which is useful when you reason about latency.

Rendering diagram…

Time to first token is mostly prefill plus queueing. Tokens per second after that is decode speed. Long prompts hurt the first number, long answers hurt the second.

Code

You rarely implement sampling yourself, but writing it once makes the knobs concrete. This is plain NumPy operating on a fake logits vector.

import numpy as np

rng = np.random.default_rng(0)

def sample(logits, temperature=1.0, top_k=None, top_p=None):
    logits = np.asarray(logits, dtype=np.float64)
    if temperature <= 0:
        return int(np.argmax(logits))  # greedy
    scaled = logits / temperature
    probs = np.exp(scaled - scaled.max())
    probs /= probs.sum()

    order = np.argsort(probs)[::-1]
    keep = np.ones_like(probs, dtype=bool)
    if top_k is not None:
        keep[order[top_k:]] = False
    if top_p is not None:
        cumulative = np.cumsum(probs[order])
        cutoff = np.searchsorted(cumulative, top_p) + 1
        keep[order[cutoff:]] = False

    probs = np.where(keep, probs, 0.0)
    probs /= probs.sum()
    return int(rng.choice(len(probs), p=probs))

vocab = ["Paris", "Lyon", "London", "banana"]
logits = [6.0, 3.5, 2.0, -1.0]
for t in (0.0, 0.7, 1.5):
    picks = [vocab[sample(logits, temperature=t, top_p=0.95)] for _ in range(10)]
    print(t, picks)

Run it and you will see temperature 0 always pick "Paris", 0.7 mostly pick it, and 1.5 wander into "Lyon" and "London". With top-p 0.95, "banana" never shows up because it sits outside the nucleus.

Trade-offs and pitfalls

  • Low temperature is not the same as correctness. It makes the model consistent, including consistently wrong.
  • High temperature for creativity also raises the rate of format errors. If you need valid JSON, use structured outputs rather than hoping.
  • max_tokens truncates silently from the model's point of view. Always check the stop reason (max_tokens versus end_turn or stop) before trusting an output.
  • Stop sequences are matched on generated text, so they can cut off inside something you wanted. Prefer structured formats over clever stop strings.
  • Reasoning models spend hidden or summarized tokens before answering. Those count toward output cost and latency even if you never show them (see reasoning models).
  • Sampling parameters are provider and model specific. A config that worked last quarter may be rejected by a newer model.

Checklist

  • You know whether your model accepts temperature, top-p and top-k, and you only send what you need.
  • Every response handler checks the stop reason.
  • max_tokens is set per task, not left at a huge default.
  • Evals run each prompt several times rather than once.
  • You measure time to first token and output tokens per second separately.
  • You never rely on temperature 0 for byte-identical outputs.

Further reading

Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.