Every method in this course calls the same operation: given a prompt, draw a continuation from a frozen or partly trained language model. This module fixes that operation before any reasoning trick is added. The model is the Qwen3 0.6B base checkpoint. Its blocks are described in Module 9. Here the model is a function from token ids to next-token logits.

A conditional language model

Definition 2.1 (Autoregressive model).

A model defines a distribution over token sequences by a product of conditionals,

Definition 2.1 is the chain rule, not an extra assumption. The modeling choice is that one network, shared across positions, produces every factor. Generation is the same product, read left to right: pick from the distribution at step , append it, and repeat until an end-of-sequence token or a length limit.

The prompt is just a prefix. A completion then has

Later modules reuse this sum. Module 5 averages it to score confidence. Module 6 keeps the sum, because a single reward is assigned to the whole completion.

From text to ids

The model never sees characters. A tokenizer splits a string into integer ids from a fixed vocabulary. Qwen3’s vocabulary has entries. Special tokens mark chat structure (<|im_start|>, <|im_end|>) and, on the reasoning tokenizer, the thinking span. The base tokenizer does not treat <think> as one id. That fact matters in Module 7, where a format reward depends on those ids being atomic.

Two practical consequences:

  • The same string can have different lengths under the base tokenizer and the reasoning tokenizer. Log-probability sums are not comparable across those tokenizations.
  • Decoding must invert encoding. A generation loop that appends ids and only decodes at the end avoids the drift you get from repeatedly decoding and re-encoding a growing string.

The generation loop

prompt ids logits sample append
Figure 2.1. One step of generation. The new id is appended and the loop returns to the model.

Figure 2.1 is the whole algorithm. In code it is a short loop.

ids = tokenize(prompt)
for _ in range(max_new_tokens):
    logits = model(ids)[:, -1, :]
    next_id = sample(logits, temperature, top_p)
    ids = append(ids, next_id)
    if next_id == eos_id:
        break

sample is greedy when the temperature is zero: take the argmax. Module 4 replaces that choice with temperature and top- sampling. Until then, greedy decoding is the right default, because it makes evaluation repeatable.

The shape of logits is (batch, time, vocab). Only the last time index is a distribution over the next token. Earlier positions are predictions the loop does not use.

KV cache

Without a cache, step recomputes keys and values for all positions in every layer. Almost all of that work repeated the previous step.

Definition 2.2 (KV cache).

A KV cache stores, for each layer, the key and value tensors of tokens already processed. The next step runs the model on the new token only, appends its key and value, and attends over the whole cache.

Definition 2.2 does not change the distribution. It changes the amount of work. If a prompt has tokens and the completion has tokens, an uncached loop pays attention cost proportional to in the naive implementation that re-encodes the full sequence. A cached loop pays for the prompt once, then for one new query per step against a growing key cache.

Two details are easy to get wrong:

  • Positions for rotary embeddings must continue from the cache length, not restart at zero. Otherwise the new token is rotated as if it were at the start of the sequence.
  • The causal mask for a single new query has shape (1, 1, 1, P+t): the query may attend to every cached key, and to itself.

The cache is per sequence. A new prompt must reset it. Forgetting the reset is a silent bug: the model attends into the previous question.

Compilation is a speedup

torch.compile fuses kernels. It does not change the mathematical function, aside from the usual floating-point reassociation. Treat it as an optional accelerator for the same loop, and turn it off when you are debugging a numerical mismatch. The same remark applies to a lower-precision dtype: Qwen3 0.6B is stored in bfloat16, and the logits you sample from are those low-precision values.

What you need installed

The notebooks use Python, PyTorch, and the reasoning_from_scratch package. Chapters 2–4 are comfortable on a CPU. The training loops in modules 6–8 are much faster on a GPU. Setup notes, including a GPU-oriented variant of the model, are in the repository rather than repeated here.

Exercises: Homework 2.

Code