Coding tutorial · Build it from scratch

Post-Train an LLM

We take one pretrained small model through supervised fine-tuning, preference optimization and reinforcement learning. Every loss is written by hand. Most are checked against a trusted library (Hugging Face, PEFT, TRL). The others are checked against values worked out by hand.

Supervised fine-tuningDPOGRPO

A small package, posttrain, that takes SmolLM2-135M through supervised fine-tuning, DPO and GRPO on arithmetic problems with an exact reward. Every mask and every loss is yours to read, print and break.

Time
An afternoon to read and type. Training runs take extra time.
Hardware
Every script is written to run on a CPU. We ran the tests, the benchmarks, the inspect and break-it scripts and SFT on a CPU. The full SFT run took 2463.8 s on an AMD EPYC 7R13 with 8 threads and 132.5 s on one NVIDIA H100. Both are single runs on shared machines. The reward model, DPO and RL training were not run on the CPU. Their results come from the H100 only.
You need
Python 3.10+, PyTorch, transformers, and peft and trl for the comparison tests
Package
posttrain
Final repo tree c06-post-training/
c06-post-training/
├── benchmarks/
│   ├── bench_memory.py  # full vs LoRA, one process each
│   ├── bench_packing.py  # padded vs packed
│   └── bench_rollout.py  # rollouts per second
├── posttrain/
│   ├── chat.py  # chat template and assistant-only labels
│   ├── dpo.py  # preference pairs and the DPO loss
│   ├── evaluate.py  # greedy accuracy on held-out prompts
│   ├── generation.py  # left padding, sampling, completion masks
│   ├── grpo.py  # group advantages, clipped surrogate, KL
│   ├── logprobs.py  # per-token and per-sequence log-probs
│   ├── lora.py  # a minimal LoRA, checked against PEFT
│   ├── models.py  # policy, frozen reference, tiny test model
│   ├── packing.py  # padding, packing, block-causal mask
│   ├── reinforce.py  # REINFORCE and a gradient-noise meter
│   ├── reward_model.py  # optional pairwise reward model
│   ├── rollout.py  # workers, policy versions, training batch
│   ├── sft.py  # masked loss and the SFT loop
│   ├── tasks.py  # arithmetic data and the exact reward
│   └── utils.py  # device, seeds, parameter counts
├── results/  # captured outputs quoted in this post
├── scripts/
│   ├── break_it.py  # runs the classic bugs on purpose
│   ├── inspect_mask.py  # prints one conversation token by token
│   ├── inspect_state.py  # prints one DPO pair and one GRPO group
│   ├── reinforce_variance.py  # measures gradient noise per estimator
│   ├── train_dpo.py  # stage 2
│   ├── train_reward_model.py  # stage 3
│   ├── train_rl.py  # stages 4 to 7
│   └── train_sft.py  # stage 1, full or LoRA, padded or packed
├── tests/
│   ├── test_chat_and_packing.py
│   ├── test_dpo.py
│   ├── test_grpo.py
│   └── test_lora_and_reward.py
├── README.md  # how to run everything, results table
└── conftest.py  # puts this folder on sys.path

The plan

A pretrained model continues text. What has to change, tensor by tensor, before it answers a question, then prefers a right answer over a wrong one, and then earns a reward for being right?

Post-training is the name for those changes. We build three stages on one base model, in one codebase. Each stage gets a weaker signal than the one before it.

All three rest on one quantity: the log-probability of the completion tokens given the prompt. Figure 1 shows how each stage turns that quantity into a loss. The rest of the post builds each of those tensors by hand.

Figure 1One prompt and completion, then three losses. The SFT tokens are real, taken from results/mask_example.json. The DPO and GRPO rows are drawn by hand to show the layout, so they carry no measured values.

We post-train a real pretrained model, HuggingFaceTB/SmolLM2-135M. The tiny from-scratch models of C4 and C5 are not capable enough for preferences or reinforcement learning. A model has to produce some right answers and some wrong ones before there is anything to prefer. Step 6 tests this claim with a control run from randomly initialised weights.

One task family carries the whole tutorial: small arithmetic problems. Because we generate the data, every label is exact and every reward is exact.

Where each stage lives
StageStepsModuleScript
1. SFT1 to 7tasks, chat, packing, sft, loratrain_sft.py
2. DPO8 to 11logprobs, models, dpotrain_dpo.py
3. Reward model (optional)12reward_modeltrain_reward_model.py
4. REINFORCE13reinforcereinforce_variance.py
5. GRPO14grpotrain_rl.py
6. Verifiable reward1 and 16taskstrain_rl.py
7. Rollout engine15generation, rolloutbench_rollout.py

Clone the repo once. Every command below runs from its root.

$ git clone https://github.com/srini-anirudh/blog-coding-tutorials.git
$ cd blog-coding-tutorials
$ python -m venv .venv && .venv/bin/pip install -e ".[dev]"
Step 01Stage 1: SFT

Generate conversations with answers we can check

Goal A dataset where the right answer is known exactly, so a label or a reward is never a matter of opinion.

A real post-training dataset is a list of conversations. Each conversation is a list of messages, and each message has a role and some content.

{
  "messages": [
    {"role": "user", "content": "..."},
    {"role": "assistant", "content": "..."}
  ]
}

We keep that format and generate the content. A Problem holds a question, its worked steps and its answer. The method solution writes the reply in one fixed form, so the answer is easy to find later.

@dataclass
class Problem:
    question: str
    steps: list[str]
    answer: int
    kind: str
    follow_up: tuple[str, list[str], int] | None = field(default=None)

    def solution(self) -> str:
        return " ".join(self.steps) + f" The answer is {self.answer}."
Listing 1A problem. Every reply ends with the same sentence, The answer is N.

The next function turns a problem into messages. The flag with_answer matters later. Without the answer, the list stops at the user turn, and that is the prompt for generation.

def to_messages(p: Problem, with_system: bool = True, with_answer: bool = True) -> list[dict[str, str]]:
    """Render a problem as chat messages. Without the answer, the list ends on the user turn (a prompt)."""
    msgs: list[dict[str, str]] = []
    if with_system:
        msgs.append({"role": "system", "content": SYSTEM_PROMPT})
    msgs.append({"role": "user", "content": p.question})
    if not with_answer:
        return msgs
    msgs.append({"role": "assistant", "content": p.solution()})
    if p.follow_up is not None:
        text, steps, value = p.follow_up
        msgs.append({"role": "user", "content": text})
        msgs.append({"role": "assistant", "content": " ".join(steps) + f" The answer is {value}."})
    return msgs
Listing 2Rendering a problem as chat messages. About 30% of the training set gets a second user turn, so some conversations have two assistant replies.

Now the part the later stages depend on. A verifiable reward is a function a machine can run, with no judge and no model in the loop. Ours reads the first answer in the reply and compares it to the truth.

def extract_answer(text: str) -> int | None:
    """The first 'The answer is N.' in a completion, or None if the format is broken."""
    m = ANSWER_RE.search(text)
    return int(m.group(1)) if m else None


def exact_reward(completion: str, truth: int) -> float:
    """The verifiable reward: 1.0 for the exact right number in the right format, else 0.0."""
    return 1.0 if extract_answer(completion) == truth else 0.0
Listing 3The reward. A broken format earns 0, even when the right number appears somewhere in the text.

The one conversation this post inspects came from make_problem with seed 0 and kind chain, plus one follow-up turn from add_follow_up with seed 1. It looks like this after the next step renders it.

<|im_start|>system
You are a careful calculator. Work step by step, then finish with 'The answer is N.'<|im_end|>
<|im_start|>user
What is 59 + 63 - 15?<|im_end|>
<|im_start|>assistant
59 + 63 = 122. 122 - 15 = 107. The answer is 107.<|im_end|>
<|im_start|>user
Now add 6 to that.<|im_end|>
<|im_start|>assistant
107 + 6 = 113. The answer is 113.<|im_end|>

Checkpoint

  • to_messages(p, with_answer=False) ends on a user turn.
  • test_exact_reward_is_strict passes.
Step 02Stage 1: SFT

Serialize messages with a chat template

Goal Turn a list of messages into one token sequence, in a form the model will also see when it answers.

A model reads one flat stream of tokens. The chat template decides how roles are written into that stream. We use ChatML, which wraps each message in two markers. The base SmolLM2-135M tokenizer ships without a template, but its vocabulary already holds the markers: <|im_start|> is id 1 and <|im_end|> is id 2.

CHAT_TEMPLATE = (
    "{%- for message in messages %}"
    "{{- '<|im_start|>' + message['role'] + '\\n' }}"
    "{%- if message['role'] == 'assistant' %}"
    "{% generation %}{{- message['content'] + '<|im_end|>' }}{% endgeneration %}{{- '\\n' }}"
    "{%- else %}"
    "{{- message['content'] + '<|im_end|>' + '\\n' }}"
    "{%- endif %}"
    "{%- endfor %}"
    "{%- if add_generation_prompt %}{{- '<|im_start|>assistant\\n' }}{%- endif %}"
)
Listing 5The template. The generation markers let Hugging Face compute an assistant mask too, which gives us something to test our own mask against in the next step.
def load_tokenizer(name: str = BASE_MODEL) -> PreTrainedTokenizerBase:
    """Base tokenizer + ChatML template. Pad is <|endoftext|>, never <|im_end|> (see `encode_chat`)."""
    tok = AutoTokenizer.from_pretrained(name)
    tok.chat_template = CHAT_TEMPLATE
    tok.pad_token = "<|endoftext|>"
    tok.padding_side = "right"
    return tok
Listing 6Loading the tokenizer. The pad token is deliberately not the end-of-turn token. Step 3 shows what breaks if it is.

The last line of the template adds <|im_start|>assistant\n when we ask for a generation prompt. That small detail decides what we train on. At inference we feed the header ourselves, so the model never has to predict it.

Why this matters inTeaching a language model to follow instructions

Checkpoint

  • The rendered text in step 1 has one header and one <|im_end|> per message.
  • test_manual_ids_match_chat_template passes. It downloads the tokenizer.
Step 03Stage 1: SFT

Build assistant-only labels and look at them

Goal A label for every token, set to -100 wherever the model should not be graded.

Pretraining grades every token. SFT does not. We want the model to write replies, not to write user questions, so we mask everything except the assistant’s words.

What each kind of token gets as its label
TokenLabelWhy
system and user content-100Context only. We never want the model to write these.
<|im_start|>assistant\n-100We feed this at inference through the generation prompt.
assistant contenttoken idThis is the skill we are teaching.
<|im_end|> after a replytoken idThis is how the model learns to stop.
\n after a message-100Generation stops at <|im_end|>, so this is never produced.

We could tokenize the rendered text and then search for assistant spans. Instead we tokenize one piece at a time and record who produced each token. Then no search can go wrong.

def encode_chat(tok: PreTrainedTokenizerBase, messages: list[dict[str, str]], mode: str = "assistant") -> ChatExample:
    """Tokenize a conversation and build its labels.

    mode="assistant": train on every assistant reply (content + <|im_end|>), mask everything else.
    mode="last":      train on the final assistant reply only.
    mode="all":       train on every token, the way pretraining would.

    The "<|im_start|>assistant\\n" header is masked because at inference we feed it ourselves
    (add_generation_prompt). The closing <|im_end|> is a target: it is how the model learns to stop.
    """
    ids: list[int] = []
    labels: list[int] = []
    roles: list[str] = []
    last_assistant = max(i for i, m in enumerate(messages) if m["role"] == "assistant")

    def add(text: str, role: str, train: bool) -> None:
        piece = tok(text, add_special_tokens=False)["input_ids"]
        ids.extend(piece)
        labels.extend(piece if (train or mode == "all") else [IGNORE_INDEX] * len(piece))
        roles.extend([role] * len(piece))

    for i, m in enumerate(messages):
        is_target = m["role"] == "assistant" and (mode != "last" or i == last_assistant)
        add(f"<|im_start|>{m['role']}\n", "header", train=False)
        add(m["content"] + "<|im_end|>", m["role"], train=is_target)
        add("\n", "sep", train=False)
    return ChatExample(ids, labels, roles)
Listing 8Labels built one message at a time. The inner function add decides for each piece whether its tokens become targets.

The check is to print it. Here is the part of the table around the first assistant reply, and the end of the second reply.

$ .venv/bin/python c06-post-training/scripts/inspect_mask.py
pos      id  token            role       label
 41      47  '?'              user       -100
 42       2  '<|im_end|>'     user       -100
 43     198  '\n'             sep        -100
 44       1  '<|im_start|>'   header     -100
 45     520  'ass'            header     -100
 46    9531  'istant'         header     -100
 47     198  '\n'             header     -100
 48      37  '5'              assistant  37
 49      41  '9'              assistant  41
 50    1232  ' +'             assistant  1232
 51     216  ' '              assistant  216
...
115     216  ' '              assistant  216
116      33  '1'              assistant  33
117      33  '1'              assistant  33
118      35  '3'              assistant  35
119      30  '.'              assistant  30
120       2  '<|im_end|>'     assistant  2
121     198  '\n'             sep        -100

122 tokens, 56 targets, 66 masked

Figure 2 holds the whole conversation. Step through the three label modes, and click any token to see which earlier token predicts it.

Tokens
Targets
Masked
Selected tokenClick a token

Figure 2Every token of one real conversation, from results/mask_example.json. The number under each token is its label. Blue tokens are targets, and orange marks a target stop token.

Checkpoint

  • inspect_mask.py prints 122 tokens, 56 targets and 66 masked.
  • test_assistant_mask_matches_hf_generation_mask passes. Our mask equals the one Hugging Face derives from the template.
Step 04Stage 1: SFT

Write the masked loss

Goal Next-token cross-entropy on target positions only, equal to what Hugging Face computes.

Logits at position t predict the token at position t + 1. So we drop the last logit and the first label, and the two line up. Cross-entropy already knows how to skip -100.

def masked_lm_loss(logits: torch.Tensor, labels: torch.Tensor, reduction: str = "mean") -> torch.Tensor:
    """Next-token cross-entropy on positions whose label is not -100.

    logits: (B, L, V), labels: (B, L). reduction="mean" divides by the number of target tokens in the batch,
    which is what Hugging Face does; reduction="sum" returns the total, for gradient accumulation.
    """
    shift_logits = logits[:, :-1].float()  # position t predicts token t+1
    shift_labels = labels[:, 1:]
    loss = F.cross_entropy(
        shift_logits.reshape(-1, shift_logits.shape[-1]),
        shift_labels.reshape(-1),
        ignore_index=IGNORE_INDEX,
        reduction="sum",
    )
    return loss / (shift_labels != IGNORE_INDEX).sum().clamp(min=1) if reduction == "mean" else loss
Listing 9The loss. We sum first and divide by the target count ourselves, so the same function also serves gradient accumulation.
Shapes in the masked loss
TensorShapeMeaning
input_ids, labels(B, L)Tokens, and their targets or -100.
logits(B, L, V)One score per vocabulary entry per position.
shift_logits(B, L−1, V)Positions 0 to L−2, each predicting the next token.
shift_labels(B, L−1)Positions 1 to L−1.
lossscalarSum over targets, divided by the number of targets in the batch.

The first assistant token in Figure 2 sits at position 48. Its prediction comes from position 47, the newline at the end of the header. The header is masked as a target, but it still does the predicting.

Checkpoint

  • test_masked_loss_matches_hf_loss_on_padded_batch passes. It needs no download, because it uses a tiny random model.
Step 05Stage 1: SFT

Batch by padding, then by packing

Goal Spend less compute on empty slots, without letting one conversation read another.

Start with the simple version. Each conversation gets its own row, and short rows are filled with pad tokens. The width is rounded up to a multiple of 32, because a device that compiles kernels per shape pays a cost for every new length.

def pad_batch(examples: list[ChatExample], pad_id: int, multiple: int = 32) -> dict[str, torch.Tensor]:
    """Right-pad to the longest example, rounded up to `multiple`.

    Rounding matters on MPS: every new sequence length compiles new kernels, which costs seconds.
    Returns input_ids, labels, attention_mask, each (B, L) with L = round_up(L_max, multiple).
    """
    L = round_up(max(len(e.input_ids) for e in examples), multiple)
    ids = torch.full((len(examples), L), pad_id, dtype=torch.long)
    labels = torch.full((len(examples), L), IGNORE_INDEX, dtype=torch.long)
    attn = torch.zeros((len(examples), L), dtype=torch.long)
    for i, e in enumerate(examples):
        n = len(e.input_ids)
        ids[i, :n] = torch.tensor(e.input_ids)
        labels[i, :n] = torch.tensor(e.labels)
        attn[i, :n] = 1
    return {"input_ids": ids, "labels": labels, "attention_mask": attn}
Listing 11Padding. Every pad slot still costs compute inside the model.

Packing puts several whole conversations into one row. We use first-fit-decreasing bin packing, a classic greedy rule: sort by length, then put each conversation in the first row with room. Conversations are never split, because a second half without its prompt teaches nothing useful.

def pack_examples(examples: list[ChatExample], max_len: int) -> list[PackedRow]:
    """First-fit-decreasing bin packing of whole conversations into rows of at most `max_len` tokens.

    Conversations are never split: a split conversation would train its second half without its prompt.
    """
    order = sorted(range(len(examples)), key=lambda i: -len(examples[i].input_ids))
    bins: list[list[int]] = []
    space: list[int] = []
    for i in order:
        n = len(examples[i].input_ids)
        if n > max_len:
            raise ValueError(f"example {i} has {n} tokens > max_len={max_len}")
        for b, free in enumerate(space):
            if n <= free:
                bins[b].append(i)
                space[b] -= n
                break
        else:
            bins.append([i])
            space.append(max_len - n)

    rows = []
    for members in bins:
        row = PackedRow([], [], [], [])
        for k, i in enumerate(members):
            e = examples[i]
            row.input_ids += e.input_ids
            # The first token of a conversation must not be predicted from the previous conversation.
            row.labels += [IGNORE_INDEX] + e.labels[1:]
            row.position_ids += list(range(len(e.input_ids)))
            row.seq_ids += [k] * len(e.input_ids)
        rows.append(row)
    return rows
Listing 12First-fit-decreasing packing. The highlighted lines sort by length, stop the first token of a conversation from being a target, and restart the positions at 0.

Packing is only safe if the model cannot tell the conversations are neighbours. That takes two things: positions that restart, and attention that cannot cross a boundary. The second is a block-causal mask.

def block_causal_mask(seq_ids: torch.Tensor) -> torch.Tensor:
    """(B, L) segment ids -> (B, 1, L, L) bool mask, True where query i may attend to key j.

    Allowed iff j <= i (causal) and both tokens are in the same conversation. Padding (-1) attends to itself
    only, so no row of the mask is all False (an all-False row makes softmax produce NaN).
    """
    L = seq_ids.shape[1]
    causal = torch.ones(L, L, dtype=torch.bool, device=seq_ids.device).tril()
    same = seq_ids[:, :, None] == seq_ids[:, None, :]
    pad_self = torch.eye(L, dtype=torch.bool, device=seq_ids.device) & (seq_ids[:, :, None] < 0)
    return ((causal & same) | pad_self)[:, None]
Listing 13The block-causal mask. Padding attends to itself only, so no row of the mask is empty. An empty row would make softmax return nan.
Shapes of a packed batch
TensorShapeMeaning
input_ids, labels(B, max_len)Several conversations end to end in each row.
position_ids(B, max_len)Restarts at 0 for each conversation.
seq_ids(B, max_len)Which conversation owns each token. -1 marks padding.
attention_mask(B, 1, max_len, max_len)Boolean. True where query i may attend to key j.

Figure 3 runs the packer on five conversations, the same lengths the unit test uses. Move the slider to change the row length.

Real tokens
Padded slots
Packed slots
Packed rows

Figure 3Packing conversations of 10, 7, 12, 5 and 9 tokens. The counts are arithmetic on these lengths, not a measurement. Padding here means two rows per batch with no rounding. The last frame shows the mask of the first row: blue cells may attend.

Now measure it on the real data. The benchmark compares padded batches of 8 with packed batches of 4 rows of 256 tokens.

$ .venv/bin/python c06-post-training/benchmarks/bench_packing.py --steps 12

The CPU run is first. It times 12 steps on an AMD EPYC 7R13 with 8 threads.

2000 conversations, 62-124 tokens, 159383 real tokens
padding (8 per batch): 250112 slots, 63.7% real
packing (256 per row): 177408 slots, 89.8% real
hardware: AMD EPYC 7R13, 8 threads
batching              sec/step  targets/step  slots/step  targets/sec
padded 8 x bucket         2.25           222        1003           99
packed 4 x 256            2.48           331        1024          134

The same benchmark on one NVIDIA H100, timed over 20 steps.

2000 conversations, 62-124 tokens, 159383 real tokens
padding (8 per batch): 250112 slots, 63.7% real
packing (256 per row): 177408 slots, 89.8% real
hardware: NVIDIA H100 80GB HBM3, torch 2.15.0, CUDA 13.2
batching              sec/step  targets/step  slots/step  targets/sec
padded 8 x bucket         0.17           224         998         1332
packed 4 x 256            0.16           329        1024         2118

Packing fills 89.8% of its slots with real tokens. Padding fills 63.7%. The slot fractions are exact and do not depend on the hardware. The target tokens per step depend on the batches drawn, so they differ a little between runs. So a step of about the same size carries more of what we grade. On the CPU run that is about 331 target tokens per packed step against 222 per padded step. On the H100 run it is 329 against 224.

On the CPU, a packed step took 2.48 s and a padded step took 2.25 s. That gives 134 target tokens per second against 99. On the H100, a packed step took 0.16 s and a padded step took 0.17 s. That gives 2,118 against 1,332 target tokens per second. The hardware was shared with other jobs, and step times vary from run to run, so read the seconds as rough. Each number comes from one run.

def test_packed_logits_equal_unpacked_logits():
    model = tiny_llama()
    a, b = _ex(range(3, 13)), _ex(range(20, 27))
    batch = collate_packed(pack_examples([a, b], 24), 24, pad_id=0)
    with torch.no_grad():
        packed = model(input_ids=batch["input_ids"], attention_mask=batch["attention_mask"],
                       position_ids=batch["position_ids"], use_cache=False).logits
        alone_b = model(input_ids=torch.tensor([b.input_ids])).logits
    torch.testing.assert_close(packed[0, 10:17], alone_b[0], atol=1e-5, rtol=1e-5)
def test_naive_packing_leaks_across_conversations():
    model = tiny_llama()
    a, b = _ex(range(3, 13)), _ex(range(20, 27))
    ids = torch.tensor([a.input_ids + b.input_ids])
    with torch.no_grad():
        naive = model(input_ids=ids).logits  # one long causal sequence: b attends to a
        alone_b = model(input_ids=torch.tensor([b.input_ids])).logits
    assert (naive[0, 10:] - alone_b[0]).abs().max() > 1e-2

Checkpoint

  • Packed logits equal the logits of the conversation run alone.
  • test_block_mask_is_causal_and_block_diagonal passes.
Step 06Stage 1: SFT

Write the SFT loop and train

Goal A plain PyTorch loop that teaches the base model the answer format, plus a measure of what it learned.

The loop is ordinary, which is the point. It uses the masked loss, AdamW, gradient clipping, and a schedule with linear warmup and cosine decay down to 10% of the peak.

def lr_at(step: int, cfg: SFTConfig) -> float:
    """Linear warmup, then cosine decay to 10% of the peak."""
    if step < cfg.warmup:
        return cfg.lr * (step + 1) / cfg.warmup
    t = (step - cfg.warmup) / max(1, cfg.steps - cfg.warmup)
    return cfg.lr * (0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * t)))
def train_sft(model, examples: list[ChatExample], pad_id: int, cfg: SFTConfig, device: torch.device) -> list[dict]:
    """Plain PyTorch SFT loop. Returns one log dict per `log_every` steps."""
    params = [p for p in model.parameters() if p.requires_grad]
    opt = torch.optim.AdamW(params, lr=cfg.lr, weight_decay=cfg.weight_decay)
    model.train()
    stream = batches(examples, cfg.batch_size, pad_id, cfg.pack, cfg.max_len, cfg.seed)
    t0, tokens, peak = time.time(), 0, 0.0
    for step in range(cfg.steps):
        batch = {k: v.to(device) for k, v in next(stream).items()}
        for g in opt.param_groups:
            g["lr"] = lr_at(step, cfg)
        model_inputs = {k: batch[k] for k in ("input_ids", "attention_mask", "position_ids") if k in batch}
        logits = model(**model_inputs, use_cache=False).logits
        loss = masked_lm_loss(logits, batch["labels"])
        peak = max(peak, device_memory_mb(device))  # params + optimizer state + live activations
        loss.backward()
        peak = max(peak, device_memory_mb(device))  # params + optimizer state + gradients
        torch.nn.utils.clip_grad_norm_(params, 1.0)
        opt.step()
        opt.zero_grad(set_to_none=True)
        tokens += int((batch["labels"] != IGNORE_INDEX).sum())
        if (step + 1) % cfg.log_every == 0 or step == 0:
            synchronize(device)
            row = {"step": step + 1, "loss": round(loss.item(), 4), "lr": lr_at(step, cfg),
                   "target_tokens": tokens, "sec": round(time.time() - t0, 1), "mem_mb": round(peak, 1)}
            if cfg.eval_fn is not None and cfg.eval_every and (step + 1) % cfg.eval_every == 0:
                row["eval"] = cfg.eval_fn(model)
            cfg.history.append(row)
            print(row, flush=True)
    return cfg.history
Listing 17The SFT loop. The only line specific to post-training is the loss, and use_cache=False keeps packing safe.

Accuracy is measured with greedy decoding on held-out prompts, and split by problem kind. We also record format: the fraction of replies that contain a parseable answer. The two can move apart, and that gap tells us what was learned.

@torch.no_grad()
def evaluate(
    model: torch.nn.Module,
    tok: PreTrainedTokenizerBase,
    problems: list[Problem],
    batch_size: int = 64,
    max_new_tokens: int = 48,
) -> dict[str, float]:
    """Returns accuracy overall and per kind, plus the fraction of completions with a parseable answer."""
    was_training = model.training
    model.eval()
    hits: dict[str, list[float]] = defaultdict(list)
    formatted = []
    for s in range(0, len(problems), batch_size):
        chunk = problems[s : s + batch_size]
        prompts = [encode_prompt(tok, to_messages(p, with_answer=False)) for p in chunk]
        gen = generate(model, tok, prompts, max_new_tokens=max_new_tokens, do_sample=False)
        for p, text in zip(chunk, gen.texts):
            r = exact_reward(text, p.answer)
            hits[p.kind].append(r)
            hits["all"].append(r)
            formatted.append(extract_answer(text) is not None)
    model.train(was_training)
    result = {k: sum(v) / len(v) for k, v in hits.items()}
    result["format"] = sum(formatted) / len(formatted)
    return result
Listing 18Evaluation. No question in the test set appears in the training set.
$ .venv/bin/python c06-post-training/scripts/train_sft.py --mode full --steps 500
$ .venv/bin/python c06-post-training/scripts/train_sft.py --mode full --pack --batch-size 5 --steps 500
$ .venv/bin/python c06-post-training/scripts/train_sft.py --mode full --init random --steps 500

Full fine-tuning ran on both machines. Overall accuracy is the same, 74.5%. The split by problem kind differs by a couple of points, so the two runs are not identical.

sft-full  on AMD EPYC 7R13, 8 threads, 500 steps, batch 16, lr 5e-05
trainable 134,515,008 of 134,515,008
before  accuracy 0.0%  format 0.0%  (add 0.0% sub 0.0% chain 0.0% mul 0.0%)
after   accuracy 74.5%  format 100.0%  (add 98.0% sub 86.0% chain 68.0% mul 46.0%)
training time 2463.8 s, checkpoint 513.2 MB
sft-full  on NVIDIA H100 80GB HBM3, torch 2.15.0, CUDA 13.2, 500 steps, batch 16, lr 5e-05
trainable 134,515,008 of 134,515,008
before  accuracy 0.0%  format 0.0%  (add 0.0% sub 0.0% chain 0.0% mul 0.0%)
after   accuracy 74.5%  format 100.0%  (add 96.0% sub 86.0% chain 68.0% mul 48.0%)
training time 132.5 s, checkpoint 513.2 MB

The H100 took 132.5 s and the CPU took 2463.8 s. Both times include an evaluation every 50 steps. Both machines were shared with other jobs, and the repository README records an earlier identical H100 run that took 102 s. So these times are single observations, and we make no speed claim from them.

Two controls follow, both on the H100. The first starts from random weights instead of the pretrained model. The second packs the batches.

sft-full-random  on NVIDIA H100 80GB HBM3, torch 2.15.0, CUDA 13.2, 500 steps, batch 16, lr 5e-05
trainable 134,515,008 of 134,515,008
before  not evaluated (random weights)
after   accuracy 1.5%  format 100.0%  (add 2.0% sub 4.0% chain 0.0% mul 0.0%)
training time 112.0 s, checkpoint 513.2 MB
sft-full-packed  on NVIDIA H100 80GB HBM3, torch 2.15.0, CUDA 13.2, 500 steps, batch 5, lr 5e-05
trainable 134,515,008 of 134,515,008
before  accuracy 0.0%  format 0.0%  (add 0.0% sub 0.0% chain 0.0% mul 0.0%)
after   accuracy 69.0%  format 100.0%  (add 96.0% sub 80.0% chain 48.0% mul 52.0%)
training time 98.2 s, checkpoint 513.2 MB

The random-weights run is the clearest control in this tutorial. It is a randomly initialised SmolLM2-135M, trained with SFT only. We tried no DPO or RL from it. It learns the format: 100.0% of its replies contain a parseable answer. It does not learn the arithmetic: accuracy is 1.5%.

At step 500 its logged training loss is 0.35, against 0.02 for the pretrained model, and it was still falling. So 500 steps may simply be too few for a model trained from scratch. Within this budget, the arithmetic does not come from SFT alone. The likely reading is that pretraining put the capability in the weights, and SFT teaches the model to show it in the right form. The base model scores 0.0% before SFT because it never writes The answer is N., and its format score is also 0.0%.

The packed run scored 69.0%, below the padded run. It used 5 rows of 256 tokens per batch, chosen to give about as many tokens per step as the padded batch of 16. The two runs took the same number of steps, but the packed run saw fewer target tokens. By step 500 it had seen 206,376 and the padded run 230,348 (the target_tokens field in each saved history). This is one seed, and one standard error on 200 prompts is about 3 points. The gap is confounded by that token deficit and by the different batch size. A 5.5-point gap is also within the noise we expect. So this run does not show that packing hurts quality.

Each script draws its own 200 held-out prompts. The periodic evaluation inside a run uses only the first 100 of them, and the final evaluation uses all 200. So the two can differ even at the last step. The H100 full run read 77.0% on 100 prompts at step 500, and 74.5% on all 200. Later stages draw different prompts again, so the same checkpoint has a different “before” value there.

Figure 4Training loss per step for the four SFT runs on the H100. Hover for values. Each series is read from its file in results/h100/. The runs use different learning rates and batches, so compare the shapes and not the exact levels.

Checkpoint

  • A checkpoint exists at c06-post-training/checkpoints/sft-full. Every later stage loads it.
  • format rises after training. A flat format means the labels are wrong, not that the model is weak.
Step 07Stage 1: SFT

Compare full fine-tuning with LoRA

Goal Write a LoRA layer by hand, confirm it matches PEFT, and compare it with full fine-tuning on the same task.

Full fine-tuning updates every weight. LoRA freezes them and learns a small correction made of two thin matrices. The derivation is in the theory post, so here we only write the layer.

Derivation inHow LoRA changes a model without rewriting it
class LoRALinear(nn.Module):
    def __init__(self, base: nn.Linear, r: int = 16, alpha: float = 32.0, dropout: float = 0.0):
        super().__init__()
        self.base = base
        self.base.weight.requires_grad_(False)
        self.r, self.scale = r, alpha / r
        self.lora_A = nn.Parameter(torch.empty(r, base.in_features, device=base.weight.device))
        self.lora_B = nn.Parameter(torch.zeros(base.out_features, r, device=base.weight.device))
        nn.init.kaiming_uniform_(self.lora_A, a=math.sqrt(5))  # same init as PEFT
        self.dropout = nn.Dropout(dropout) if dropout > 0 else nn.Identity()

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        # x: (..., in) -> (..., out). B = 0 at init, so the wrapped model starts exactly at the base model.
        return self.base(x) + self.scale * (self.dropout(x) @ self.lora_A.T @ self.lora_B.T)

    @torch.no_grad()
    def merge(self) -> nn.Linear:
        """Fold B A into W so inference costs nothing extra."""
        self.base.weight += self.scale * (self.lora_B @ self.lora_A).to(self.base.weight.dtype)
        return self.base
Listing 19The layer. lora_B starts at zero, so the wrapped model begins exactly at the base model.
Shapes inside one LoRA layer
TensorShapeTrains
base.weight (W)(out, in)No
lora_A(r, in)Yes
lora_B(out, r)Yes, starts at zero
x, output(..., in), (..., out)Output is W x plus the scaled correction.
Weights in W
Weights in A and B
Fraction

Figure 5One linear layer, frozen, with its two LoRA factors. Rectangle sizes follow the sliders. The readout is the arithmetic r(in + out) against in × out for the sizes you pick, so it counts one layer rather than a whole model.

The wrapping function walks the module tree and replaces each target projection in place. Merging reverses this and folds B A into W, so later stages can load a plain model.

def apply_lora(model: nn.Module, r: int = 16, alpha: float = 32.0, targets: tuple[str, ...] = DEFAULT_TARGETS) -> nn.Module:
    """Freeze every weight, then wrap each target nn.Linear in a LoRALinear (in place)."""
    for p in model.parameters():
        p.requires_grad_(False)
    for name, module in list(model.named_modules()):
        for child_name, child in list(module.named_children()):
            if child_name in targets and isinstance(child, nn.Linear):
                setattr(module, child_name, LoRALinear(child, r, alpha))
    return model
$ .venv/bin/python c06-post-training/scripts/train_sft.py --mode lora
sft-lora  on NVIDIA H100 80GB HBM3, torch 2.15.0, CUDA 13.2, 500 steps, batch 16, lr 0.001
trainable 4,884,480 of 139,399,488
before  accuracy 0.0%  format 0.0%  (add 0.0% sub 0.0% chain 0.0% mul 0.0%)
after   accuracy 75.0%  format 100.0%  (add 96.0% sub 84.0% chain 72.0% mul 48.0%)
training time 208.5 s, checkpoint 18.7 MB
Full fine-tuning against LoRA on the NVIDIA H100, same data and step count, computed from results/h100/
AspectFullLoRA r=16
Trainable parameters134,515,0084,884,480
Learning rate5e-050.001
Held-out accuracy after74.5%75.0%
Checkpoint size513.2 MB18.7 MB
Peak GPU memory, training only, batch 165,938 MiB4,695 MiB

LoRA matches full fine-tuning on this task, 75.0% against 74.5%, with 4,884,480 trainable parameters instead of 134,515,008. The saved adapter is 18.7 MB, against 513.2 MB for the full model. A gap of half a point is well inside the noise of one seed. The two runs use different learning rates, 1e-3 for LoRA and 5e-5 for full fine-tuning. A larger learning rate for adapters is common practice.

The table leaves out time on purpose. The H100 runs took 132.5 s for full fine-tuning and 208.5 s for LoRA, one run each. Run-to-run variation on this shared hardware was large enough that we do not call that a speed difference.

Memory needs its own benchmark. Peak memory only ever goes up, so one evaluation that generates text would hide the training number. bench_memory.py therefore runs each mode in a fresh process that only loads the model and takes optimizer steps. The H100 run is below. It used 20 steps at batch 16.

$ POSTTRAIN_RESULTS=h100 .venv/bin/python c06-post-training/benchmarks/bench_memory.py --steps 20
hardware: NVIDIA H100 80GB HBM3, torch 2.15.0, CUDA 13.2, batch 16, memory = peak CUDA memory allocated
MiB columns: peak so far after loading, then after the first forward, backward and optimizer step
mode         trainable   loaded  forward  backward  opt step    peak  sec/step
full       134,515,008      521     4516      4898      4898    5938      0.24
lora         4,884,480      540     4275      4657      4657    4695      0.31

On the H100 at batch 16, LoRA's peak is 4,695 MiB and full fine-tuning's is 5,938 MiB. That is about 21% lower for LoRA. The seconds per step in the last column are single runs and are noisy, so we draw no speed comparison from them.

def device_memory_mb(device: torch.device) -> float:
    """Memory in MiB: peak allocated on CUDA, currently allocated on MPS, peak resident set of this process on CPU.

    The CPU number includes Python and the libraries, so it only compares runs made in separate processes.
    """
    if device.type == "cuda":
        return torch.cuda.max_memory_allocated() / 2**20
    if device.type == "mps":
        return torch.mps.current_allocated_memory() / 2**20
    peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss  # KiB on Linux, bytes on macOS
    return peak / 2**20 if sys.platform == "darwin" else peak / 2**10
Listing 22What the memory number means on each device.

The same benchmark on the CPU gives a different answer. The CPU number is the peak resident memory of the whole process, so it includes Python and the libraries. These runs took 10 steps each, at batch 16 and at batch 2.

$ .venv/bin/python c06-post-training/benchmarks/bench_memory.py --steps 10
$ .venv/bin/python c06-post-training/benchmarks/bench_memory.py --steps 10 --batch-size 2 --out bench_memory_b2.json
hardware: AMD EPYC 7R13, 8 threads, batch 16, memory = peak of the training process
MiB columns: peak so far after loading, then after the first forward, backward and optimizer step
mode         trainable   loaded  forward  backward  opt step    peak  sec/step
full       134,515,008     1171     5432      5814      5814    7045      4.70
lora         4,884,480     1192     7001      7381      7381    7381      8.25
hardware: AMD EPYC 7R13, 8 threads, batch 2, memory = peak of the training process
MiB columns: peak so far after loading, then after the first forward, backward and optimizer step
mode         trainable   loaded  forward  backward  opt step    peak  sec/step
full       134,515,008     1195     1355      2014      2854    3165      1.09
lora         4,884,480     1220     1532      1568      1568    1897      0.73

Checkpoint

  • test_lora_starts_at_the_base_model and test_only_adapter_weights_train pass.
  • test_merge_preserves_outputs_and_removes_the_wrappers passes.
Step 08Stage 2: DPO

Build a preference dataset

Goal Prompt, chosen and rejected, laid out as tensors so that the prompt can never enter the score.

The SFT model can write in the right form, but it still gets sums wrong. Now we change the signal. Instead of giving the answer, we say which of two answers is better. A preference pair has three parts.

prompt
chosen
rejected

We build pairs in two ways. The first is synthetic. The chosen reply is the correct solution, and the rejected reply is the same solution with a carry-sized error, so the two differ only in the digits that matter.

def synthetic_pairs(problems: list[Problem], seed: int = 0) -> list[dict]:
    """Chosen = the correct worked solution. Rejected = the same solution with a carry-sized error."""
    rng = random.Random(seed)
    pairs = []
    for p in problems:
        pairs.append({
            "prompt": to_messages(p, with_answer=False),
            "chosen": [{"role": "assistant", "content": p.solution()}],
            "rejected": [{"role": "assistant", "content": near_miss(rng, p)}],
            "answer": p.answer,
        })
    return pairs
def near_miss(rng: random.Random, p: Problem) -> str:
    """A plausible wrong solution: the same steps with one result off by a carry-sized error."""
    delta = rng.choice([-10, -1, 1, 10, 2, -2])
    wrong = p.answer + delta
    steps = list(p.steps)
    lhs = steps[-1].rsplit("=", 1)[0]
    steps[-1] = f"{lhs}= {wrong}."
    return " ".join(steps) + f" The answer is {wrong}."

The second way is on-policy. We sample from the SFT model itself, then pair one of its right answers with one of its wrong answers on the same prompt. These are the mistakes this model actually makes. A prompt where every sample is right, or every sample is wrong, gives no pair.

@torch.no_grad()
def on_policy_pairs(model, tok, problems: list[Problem], samples: int = 4, temperature: float = 1.0) -> list[dict]:
    """Sample from the SFT model; pair one of its correct answers with one of its wrong answers.

    Prompts where all samples are right (or all wrong) give no pair, which is itself a useful statistic.
    """
    pairs = []
    prompts = [encode_prompt(tok, to_messages(p, with_answer=False)) for p in problems]
    for s in range(0, len(problems), 16):
        chunk = problems[s : s + 16]
        gen = generate(model, tok, [q for q in prompts[s : s + 16] for _ in range(samples)], temperature=temperature)
        for i, p in enumerate(chunk):
            texts = gen.texts[i * samples : (i + 1) * samples]
            good = [t for t in texts if exact_reward(t, p.answer) == 1.0]
            bad = [t for t in texts if exact_reward(t, p.answer) == 0.0]
            if good and bad:
                pairs.append({
                    "prompt": to_messages(p, with_answer=False),
                    "chosen": [{"role": "assistant", "content": good[0]}],
                    "rejected": [{"role": "assistant", "content": bad[0]}],
                    "answer": p.answer,
                })
    return pairs
Listing 25On-policy pairs. The number of usable pairs is itself a measurement of how uncertain the model is.

Next, tensors. We tokenize the prompt with its generation header. Each completion is whatever follows the prompt in the full rendered conversation, so it includes <|im_end|> and the trailing newline.

def tokenize_pair(tok, pair: dict) -> dict[str, list[int]]:
    """prompt_ids, chosen_ids, rejected_ids, split the way TRL splits them.

    The prompt is rendered with the generation header; each completion is the rest of the full conversation,
    so it includes <|im_end|> and the template's trailing newline.
    """
    prompt_ids = encode_prompt(tok, pair["prompt"])
    full = {}
    for key in ("chosen", "rejected"):
        text = tok.apply_chat_template(pair["prompt"] + pair[key], tokenize=False)
        full[key] = tok(text, add_special_tokens=False)["input_ids"]
    n = min(_common_prefix(prompt_ids, full["chosen"]), _common_prefix(prompt_ids, full["rejected"]))
    return {"prompt_ids": prompt_ids[:n], "chosen_ids": full["chosen"][n:], "rejected_ids": full["rejected"][n:]}
def collate_pairs(examples: list[dict[str, list[int]]], pad_id: int, multiple: int = 1) -> dict[str, torch.Tensor]:
    """Right-padded (2B, L) batch: rows [0, B) are prompt+chosen, rows [B, 2B) are prompt+rejected.

    completion_mask is 1 on response tokens only, so the prompt never contributes to log pi(y|x).
    """
    rows, masks = [], []
    for key in ("chosen_ids", "rejected_ids"):
        for e in examples:
            rows.append(e["prompt_ids"] + e[key])
            masks.append([0] * len(e["prompt_ids"]) + [1] * len(e[key]))
    L = -(-max(len(r) for r in rows) // multiple) * multiple
    ids = torch.full((len(rows), L), pad_id, dtype=torch.long)
    attn = torch.zeros((len(rows), L), dtype=torch.long)
    cmask = torch.zeros((len(rows), L), dtype=torch.long)
    for i, (r, m) in enumerate(zip(rows, masks)):
        ids[i, : len(r)] = torch.tensor(r)
        attn[i, : len(r)] = 1
        cmask[i, : len(m)] = torch.tensor(m)
    return {"input_ids": ids, "attention_mask": attn, "completion_mask": cmask}
Listing 27Collation. Chosen rows come first and rejected rows second, so chunk(2) recovers them. completion_mask is 1 on response tokens only.
Shapes of a preference batch with B pairs
TensorShapeMeaning
input_ids(2B, L)Rows 0 to B−1 are prompt + chosen. Rows B to 2B−1 are prompt + rejected.
attention_mask(2B, L)1 on real tokens, 0 on right padding.
completion_mask(2B, L)1 on response tokens, 0 on prompt and padding.

Checkpoint

  • A chosen row and its rejected row have identical prompt tokens.
  • completion_mask sums to the reply length for each row.
Step 09Stage 2: DPO

Compute sequence log-probabilities

Goal The probability the model gives a whole reply, as a sum over tokens. DPO, REINFORCE and GRPO all use it.

The chain rule says a reply’s log-probability is a sum: log π(y | x) = Σt log π(yt | x, y<t). Start with the naive version, which is a Python loop. It sits in a test, because it is the reference every faster version must match.

def test_sequence_logprob_matches_explicit_loop():
    model = tiny_llama()
    ids, attn, comp = _batch()
    with torch.no_grad():
        got = sequence_logprobs(model, ids, attn, comp)
        logits = model(input_ids=ids, attention_mask=attn).logits
    log_p = logits.log_softmax(-1)
    for row in range(2):
        want = sum(log_p[row, t - 1, ids[row, t]] for t in range(ids.shape[1]) if comp[row, t])
        assert abs(got[row].item() - want.item()) < 1e-4
Listing 28The naive version: for each completion token, read the log-probability from the position before it.

Now the batched version. gather_logprobs picks the target’s log-probability without building the whole log-softmax tensor. For a vocabulary of size V that saves a large allocation at every position.

def gather_logprobs(logits: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
    """log softmax(logits)[target] without materialising the full (B, T, V) log-softmax.

    logits: (B, T, V)   targets: (B, T)   ->   (B, T)
    """
    logits = logits.float()  # bf16 keeps about 3 significant digits; ratios of log-probs need more
    picked = torch.gather(logits, -1, targets.unsqueeze(-1)).squeeze(-1)
    return picked - torch.logsumexp(logits, dim=-1)
Listing 29Log-softmax at the target only: the picked logit minus logsumexp over the vocabulary.
def per_token_logprobs(
    model: torch.nn.Module, input_ids: torch.Tensor, attention_mask: torch.Tensor, logits_to_keep: int | None = None
) -> torch.Tensor:
    """Log-prob of every token given its prefix.

    input_ids, attention_mask: (B, L).
    Returns (B, L - 1) aligned with input_ids[:, 1:], or (B, K) for the last K tokens if logits_to_keep=K.
    """
    kwargs = {}
    if logits_to_keep is not None:
        # One extra position: the logit before the first kept token predicts it.
        kwargs["logits_to_keep"] = logits_to_keep + 1
    out = model(
        input_ids=input_ids,
        attention_mask=attention_mask,
        position_ids=position_ids_from_mask(attention_mask),
        use_cache=False,
        **kwargs,
    )
    logits = out.logits[:, :-1]  # (B, L-1, V) or (B, K, V)
    targets = input_ids[:, 1:] if logits_to_keep is None else input_ids[:, -logits_to_keep:]
    return gather_logprobs(logits, targets)
def sequence_logprobs(
    model: torch.nn.Module,
    input_ids: torch.Tensor,
    attention_mask: torch.Tensor,
    completion_mask: torch.Tensor,
    average: bool = False,
) -> torch.Tensor:
    """Sum (or mean) of log-probs over completion tokens only.

    input_ids, attention_mask, completion_mask: (B, L), completion_mask = 1 on response tokens.
    Returns (B,).
    """
    logps = per_token_logprobs(model, input_ids, attention_mask)  # (B, L-1)
    mask = completion_mask[:, 1:].to(logps.dtype)  # token t+1 is scored by logits at t
    total = (logps * mask).sum(-1)
    return total / mask.sum(-1).clamp(min=1) if average else total
Listing 31The sum over completion tokens. The mask shifts by one as well, because token t+1 is scored by logits at t.
Shapes in a sequence log-probability
TensorShapeMeaning
logits(2B, L−1, V)After dropping the last position.
targets(2B, L−1)input_ids[:, 1:].
logps(2B, L−1)Log-probability of each actual next token.
mask(2B, L−1)completion_mask[:, 1:].
total(2B,)One number per row.

Figure 6 walks through these tensors for one pair.

Figure 6One preference pair, tensor by tensor.
$ .venv/bin/python c06-post-training/scripts/inspect_state.py
prompt 44 tokens, chosen 20 tokens, rejected 22 tokens
chosen_ids sum log-prob -0.144
   '3':-0.00 '9':0.00 ' +':-0.00 ' ':-0.00 '5':0.00 '7':-0.00 ' =':0.00 ' ':-0.00 '9':-0.00 '6':-0.00 '.':0.00 ' The':-0.00 ' answer':-0.00 ' is':0.00 ' ':-0.00 '9':-0.00 '6':-0.00 '.':0.00 '<|im_end|>':-0.01 '\n':-0.14
rejected_ids sum log-prob -7.184
   '3':-0.00 '9':0.00 ' +':-0.00 ' ':-0.00 '5':0.00 '7':-0.00 ' =':0.00 ' ':-0.00 '1':-6.00 '0':-1.05 '6':-0.00 '.':0.00 ' The':-0.00 ' answer':-0.00 ' is':0.00 ' ':0.00 '1':-0.00 '0':0.00 '6':-0.00 '.':0.00 '<|im_end|>':-0.01 '\n':-0.13

Checkpoint

  • test_sequence_logprob_matches_explicit_loop passes.
  • test_padding_does_not_change_sequence_logprob and test_left_and_right_padding_agree pass.
Step 10Stage 2: DPO

Freeze a reference and write the DPO loss

Goal The DPO loss in a few lines, with a reference model that takes no gradient and no updates.

DPO rewards the policy for moving probability toward the chosen reply, relative to where it started. Where it started is the reference: a frozen copy of the SFT model. The theory post derives why this ratio acts as an implicit reward.

Derivation inTeaching a model what we prefer
def frozen_copy(model: torch.nn.Module) -> torch.nn.Module:
    """A reference model: same weights, eval mode, no gradients, never updated."""
    ref = copy.deepcopy(model)
    ref.eval()
    for p in ref.parameters():
        p.requires_grad_(False)
    return ref
Listing 32The reference. Same weights, eval mode, no gradients, never updated.
def dpo_loss(
    policy_chosen: torch.Tensor,
    policy_rejected: torch.Tensor,
    ref_chosen: torch.Tensor,
    ref_rejected: torch.Tensor,
    beta: float = 0.1,
) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:
    """All inputs are (B,) summed sequence log-probs. Returns the mean loss and the implicit rewards."""
    chosen_reward = beta * (policy_chosen - ref_chosen)  # implicit reward r = beta * log(pi / ref)
    rejected_reward = beta * (policy_rejected - ref_rejected)
    margin = chosen_reward - rejected_reward
    loss = -F.logsigmoid(margin).mean()
    return loss, {
        "chosen_reward": chosen_reward.detach(),
        "rejected_reward": rejected_reward.detach(),
        "margin": margin.detach(),
        "accuracy": (margin > 0).float().detach(),
    }
Listing 33The loss. Every input has shape (B,). We write the implicit reward as its own line, because it is the idea of the whole method.
def dpo_batch_loss(policy, ref, batch: dict[str, torch.Tensor], beta: float = 0.1, average: bool = False):
    """Forward the policy (with grad) and the frozen reference (without) on one collated batch."""
    args = (batch["input_ids"], batch["attention_mask"], batch["completion_mask"])
    logps = sequence_logprobs(policy, *args, average=average)  # (2B,)
    with torch.no_grad():
        ref_logps = sequence_logprobs(ref, *args, average=average)
    pc, pr = logps.chunk(2)
    rc, rr = ref_logps.chunk(2)
    return dpo_loss(pc, pr, rc, rr, beta)
Listing 34One batch: the policy with gradients, the reference without, both over the same (2B, L) tensors.

Before any training we can predict the first loss. The reference equals the policy, so both log-ratios are 0, the margin is 0, and the loss is −log σ(0) = log 2, about 0.6931. Any other first value means the two models differ. Dropout left on, for example.

Play with the loss in Figure 7. The readout that matters most is the gradient weight.

Margin
Loss
Gradient weight σ(−m)
Figure 7The DPO loss for one pair. Δ chosen is log π(chosen) − log ref(chosen), and Δ rejected is the same for the rejected reply. These are formula values for numbers you choose, not a training run. The margin is β (Δ chosen − Δ rejected).

Checkpoint

  • The first logged DPO loss is 0.6931.
  • test_matches_trl_dpo_trainer_on_the_same_batch passes. It downloads a tokenizer.
Step 11Stage 2: DPO

Train DPO, then debug it on purpose

Goal Run DPO on both kinds of pairs, then see what each classic bug looks like.

    for step in range(args.steps):
        chunk = rng.sample(examples, args.batch_size)
        batch = {k: v.to(device) for k, v in collate_pairs(chunk, tok.pad_token_id, multiple=32).items()}
        loss, m = dpo_batch_loss(policy, ref, batch, beta=args.beta)
        loss.backward()
        torch.nn.utils.clip_grad_norm_(policy.parameters(), 1.0)
        opt.step()
        opt.zero_grad(set_to_none=True)
Listing 38The training step. Only the loss differs from SFT.
$ .venv/bin/python c06-post-training/scripts/train_dpo.py --pairs synthetic --steps 200
$ .venv/bin/python c06-post-training/scripts/train_dpo.py --pairs on-policy --steps 200
$ .venv/bin/python c06-post-training/scripts/train_dpo.py --pairs synthetic --steps 200 --lr 1e-6 --tag dpo-synthetic-lr1e-6
$ .venv/bin/python c06-post-training/scripts/train_dpo.py --pairs on-policy --steps 200 --lr 1e-6 --tag dpo-on-policy-lr1e-6

All four runs below are on one NVIDIA H100, start from the SFT checkpoint trained on that machine, and use full fine-tuning with beta 0.1 and a batch of 4 pairs. The first two use the default learning rate, 5e-6.

dpo-synthetic  on NVIDIA H100 80GB HBM3, torch 2.15.0, CUDA 13.2, 200 steps, beta 0.1, lr 5e-06, 800 pairs
before  accuracy 79.5%  format 100.0%  (add 100.0% sub 86.0% chain 62.0% mul 70.0%)
after   accuracy 44.5%  format 99.5%  (add 88.0% sub 46.0% chain 14.0% mul 30.0%)
last logged step: step 200  loss 0.45  margin 0.624  pair_acc 0.75
dpo-on-policy  on NVIDIA H100 80GB HBM3, torch 2.15.0, CUDA 13.2, 200 steps, beta 0.1, lr 5e-06, 305 pairs
before  accuracy 79.5%  format 100.0%  (add 100.0% sub 86.0% chain 62.0% mul 70.0%)
after   accuracy 42.0%  format 100.0%  (add 70.0% sub 36.0% chain 30.0% mul 32.0%)
last logged step: step 200  loss 0.3951  margin 0.742  pair_acc 1.0

The accuracy went down. These prompts are unseen by the stage being trained, but about 26 to 29% of their questions also appeared in the SFT training set. Before and after numbers within the stage still compare like with like. The same checkpoint scored 79.5% before DPO on this script’s 200 held-out prompts, and 44.5% after DPO on synthetic pairs and 42.0% after DPO on on-policy pairs. Note that 79.5% is not the 74.5% of the SFT step. Each script draws its own held-out prompts, so compare a stage only with its own “before” value. A lower learning rate hurts less. It does not fix it.

DPO runs on NVIDIA H100 80GB HBM3, torch 2.15.0, CUDA 13.2, computed from results/
PairsLearning ratePairs usedAccuracy beforeAccuracy afteradd / sub / chain / mul afterMean margin, last 10 logged batchesPair accuracy per logged batch of 4: lowest after step 1 / last
synthetic pairs5e-680079.5%44.5%88 / 46 / 14 / 300.440.50 / 0.75
on-policy pairs5e-630579.5%42.0%70 / 36 / 30 / 320.680.00 / 1.00
synthetic pairs1e-680079.5%66.5%96 / 70 / 52 / 480.200.25 / 1.00
on-policy pairs1e-630579.5%65.5%96 / 66 / 48 / 520.230.25 / 1.00

Greedy accuracy on 200 held-out prompts, one seed per row. One standard error is about 3 points. These prompts are unseen by DPO, but about 26 to 29% of their questions also appeared in the SFT training set.

DPO fails quietly. Every bug below produces a loss that runs and often goes down. Each bug in the list has a test here. The script break_it.py runs most of them on the real model.

$ .venv/bin/python c06-post-training/scripts/break_it.py
[ref has grad]  gradient norm that lands on the reference: 3.95 (must be 0)
[sum vs mean]  reply ~23 tokens. |margin| sum 0.0031, mean 0.0001. grad norm sum 3.96, mean 0.19
(on AMD EPYC 7R13, 8 threads)
The DPO debugging list
BugSymptomHow to catch itTest
Prompt tokens in the scoreThe score is dominated by a part both replies share.Compare with the explicit loop.test_prompt_tokens_do_not_count
Padding in the scoreA row’s score changes with its batch.Score a row alone and in a batch.test_padding_does_not_change_sequence_logprob
Off-by-one on the maskThe first reply token drops out, and a pad token can enter.Print one row, token by token.test_sequence_logprob_matches_explicit_loop
Mean instead of sumThe margin shrinks by about the reply length, so β means something else.Log the margin, not only the loss.test_sum_vs_mean_changes_the_margin
Reference is the policyThe margin stays at 0 and the loss at log 2. The gradient is not 0.A loss of 0.6931 and a margin of 0 that never move after step 0.test_equal_policy_and_reference_give_log_two is the closest. test_reference_copy_is_frozen checks only eval mode and no gradients. Neither catches passing the policy object itself.
Reference has gradientsGradient lands on a model that should not move, and a second graph costs memory.Check p.grad is None on the reference.test_reference_gets_no_gradient

Checkpoint

  • All tests in tests/test_dpo.py pass.
  • break_it.py reports a non-zero gradient on an unfrozen reference. test_reference_gets_no_gradient shows the frozen one gets none.
Step 12Stage 3: reward model, optional

Train a pairwise reward model

Goal See the explicit reward model that DPO lets us skip, and see that its loss has the same form.

The older route to preferences trains a separate model to score replies, and then trains the policy with reinforcement learning against that score. This step is optional. We build only the scorer, because seeing it clarifies what DPO removes.

class RewardModel(nn.Module):
    def __init__(self, name_or_path: str):
        super().__init__()
        self.body = AutoModel.from_pretrained(name_or_path)  # the decoder without its LM head
        self.head = nn.Linear(self.body.config.hidden_size, 1)
        nn.init.zeros_(self.head.weight)
        nn.init.zeros_(self.head.bias)

    def forward(self, input_ids: torch.Tensor, attention_mask: torch.Tensor) -> torch.Tensor:
        """(B, L) right-padded -> (B,) scores, read at each row's last real token."""
        h = self.body(input_ids=input_ids, attention_mask=attention_mask, use_cache=False).last_hidden_state
        last = attention_mask.sum(-1) - 1  # (B,) index of the last non-pad token
        h_last = h[torch.arange(h.shape[0], device=h.device), last]  # (B, D)
        return self.head(h_last).squeeze(-1)
Listing 39A transformer body with one linear head, read at the last real token. The head starts at zero, so every reply starts with score 0.
def pairwise_loss(chosen: torch.Tensor, rejected: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
    """Bradley-Terry: (B,), (B,) -> mean loss, accuracy (fraction with chosen scored higher)."""
    return -F.logsigmoid(chosen - rejected).mean(), (chosen > rejected).float().mean()
Listing 40The Bradley-Terry loss.
$ .venv/bin/python c06-post-training/scripts/train_reward_model.py --steps 300
$ .venv/bin/python c06-post-training/scripts/train_reward_model.py --steps 1500 --batch-size 16 --tag reward_model_long
on NVIDIA H100 80GB HBM3, torch 2.15.0, CUDA 13.2, 300 steps
held-out pair accuracy before: 0.000
held-out pair accuracy after:  0.555
on NVIDIA H100 80GB HBM3, torch 2.15.0, CUDA 13.2, 1500 steps
held-out pair accuracy before: 0.000
held-out pair accuracy after:  0.595
Reward model runs on NVIDIA H100 80GB HBM3, torch 2.15.0, CUDA 13.2, computed from results/
RunBatchHeld-out pair accuracyTraining accuracy at the last step
300 steps455.5%0.75
1500 steps1659.5%1.00

Chance is 50%. The held-out set is 200 pairs, so one standard error is about 3.5 points. These pairs are unseen by the reward model, but about 26 to 29% of their questions also appeared in the SFT training set.

Checkpoint

  • Accuracy before training reflects a head at zero. All scores tie, so the strict comparison chosen > rejected counts no hits.
  • test_pairwise_loss_by_hand passes.
Step 13Stage 4: REINFORCE

Write REINFORCE and measure its noise

Goal The simplest policy gradient, plus a meter that shows why nobody stops there.

Now the model samples its own answers, and a checker scores them. The simplest update is REINFORCE: raise the log-probability of each sample in proportion to its reward.

Derivation inReinforcement learning from first principles
prompt
 ↓
rollout
 ↓
reward
 ↓
policy gradient
def reinforce_loss(logps: torch.Tensor, mask: torch.Tensor, weights: torch.Tensor) -> torch.Tensor:
    """-(weight * log pi(y|x)).mean() over sequences.

    logps, mask: (N, C) per-token log-probs and completion mask.  weights: (N,) = R - b, no grad.
    The sum over tokens (not the mean) is what makes this the true gradient of log pi(y|x).
    """
    seq_logp = (logps * mask.to(logps.dtype)).sum(-1)  # (N,)
    return -(weights.detach() * seq_logp).mean()
Listing 41REINFORCE. It sums over tokens because log π(y | x) is a sum. It uses the same quantity as DPO, now multiplied by a weight.

With a 0 or 1 reward and no baseline, every wrong sample contributes nothing. Every right sample pushes up whatever it happened to say. A baseline fixes the first problem. We compare four weightings on the same budget of rollouts.

def estimator_weights(rewards: torch.Tensor, group_size: int, estimator: str) -> torch.Tensor:
    """Per-sample weights for the four estimators compared in scripts/reinforce_variance.py.

    "none":      R                     (vanilla REINFORCE)
    "batch":     R - mean over batch   (one shared baseline)
    "group":     R - mean over the G samples of the same prompt (RLOO-style, without leave-one-out)
    "group_std": (R - group mean) / group std  (GRPO advantages)
    """
    if estimator == "none":
        return rewards
    if estimator == "batch":
        return rewards - rewards.mean()
    if estimator == "group":
        return group_advantages(rewards, group_size, scale="none")
    if estimator == "group_std":
        return group_advantages(rewards, group_size, scale="group")
    raise ValueError(estimator)

Try them in Figure 8. Each cell is one sampled reply. Click a cell to flip its reward. Then step through the estimators.

Estimator
Flat groups
Sum of weights

Figure 8Three prompts with four samples each. Rewards are yours to set. The weights are computed by the same formulas as estimator_weights, including the unbiased standard deviation and eps = 1e-4. They are not a training run.

To measure noise, we draw several independent gradient estimates for the same policy. Two estimates of one gradient should point the same way, so we report their mean pairwise cosine and a signal-to-noise ratio.

Two limits on this measurement. The gradient is that of the last transformer block only, 3,540,096 of the 134,515,008 parameters, and not of the whole model. And each of the 12 estimates for an estimator uses a fresh slice of prompts from one pool, 32 prompts for the two one-sample estimators and 8 for the two group estimators. So the estimates are independent draws over prompts and samples, and not repeated draws for one fixed batch. The estimators also see different prompt slices from each other.

def gradient_noise(grads: torch.Tensor) -> dict[str, float]:
    """grads: (K, D), K independent estimates of the same gradient.

    Returns the signal-to-noise ratio ||mean||^2 / E||g - mean||^2 and the mean pairwise cosine similarity.
    Pairwise cosine near 0 means two independent batches disagree about which way to move.
    """
    mean = grads.mean(0)
    noise = ((grads - mean) ** 2).sum(-1).mean()
    unit = grads / grads.norm(dim=-1, keepdim=True).clamp(min=1e-12)
    cos = unit @ unit.T
    K = grads.shape[0]
    off_diag = (cos.sum() - cos.diagonal().sum()) / (K * (K - 1))
    return {
        "snr": float(mean.pow(2).sum() / noise.clamp(min=1e-30)),
        "pairwise_cos": float(off_diag),
        "mean_norm": float(grads.norm(dim=-1).mean()),
    }
$ .venv/bin/python c06-post-training/scripts/reinforce_variance.py --trials 12 --samples 32

The CPU run used the SFT checkpoint trained on the CPU. The H100 run used the checkpoint trained on the H100, so the two runs differ in both hardware and model.

hardware: AMD EPYC 7R13, 8 threads, gradient dimension 3,540,096, 32 rollouts per estimate, 12 estimates each
estimator     prompts x G  mean reward  grad norm  pairwise cos      SNR
none               32 x 1        0.656       0.73         0.037    0.147
batch              32 x 1        0.656       1.45        -0.007    0.080
group               8 x 4        0.656       1.21         0.007    0.104
group_std           8 x 4        0.656       2.29         0.005    0.101
SNR of pure noise with 12 estimates: about 0.091
hardware: NVIDIA H100 80GB HBM3, torch 2.15.0, CUDA 13.2, gradient dimension 3,540,096, 32 rollouts per estimate, 12 estimates each
estimator     prompts x G  mean reward  grad norm  pairwise cos      SNR
none               32 x 1        0.701       0.87         0.042    0.115
batch              32 x 1        0.701       1.37         0.014    0.108
group               8 x 4        0.669       1.02         0.002    0.106
group_std           8 x 4        0.669       1.86         0.002    0.106
SNR of pure noise with 12 estimates: about 0.091

Pure noise gives an SNR of about 0.091 with 12 estimates. Every estimator on both machines sits close to it, or modestly above it. For the last block, two independent gradients from 32 rollouts barely agree on a direction. That is the point of this measurement: at this budget, policy-gradient estimates of that slice are very noisy. We did not measure the other layers.

The measurement does not rank the estimators. On the CPU, the estimator with no baseline had the highest SNR, 0.147. On the H100 it did not stand out, 0.115. The two runs differ in checkpoint and in hardware, and 12 estimates per estimator is a small sample. So we cannot say whether the gap between those two numbers is real.

Do not read the CPU result as “no baseline is best”. A possible reason for its higher SNR is that, without a baseline, every rewarded sample pushes up its own log-probability. That shared direction is consistent without saying much about the reward. We did not test this.

Checkpoint

  • test_reinforce_sums_over_tokens_and_ignores_padding passes.
  • test_estimators_zero_out_constant_rewards_except_vanilla passes.
Step 14Stage 5: GRPO

Write the GRPO loss

Goal Group advantages, old log-probs, clipping, a KL penalty and token masks, each on its own line.

GRPO samples G completions per prompt and uses the group as its own baseline: Ai = (ri − μr) / σr. There is no value network to train. The reasoning behind this is in the theory post.

Derivation inHow reinforcement learning teaches models to reason
def group_advantages(rewards: torch.Tensor, group_size: int, scale: str = "group", eps: float = 1e-4) -> torch.Tensor:
    """rewards: (P * G,) laid out prompt-major (all G samples of prompt 0 first). Returns (P * G,).

    scale="group": divide by the group's std (GRPO).  scale="none": only subtract the mean (Dr. GRPO).
    A group where every sample gets the same reward has advantage 0 everywhere: it teaches nothing.
    """
    r = rewards.view(-1, group_size)  # (P, G)
    adv = r - r.mean(dim=1, keepdim=True)
    if scale == "group":
        adv = adv / (r.std(dim=1, keepdim=True) + eps)  # unbiased std, as in TRL
    return adv.reshape(-1)
Listing 44Group advantages. The rewards are laid out with all G samples of prompt 0 first.

We can check this by hand. With rewards [1, 0, 0, 0] the mean is 0.25 and the unbiased standard deviation is 0.5, so the advantages are [1.5, −0.5, −0.5, −0.5]. test_group_advantages_by_hand asserts exactly these numbers.

Now the loss. Every line below works per token, and old_logps comes from the policy that sampled the data.

def grpo_loss(
    logps: torch.Tensor,
    old_logps: torch.Tensor,
    advantages: torch.Tensor,
    mask: torch.Tensor,
    ref_logps: torch.Tensor | None = None,
    cfg: GRPOLossConfig = GRPOLossConfig(),
) -> tuple[torch.Tensor, dict[str, float]]:
    """Clipped surrogate + KL, on completion tokens only.

    logps:      (N, C) log pi_theta of each sampled token, with grad.
    old_logps:  (N, C) log pi_old, the policy that sampled the data (no grad).
    advantages: (N,)   one scalar per completion, broadcast to its tokens.
    mask:       (N, C) 1 on real completion tokens (up to and including <|im_end|>), 0 on padding.
    ref_logps:  (N, C) log pi_ref of the frozen reference (no grad), needed when beta > 0.
    """
    mask = mask.to(logps.dtype)
    ratio = torch.exp(logps - old_logps)  # 1.0 on the first inner step, by construction
    adv = advantages.unsqueeze(1)  # (N, 1)
    unclipped = ratio * adv
    clipped = torch.clamp(ratio, 1 - cfg.clip_eps, 1 + cfg.clip_eps) * adv
    per_token = -torch.min(unclipped, clipped)  # pessimistic bound: never profit from moving too far

    kl = torch.zeros_like(per_token)
    if cfg.beta > 0:
        assert ref_logps is not None, "beta > 0 needs reference log-probs"
        d = ref_logps - logps
        kl = torch.exp(d) - d - 1  # k3 estimator of KL(pi || ref): >= 0, unbiased, low variance
        per_token = per_token + cfg.beta * kl

    if cfg.loss_type == "grpo":
        loss = ((per_token * mask).sum(-1) / mask.sum(-1).clamp(min=1)).mean()
    elif cfg.loss_type == "dapo":
        loss = (per_token * mask).sum() / mask.sum().clamp(min=1)
    else:
        raise ValueError(cfg.loss_type)

    with torch.no_grad():
        n = mask.sum().clamp(min=1)
        is_clipped = ((ratio < 1 - cfg.clip_eps) & (adv < 0)) | ((ratio > 1 + cfg.clip_eps) & (adv > 0))
        stats = {
            "clip_frac": float((is_clipped.to(mask.dtype) * mask).sum() / n),
            "kl": float((kl * mask).sum() / n),
            "ratio_mean": float((ratio * mask).sum() / n),
        }
    return loss, stats
Listing 45The loss. The highlighted lines are the ratio, the clip, the pessimistic minimum, the KL penalty and the masked mean.
Shapes in the GRPO loss, for N = P × G completions of up to C tokens
TensorShapeMeaning
logps(N, C)Log πθ of each sampled token, with gradient.
old_logps(N, C)Log πold. Fixed for all inner steps.
ref_logps(N, C)Log πref, from the frozen model. Used by the KL term.
advantages(N,) → (N, 1)One scalar per completion, broadcast to its tokens.
mask(N, C)1 up to and including the first <|im_end|>.
per_token(N, C)Clipped surrogate plus β times KL.
lossscalarMean over tokens in each sequence, then over sequences.

The clip is the part most people find hard to picture. Drag the ratio in Figure 9, and flip the sign of the advantage.

Objective min(…)
Clipped
Gradient wrt ratio

Figure 9The surrogate for one token, as a function of the ratio π / πold. We maximise this value, and the loss is its negative. The thick line is the minimum of the dashed term, ratio · A, and the dotted clipped term. Its flat part has zero gradient. All values here are formula values for the inputs you pick.

The KL term uses the k3 estimator: with d = log ref − log π, it computes ed − d − 1. This is at least 0 for any d, and it is exactly 0 at the reference. It has the same purpose as the DPO reference: it stops the policy drifting too far from where it began. Setting beta=0 removes the reference model altogether.

Checkpoint

  • test_first_inner_step_has_ratio_one_and_no_clipping passes.
  • test_matches_trl_grpo_loss_on_the_same_tensors passes for both grpo and dapo.
Step 15Stage 7: rollout engine

Build the rollout engine

Goal A small system that turns prompts into a training batch, and records which policy version made each sample.

The GRPO loss needs tensors that do not exist yet. Something has to sample them, score them and pad them. This machinery becomes the larger part of an RL system once rewards get slow, so we write it as its own layer.

prompts
 ↓
generation workers
 ↓
rollouts
 ↓
reward
 ↓
training batch
 ↓
optimizer

Sampling needs left padding, so that the last prompt token of every row sits in the same column and the next token is always generated from there. The completion is then right-padded, and its mask ends at the first stop token.

def left_pad(prompts: list[list[int]], pad_id: int, multiple: int = 32) -> tuple[torch.Tensor, torch.Tensor]:
    """Left padding keeps the last prompt token of every row in the same column, which generate() needs.

    The width is rounded up to `multiple` so MPS sees few distinct shapes.
    """
    P = -(-max(len(p) for p in prompts) // multiple) * multiple
    ids = torch.full((len(prompts), P), pad_id, dtype=torch.long)
    mask = torch.zeros((len(prompts), P), dtype=torch.long)
    for i, p in enumerate(prompts):
        ids[i, P - len(p) :] = torch.tensor(p)
        mask[i, P - len(p) :] = 1
    return ids, mask
def completion_mask_from_ids(completion_ids: torch.Tensor, eos_id: int) -> tuple[torch.Tensor, torch.Tensor]:
    """1 for tokens up to and including the first eos, 0 after it. (N, C) -> (N, C), (N,)."""
    is_eos = completion_ids == eos_id
    has_eos = is_eos.any(-1)
    first = torch.where(has_eos, is_eos.int().argmax(-1), completion_ids.shape[1] - 1)
    cols = torch.arange(completion_ids.shape[1], device=completion_ids.device)
    return (cols[None, :] <= first[:, None]).long(), ~has_eos
@torch.no_grad()
def generate(
    model: torch.nn.Module,
    tok: PreTrainedTokenizerBase,
    prompts: list[list[int]],
    max_new_tokens: int = 48,
    temperature: float = 1.0,
    do_sample: bool = True,
) -> Generations:
    device = next(model.parameters()).device
    eos_id = tok.convert_tokens_to_ids("<|im_end|>")
    ids, mask = left_pad(prompts, tok.pad_token_id)
    ids, mask = ids.to(device), mask.to(device)
    # Sample from the full distribution, so the log-probs we score later are the ones that were sampled.
    sampling = {"temperature": temperature, "top_p": 1.0, "top_k": 0} if do_sample else {}
    out = model.generate(
        input_ids=ids,
        attention_mask=mask,
        max_new_tokens=max_new_tokens,
        do_sample=do_sample,
        eos_token_id=eos_id,
        pad_token_id=tok.pad_token_id,
        **sampling,
    )
    completion = out[:, ids.shape[1] :]
    cmask, truncated = completion_mask_from_ids(completion, eos_id)
    completion = completion.masked_fill(cmask == 0, tok.pad_token_id)
    texts = tok.batch_decode(completion, skip_special_tokens=True)
    return Generations(ids, mask, completion, cmask, texts, truncated)
Listing 51Sampling from the full distribution. With top-k or top-p truncation, the log-probabilities we score later would not be those of the distribution that actually sampled the tokens.

To score those tokens we run one forward pass over prompt plus completion, and keep only the last C positions. That matches TRL’s layout.

def score_completions(
    model: torch.nn.Module,
    prompt_ids: torch.Tensor,
    prompt_mask: torch.Tensor,
    completion_ids: torch.Tensor,
    completion_mask: torch.Tensor,
) -> torch.Tensor:
    """Per-token log-probs of the completion under `model`: (N, C). Same layout as TRL's GRPOTrainer."""
    input_ids = torch.cat([prompt_ids, completion_ids], dim=1)  # (N, P + C)
    attn = torch.cat([prompt_mask, completion_mask], dim=1)
    return per_token_logprobs(model, input_ids, attn, logits_to_keep=completion_ids.shape[1])

Each rollout records the problem, the tokens, its reward, and the version of the policy that produced it.

@dataclass
class Rollout:
    problem: Problem
    prompt_ids: list[int]
    completion_ids: list[int]  # up to and including <|im_end|>
    text: str
    truncated: bool
    policy_version: int
    worker_id: int
    reward: float = 0.0
class GenerationWorker:
    """Generates `group_size` samples per prompt with its own copy of the policy."""

    def __init__(self, model, tok, worker_id: int, share_weights: bool, max_new_tokens: int, temperature: float):
        # share_weights=True: the worker *is* the trainer's model (always current, no copy, no parallelism).
        self.model = model if share_weights else copy.deepcopy(model).eval()
        self.tok, self.worker_id, self.share = tok, worker_id, share_weights
        self.max_new_tokens, self.temperature = max_new_tokens, temperature
        self.version = 0

    def sync(self, policy: torch.nn.Module, version: int) -> None:
        if not self.share:
            with torch.no_grad():
                for dst, src in zip(self.model.parameters(), policy.parameters()):
                    dst.copy_(src)
        self.version = version

    def run(self, problems: list[Problem], group_size: int) -> list[Rollout]:
        prompts = [encode_prompt(self.tok, to_messages(p, with_answer=False)) for p in problems]
        flat = [q for q in prompts for _ in range(group_size)]  # prompt-major: G copies of prompt 0 first
        gen = generate(self.model, self.tok, flat, self.max_new_tokens, self.temperature, do_sample=True)
        out = []
        for i, q in enumerate(flat):
            n = int(gen.completion_mask[i].sum())
            out.append(Rollout(problems[i // group_size], q, gen.completion_ids[i, :n].tolist(), gen.texts[i],
                               bool(gen.truncated[i]), self.version, self.worker_id))
        return out
Listing 54A worker holds a policy replica. With one worker it shares the trainer’s model and copies nothing. With more, its replica only changes when the trainer pushes weights.
    def collect(self, problems: list[Problem]) -> list[Rollout]:
        """Shard prompts across workers (whole groups stay on one worker), generate, then score."""
        t = time.time()
        shards = [problems[i :: len(self.workers)] for i in range(len(self.workers))]
        futures = [self.pool.submit(w.run, s, self.group_size) for w, s in zip(self.workers, shards) if s]
        rollouts = [r for f in futures for r in f.result()]
        self.timings["generate_sec"] = time.time() - t
        t = time.time()
        for r in rollouts:  # verifiers are cheap here; for code or agents this becomes its own worker pool
            r.reward = self.reward_fn(r.text, r.problem.answer)
        self.timings["reward_sec"] = time.time() - t
        return rollouts
Listing 55Whole groups stay on one worker, so a group mean is always over samples of one prompt.
    def build_batch(self, rollouts: list[Rollout], scale: str = "group") -> dict[str, torch.Tensor]:
        """Pad rollouts into the tensors the GRPO loss consumes.

        prompt_ids, prompt_mask: (N, P) left-padded.  completion_ids, completion_mask: (N, C) right-padded.
        rewards, advantages, versions: (N,).
        """
        pad = self.tok.pad_token_id
        prompt_ids, prompt_mask = left_pad([r.prompt_ids for r in rollouts], pad)
        C = -(-max(len(r.completion_ids) for r in rollouts) // 32) * 32  # few distinct shapes for MPS
        completion_ids = torch.full((len(rollouts), C), pad, dtype=torch.long)
        completion_mask = torch.zeros((len(rollouts), C), dtype=torch.long)
        for i, r in enumerate(rollouts):
            completion_ids[i, : len(r.completion_ids)] = torch.tensor(r.completion_ids)
            completion_mask[i, : len(r.completion_ids)] = 1
        rewards = torch.tensor([r.reward for r in rollouts])
        return {
            "prompt_ids": prompt_ids,
            "prompt_mask": prompt_mask,
            "completion_ids": completion_ids,
            "completion_mask": completion_mask,
            "rewards": rewards,
            "advantages": group_advantages(rewards, self.group_size, scale=scale),
            "versions": torch.tensor([r.policy_version for r in rollouts]),
        }

Figure 10 follows one batch through the engine.

Figure 10The tensors of one rollout batch, for 2 prompts and 2 samples each. Lengths and rewards are drawn by hand to show the layout, so they are not measured.
$ .venv/bin/python c06-post-training/benchmarks/bench_rollout.py

The CPU run is first, on an AMD EPYC 7R13 with 8 threads. Each run generates 64 rollouts of up to 48 new tokens.

hardware: AMD EPYC 7R13, 8 threads, 64 rollouts, up to 48 new tokens each
engine                           sec  rollouts/sec  generate    reward
sequential (batch 4)           36.04           1.8     36.04    0.0004
batched (batch 64)              9.38           6.8      9.38    0.0002
2 workers (batch 32 each)       8.87           7.2      8.87    0.0002
weight sync to 2 replicas: 191 ms

The same benchmark on one NVIDIA H100.

hardware: NVIDIA H100 80GB HBM3, torch 2.15.0, CUDA 13.2, 64 rollouts, up to 48 new tokens each
engine                           sec  rollouts/sec  generate    reward
sequential (batch 4)           16.55           3.9     16.54    0.0003
batched (batch 64)              1.90          33.7      1.90    0.0001
2 workers (batch 32 each)       2.58          24.8      2.58    0.0001
weight sync to 2 replicas: 14 ms

Sequential generation gave 1.8 rollouts per second on the CPU and 3.9 on the H100. One batched call gave 6.8 on the CPU and 33.7 on the H100. Batching is the big lever on both machines.

Two threaded workers gave 7.2 on the CPU, about the same as one batched call. On the H100 they gave 24.8, below one batched call. A likely cause is that both workers share one GPU and one Python process. The two-worker design should pay off when replicas sit on different devices or the environment is slow, as in agent RL. We did not test that here.

Pushing new weights to two replicas took 191 ms on the CPU and 14 ms on the H100. Scoring with the exact reward took under a millisecond in every run. Each figure is one run on shared hardware.

Checkpoint

  • test_worker_replica_only_changes_on_sync passes.
  • test_rollout_engine_builds_a_consistent_batch passes for one and two workers. It downloads a tokenizer.
Step 16Stage 6: verifiable reward

Train on a verifiable reward

Goal Run GRPO and REINFORCE with the same rollout budget, and judge them on held-out prompts that these runs never trained on.

The reward is the exact function from step 1. Nothing in the loop has an opinion. Both algorithms spend the same number of rollouts per step: GRPO uses 8 prompts with 4 samples each, and REINFORCE uses 32 prompts with one sample each.

    for step in range(args.steps):
        policy.eval()
        engine.sync(policy, step)
        rollouts = engine.collect(rng.sample(train, n_prompts))
        scale = "group" if args.algo == "grpo" else "none"  # REINFORCE has groups of 1, which have no std
        batch = {k: v.to(device) for k, v in engine.build_batch(rollouts, scale=scale).items()}
        policy.train()
        args_tensors = (batch["prompt_ids"], batch["prompt_mask"], batch["completion_ids"], batch["completion_mask"])

        stats: dict[str, float] = {}
        if args.algo == "grpo":
            with torch.no_grad():
                old = score_completions(policy, *args_tensors)  # the policy that sampled this data
                ref_logps = score_completions(ref, *args_tensors) if ref is not None else None
            for _ in range(args.inner):
                logps = score_completions(policy, *args_tensors)
                loss, stats = grpo_loss(logps, old, batch["advantages"], batch["completion_mask"], ref_logps, loss_cfg)
                loss.backward()
                torch.nn.utils.clip_grad_norm_(policy.parameters(), 1.0)
                opt.step()
                opt.zero_grad(set_to_none=True)
Listing 57The loop, up to the first GRPO update. Old log-probs are computed once per batch. Then the policy takes inner gradient steps against them.
$ .venv/bin/python c06-post-training/scripts/train_rl.py --algo grpo --steps 100 --eval-every 20 --seed 0 --tag grpo
$ .venv/bin/python c06-post-training/scripts/train_rl.py --algo reinforce --steps 100 --eval-every 20 --seed 0 --tag reinforce

Both runs are on one NVIDIA H100, start from the SFT checkpoint trained there, and use AdamW with learning rate 1e-5. GRPO takes 2 inner steps per batch, with clip 0.2 and a KL coefficient of 0.04. REINFORCE takes one step per batch. The blocks show seed 0. The start accuracy is 80.0%, from this script’s own 200 held-out prompts. These prompts are unseen by the stage being trained, but about 26 to 29% of their questions also appeared in the SFT training set. It is not the 74.5% of the SFT step, for the reason given in step 11.

grpo  on NVIDIA H100 80GB HBM3, torch 2.15.0, CUDA 13.2, 100 steps, 8 prompts x 4 samples, lr 1e-05
start     accuracy 80.0%  format 100.0%  (add 98.0% sub 88.0% chain 70.0% mul 64.0%)
step   20 accuracy 72.0%  format 100.0%  (add 98.0% sub 80.0% chain 58.0% mul 52.0%)
step   40 accuracy 59.5%  format 100.0%  (add 96.0% sub 66.0% chain 38.0% mul 38.0%)
step   60 accuracy 65.5%  format 100.0%  (add 90.0% sub 70.0% chain 48.0% mul 54.0%)
step   80 accuracy 68.0%  format 100.0%  (add 86.0% sub 80.0% chain 56.0% mul 50.0%)
step  100 accuracy 64.5%  format 100.0%  (add 94.0% sub 78.0% chain 34.0% mul 52.0%)
reinforce  on NVIDIA H100 80GB HBM3, torch 2.15.0, CUDA 13.2, 100 steps, 32 prompts x 1 samples, lr 1e-05
start     accuracy 80.0%  format 100.0%  (add 98.0% sub 88.0% chain 70.0% mul 64.0%)
step   20 accuracy 74.0%  format 100.0%  (add 96.0% sub 76.0% chain 72.0% mul 52.0%)
step   40 accuracy 75.5%  format 100.0%  (add 92.0% sub 88.0% chain 68.0% mul 54.0%)
step   60 accuracy 75.0%  format 100.0%  (add 94.0% sub 88.0% chain 70.0% mul 48.0%)
step   80 accuracy 73.0%  format 100.0%  (add 98.0% sub 80.0% chain 64.0% mul 50.0%)
step  100 accuracy 73.0%  format 100.0%  (add 94.0% sub 76.0% chain 66.0% mul 56.0%)

Neither run improved the model. A single run on 200 prompts is noisy, so we ran seeds 1 and 2 as well, and a second learning rate, 1e-6, for seed 0 only.

$ .venv/bin/python c06-post-training/scripts/train_rl.py --algo grpo --steps 100 --eval-every 20 --seed 1 --tag grpo-seed1
$ .venv/bin/python c06-post-training/scripts/train_rl.py --algo reinforce --steps 100 --eval-every 20 --seed 1 --tag reinforce-seed1
$ .venv/bin/python c06-post-training/scripts/train_rl.py --algo grpo --steps 100 --eval-every 20 --seed 0 --lr 1e-6 --tag grpo-lr1e-6
$ .venv/bin/python c06-post-training/scripts/train_rl.py --algo reinforce --steps 100 --eval-every 20 --seed 0 --lr 1e-6 --tag reinforce-lr1e-6
RL runs on NVIDIA H100 80GB HBM3, torch 2.15.0, CUDA 13.2, 100 steps, computed from results/
AlgorithmLearning rateSeedAccuracy at startAccuracy after 100 stepsChange in pointsMean KL to reference, last 10 steps
GRPO1e-5080.0%64.5%-15.50.034
GRPO1e-5180.0%65.5%-14.50.037
GRPO1e-5280.0%59.0%-21.00.042
REINFORCE1e-5080.0%73.0%-7.0not logged
REINFORCE1e-5180.0%76.0%-4.0not logged
REINFORCE1e-5280.0%79.0%-1.0not logged
GRPO1e-6080.0%78.5%-1.50.006
REINFORCE1e-6080.0%81.0%+1.0not logged

Greedy accuracy on 200 held-out prompts. One standard error is about 3 points. These prompts are unseen by the RL runs, but about 26 to 29% of their questions also appeared in the SFT training set.

Figure 11Greedy accuracy on 200 held-out prompts, at the start and every 20 steps, for the six runs at learning rate 1e-5 on the H100. The vertical axis starts at 0.50. Each line is read from its file in results/h100/. No run finished above its starting accuracy. Hover for values.

Why did the model not improve? We did not isolate a cause. The SFT model already solves about 80% of problems, so some groups probably have identical rewards and so no advantage. We did not measure how many. That could slow learning, but it would not explain a fall in accuracy. Things worth trying are a harder task or a weaker start, a larger group, a smaller learning rate with more steps, and the exercises at the end.

Checkpoint

  • The logged ratio_mean is from the last inner step, and it stays close to 1. Far from 1 means the step size is too large.
  • The logged truncated fraction stays low. A high value means the stop token was not learned in step 3.

The stages compared

Rows are the methods we built. Columns are the aspects this post introduced. Read the “signal” column first. SFT needs the answer, preference methods need a ranking, and the RL methods need only a checker, so the machinery around the model grows as the labels get cheaper.

Post-training methods in this tutorial. The last column is computed from results/h100/ unless it says CPU.
MethodSignalReductionReference modelSamples during trainingTrusted checkGreedy held-out accuracy, before to after
SFTThe answerMean over target tokens in the batchNoNoHugging Face loss0.0% to 74.5% on the H100, and to 74.5% on the CPU
LoRA SFTThe answerSame as SFTNoNoPEFT logits0.0% to 75.0%
DPOA is better than BSum over reply tokens, mean over pairsYes, requiredBefore training, for on-policy pairsTRL DPO lossIt went down. Synthetic pairs: 79.5% to 44.5%. On-policy pairs: 79.5% to 42.0%. At lr 1e-6: 66.5% and 65.5%
Reward modelA is better than BMean over pairsNoNoA by-hand valueNone: it scores pairs. Held-out pair accuracy 55.5% after 300 steps and 59.5% after 1500 steps, where chance is 50%
REINFORCEA checker’s scoreSum over tokens, mean over samplesNoYesA by-hand valueIt did not improve. From 80.0% to 73.0%, 76.0% and 79.0% for three seeds
GRPOA checker’s score, relative to the groupMean per sequence, then over sequencesOptional, for KLYesTRL GRPO lossIt went down. From 80.0% to 64.5%, 65.5% and 59.0% for three seeds

Each script draws its own 200 held-out prompts, so the same checkpoint has a different “before” value in the SFT, DPO and RL rows. Compare each row only with its own “before” value. The DPO, reward model and RL prompts are unseen by the stage being trained, but about 26 to 29% of their questions also appeared in the SFT training set. The runs also differ in length and learning rate, so read the column as a record of each run and not as a ranking of methods. The pattern is plain, though. SFT is the only stage that raised accuracy here.

Run everything

The final folder, and every command that produced a number in this post. Run them in this order, because later stages load checkpoints/sft-full. The numbers here come from two machines: an AMD EPYC 7R13 with 8 threads, and one NVIDIA H100 80GB HBM3. Setting POSTTRAIN_RESULTS=h100 writes the results to results/h100/ instead of results/. The H100 runs used it.

c06-post-training/ final tree
c06-post-training/
├── benchmarks/
│   ├── bench_memory.py  # full vs LoRA, one process each
│   ├── bench_packing.py  # padded vs packed
│   └── bench_rollout.py  # rollouts per second
├── posttrain/
│   ├── chat.py  # chat template and assistant-only labels
│   ├── dpo.py  # preference pairs and the DPO loss
│   ├── evaluate.py  # greedy accuracy on held-out prompts
│   ├── generation.py  # left padding, sampling, completion masks
│   ├── grpo.py  # group advantages, clipped surrogate, KL
│   ├── logprobs.py  # per-token and per-sequence log-probs
│   ├── lora.py  # a minimal LoRA, checked against PEFT
│   ├── models.py  # policy, frozen reference, tiny test model
│   ├── packing.py  # padding, packing, block-causal mask
│   ├── reinforce.py  # REINFORCE and a gradient-noise meter
│   ├── reward_model.py  # optional pairwise reward model
│   ├── rollout.py  # workers, policy versions, training batch
│   ├── sft.py  # masked loss and the SFT loop
│   ├── tasks.py  # arithmetic data and the exact reward
│   └── utils.py  # device, seeds, parameter counts
├── results/  # captured outputs quoted in this post
├── scripts/
│   ├── break_it.py  # runs the classic bugs on purpose
│   ├── inspect_mask.py  # prints one conversation token by token
│   ├── inspect_state.py  # prints one DPO pair and one GRPO group
│   ├── reinforce_variance.py  # measures gradient noise per estimator
│   ├── train_dpo.py  # stage 2
│   ├── train_reward_model.py  # stage 3
│   ├── train_rl.py  # stages 4 to 7
│   └── train_sft.py  # stage 1, full or LoRA, padded or packed
├── tests/
│   ├── test_chat_and_packing.py
│   ├── test_dpo.py
│   ├── test_grpo.py
│   └── test_lora_and_reward.py
├── README.md  # how to run everything, results table
└── conftest.py  # puts this folder on sys.path
$ .venv/bin/python -m pytest c06-post-training -m "not slow and not gpu and not network" -q
$ .venv/bin/python -m pytest c06-post-training -m network -q
$ cd c06-post-training
$ python scripts/inspect_mask.py
$ python scripts/train_sft.py --mode full --steps 500
$ python scripts/train_sft.py --mode lora --steps 500
$ python scripts/train_sft.py --mode full --pack --batch-size 5 --steps 500
$ python scripts/train_sft.py --mode full --init random --steps 500
$ python benchmarks/bench_packing.py --steps 12
$ python benchmarks/bench_memory.py --steps 10
$ python benchmarks/bench_memory.py --steps 10 --batch-size 2 --out bench_memory_b2.json
$ python scripts/train_reward_model.py --steps 300
$ python scripts/train_reward_model.py --steps 1500 --batch-size 16 --tag reward_model_long
$ python scripts/train_dpo.py --pairs synthetic --steps 200
$ python scripts/train_dpo.py --pairs on-policy --steps 200
$ python scripts/train_dpo.py --pairs synthetic --steps 200 --lr 1e-6 --tag dpo-synthetic-lr1e-6
$ python scripts/train_dpo.py --pairs on-policy --steps 200 --lr 1e-6 --tag dpo-on-policy-lr1e-6
$ python scripts/reinforce_variance.py --trials 12 --samples 32
$ python scripts/train_rl.py --algo grpo --steps 100 --eval-every 20 --seed 0 --tag grpo
$ python scripts/train_rl.py --algo reinforce --steps 100 --eval-every 20 --seed 0 --tag reinforce
$ python scripts/train_rl.py --algo grpo --steps 100 --eval-every 20 --seed 0 --lr 1e-6 --tag grpo-lr1e-6
$ python scripts/train_rl.py --algo reinforce --steps 100 --eval-every 20 --seed 0 --lr 1e-6 --tag reinforce-lr1e-6
$ python scripts/inspect_state.py
$ python scripts/break_it.py
$ python benchmarks/bench_rollout.py

Seeds 1 and 2 are the same two RL commands at lr 1e-5 with --seed 1 --tag grpo-seed1 and the matching REINFORCE tag, then seed 2. The H100 benchmarks used --steps 20 for bench_memory.py and bench_packing.py. The reward model, DPO and RL results exist only for the H100.

The two test commands at the top ran on the CPU, with the tests pinned to 2 threads. 38 offline tests pass, and 10 network tests pass. The network tests download SmolLM2-135M and compare against TRL and the Hugging Face chat template.

$ python -m pytest c06-post-training -m "not slow and not gpu and not network" -rA   # AMD EPYC 7R13, tests pinned to 2 threads
PASSED c06-post-training/tests/test_chat_and_packing.py::test_packing_keeps_conversations_whole_and_resets_positions
PASSED c06-post-training/tests/test_chat_and_packing.py::test_block_mask_is_causal_and_block_diagonal
PASSED c06-post-training/tests/test_chat_and_packing.py::test_packed_logits_equal_unpacked_logits
PASSED c06-post-training/tests/test_chat_and_packing.py::test_naive_packing_leaks_across_conversations
PASSED c06-post-training/tests/test_chat_and_packing.py::test_position_ids_alone_need_use_cache_false
PASSED c06-post-training/tests/test_chat_and_packing.py::test_masked_loss_matches_hf_loss_on_padded_batch
PASSED c06-post-training/tests/test_dpo.py::test_sequence_logprob_matches_explicit_loop
PASSED c06-post-training/tests/test_dpo.py::test_prompt_tokens_do_not_count
PASSED c06-post-training/tests/test_dpo.py::test_padding_does_not_change_sequence_logprob
PASSED c06-post-training/tests/test_dpo.py::test_left_and_right_padding_agree
PASSED c06-post-training/tests/test_dpo.py::test_sum_vs_mean_changes_the_margin
PASSED c06-post-training/tests/test_dpo.py::test_equal_policy_and_reference_give_log_two
PASSED c06-post-training/tests/test_dpo.py::test_reference_gets_no_gradient
PASSED c06-post-training/tests/test_dpo.py::test_dpo_loss_decreases_with_margin
PASSED c06-post-training/tests/test_grpo.py::test_group_advantages_by_hand
PASSED c06-post-training/tests/test_grpo.py::test_all_same_reward_gives_zero_advantage
PASSED c06-post-training/tests/test_grpo.py::test_group_advantages_match_trl_formula
PASSED c06-post-training/tests/test_grpo.py::test_first_inner_step_has_ratio_one_and_no_clipping
PASSED c06-post-training/tests/test_grpo.py::test_clipping_removes_the_incentive_past_one_plus_eps
PASSED c06-post-training/tests/test_grpo.py::test_negative_advantage_is_never_clipped_upward
PASSED c06-post-training/tests/test_grpo.py::test_padding_tokens_do_not_change_the_loss
PASSED c06-post-training/tests/test_grpo.py::test_grpo_loss_is_length_normalised_but_dapo_is_token_weighted
PASSED c06-post-training/tests/test_grpo.py::test_kl_is_zero_at_the_reference_and_positive_elsewhere
PASSED c06-post-training/tests/test_grpo.py::test_completion_mask_stops_after_first_eos
PASSED c06-post-training/tests/test_grpo.py::test_score_completions_matches_a_full_forward
PASSED c06-post-training/tests/test_grpo.py::test_exact_reward_is_strict
PASSED c06-post-training/tests/test_grpo.py::test_reinforce_sums_over_tokens_and_ignores_padding
PASSED c06-post-training/tests/test_grpo.py::test_estimators_zero_out_constant_rewards_except_vanilla
PASSED c06-post-training/tests/test_grpo.py::test_gradient_noise_separates_signal_from_noise
PASSED c06-post-training/tests/test_grpo.py::test_snr_of_pure_noise_sits_at_one_over_k_minus_one
PASSED c06-post-training/tests/test_grpo.py::test_worker_replica_only_changes_on_sync
PASSED c06-post-training/tests/test_grpo.py::test_reference_copy_is_frozen
PASSED c06-post-training/tests/test_grpo.py::test_random_policy_does_not_keep_the_pretrained_weights
PASSED c06-post-training/tests/test_lora_and_reward.py::test_lora_starts_at_the_base_model
PASSED c06-post-training/tests/test_lora_and_reward.py::test_only_adapter_weights_train
PASSED c06-post-training/tests/test_lora_and_reward.py::test_lora_linear_matches_peft_with_the_same_factors
PASSED c06-post-training/tests/test_lora_and_reward.py::test_merge_preserves_outputs_and_removes_the_wrappers
PASSED c06-post-training/tests/test_lora_and_reward.py::test_pairwise_loss_by_hand
38 passed, 10 deselected in 21.42s

$ python -m pytest c06-post-training -m network -rA   # downloads SmolLM2-135M; compares against TRL and the HF chat template
PASSED c06-post-training/tests/test_chat_and_packing.py::test_manual_ids_match_chat_template
PASSED c06-post-training/tests/test_chat_and_packing.py::test_assistant_mask_matches_hf_generation_mask
PASSED c06-post-training/tests/test_chat_and_packing.py::test_only_assistant_content_and_im_end_are_targets
PASSED c06-post-training/tests/test_chat_and_packing.py::test_last_turn_mode_trains_one_reply
PASSED c06-post-training/tests/test_chat_and_packing.py::test_pad_token_is_not_end_of_turn
PASSED c06-post-training/tests/test_dpo.py::test_matches_trl_dpo_trainer_on_the_same_batch
PASSED c06-post-training/tests/test_grpo.py::test_matches_trl_grpo_loss_on_the_same_tensors[grpo]
PASSED c06-post-training/tests/test_grpo.py::test_matches_trl_grpo_loss_on_the_same_tensors[dapo]
PASSED c06-post-training/tests/test_grpo.py::test_rollout_engine_builds_a_consistent_batch[1]
PASSED c06-post-training/tests/test_grpo.py::test_rollout_engine_builds_a_consistent_batch[2]
10 passed, 38 deselected in 29.67s

Key insights and nuances

Exercises

  1. Lose the stop tokenEasy Change encode_chat so that <|im_end|> is masked. Retrain SFT and compare the truncated fraction from train_rl.py with and without the change.
    Hint

    Split the content and the stop token into two add calls. Only the first gets train=is_target.

  2. A better packerEasy Implement best-fit-decreasing next to first-fit-decreasing, and compare both with padding_stats at max_len values of 128, 256 and 512.
  3. Rescale β for the meanMedium Train DPO with average=True. Find the β that gives a similar margin to the summed version. Then check whether held-out accuracy matches.
    Hint

    The margin shrinks by about the mean reply length, so start with β multiplied by that length.

  4. Make DPO helpMedium Our DPO runs lowered held-out accuracy. Try a smaller β, fewer steps, and an extra SFT loss on the chosen reply. Report the held-out accuracy against the run’s own “before” value, and log the log-probability of the chosen reply to test the likelihood-displacement idea.
    Hint

    In dpo_loss, the first argument policy_chosen is the log-probability of the chosen reply. Log it next to the margin, and compare it with its value at step 0, or with ref_chosen, and not as an absolute number. If it falls below that while the margin grows, the idea holds for your run.

  5. Hack the rewardMedium Replace exact_reward with one that pays for any reply where the right number appears anywhere in the text. Train GRPO and compare all with format in the held-out results. What does the model learn to write?
  6. Drop the standard deviationHard Pass scale="none" in build_batch, which subtracts the group mean only. Run at least three seeds for each setting. Report the spread across seeds before you claim a difference.
    Hint

    The paper “Understanding R1-Zero-Like Training” in the references discusses why this term matters. Compare its argument with what you measure.

Continue reading

References

Grouped by topic. Every entry links to its primary source.

Model and tools