Prince Osei Aboagye
← All posts
Mini DeepSeek V4 / Part 07·Dec 2026

Supervised fine-tuningteaching the answer format

Spoiler: SFT taught the answer format, not the arithmetic: the kept model, step 175 of a six-epoch run, mixed right and wrong answers in only 1.6% of RL answer groups, against the 30% the gate needed.

TL;DR

I fine-tuned my 6.86B-parameter mixture of experts (1.22B active per token) on 55,083 grade-school math problems with checked solutions. Three epochs on 8×H100 took 651 s and taught the answer format: 90% of greedy answers were well-formed, up from 0%. They did not teach arithmetic: 1 of 100 development problems right, often by copying the question’s first number. Six epochs gave the lowest validation loss (0.748, step 175): 2.0% greedy and 12.0% pass@8 on 200 GSM8K problems, with web-text perplexity up 8.4%. The SFT-to-RL gate failed: only 1.6% of answer groups mixed right and wrong answers (30% required), so I changed RL’s problems and group size.

// § 01

What you’ll learn

  • What supervised fine-tuning (SFT) is, and why its loss counts only the answer tokens.
  • How a chat format and packing turn examples into training rows, and two silent bugs they hid in Megatron-LM.
  • Why SFT can teach a format within an epoch but not a skill the base model barely has.
  • How to read SFT validation loss and perplexity, and what each one does not tell you.
  • Why reinforcement learning (RL) needs answer groups with mixed outcomes, and how to measure that before RL starts.
// § 02

Supervised fine-tuning from scratch

Imitation, one token at a time

A pretrained language model continues text. Mine had read 2.6B tokens of educational web pages, and it could not answer a single math question. Asked one, it repeated phrases until it hit the length limit, with a median answer of about 1,500 tokens. It scored 0 on all six test sets. Part 6 tells that story.

Supervised fine-tuning shows the model examples of the behaviour we want and trains it to imitate them. Each example is a prompt (here, a math question) and a target response (a worked solution that ends in the answer). Training uses the same next-token objective as pretraining. The difference is which tokens count.

The SFT loss is the model’s average surprise at the answer tokens only:

\[\mathcal{L}_{\text{SFT}}(\theta) = -\frac{1}{|A|}\sum_{t \in A} \log p_\theta\!\left(y_t \mid x,\, y_{<t}\right) \tag{1}\]

Here \(\theta\) are the model’s weights and \(x\) is the question. \(y_t\) is the \(t\)-th token of the reference answer, and \(y_{<t}\) are the answer tokens before it. \(A\) is the set of answer-token positions in the batch, including the end-of-text token, and \(|A|\) is their number. \(p_\theta(y_t \mid x, y_{<t})\) is the probability the model gives the correct next token.

In words: the model is penalized by \(-\log p\) at each answer token, where \(p\) is the probability it gave the correct token.

Two consequences follow from the equation itself:

  • Teacher forcing. The model always conditions on the reference prefix \(y_{<t}\), never on its own samples.
  • No anchor. Nothing in Eq. (1) refers to the model before fine-tuning, so nothing holds it near its old behaviour.

The chat format

A chat format is the rule that turns a conversation into one string of tokens. Instruction-tuned models mark each turn with role markers, special tokens that say who is speaking. My base tokenizer, Llama 3.2’s, has no chat template.

Megatron-LM offers several SFT prompt formats, and the obvious two did not fit:

  • its default, nemotron-h-aligned, writes Nemotron’s <SPECIAL_10> and <SPECIAL_11> role markers. Llama 3.2’s vocabulary lacks them, so they would reach the model as junk text;
  • the format named default needs the tokenizer’s own chat template, which mine lacks.

So I used identity: the turns’ texts joined, with nothing added. Each example has three turns:

  • a system turn, empty, which only marks where an example starts;
  • the user turn: the question, then a newline;
  • the answer turn (the chat role named assistant): the solution in a fixed answer format, then <|end_of_text|>.

The answer format is the one the RL reward reads later (Part 8):

<think>
step-by-step working
</think>
<answer>final number</answer>

Here is a real example from the training file, exactly as stored, minus its id and source fields. votes counts how many of the teacher model’s 32 solutions agreed on the answer.

{"question": "A theater performance had an audience of 240 people. The theater company had given 30 complimentary tickets to local arts students and 40 tickets to staff members. The remaining audience members were paying customers. How many paying customers attended the performance?",
 "response": "<think>\nThe theater company gave 30 + 40 = 70 tickets away for free.\nThere were 240 people in the audience.\nSo, the number of paying customers is 240 - 70 = 170.\nThus, 170 paying customers attended the performance.\n</think>\n<answer>170</answer>",
 "answer": "170", "votes": 31, "passing_solutions": 31, "question_tokens": 48, "response_tokens": 66}

The model learns to write response when given question. RL and evaluation use the same template, with the question and a newline as the prompt. So RL sees each question exactly as SFT taught it. I checked that on all 23,226 RL and test questions with Megatron’s own tokenizer classes: 0 mismatches, and none started with a stray beginning-of-text token.

The loss mask, and why it matters

Only the answer is scoredOne packed 4,096-token training row and its loss mask; the theater example, zoomedOne row: 4,096 tokens, about 24 examples (mean 24.4), 97.8% full; widths schematicrowloss maskend paddingturnssystememptyquestionA theater performance hadan audience of 240 … ?answer<think> … 240 - 70 = 170 … </think><answer>170</answer><|end_of_text|>end tokenloss mask0 0 0 0 0 … 01 1 1 1 1 1 … 1148 tokens, then a newline66 tokensthe only stop signalattentionOne block per exampleA token (a row) attends only to the earlier tokens (columns) of its ownexample: teal. Never to another example: grey. Schematic, 4 examples.Each example starts with an empty system turn, which marks the boundary.
Figure 1. only the answer and its end token are scored. One packed row and its loss mask, with the theater example zoomed; example widths and attention blocks are schematic. Source: the SFT training set and the log of code/scripts/make_megatron_sft.py (Results).

Megatron computes Eq. (1) as an ordinary next-token loss over a whole row, with a mask:

\[\mathcal{L} = -\frac{\sum_{i=1}^{T} m_i \log p_\theta(s_i \mid s_{<i})}{\sum_{i=1}^{T} m_i}, \qquad m_i \in \{0, 1\} \tag{2}\]

Here \(s_1, \dots, s_T\) are the \(T\) tokens of a training row. The loss mask \(m_i\) is 1 for answer tokens and the end-of-text token, and 0 for system turns, questions and padding. In a packed row, \(s_{<i}\) means the earlier tokens of the same example only, because the attention mask keeps examples apart.

In words: compute the usual loss everywhere, then keep only the answer tokens’ share and average over them.

Megatron sets every question-token label to an ignore value. It then zeroes the mask wherever a label is that value or the padding token. Strictly, it averages Eq. (2) over each micro-batch of 8 rows, and the gradients are then averaged across the GPUs.

The mask matters for four reasons:

  1. The question is given, not generated. A typical question is about 54 tokens and a typical answer about 100. Without the mask, roughly a third of each row’s loss would go to predicting questions.
  2. The stop signal lives in one token. The base model almost never stopped on its own. The <|end_of_text|> after each answer is the only place SFT teaches it to stop, so that token must be in \(A\). Megatron’s SFT dataset does not append it, so the answer turn’s text carries it.
  3. Padding must not be learned. Rows are padded to 4,096 tokens, and a model trained on padding learns to predict padding.
  4. A framework may not mask at all. With the format named default, Megatron skips masking. Its comment reads “all token losses will be used for simplicity” (sft_tokenizer.py).

What SFT can and cannot teach

SFT is imitation, and it is good at teaching what appears in every example:

  • the layout of an answer;
  • the length of an answer;
  • when to stop.

It is weak at teaching a skill the base model barely has. The arithmetic inside “240 - 70 = 170” is a handful of tokens per example, and my set held 5.92M answer tokens in all. The base model had read 2.6B tokens, about a tenth of the compute-optimal amount for its 1.2B active parameters.

Teacher forcing adds a second limit. During SFT every prefix comes from the reference. At test time the model’s own tokens become the prefix, and an early wrong number carries forward.

The third limit is forgetting. Eq. (1) has no term that keeps the model near its starting point, so training only on math can make it worse at general text. I measure that with perplexity on held-out text:

\[\mathrm{PPL} = \exp\!\Big(-\frac{1}{N}\sum_{i=1}^{N}\log p_\theta(w_i \mid w_{<i})\Big) \tag{3}\]

Here \(w_1, \dots, w_N\) are the \(N\) tokens of a text the model never trained on. The logarithm is natural, so the inner average is a loss in nats per token.

In words: perplexity is the exponential of the average per-token loss, roughly the number of tokens the model is torn between at each step.

A change in loss turns into a change in perplexity directly:

\[\frac{\mathrm{PPL}_{\text{after}}}{\mathrm{PPL}_{\text{before}}} = \exp\!\left(\bar{\ell}_{\text{after}} - \bar{\ell}_{\text{before}}\right) \tag{4}\]

Here \(\bar{\ell}\) is the mean loss per token on the same held-out text, before and after fine-tuning.

In words: a rise of \(\Delta\) nats per token multiplies perplexity by \(e^{\Delta}\).

// § 03

My SFT data, in brief

Part 3 tells the full story of the data. In short:

  • Source: NVIDIA’s OpenMathInstruct-2, split augmented_gsm8k. It holds 73,643 new grade-school questions written by Llama-3.1-405B-Instruct, with 2,111,683 teacher solutions (CC BY 4.0).
  • Kept: 55,083 questions (53,970 for training, 1,113 for validation), each with one solution whose every equation is exactly true.
  • Dropped: about 11% of questions, which have no exact answer, and anything close to my RL or test questions.
  • Size: 5.92M answer tokens, a median of 100 per answer.
  • Label quality: I solved 50 fresh questions blind and matched all 50 labels; the error rate’s 95% upper bound is 7.1%.

One design choice matters here. The set holds word problems only, with no bare sums like “What is 96 + 83?”. The build excluded everything near the RL questions, and the RL warm-up tier’s bare sums are RL questions.

// § 04

How I built it in Megatron-LM

The recipe

Setting Value
Start the final pretraining checkpoint, weights only (--finetune: iteration 0, a fresh optimizer)
Learning rate 1e-5 peak, cosine decay to 1e-6, 320 warm-up samples (5 steps)
Batch 64 packed rows of 4,096 tokens per step, 8 rows per GPU
Optimizer Adam (β1 0.9, β2 0.95), weight decay 0.1, gradient clipping at 1.0, bf16
Length 6,656 samples = 104 steps = 3 epochs (later 13,312 samples = 208 steps)
Saves weights only, every 35 steps (about one epoch)
Validation every 35 steps; one batch covers all 46 validation rows
Router the pretraining router: DeepSeek-V4 scores with quantile balancing

The plan called for 2–3 epochs, with the SFT validation loss as the guide. The learning rate was the only sourced SFT value I had, from SmolLM3. Without --finetune, Megatron restores the checkpoint’s iteration counter, and SFT can stop after 0 steps.

Silent bug 1: a pad token that did not exist

Megatron’s identity format set the pad token to <unk>. Llama 3.2’s vocabulary has no <unk>, so the lookup returned None, and SFT would have crashed at the first padded row.

The crash was the lucky case. The dangerous case is a tokenizer that maps the pad to a real token. Megatron masks every label equal to the pad, so a pad equal to the end-of-text token would hide the stop signal from the loss. The model would train, its loss would fall, and it would never learn to stop.

The fix is part of my Megatron patch:

pad_token_id = tokenizer.convert_tokens_to_ids("<unk>")
if pad_token_id is None:
    pad_token_id = tokenizer.pad_token_id
if pad_token_id is None or pad_token_id == tokenizer.eos_token_id:
    raise ValueError(
        "identity prompt format needs an <unk> or a pad token distinct from EOS, got "
        f"pad={pad_token_id}, eos={tokenizer.eos_token_id}"
    )

For Llama 3.2 the pad becomes <|finetune_right_pad_id|>, id 128004, distinct from end-of-text, id 128001. The refusal earned its place later. Qwen’s tokenizer, in the control run of Part 14, has its pad equal to its end token, so I gave it a different pad.

Silent bug 2: one example per line

Megatron’s SFT dataset turns each JSONL line into one 4,096-token training row. It splits a line into conversations at each system turn and packs them, with attention boundaries between them.

With one example per line, the median example of 154 tokens would fill under 4% of its row. Every row would be about 96% padding, and three epochs would take about 2,530 steps instead of 104. Nothing would crash. The run would simply take about 25 times as long, far past the half hour planned for SFT.

Packing cut 3 epochs from about 2,530 steps to 104Each square is one 4,096-token training row, wrapped into 64 lines of 64 tokensOne example per row154 tokens used (the median example), about 96% paddingPacked rows24.4 examples per row on average, 97.8% fullpackabout 2,530 steps104 stepsfor 3 epochs, at 64 rows per stepfor 3 epochs: 2,210 rows, 64 per stepexample tokenspaddingNotches mark where one example ends (equal lengths drawn: schematic).
Figure 2. packing cut three epochs from about 2,530 steps to 104. Rows drawn to scale; the example boundaries in the packed row are schematic. Source: the log of code/scripts/make_megatron_sft.py (Results).

code/scripts/make_megatron_sft.py packs instead. It shuffles the examples with a fixed seed, fills each line greedily up to 4,096 tokens, and starts each example with an empty system turn.

File Examples Lines Examples per line Fill
train 53,970 2,210 24.4 97.8%
validation 1,113 46 24.2 96.0%

The script stops if any check fails:

  • every example fits in one line;
  • each conversation’s turns, tokenized one at a time, join to exactly the whole conversation’s tokens (Megatron asserts this when it masks);
  • each example has exactly one end-of-text token, at its end;
  • every example lands in exactly one line.

On all 55,083 examples it found 0 join failures and 0 end-token problems.

Both bugs were invisible from the flags. Each was found by reading what the dataset code does with one line and one pad token, then checking that on every example.

A third problem was loud. On the one-GPU rehearsal, the first SFT launch stopped after 70 s at an assertion. The dataset requires that the data loader build no attention mask. The flag --no-create-attention-mask-in-dataloader, which Megatron’s own SFT test sets, fixed it. Loud failures waste a minute; silent ones waste the run.

// § 05

What happened: three epochs on 8×H100

The 3-epoch run took 651 s, a median of 3.2 s per step. Training loss fell from 2.774 to 0.910, and the gradient norm from 3.7 to 0.18, with no NaN. Validation loss was 1.140, 0.971 and 0.930 at steps 35, 70 and 104, perplexities of 3.13, 2.64 and 2.53.

At each save I ran two checks:

  • greedy answers to 100 problems of the curriculum’s development split, held out from RL training, for accuracy and format compliance (the share of answers in the exact <think>/<answer> layout);
  • one batch of RL rollouts from the easy training tier: 64 problems with 8 sampled answers each.

Each check took 452–471 s.

Epoch (step) Validation loss Format Greedy correct Rollout solve rate Mixed groups Answer length, p99 (tokens)
1 (35) 1.140 69% 0 of 100 0.4% 3.1% 1,504
2 (70) 0.971 91% 3 of 100 0.4% 3.1% 634
3 (104) 0.930 90% 1 of 100 0.8% 6.3% 482

The format arrived within one epoch. By the second, the model had learned to stop: the 99th-percentile answer length fell from 1,504 tokens to 634. Accuracy did not move.

The answers show why. After one epoch, the model wrote the format exactly and filled it with the question’s first number:

  • “What is 96 + 83?” → <think> The answer is 96. </think> <answer>96</answer>;
  • “What is 98 + 83 − 33?” → 98;
  • “42 raisin cookies, ratio 6:1, combined?” → “42 + 6 = 42 … <answer>42</answer>”, where the right answer is 49.

Two causes are on record. The data has no bare arithmetic, by design. And 2.6B pretraining tokens are about a tenth of the compute-optimal amount for 1.2B active parameters. So SFT had a weak base, and the model learned the part of each example that repeats: the layout.

The router during SFT

My model is a mixture of experts: each token goes to 8 of 64 expert networks, chosen by a router. Math text is narrower than web text, so SFT could have unbalanced the experts. It did not.

MaxVio measures balance: the busiest expert’s load divided by the mean load, minus 1, so 0 is perfectly even. It was 0.062 at step 26 and 0.039 at step 104, against 0.063 at pretraining’s last count, step 1,200. No expert got under 1% of an even share. Part 6 explains the router and its balancing.

// § 06

The SFT-to-RL gate

Before RL, a gate written into the plan had to pass. Its main checks:

  • a GSM8K accuracy recorded, even if it is 0;
  • format compliance above 50% on development prompts;
  • at least 30% of answer groups with mixed results, at 8 answers per problem;
  • the first RL update’s ratio exactly 1 and its KL near 0, which RL itself checks.

Why RL needs mixed groups

GSPO, my RL method, samples a group of \(G\) answers to each problem and gives each one a reward. Part 8 explains the reward and Part 9 the algorithm. The signal for answer \(i\) is its advantage, its reward compared with the rest of its group:

\[A_i = \frac{r_i - \bar r}{\epsilon + \sigma_r} \tag{5}\]

Here \(r_i\) is the reward of answer \(i\). \(\bar r\) and \(\sigma_r\) are the mean and standard deviation of the rewards in its group, and \(\epsilon = 10^{-4}\) prevents division by zero. In my setup, a group whose answers are all right or all wrong gets \(A_i = 0\) for every answer.

In words: an answer is pushed up only if it beat its siblings. A group whose answers are all right, or all wrong, teaches nothing.

So what share of groups carries a signal? Suppose the model solves a problem with probability \(p\), and its \(G\) answers are independent draws:

\[P(\text{mixed}) = 1 - (1-p)^G - p^G \tag{6}\]

Here \((1-p)^G\) is the chance that all \(G\) answers are wrong, and \(p^G\) the chance that all are right.

In words: a group is useful unless every answer fails or every answer succeeds.

In Zhoutong Fu’s example, at \(p = 0.01\) the chance of a mixed group “rises from 7.73% for 8 responses to 47.44% for 64” (source). Larger groups find a model’s rare successes.

Derivation: uneven solve rates can only lower the share

Write \(f(p) = 1 - (1-p)^G - p^G\). Its second derivative is

\[f''(p) = -G(G-1)\left[(1-p)^{G-2} + p^{G-2}\right] < 0 \quad \text{for } G \ge 2, \tag{7}\]

so \(f\) is concave on \([0, 1]\). By Jensen’s inequality, averaging \(f(p_j)\) over problems with different rates \(p_j\) gives at most \(f\) of their average rate.

In words: for a fixed overall solve rate, spreading it unevenly over problems can only lower the expected share of mixed groups.

The gate after three epochs: format passed, signal failed

After three epochs, the format check passed at 90%. The group signal failed: 6.3% of groups were mixed, so GSPO would have skipped 94% of its groups.

I considered four options:

  1. GSPO as planned, which would still measure the systems metrics but likely leave accuracy flat;
  2. a short, targeted arithmetic SFT;
  3. larger groups;
  4. more SFT epochs on the same data.

I chose the fourth first. It was the plan’s own remedy, and the validation loss was still falling, by 0.169 and then 0.041 per epoch.

Six epochs, and the gate again

The 6-epoch run was a fresh run with the same recipe and one cosine schedule over 208 steps. It took 988 s.

Step (epoch) 35 (1) 70 (2) 105 (3) 140 (4) 175 (5) 208 (6)
Validation loss, 6-epoch run 1.158 0.907 0.811 0.776 0.748 0.762
Validation loss, 3-epoch run 1.140 0.971 0.930 (step 104) — — —
The rule kept step 175SFT validation loss at each save, 3-epoch and 6-epoch runs on 8×H100; one run each, no error bars6-epoch run (208 steps)3-epoch run (104 steps)validation loss (nats per answer token)0.60.70.80.91.01.11.203570105140175208SFT step (35 steps ≈ 1 epoch)kept: step 175, 0.7480.9300.762
Figure 3. the rule fixed in advance kept step 175 (0.748). SFT validation loss by step for both runs; one run each, no error bars. Source: the validation losses logged by the two SFT runs (Results).

The gate on the kept model, step 175, failed again, and worse. Format passed at 74.5% (149 of 200 development prompts). That sample differs from the 100 prompts per epoch above, so the two format numbers do not compare directly. Only 1 group of 64 was mixed (1.6%), at a solve rate of 0.2%. So 98.4% of groups would carry no signal.

The extra epochs bought a better fit (validation 0.930 → 0.748) and slightly better test accuracy. They did not buy the signal GSPO needs at \(G = 8\). One signal remained: pass@8 of 12–17% on four of the five word-problem test sets (MAWPS 3.0%). A correct answer does appear when the model samples enough.

What I did: the medium tier, with groups of 32

Eq. (6) offers two levers: raise \(p\) by choosing problems the model can sometimes solve, or raise \(G\). I pulled both:

  • The medium tier (ASDiv and SVAMP problems), held fixed. It was the development split’s best tier (8.6% greedy), and the ASDiv and SVAMP test sets reached 13.0% and 12.0% pass@8.
  • Groups of 32: 16 problems × 32 answers is the same 512 answers per step as 64 × 8, so about the same step time.

Why hold the tier fixed? My curriculum moves one tier easier when the 50-step solve rate falls under 10%. Here “easier” meant the bare sums, this model’s worst tier: 0 of 43 right at every epoch. Left alone, the curriculum would have walked GSPO toward the tier with the least signal.

I wrote the check down before the data: measure the group signal on the first calibration step, and stop if it is under 30%. It passed: 43.8% of groups were mixed (7 of 16), at a solve rate of 2.73% (14 of 512 answers).

Eq. (6) also shows what a single \(p\) hides. If every problem had \(p = 0.0273\), groups of 32 would be mixed \(1 - 0.9727^{32} \approx 59\%\) of the time (illustrative arithmetic). The measured 43.8% is lower, as Eq. (7) predicts when rates differ; 16 groups is also a small sample. The rates do differ: on the medium tier, the kept model got all 16 answers wrong on 1,487 of 1,905 problems (78%).

Bigger groups find rare successesShare of answer groups mixing right and wrong; curves: Eq. (6), illustrative; dots: measuredEq. (6), G = 32Eq. (6), G = 8measured on 8×H100mixed groups (%)02550751000.1%0.3%1%3%10%30%solve rate p (log scale)the gate: 30% of groups mixed6.3%1.6%43.8%6.3%: 3 epochs, easy tier, G = 81.6%: step 175, easy tier, G = 843.8%: step 175, medium tier, G = 32 (its curve: 59%)Curves assume one solve rate for every problem.
Figure 4. bigger groups and better-matched problems find rare successes. Curves are Eq. (6), illustrative, with one solve rate for every problem; points are measured. Source: the saved rollout statistics of the three gate checks (Results).

Kian Kyars puts the general lesson in one line: “RLVR needs a capable starting policy in the sparse-reward regime” (Reinforcement Learning from Verifiable Rewards, Ch. 5). My SFT model was barely capable on these problems. Part 9 shows what GSPO could do from there.

// § 07

Choosing a checkpoint

Which save should start RL? I fixed the rule before the 6-epoch data existed: keep the save with the lowest SFT validation loss over both runs. A short script reads the validation loss at iteration N … lm loss value: X lines in each log. It takes the minimum over saved steps and writes that step to the checkpoint folder’s latest_checkpointed_iteration.txt. It kept step 175 of the 6-epoch run, with validation loss 0.748.

What the rule does not measure matters as much:

  • The validation set is close to the training set. It is one question in 50, chosen by hash, from the same OpenMathInstruct-2 source. Those questions all grow from GSM8K seeds, so close relatives of a validation question can sit in training. Validation loss measures fit to that distribution; the evaluations below measure generalization.
  • The validation set is small. It is one batch of 46 packed rows. So the rise from 0.748 at step 175 to 0.762 at step 208 (+0.014) may be early overfitting, or noise.
  • It is not a test score. I did not choose by any test-set number: in this project, no test set drives a decision.
  • It does not measure RL’s signal. The gate failed at step 104 (4 of 64 groups mixed) and at step 175 (1 of 64), both tiny samples.
// § 08

What the kept model can do

Accuracy on the six test sets

I evaluated step 175 on six held-out test sets. Each problem got a greedy answer (the single most likely one) and 8 samples at temperature 1. pass@8 counts a problem as solved if any of its 8 samples is right. Large sets were cut to a fixed 200-problem subset; the evaluation took 1,147 s.

Test set Problems Greedy Format pass@8
GSM8K 200 (subset) 2.0% 92% 12.0%
MATH 200 (subset) 0.5% 37% 4.0%
SVAMP 300 (whole) 3.3% 98% 12.0%
ASDiv 407 (whole) 5.7% 96% 13.0%
MAWPS 200 (subset) 0% 96% 3.0%
MultiArith 180 (all) 3.3% 99% 17.2%

The format holds on the five grade-school sets (92–99%) and falls to 37% on MATH, whose competition problems differ in style from the SFT data’s word problems. Averaged over the six sets, avg@8 (the mean share of right answers among the 8 samples) was 1.46%.

Read these numbers against two yardsticks:

  • The free score. Always giving a set’s most common gold answer would score 8.33% on SVAMP and 7.78% on MultiArith. This model’s greedy score was 3.3% on both. Part 8 explains these floors.
  • Noise. Even greedy decoding did not repeat. The development split’s 35 medium problems scored 3 in one pass and 2 in another. The inference engine batched requests differently, and its kernels are not batch-invariant. Part 13 measures this noise floor.

What SFT made the model forget

I measured forgetting with Eq. (3) on about 26M tokens of held-out FineWeb-Edu text, the same text before and after SFT.

Model Loss (nats per token) Perplexity
Before SFT (end of pretraining) 3.0430 20.97
After SFT (step 175) 3.1241 22.74

The loss rose by 0.0811 nats per token, so by Eq. (4) perplexity rose by a factor of \(e^{0.0811} \approx 1.084\): 8.4%. That is mild forgetting of general text after 5 epochs of math-only SFT. I did not measure the 3-epoch save, so how much of the 8.4% the extra epochs added is unknown. GSPO afterwards added no more: 22.76.

// § 09

What went wrong, and what I would change

  • The SFT data and the RL warm-up tier did not match. SFT taught the format on word problems. The RL warm-up tier was bare sums, this model’s worst tier.
  • The base was too weak for SFT to reveal arithmetic. With about a tenth of compute-optimal pretraining, there was little skill to bring out. The control run of Part 14 later showed that the base, not the RL pipeline, limited the gains.
  • The gate earned its place. Without it, GSPO would have spent its window on groups with no signal: 94% of them, at the planned settings.
  • Next steps, on record but not yet run. Pretraining with math in the mix (backlog row 34). SFT on the model’s own correct answers (rejection sampling), which the medium-tier filter pass saved.
// § 10

Run it yourself

Hardware and time.

  • Data: a laptop CPU. The final SFT data build took 851.6 s.
  • SFT: one 8×H100 node. Three epochs took 651 s and six took 988 s. Each format check took 452–471 s, and the after-SFT evaluation 1,147 s.

1. Build the SFT data (laptop). This needs the RL curriculum and the Llama 3.2 tokenizer from the data guide.

# from MyModel/
bash code/scripts/download_openmathinstruct2.sh          # 32 files, each checked against its SHA-256
cd code
python3 scripts/prepare_sft_data.py \
    --input-dir ../data/sft/openmathinstruct2/469216e3f46f4dacf476b382e192485ea51a143e \
    --curriculum-dir ../data/curriculum --tokenizer ../data/tokenizer/llama-3.2/tokenizer.json \
    --out-dir ../data/sft
cd ..
python -I code/scripts/make_megatron_sft.py --tokenizer data/tokenizer/llama-3.2 \
    --inputs data/sft/sft_train.jsonl data/sft/sft_valid.jsonl --out-dir data/sft/megatron

2. Train (8×H100). After the pod setup in the setup guide, load the environment it writes. The run helper gives each run its own folder and log, and stops a run whose logs stay unchanged for 15 minutes.

source /workspace/env.sh                 # MEGATRON_PATH, TOKENIZER_DIR, SFT_DIR, CURRICULUM_DIR
run() { export RUN_NAME=$1 RUN_DIR=/workspace/runs/$1; mkdir -p "$RUN_DIR"; shift
        python -I code/scripts/stall_guard.py --log "$RUN_DIR.log" --watch /workspace/runs -- "$@"; }
M=code/scripts/megatron
# 3 epochs (104 steps). For 6 epochs (208 steps), prefix SFT_SAMPLES=13312.
PRETRAIN_CKPT=/workspace/ckpt/pretrain CKPT_DIR=/workspace/ckpt/sft run sft bash $M/sft.sh

3. Check each save, keep one, evaluate it.

for e in 35 70 104; do                   # the 3-epoch run's saves
  EVAL_CKPT=/workspace/ckpt/sft EVAL_CKPT_STEP=$e EVAL_CONFIG=code/rl/dev_eval_env.yaml EVAL_PROMPTS=100 \
      run sft_epoch_$e bash $M/eval.sh
done
grep "validation loss at iteration" /workspace/runs/sft.log
STEP=104                                 # the saved step with the lowest validation loss (ours: 0.930)
echo $STEP > /workspace/ckpt/sft/latest_checkpointed_iteration.txt
LM_EVAL_CKPT=/workspace/ckpt/sft run lm_sft bash $M/lm_eval.sh  # hold-out perplexity, Eq. (3)

Then run the 15-minute after-SFT evaluation on the six test sets with code/rl/heldout_eval_env.yaml, exactly as in the evaluation guide. Its first pass covers the fixed 200-problem subsets; whole sets follow while time remains.

Tests (laptop, seconds):

cd code && python -m unittest tests.test_prepare_sft_data tests.test_make_megatron_sft -v

Config files and code:

Results to expect (ours, one run each; greedy numbers can move by a problem or two between passes):

  • 3 epochs: validation loss 1.140, 0.971, 0.930; format 69%, 91%, 90%; mixed groups 3.1%, 3.1%, 6.3%.
  • 6 epochs: the lowest validation loss, 0.748, at step 175.
  • Step 175: GSM8K (200-problem subset) 2.0% greedy and 12.0% pass@8; hold-out perplexity 22.74, up from 20.97.

All results are collected in the results reference, and the SFT guide has the step-by-step version.

// § 11

What to take away

  • SFT is imitation with a mask: the loss covers the answer and its end token, never the question or the padding.
  • Check what your framework masks and pads. Megatron’s default format trains on everything, and a pad equal to the end token would have hidden the stop signal.
  • Pack short examples: one example per row would have been 96% padding and about 25 times the steps.
  • SFT quickly teaches what repeats in every example: layout, length and stopping. It did not teach arithmetic to a weak base.
  • Measure the RL signal before RL. At 8 answers per problem, 1.6% of groups were mixed; 32 answers on a better-matched tier gave 43.8%.
  • Validation loss chooses a checkpoint by fit, not by skill. Report forgetting beside it: here, +8.4% perplexity on general text.

References

  1. Shubham Toshniwal et al., “OpenMathInstruct-2: Accelerating AI for Math with Massive Open-Source Instruction Data”, arXiv:2410.01560. https://arxiv.org/abs/2410.01560
  2. NVIDIA, OpenMathInstruct-2 dataset (CC BY 4.0). https://huggingface.co/datasets/nvidia/OpenMathInstruct-2
  3. NVIDIA, Megatron-LM at commit d6316eb45: the SFT tokenizer and dataset. https://github.com/NVIDIA/Megatron-LM/tree/d6316eb45bf1bfbb6f1f848c0b56e55166564d80
  4. Kian Kyars, Reinforcement Learning from Verifiable Rewards, Ch. 5, “Turning Checks into Training Signal” (v1 of 2026-09-26; accessed 2026-12-03). https://rlvrbook.com/chapters/05-turning-checks-into-training-signal.html
  5. Zhoutong Fu, “Entropy in LLM RL: Dynamics and Control” (2026-10-21). https://zhoutongfu.github.io/zhoutong-ai-blog/posts/entropy-in-llm-rl/
  6. Zheng et al., “Group Sequence Policy Optimization”, arXiv:2507.18071. https://arxiv.org/abs/2507.18071

Cite this

@misc{aboagye2026minidsv4part07,
  author       = {Aboagye, Prince Osei},
  title        = {Mini DeepSeek V4, Part 7: Supervised fine-tuning: teaching the answer format},
  year         = {2026},
  howpublished = {\url{https://poaboagye.github.io/blog/07-sft/}}
}