Chapter 1 · Frame and baseline

Autoregressive decoding policies

The model supplies possibilities; the decoding policy decides which possibilities can become product behavior.

65–90 min4 key conceptsReviewed 26 Aug 2026
01 · Production proposition

Long-context generation breaks latency and cost targets.

This chapter moves from start from logits to choose and account. We will make the idea concrete in a small code example before placing it back inside a production system with p99 first-token and cost/token SLOs.

Decision

Sample or take the argmax, append one token, and record probability, latency, seed, and the exact reason generation stopped.

Evidence

Verify the behavior illustrated in decode.py, then measure decision utility, slice reliability, and system latency.

Failure consequence

Maximizing aggregate tokens/s destroys p99 first-token latency and harms a rare-language quality slice. An unsafe release must degrade to a named baseline or the last known-good version.

02 · Guided chapter

Build the idea one layer at a time.

A language model does not choose words; it assigns a score to every possible next token. The decoding policy turns those scores into an actual continuation, so changing the policy can change usefulness, safety, latency, and reproducibility without changing a single model weight.

Generation repeats one loop: run the model, transform the final-position logits, choose one token, append it, and stop when a boundary is reached. Greedy decoding always takes the largest logit. Temperature rescales confidence, while top-k and nucleus sampling remove unlikely choices before sampling. These controls operate in a specific order, and each changes the probability distribution the user experiences.

Treat decoding as part of the released system rather than a UI preference. A support-answering task may need low temperature and strict stop tokens; brainstorming can tolerate broader sampling. Record the prompt template, tokenizer, seed, sampling parameters, maximum length, and stop reason so an output can be explained or replayed.

Keep in view
  • prefill/decode
  • sampling
  • KV layout
  • GQA/MQA
WORKED PATH

Follow the reasoning before touching the code.

  1. 01

    Start from logits

    Use only the logits at the newest position and apply any policy constraints, such as forbidden tokens or a repetition rule, before normalization.

  2. 02

    Shape the distribution

    Divide by temperature, filter with top-k or top-p, then normalize the surviving values with a numerically stable softmax.

  3. 03

    Choose and account

    Sample or take the argmax, append one token, and record probability, latency, seed, and the exact reason generation stopped.

pythondecode.py
import numpy as np

def choose(logits, temperature=0.7, top_k=3, seed=7):
    scaled = np.asarray(logits) / temperature
    keep = np.argpartition(scaled, -top_k)[-top_k:]
    kept = scaled[keep]
    probs = np.exp(kept - kept.max())
    probs /= probs.sum()
    rng = np.random.default_rng(seed)
    return int(rng.choice(keep, p=probs)), probs

token, local_probs = choose([1.2, 0.1, 2.4, 1.7])
print(token, local_probs.round(3))

A small temperature-and-top-k decoding step

READ THE EXAMPLE

What to notice

  • Lowering temperature preserves the logit order but concentrates probability on the largest values.
  • The returned probabilities describe only the retained top-k set; filtered tokens have exactly zero chance under this policy.
YOUR TURN Pause and predict before revealing the answer.

Run the example with temperature 0.2 and then 1.5. Which setting should produce more varied outputs across several seeds?

Need a hint?

Temperature divides every logit before softmax; compare how far apart the scaled values become.

Check your reasoning

Temperature 1.5 flattens the retained distribution, so repeated draws vary more. Temperature 0.2 makes the largest retained logit dominate.

Bring forward

Transformer from scratch, Foundation models

03 · Formal treatment

Connect the chapter to the course’s quantitative spine.

The model supplies possibilities; the decoding policy decides which possibilities can become product behavior. The kv-cache memory estimate below is the shared course-level lens that helps quantify the surrounding system. Name each symbol, check its units or shape, and use only values that were available at the production cutoff.

Formal treatment
MKV≈2⋅L⋅B⋅S⋅Hkv⋅dh⋅qM_{\mathrm{KV}} \approx 2 \cdot L \cdot B \cdot S \cdot H_{\mathrm{kv}} \cdot d_h \cdot q

KV-cache memory estimate

Symbol, shape or unit contract
SymbolMeaning / shape / unit
Ldecoder layers
Bactive sequences
Scached tokens
H_kvKV heads
qbytes per scalar
Open derivation and numerical substitution

Start from the production quantity being optimized, substitute the observed values with their declared units, then isolate the model-controlled term. Preserve shape annotations at each step so broadcasting or aggregation cannot silently change the result.

  1. Write the named inputs: L, B, S, H_kv, q.
  2. Substitute one small, hand-checkable batch before vectorizing.
  3. Calculate an independent reference value and compare within a declared tolerance.
# equation → code contract
inputs = validate_shapes_and_units(batch)
value = compute_c16(inputs)
assert is_finite(value)
04 · Deterministic lab

Change one assumption and make the tradeoff visible.

Use the worked chapter as your prediction, then change one input in the lab and explain why the output moves. The lab runs predefined TypeScript and never executes learner code, so the focus stays on the concept rather than setup.

Estimate

GPU memory ledger

Change microbatch size and calculate a simplified training-memory budget.

samples
Primary8.6 GB
Secondary36.0%
DiagnosisFits

Assumption: 3.2 GB weights+grads+optimizer, 0.34 GB activations per sample, 24 GB device, 10% reserve.

Open nonvisual data table
ItemComputed stateInterpretation
block 11.09 GB activationsresident
block 22.18 GB activationsresident
block 33.26 GB activationsresident
block 44.35 GB activationsresident
block 55.44 GB activationsresident
05 · Production implications

Trace the complete operating path.

Carry the chapter’s central idea into the system: The model supplies possibilities; the decoding policy decides which possibilities can become product behavior. The path below shows where that reasoning needs an artifact, a test, an owner, or a fallback.

  1. 01

    Turn “Start from logits” into a written invariant and a failing test.

  2. 02

    Promote decode.py from illustration to a versioned implementation with representative fixtures.

  3. 03

    Use “Choose and account” as the release checkpoint: Sample or take the argmax, append one token, and record probability, latency, seed, and the exact reason generation stopped.

  4. 04

    Serve or materialize behind explicit p99 first-token and cost/token SLOs.

  5. 05

    Join telemetry to mature outcomes and retain a rollback path.

Observability

Join service health, input quality, prediction distributions, slice behavior, and mature outcomes by exact version.

Cost

Measure storage, preprocessing, compute, queueing, and human review under a representative arrival pattern.

Failure modes

Maximizing aggregate tokens/s destroys p99 first-token latency and harms a rare-language quality slice. Add a detector, owner, mitigation, and stop condition for this class of failure.

Alternatives

Compare a rule, a simpler statistical baseline, and a different system boundary before adding model complexity.

06 · Check understanding

Explain the contract, not just the vocabulary.

Browser-graded checkpointPass ≥ 80%
01Why does KV memory grow with context?
02Why can continuous batching hurt a request?
03When is quantization acceptable?
07 · Apply in production

LLM inference capacity plan

Benchmark cache, batching, concurrency, sampling, and one quantized path on mixed traces.

  • Benchmark contract
  • Profiler/bottleneck report
  • Quality gates
  • Capacity and cost recommendation
Open assignment and rubric
08 · Sources & next depth

Read primary material with a purpose.

09 · Production resolution

Return to the opening failure.

Choose optimizations from workload traces with quality gates, tail latency, memory headroom, and cost per token.

For this lesson, the release evidence is the worked code example, a hand-checked formal result, deterministic simulation output, a ≥80% checkpoint, the production rubric, and a named fallback. The course resolves when the system can produce a capacity plan using efficient attention, quantization, batching, and modern routing.