Skip to content

LLM Field Guide 03 — Training and Generation: Where Weights Come From and How Tokens Get Picked

Every one of an 8B model's 8 billion weights starts as random noise and ends up useful because of one loop: predict the next token, measure the error, nudge every weight a tiny bit, repeat about a million times. At inference time the same model outputs a probability for every token in its vocabulary, and a sampler you configure per request picks one. This post works both halves with real numbers on "The cat sat": logits, loss, gradients, AdamW, the cost of a pretraining run, then temperature, top-p, min-p, constrained decoding, and why temperature=0 still isn't deterministic.

In this post:

LLM Field Guide — all 12 posts
  1. How an LLM reads text
  2. Inside the transformer
  3. Training and generation ← you are here
  4. KV cache and long context
  5. Prompting, context, and RAG
  6. Reasoning models and agents
  7. Choosing a base model
  8. Adapting a model
  9. Making it smaller and faster
  10. Serving at scale
  11. Safety and evaluation
  12. Putting it all together

Where this fits: Post 02 finished the forward pass: every matrix a token passes through. This post explains where the numbers in those matrices come from (pretraining) and what happens after the last layer at inference (sampling). Fine-tuning and RL (post 08) reuse the same training machinery with different data.

The training loop in one picture

          ┌──────────────────────────────────────────────────────────┐
          │                                                          │
 text ──► forward pass ──► logits ──► loss ──► backward pass ──► optimizer step
 batch    (post 02)        (scores)   (one     (gradient for       (nudge every
                                       number)  every weight)       weight)
          │                                                          │
          └───────────────────── repeat ~1,000,000× ─────────────────┘
Stage Question it answers Output
Loss How wrong was the prediction? one number
Backpropagation How much did each weight contribute to that wrongness? one gradient per weight
Optimizer (AdamW) Given those gradients, how far should each weight move? updated weights

Pretraining needs no human labels. The next token in real text is the label, which is why it's called self-supervised learning. Shift the sequence by one position and every token becomes a training example:

input:   The    cat    sat    on     the
target:  cat    sat    on     the    mat
         ↑      ↑      ↑      ↑      ↑
     5 predictions from one 6-token sentence, all computed in one forward pass

The causal mask (post 02) makes this legal: position 3 can't see position 4, so predicting it isn't cheating. A 4,096-token training sequence gives 4,095 next-token predictions for the price of one forward pass.

Logits: one score per vocabulary token

Output projection: final hidden state times the embedding table gives one logit per vocabulary token

After the last transformer block, "sat" has a final hidden vector. The language-model head multiplies it by a d × V matrix to get one raw score, a logit, for every token in the vocabulary. This is the model's entire output. Training grades these scores; generation samples from them.

In our toy model, d = 4 and we show 6 vocabulary rows. The final hidden state for "sat" is h_sat = [0.71, 0.63, 0.58, 0.52]. Each logit is h_sat dotted with that token's row. Here we reuse the toy embedding table from post 01 as the output matrix. That's called weight tying; some small models do it, while Llama 3.1 8B and Qwen3-8B keep separate input and output matrices12.

logit(" on") = [0.71, 0.63, 0.58, 0.52] · [0.7, 0.1, 0.4, 0.6]
             = 0.497 + 0.063 + 0.232 + 0.312 = 1.104

Softmax turns logits into probabilities that sum to 1:

P(tokenᵢ) = e^(logitᵢ) / Σⱼ e^(logitⱼ)
Token Logit e^logit Probability
"The" 1.104 3.016 14.7%
" cat" 1.517 4.559 22.3% ← model's top pick
" sat" 1.193 3.297 16.1%
" on" 1.104 3.016 14.7% ← correct answer
" the" 1.096 2.992 14.6%
" mat" 1.273 3.572 17.5%
sum = 20.452 100%

This untrained model is wrong. It favors " cat" and gives the right answer only 14.7%. A real model does this over the full vocabulary: 128,256 logits for Llama 3.1 8B, 151,936 for Qwen3-8B12.

Cross-entropy loss: turning "wrong" into one number

Cross-entropy loss: negative log of the probability assigned to the correct token

The loss for one prediction is the negative log of the probability given to the correct token:

L = −log P(correct token) = −log(0.1475) = 1.914
Situation P(correct) Loss
Perfect prediction 1.0 0
Our toy model 0.147 1.914
Confidently wrong 0.0001 9.21
Uniform guess over Llama 3's 128,256 tokens 1/128,256 11.76

An untrained model starts near ln(V), about 11.8 for a 128K–152K vocabulary. Watching the loss fall from ~11.8 toward 2 and below is what "training is working" looks like. Over a batch you average across every predicted position: L_batch = −(1/N) × Σ log P(correct_tokenᵢ).

You'll also see perplexity, which is just e^loss. A loss of 1.914 is a perplexity of 6.78: the model is as uncertain as if it were picking uniformly among about 7 tokens.

Why log? It punishes confident mistakes hard. Going from P = 0.01 to 0.001 costs as much loss (2.3) as going from 0.1 to 0.01. That forces the model never to put near-zero probability on things that actually happen, which is exactly the calibrated-guessing skill a language model needs.

Backpropagation: blame for every weight

Backpropagation: gradients flow from the loss back through every layer

The loss is one number; the model has billions of weights. Backpropagation uses the chain rule to compute, for every weight, how much the loss would change if that weight moved slightly. That's the weight's gradient.

At the output, the gradient of cross-entropy with respect to each logit has a clean form: P(tokenᵢ) − 1 for the correct token, P(tokenᵢ) for every other one.

Token P Gradient Meaning
"The" 0.147 +0.147 push down a bit
" cat" 0.223 +0.223 push down most (the wrong favorite)
" sat" 0.161 +0.161 push down
" on" 0.147 −0.853 push up hard
" the" 0.146 +0.146 push down
" mat" 0.175 +0.175 push down

The gradients sum to zero: probability taken from wrong tokens goes to the right one. The chain rule carries these numbers backward through the output matrix, then each block's FFN, attention, and norms, all the way to the embedding table.

The backward pass costs about 2× the forward pass, because each matmul needs two gradient matmuls (one for inputs, one for weights). Forward ≈ 2 FLOPs per parameter per token, backward ≈ 4, total ≈ 6 FLOPs per parameter per token. That rule prices the whole pretraining run below.

AdamW: turning gradients into updates

AdamW: momentum, adaptive scaling, and decoupled weight decay

Plain gradient descent does w ← w − lr × g. That's too noisy and too uniform for LLMs. AdamW is the standard LLM optimizer, and it adds three things:

m ← β₁·m + (1−β₁)·g            momentum: running average of gradients
v ← β₂·v + (1−β₂)·g²           running average of squared gradients
m̂ = m / (1−β₁ᵗ),  v̂ = v / (1−β₂ᵗ)   bias correction for early steps

w ← w − lr · m̂ / (√v̂ + ε)  −  lr · λ · w
         └─ adaptive step ─┘     └─ decoupled weight decay ─┘
Ingredient What it does Why LLMs need it
Momentum m Smooths gradients over steps One batch is noisy; the trend is signal
Adaptive scale √v Divides each weight's step by its typical gradient size Huge-gradient weights don't explode; rarely updated ones still move
Decoupled weight decay λ Shrinks weights toward zero, separately from the gradient Regularizes; L2 penalties and weight decay are not equivalent for Adam, hence the "W"3

LLM hyperparameters differ from PyTorch defaults (β₂ = 0.999, weight_decay = 0.01). LLaMA used β₁ = 0.9, β₂ = 0.95, weight decay 0.1, and gradient clipping at 1.04, and most open recipes since look similar.

One weight, one step, by hand

Take w = 0.50 with gradient g = −0.853, lr = 2×10⁻⁴, β₁ = 0.9, β₂ = 0.95, λ = 0.1, first step t = 1:

m  = 0.9×0 + 0.1×(−0.853)        = −0.0853
v  = 0.95×0 + 0.05×(0.853²)      =  0.0364
m̂  = −0.0853 / (1 − 0.9)         = −0.853
v̂  =  0.0364 / (1 − 0.95)        =  0.728      → √v̂ = 0.853

adaptive step = 2e-4 × (−0.853 / 0.853) = −0.0002
weight decay  = 2e-4 × 0.1 × 0.50       =  0.00001

w_new = 0.50 − (−0.0002) − 0.00001 = 0.50019

The weight moved by 0.0002. On step 1 the adaptive step is exactly lr in size: Adam normalizes the gradient's magnitude away and keeps its sign. Training is billions of weights each taking steps this small, about a million times.

This runs on a laptop CPU and reproduces every number in this section and the three before it:

# pip install "torch>=2.6"
import torch
import torch.nn.functional as F

vocab = ["The", " cat", " sat", " on", " the", " mat"]
E = torch.tensor([[1.0, 0.0, 0.5, 0.2],   # toy 6-token embedding / output table, d=4
                  [0.5, 1.0, 0.2, 0.8],
                  [0.2, 0.5, 1.0, 0.3],
                  [0.7, 0.1, 0.4, 0.6],
                  [0.9, 0.1, 0.5, 0.2],
                  [0.4, 0.9, 0.1, 0.7]])
h_sat = torch.tensor([0.71, 0.63, 0.58, 0.52])  # final hidden state for "sat"

logits = (E @ h_sat).detach().requires_grad_()
target = torch.tensor([3])                       # " on"
loss = F.cross_entropy(logits.unsqueeze(0), target)
loss.backward()

for t, p, g in zip(vocab, logits.softmax(-1).tolist(), logits.grad.tolist()):
    print(f"{t!r:7}  p={p:.3f}  grad={g:+.3f}")
print(f"loss={loss.item():.3f}  perplexity={loss.exp().item():.2f}")   # 1.914, 6.78

w = torch.nn.Parameter(torch.tensor([0.50]))
opt = torch.optim.AdamW([w], lr=2e-4, betas=(0.9, 0.95), eps=1e-8, weight_decay=0.1)
w.grad = torch.tensor([-0.853])
opt.step()
print(f"w after one AdamW step: {w.item():.5f}")                      # 0.50019
  • Change target to [1] (" cat"). Why does the loss drop to about 1.50?
  • Run opt.step() a second time with the same gradient. Is the step still exactly lr?
  • Set weight_decay=0.0 and confirm the decay term disappears.

The real training loop: precision, clipping, and schedule

Put the four steps in a loop and add the production pieces:

# Sketch of one pretraining step (PyTorch). Model = any causal LM returning logits.
def train_step(model, batch, optimizer, scheduler):
    inputs, targets = batch[:, :-1], batch[:, 1:]          # shift by one token
    with torch.autocast("cuda", dtype=torch.bfloat16):      # BF16 forward pass
        logits = model(inputs)                              # (B, T, V)
        loss = F.cross_entropy(logits.flatten(0, 1).float(), targets.flatten())
    loss.backward()                                         # gradients for every weight
    torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) # cap gradient norm at 1.0
    optimizer.step()                                        # AdamW update
    scheduler.step()                                        # warmup → cosine decay
    optimizer.zero_grad(set_to_none=True)
    return loss.item()

A big learning rate on random weights blows up training; a big learning rate late in training stops it from settling. The standard recipe is linear warmup, then cosine decay to about 1–10% of the peak. Llama 3 405B's published schedule5:

Setting Value
Peak learning rate 8 × 10⁻⁵
Warmup 8,000 steps, linear
Decay cosine to 8 × 10⁻⁷ over 1,200,000 steps
Batch size 4M tokens → 8M after 252M tokens → 16M after 2.87T tokens

The batch size grows too. Small batches early give more updates while the model learns basics; big batches later give cleaner gradients.

Training memory: 16 bytes per parameter

Mixed-precision AdamW keeps, per parameter: a 16-bit weight (2 bytes), a 16-bit gradient (2), plus an FP32 master copy, momentum, and variance (4 + 4 + 4). That's 16 bytes per parameter before any activations7.

Llama 3.1 8B inference (BF16 weights):    8.03B × 2  bytes ≈  16 GB
Llama 3.1 8B training (mixed AdamW):      8.03B × 16 bytes ≈ 128 GB  + activations

One 80 GB GPU can serve an 8B model but can't hold its optimizer state. That's why full training shards state across GPUs with ZeRO/FSDP (post 10) and why most fine-tuning uses LoRA or QLoRA (post 08).

Pretraining compute: the 6·N·D rule

Pretraining at scale: trillions of tokens, thousands of GPUs, one next-token objective

Nothing conceptually new happens in pretraining. The loop above runs on trillions of tokens across thousands of GPUs.

Model Pretraining tokens Data notes
Llama 3 (405B flagship) 15.6T5 ~50% general knowledge, 25% math & reasoning, 17% code, 8% multilingual
Llama 3.1 8B ~15T6 publicly available sources, cutoff December 2023
DeepSeek-V3 14.8T8 671B total / 37B active MoE
Kimi K2 15.5T9 1T total / 32B active MoE
Qwen3 ~36T10 119 languages; 30T+ at 4K context, then ~5T knowledge-heavy, then long-context to 32K

Data is curated, not scraped and dumped. Qwen3 shows the current pattern: a broad first stage, a second stage weighted toward STEM, code, and reasoning, then a long-context stage10. Mixing and ordering data is now as much of the recipe as the architecture.

Training compute ≈ 6 × N (parameters) × D (tokens) FLOPs, straight from the 2-forward + 4-backward rule. Check it against a published number: Llama 3 405B on 15.6T tokens gives 6 × 405×10⁹ × 15.6×10¹² ≈ 3.8×10²⁵ FLOPs, exactly the figure Meta reports5.

Worked example: Llama 3.1 8B's pretraining compute

FLOPs     = 6 × 8.03×10⁹ params × 15×10¹² tokens  ≈ 7.2 × 10²³ FLOPs

H100 SXM dense BF16 ≈ 989 TFLOPS   (NVIDIA lists 1,979 with sparsity)
At 40% utilization  ≈ 396 TFLOPS sustained per GPU

GPU-seconds = 7.2×10²³ / 3.96×10¹⁴ ≈ 1.8×10⁹ s  ≈ 507,000 GPU-hours

The H100 figure is from NVIDIA's spec sheet11; 40% sits inside the 38–43% model-FLOPs utilization Meta reports for Llama 3 405B5.

Meta's model card lists 1.46M H100 GPU-hours for the 8B model6, about 3× the ideal estimate. Treat 6ND as a floor, not a budget. Real runs pay for lower utilization at small scale, restarts, evaluations, and data and context-length stages the formula ignores. Two more reference points:

  • Llama 3.1 family: 39.3M H100 GPU-hours across 8B, 70B, and 405B6.
  • DeepSeek-V3: 2.788M H800 GPU-hours, which DeepSeek prices at $5.576M at $2/GPU-hour. That covers the final run only, not research or ablations8.

Chinchilla vs overtraining: how many tokens is enough?

The 2022 Chinchilla paper found that for a fixed compute budget, parameters and training tokens should scale equally12, which works out to roughly 20 tokens per parameter:

Model size Compute-optimal tokens (Chinchilla, Approach 1)
1B 20.2B
10B 205.1B
70B (Chinchilla itself) 1.4T

Llama 3.1 8B saw ~15T tokens: about 1,870 tokens per parameter, over 90× the Chinchilla ratio. That's deliberate. Chinchilla minimizes training cost. If you'll serve a model billions of times, it's cheaper to overtrain a small model than to serve a bigger "optimal" one. Qwen3's ~36T tokens across a family topping out at 235B parameters follows the same logic10.

What goes wrong in real runs

  • Hardware fails constantly. During a 54-day snapshot of Llama 3 405B pretraining, Meta logged 466 job interruptions, 419 of them unexpected5. Without automatic checkpoint and restart, large runs never finish.
  • Loss spikes waste days. DeepSeek reports no irrecoverable loss spikes or rollbacks for V38; Kimi K2 reports zero loss spikes over 15.5T tokens using MuonClip, a Muon-optimizer variant with a QK-clip fix for attention-logit blowups9. "AdamW, done" is no longer settled: Muon-family optimizers are the main challenger.
  • Precision keeps dropping. BF16 is the default; DeepSeek-V3 validated FP8 mixed-precision training at very large scale8, and FP8 training is a mainstream option on Hopper and Blackwell. Formats are in post 09.
  • The output is a base model, not an assistant. It continues text (post 01 shows the difference). SFT, preference tuning, and continued pretraining are in post 08.

Generation: from logits to one token

Training taught the model to output good logits. At inference, a sampler turns those logits into one chosen token, over and over:

prompt ──► forward pass ──► logits (128K–152K of them) ──► SAMPLER ──► one token
   ▲                                                                    │
   └──────────────────── append token, repeat ──────────────────────────┘
                         until EOS token, stop string, or max_tokens

The sampler is the only part of this loop you control per request. Everything else is fixed by the weights. The same model can be a careful SQL generator or a rambling poet depending on four or five numbers.

The toy model above was untrained and spread probability almost evenly. A trained model is far more confident. For the rest of this post, use these logits for what comes after "The cat sat" (illustrative values shaped like a real model's distribution):

Token Logit Probability (T = 1)
" on" 5.0 71.9%
" down" 3.5 16.0%
" quietly" 3.0 9.7%
" up" 1.0 1.3%
" there" 0.5 0.8%
" banana" −1.0 0.2%

A real vocabulary has ~128,000 more tokens in the tail. Each is tiny, but together the long tail can hold a meaningful slice of probability, and that tail is where nonsense comes from.

Greedy decoding and temperature

Greedy picks argmax every step: " on", always. It's simple and cheap, but worse than it sounds for open-ended text. Holtzman et al. showed that likelihood-maximizing decoding "leads to text that is bland and strangely repetitive"13; once a loop becomes the most likely continuation, greedy can't escape it.

For reasoning models, greedy is explicitly discouraged. Qwen3's model card says of thinking mode: "DO NOT use greedy decoding, as it can lead to performance degradation and endless repetitions"14. Greedy still fits short, closed-form outputs (a label, a yes/no, one extracted field), ideally with constrained decoding.

Temperature T divides every logit before softmax: P(tokenᵢ) = softmax(logitᵢ / T). T < 1 stretches the gaps so the top token gains; T > 1 shrinks them so the tail gains; T → 0 becomes greedy, and vLLM treats temperature=0 as greedy directly16.

Token T = 0.3 T = 0.7 T = 1.0 T = 1.5
" on" 99.2% 84.8% 71.9% 56.5%
" down" 0.7% 9.9% 16.0% 20.8%
" quietly" 0.1% 4.9% 9.7% 14.9%
" up" 0.0% 0.3% 1.3% 3.9%
" there" 0.0% 0.1% 0.8% 2.8%
" banana" 0.0% 0.0% 0.2% 1.0%

At T = 1.5, " banana" is 1-in-100. Over a 500-token answer you'll hit several low-probability tokens like it, and each one derails the text that follows. That's why high temperature alone gets incoherent, and why truncation exists.

Temperature doesn't change the ranking

Dividing by T keeps token order the same; it only changes how far apart the probabilities are. If the model's top choice is wrong, no temperature makes it right.

Truncation: top-k, top-p, min-p

Truncation zeroes out unlikely tokens, renormalizes the survivors, then samples.

Top-k keeps the k most likely tokens. top_k = 2 keeps " on" and " down": 71.9 / (71.9 + 16.0) = 81.8% " on", 18.2% " down". The flaw: k is fixed, but confidence isn't. After "The capital of France is", k = 40 lets in 39 bad options; after "My favorite food is", k = 2 is far too tight.

Top-p (nucleus) keeps the smallest set covering p of the mass, sampling from "the dynamic nucleus of the probability distribution"13. With top_p = 0.9:

" on"       71.9%   cumulative 71.9%   keep
" down"     16.0%   cumulative 87.9%   keep (still below 90%)
" quietly"   9.7%   cumulative 97.7%   keep (this one crosses 90%)
" up"        1.3%                      drop
...                                    drop

The nucleus grows when the model is uncertain and shrinks when it's confident. That adaptivity made top-p the default in most APIs.

Min-p keeps tokens above a fraction of the top token: keep token i only if P(i) ≥ min_p × P(top), using "the top token's probability as a scaling factor"18. With min_p = 0.1 at T = 1.5, the top token is 56.5%, so the threshold is 5.65%:

Token P at T = 1.5 Above 5.65%?
" on" 56.5% keep
" down" 20.8% keep
" quietly" 14.9% keep
" up" 3.9% drop
" banana" 1.0% drop

Min-p lets you run hotter temperatures for variety without letting garbage in, because the cutoff tracks the model's confidence. It was an ICLR 2025 oral, and the authors report adoption in Hugging Face Transformers and vLLM18.

Method Rule Adapts to confidence? Starting range
Greedy top token only n/a classification, extraction
Temperature softmax(logits / T) no (reshapes, never cuts) 0.6–0.8 for chat
Top-k keep k best no 20–50, as a safety cap
Top-p smallest set with mass ≥ p yes 0.8–0.95
Min-p keep P ≥ min_p · P_max yes 0.05–0.1 when running T > 1

These are starting ranges, not laws. Use the model creator's values first, then tune on your own eval set (post 11).

Penalties: discourage repetition, carefully

Penalties edit the logits of tokens that already appeared. vLLM exposes three, all off by default16:

Parameter Default Effect
presence_penalty 0.0 Subtracts a flat amount from any token already in the output (> 0 → favor new tokens)
frequency_penalty 0.0 Subtracts more the more often a token has appeared
repetition_penalty 1.0 Scales down logits of tokens seen in the prompt or output (> 1 → favor new tokens)

repetition_penalty comes from the 2019 CTRL paper, which found "greedy sampling and θ ≈ 1.2 yields a good balance between truthful generation and lack of repetition"19.

Penalties punish tokens you need to repeat

A penalty can't tell a boring loop from a variable name that must appear 30 times, or a JSON key that repeats on every row. Qwen notes a higher presence_penalty "may occasionally result in language mixing and a slight decrease in model performance"14. Use penalties to fix an observed repetition problem, and keep them off for code and structured output.

Order of operations and a 30-line sampler

Settings interact, so order changes the result. vLLM's sampler applies them like this17:

logits
  │ 1. allowed-token / bad-word filters, logit bias, min-tokens
  │ 2. penalties (repetition, presence, frequency)
  │ 3. temperature            (if temperature < 1e-5 → greedy argmax)
  │ 4. min_p
  │ 5. top_k and top_p
  ▼
sample one token

Transformers, llama.cpp, and SGLang use similar but not always identical orders. If output style changes when you move a prompt between engines with the "same" settings, check order and defaults before blaming the model.

Implementing it once removes the mystery. This follows vLLM's order and reproduces the numbers above:

# pip install "torch>=2.6"
import torch

def sample(logits, temperature=1.0, top_k=0, top_p=1.0, min_p=0.0, generator=None):
    """vLLM-style order: temperature -> min_p -> top_k/top_p -> draw."""
    if temperature == 0:                                   # greedy
        return int(logits.argmax())
    probs = (logits / temperature).softmax(-1)
    if min_p > 0:                                          # relative cutoff
        probs[probs < min_p * probs.max()] = 0
    if top_k > 0:                                          # keep the k best
        probs[probs < probs.topk(top_k).values[-1]] = 0
    if top_p < 1.0:                                        # nucleus
        sorted_p, idx = probs.sort(descending=True)
        sorted_p = sorted_p / sorted_p.sum()
        mass_before = sorted_p.cumsum(-1) - sorted_p
        probs[idx[mass_before >= top_p]] = 0
    probs = probs / probs.sum()                            # renormalize survivors
    return int(torch.multinomial(probs, 1, generator=generator))

vocab  = [" on", " down", " quietly", " up", " there", " banana"]
logits = torch.tensor([5.0, 3.5, 3.0, 1.0, 0.5, -1.0])    # after "The cat sat"

g = torch.Generator().manual_seed(0)
for cfg in [dict(temperature=0), dict(temperature=1.0), dict(temperature=1.0, top_k=2),
            dict(temperature=1.0, top_p=0.9), dict(temperature=1.5, min_p=0.1)]:
    picks = [vocab[sample(logits.clone(), generator=g, **cfg)] for _ in range(10_000)]
    print(cfg, {t: round(picks.count(t) / 1e4, 3) for t in vocab if t in picks})

# {'temperature': 0} {' on': 1.0}
# {'temperature': 1.0} {' on': 0.711, ' down': 0.163, ' quietly': 0.103, ' up': 0.013, ...}
# {'temperature': 1.0, 'top_k': 2} {' on': 0.813, ' down': 0.187}
# {'temperature': 1.0, 'top_p': 0.9} {' on': 0.734, ' down': 0.158, ' quietly': 0.108}
# {'temperature': 1.5, 'min_p': 0.1} {' on': 0.613, ' down': 0.227, ' quietly': 0.16}

The sampled shares match the hand calculations within sampling noise (81.3% vs 81.8% for top-k, for example).

Sampling itself is cheap: a softmax and a sort over ~150K numbers. The cost is the forward pass per generated token, which is memory-bandwidth-bound and covered in post 04. None of the knobs in this post change it.

Constrained decoding: make invalid output impossible

Sometimes you don't want likely text, you want valid text: JSON matching a schema, one of five labels, SQL that parses. Constrained decoding masks the logits of every token that would break the grammar before sampling, so the model physically can't produce invalid output.

schema says: next must be  "  or  }
logits:      " on"=5.0   "\""=2.1   "}"=1.3   "banana"=0.4 ...
mask:          −∞         keep       keep       −∞
sample from:  { "\"", "}" }  only

Doing this per token over a 150K vocabulary used to be slow. XGrammar precomputes which tokens are grammar-safe regardless of parser state and checks only the rest at runtime, reporting up to 100× speedup over earlier approaches20. vLLM documents xgrammar and guidance backends with auto as the default; lm-format-enforcer is deprecated as of v0.3321.

# pip install "vllm==0.33.0"
from vllm import LLM, SamplingParams
from vllm.sampling_params import StructuredOutputsParams

llm = LLM(model="Qwen/Qwen3-8B")

# Creative chat: the model creator's non-thinking settings
chat = SamplingParams(temperature=0.7, top_p=0.8, top_k=20, min_p=0.0, max_tokens=256)

# Classification: constrain to exact labels; greedy is fine here
label = SamplingParams(
    temperature=0,
    max_tokens=5,
    structured_outputs=StructuredOutputsParams(choice=["positive", "negative", "neutral"]),
)

print(llm.generate("Write one sentence about a cat.", chat)[0].outputs[0].text)
print(llm.generate("Sentiment of 'the deploy failed again': ", label)[0].outputs[0].text)

Against a running OpenAI-compatible vLLM server, vLLM accepts its extra sampling fields (top_k, min_p) alongside the standard ones:

curl -s http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "Qwen/Qwen3-8B",
    "messages": [{"role": "user", "content": "Name three Bangkok districts."}],
    "temperature": 0.7, "top_p": 0.8, "top_k": 20, "min_p": 0.0,
    "max_tokens": 200
  }' | jq -r '.choices[0].message.content'

Tool calling relies on exactly this kind of constrained JSON (post 06).

Model-card defaults and settings by task

Model makers tune their recommended sampling settings against their own evals. Qwen3's14:

Mode Temperature Top-p Top-k Min-p
Thinking (enable_thinking=True) 0.6 0.95 20 0
Non-thinking 0.7 0.8 20 0

Qwen3-8B also ships the thinking-mode values in its generation_config.json (temperature 0.6, top_k 20, top_p 0.95)15. vLLM applies a model's generation_config.json by default when you don't pass sampling parameters; generation_config="vllm" opts out22.

vLLM's raw defaults are not chat defaults

Construct SamplingParams() yourself and you get temperature=1.0, top_p=1.0, top_k=0 (all tokens), and max_tokens=1616. That's untruncated sampling capped at 16 tokens: a common cause of "the model rambles" and "the answer is cut off" tickets.

Hosted reasoning models often restrict sampling knobs. Several providers fix or reject temperature and top_p for reasoning models tuned to one setting, so check the API reference per model (post 06 covers thinking models).

Pick settings by task, then tune on your evals:

Task Temperature Truncation Penalties Constrained?
Classification, extraction, routing 0 n/a off yes: choice / JSON schema
Tool calls / structured JSON 0–0.3 top-p 0.9 off yes: schema
Code generation 0.2–0.6 top-p 0.95 off optional
General chat (non-thinking) model card (Qwen3: 0.7) model card (top-p 0.8, top-k 20) only if loops appear no
Reasoning / thinking mode model card (Qwen3: 0.6), never greedy model card (top-p 0.95, top-k 20) presence 0–2 only for endless repetition no
Brainstorming, creative writing 1.0–1.5 min-p 0.05–0.1 light presence penalty no

Why temperature 0 still isn't deterministic

You'd expect greedy decoding to return identical output every time. In production it usually doesn't. Thinking Machines sampled the same prompt 1,000 times at temperature 0 from Qwen3-235B-A22B-Instruct-2507 and got 80 unique completions; they matched for 102 tokens, then diverged ("Queens, New York" vs "New York City")23.

The root cause isn't random GPU threads. Kernel results depend on batch size, and batch size depends on how many other requests are on the server at that moment. A different batch shape changes floating-point summation order, which flips a near-tie between the top two tokens, and everything after diverges. With batch-invariant kernels, all 1,000 completions were identical; the cost was 26 s → 42 s for 1,000 sequences on Qwen3-8B23.

vLLM ships this as a beta feature (NVIDIA compute capability 8.0+)24:

VLLM_BATCH_INVARIANT=1 vllm serve Qwen/Qwen3-8B

Expect lower throughput; use it for RL rollouts, eval reproducibility, and debugging, not as a default. Setting seed doesn't fix this on a shared server: a seed makes the random draws repeatable, but it can't make the logits identical if the batch around your request changed.

Summary

Concept Rule Number to remember
Objective Predict the next token; the text is the label 4,095 predictions per 4,096-token sequence
Logits h · W_out, one score per vocab token; softmax → probabilities 128,256 (Llama 3.1) / 151,936 (Qwen3)
Loss −log P(correct); perplexity = e^loss starts ≈ 11.8; toy 1.914
Gradient P − 1[correct] at the output; backward ≈ 2× forward 6 FLOPs/param/token total
AdamW momentum + adaptive scale + decoupled decay β₂ 0.95, wd 0.1, clip 1.0
Schedule linear warmup → cosine decay 8K warmup, 1.2M steps (Llama 3 405B)
Training memory 16 bytes/param + activations 8B → ~128 GB
Compute 6 · N · D, then ×2–3 for reality 8B × 15T ≈ 7.2×10²³ FLOPs; 1.46M GPU-h actual
Tokens Chinchilla ~20/param is compute-optimal; deployed models overtrain Llama 3.1 8B ≈ 1,870/param
Temperature reshapes, never reorders T = 0 → greedy
Top-p / min-p adaptive truncation of the tail top-p 0.8–0.95; min-p 0.05–0.1 at T > 1
Penalties fix observed loops only off for code and JSON
Constrained decoding mask grammar-breaking tokens XGrammar up to 100× faster
Determinism batch shape changes logits 80 unique outputs / 1,000 at T = 0

Before you train or ship:

  • Compute budget: 6 × N × D ÷ (dense TFLOPS × 0.3–0.4), then add 2–3×
  • Memory: 16 bytes/param for full AdamW, or switch to LoRA/QLoRA (post 08)
  • Ops: automatic checkpoint/restart and loss-spike alerts before the first long run
  • Sampling: start from the model card or generation_config.json, not engine defaults
  • Set max_tokens explicitly; vLLM's raw default is 16
  • Use constrained decoding instead of "please return valid JSON" prompts
  • Never run reasoning models greedy; never put penalties on code or JSON
  • Need reproducibility? Batch-invariant mode plus a fixed seed, and accept the throughput cost
  • Change one sampling knob at a time and measure it on an eval set (post 11)

Next: Post 04 — Memory Is the Bottleneck: every token you sample is appended and fed back in. Here's how engines avoid recomputing the past, and what that costs in memory.

Go deeper:


  1. Meta Llama 3.1 8B config.json (mirror of the gated Meta repo) — vocab 128,256, tie_word_embeddings: false. ↩↩

  2. Qwen, Qwen3-8B config.json — vocab 151,936, untied embeddings. ↩↩

  3. Loshchilov & Hutter, Decoupled Weight Decay Regularization (2017/2019) — L2 regularization and weight decay differ for Adam; decouple the decay. ↩

  4. Touvron et al., LLaMA: Open and Efficient Foundation Language Models (2023) — AdamW β₁ = 0.9, β₂ = 0.95, weight decay 0.1, gradient clipping 1.0, 2,000 warmup steps, cosine to 10% of peak. ↩

  5. Llama Team, Meta, The Llama 3 Herd of Models (2024) — 405B on 15.6T tokens with 3.8×10²⁵ FLOPs; up to 16K H100s; 38–43% BF16 MFU; LR 8×10⁻⁵, 8,000 warmup, cosine to 8×10⁻⁷ over 1.2M steps; batch 4M→8M→16M tokens; 466 interruptions in 54 days; data mix 50/25/17/8. ↩↩↩↩↩

  6. Meta, Llama 3.1 8B model card — ~15T tokens, December 2023 cutoff; 1.46M GPU-hours (8B), 7.0M (70B), 30.84M (405B), 39.3M total on H100-80GB. ↩↩↩

  7. Rajbhandari et al., ZeRO: Memory Optimizations Toward Training Trillion Parameter Models (2019) — mixed-precision Adam needs 2Ψ + 2Ψ + 12Ψ = 16Ψ bytes for model states. ↩

  8. DeepSeek-AI, DeepSeek-V3 Technical Report (2024) — 14.8T tokens; 2.788M H800 GPU-hours ($5.576M at $2/hour, final run only); no irrecoverable loss spikes or rollbacks; FP8 mixed-precision training validated at scale. ↩↩↩↩

  9. Moonshot AI, Kimi K2: Open Agentic Intelligence (2025) — 1T total / 32B active; MuonClip (Muon + QK-clip); 15.5T tokens with zero loss spike. ↩↩

  10. Qwen Team, Qwen3: Think Deeper, Act Faster (2025) — ~36T tokens, 119 languages, three pretraining stages (30T+ at 4K, ~5T knowledge-intensive, long-context to 32K). ↩↩↩

  11. NVIDIA, H100 Tensor Core GPU — H100 SXM BF16 1,979 TFLOPS with sparsity (≈ 989 dense). ↩

  12. Hoffmann et al., Training Compute-Optimal Large Language Models (2022) — parameters and tokens should scale equally; Table 3: 1B → 20.2B tokens, 10B → 205.1B; Chinchilla 70B on 1.4T tokens. ↩

  13. Holtzman et al., The Curious Case of Neural Text Degeneration (2019/ICLR 2020) — likelihood-maximizing decoding yields bland, repetitive text; proposes Nucleus (top-p) Sampling. ↩↩

  14. Qwen, Qwen3-8B model card — "Best Practices": thinking T=0.6/top-p 0.95/top-k 20/min-p 0, non-thinking T=0.7/0.8/20/0; do not use greedy in thinking mode; presence_penalty 0–2 with caveats. ↩↩↩

  15. Qwen, Qwen3-8B generation_config.json — do_sample: true, temperature 0.6, top_k 20, top_p 0.95. ↩

  16. vLLM, SamplingParams API reference — defaults: temperature 1.0 (0 = greedy), top_p 1.0, top_k 0 (all tokens), min_p 0.0, presence/frequency 0.0, repetition 1.0, max_tokens 16. ↩↩↩

  17. vLLM source, vllm/v1/sample/sampler.py — sampler docstring: filters and logit processors, penalties, then temperature, min_p, top-k/top-p, sample; temperature below 1e-5 uses greedy. ↩

  18. Nguyen et al., Turning Up the Heat: Min-p Sampling for Creative and Coherent LLM Outputs (ICLR 2025 oral) — dynamic truncation scaled by the top token's probability; adopted in Transformers and vLLM. ↩↩

  19. Keskar et al., CTRL: A Conditional Transformer Language Model for Controllable Generation (2019) — penalized sampling discounts previously generated tokens; greedy with θ ≈ 1.2. ↩

  20. Dong et al., XGrammar: Flexible and Efficient Structured Generation Engine for Large Language Models (2024) — context-independent token precomputation, up to 100× speedup. ↩

  21. vLLM, Structured Outputs — StructuredOutputsParams (choice, json, regex, grammar); backends xgrammar and guidance, auto default; lm-format-enforcer deprecated in v0.33.0. ↩

  22. vLLM, Generative Models — applies the model's generation_config.json sampling defaults if present; generation_config="vllm" opts out. ↩

  23. Horace He and Thinking Machines Lab, Defeating Nondeterminism in LLM Inference (September 2025) — 1,000 temperature-0 samples gave 80 unique completions; root cause is lack of batch invariance; deterministic run 26 s → 42 s. ↩↩

  24. vLLM, Batch Invariance — VLLM_BATCH_INVARIANT=1; beta; NVIDIA compute capability 8.0+. ↩

Discussion

Have thoughts on this post? Share them below — questions, corrections, or your own experience are all welcome.