Prince Osei Aboagye
Guide

Supervised fine-tuning

How to fine-tune the pretrained model on 55,083 worked math problems with Megatron's SFT mode, choose the epoch to keep, and run the checks that decide whether RL can start.

// § 01

What you will do

  • Fine-tune the pretrained model on the packed SFT set from the data guide: 55,083 GSM8K-style word problems with worked answers.
  • Save weights at about each epoch, and keep the save with the lowest validation loss.
  • Measure format compliance at each saved epoch, the hold-out perplexity, and the after-SFT evaluation.
  • Check the gate that decides whether reinforcement learning (RL) can start.

Supervised fine-tuning (SFT) trains on example answers with the ordinary next-token loss, counted on the answer tokens only. Format compliance is the share of answers written as <think>...</think> then <answer>...</answer>.

// § 02

Hardware and time

8×H100, the same layout as pretraining. Three epochs (104 steps) took 651 s, a median of 3.2 s per step.

Six epochs (208 steps) took 988 s. Each per-epoch format check took 452–471 s, and the after-SFT evaluation 1,147 s. On one H100, the rehearsal runs the same script on the shrunk model.

// § 03

The settings

code/scripts/megatron/sft.sh uses the pretraining model arrays, plus the SFT arrays in code/scripts/megatron/sft_common.sh:

Setting Value
Data --sft, Megatron’s SFTTokenizer with the identity prompt format, the packed lines in $SFT_DIR
Start --finetune from the pretraining checkpoint: its weights, iteration 0, a fresh optimizer
Optimizer peak learning rate 1e-5, cosine to 1e-6, 320 warm-up samples (5 steps); 64 rows per step; clip 1
Saves weights only, every 35 steps (about one epoch)
Validation every 35 steps, one batch, which covers all 46 validation lines
Expert counts every 26 steps
Router the main run’s router, with its balancing on

--no-create-attention-mask-in-dataloader is required: Megatron’s SFT dataset asserts that no attention mask is built in the data loader. Without it, our rehearsal’s SFT stopped before its first step.

Pretraining’s document-reset flags stay out too, since the SFT dataset resets positions itself.

How many steps

\[S = \left\lceil \frac{n_{\text{epochs}} \times N_{\text{lines}}}{B} \right\rceil, \qquad \texttt{SFT\_SAMPLES} = S \times B\]

where \(S\) is the number of steps, \(n_{\text{epochs}}\) the passes over the data, \(N_{\text{lines}}\) the packed training lines, and \(B\) the rows per step.

In words: count the packed lines you want to see, divide by the rows per step, and round up to whole steps.

With 2,210 lines and 64 rows per step, 3 epochs are 104 steps (6,656 samples, the default) and 6 epochs are 208 steps (SFT_SAMPLES=13312). Unpacked, 3 epochs would have been about 2,530 steps.

// § 04

Steps

1. Train

From the shell you set up for pretraining (env.sh sourced, MAIN_ROUTER=qb exported):

EXTRA_ARGS="--moe-routing-trace-path /workspace/runs/sft/trace --moe-routing-trace-max-training-iters 5 \
  --moe-routing-trace-capture-logits" PRETRAIN_CKPT=/workspace/ckpt/pretrain CKPT_DIR=/workspace/ckpt/sft \
  run sft bash $M/sft.sh
unset EXTRA_ARGS

EXTRA_ARGS records the routing of SFT’s first 5 iterations, which shows the router of the end-of-pretraining model.

For six epochs, as in our final run, add SFT_SAMPLES=13312: one cosine schedule over 208 steps, saves at 35, 70, 105, 140, 175 and 208.

2. Routing and balance

python $GIST_DIR/router_watch.py trace /workspace/runs/sft/trace --num-experts 64 --ranks 0 --score sqrtsoftplus \
  --scale 2.5 > /workspace/runs/sft/routing.jsonl   # routing entropy (8 selected), Max1/Max2, MaxVio per call
python -I code/scripts/router_zloss.py $GIST_DIR /workspace/runs/sft/trace --num-experts 64 --json /workspace/runs/sft/zloss.jsonl
python $GIST_DIR/router_watch.py counts /workspace/ckpt/sft/tokens_per_expert $RW > /workspace/runs/sft/maxvio.jsonl
python -I code/scripts/checkpoint_router_bias.py "$MEGATRON_PATH" /workspace/ckpt/sft --all \
    --base /workspace/ckpt/pretrain > /workspace/runs/sft/router_bias.jsonl
cp -r /workspace/ckpt/sft/tokens_per_expert /workspace/runs/sft/

3. Format compliance at each saved epoch

Each check answers 100 dev-split problems greedily with the saved weights:

for e in 35 70 104; do
  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

Each check also runs one RL rollout batch at the easy tier, 64 groups of 8 answers, and writes its solve rate and mixed groups to step_stats.jsonl. That is the gate’s group signal. For six epochs, loop over the six save steps.

4. Keep the best epoch

Choose the save with the lowest SFT validation loss, then set /workspace/ckpt/sft/latest_checkpointed_iteration.txt to its step. Megatron loads the step that file names, so every later stage uses your choice. I fixed this rule before seeing the data, and it kept step 175 of the six-epoch run.

5. Forgetting and the after-SFT evaluation

Measure the hold-out perplexity on the save you kept, then run the after-SFT evaluation with a 15-minute limit:

LM_EVAL_CKPT=/workspace/ckpt/sft run lm_sft bash $M/lm_eval.sh
python -I code/scripts/eval_budget.py --name eval_sft --ckpt /workspace/ckpt/sft \
    --config code/rl/heldout_eval_env.yaml --budget-min 15

The evaluation guide explains what eval_budget.py runs within its limit.

6. The SFT → RL gate

RL learns only from groups of answers to one problem that are neither all right nor all wrong. The gate checks there are enough of them before you use GPU time on RL:

Check Threshold If it fails
GSM8K accuracy, greedy recorded; literally 0% means RL has no signal more or different SFT
Format compliance, dev split above 50% the template was not learned: more SFT
Group signal, 8 answers per problem at least 30% of groups mixed change the difficulty or the group size

What group size you need. If every problem had the same solve rate \(p\), the chance that a group of \(G\) answers is mixed would be:

\[P_{\text{mixed}} = 1 - (1 - p)^{G} - p^{G}\]

where \(p\) is the chance that one sampled answer is right and \(G\) the answers per problem.

In words: a group carries signal unless all its answers are wrong or all are right.

At the easy tier our kept model solved 0.2%, so with \(G = 8\) the formula gives 1.6% mixed, exactly what we measured.

At the medium tier with \(G = 32\) and a 2.73% solve rate it gives 59%; our first calibration step measured 43.8%.

The other two calibration steps, sampled from the same weights, measured 31.3% and 12.5%: one batch of 16 groups is a noisy reading. Real problems differ in difficulty, and many had no right answer at all, so treat the formula as an upper estimate.

// § 05

What to expect

Three epochs (from the end of pretraining): training loss 2.774 → 0.910, and the gradient norm 3.7 → 0.18.

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

Six epochs, the run we kept:

Step (epoch) 35 (1) 70 (2) 105 (3) 140 (4) 175 (5) 208 (6)
Validation loss 1.158 0.907 0.811 0.776 0.748 0.762
  • Kept: step 175, validation loss 0.748. The validation set is one batch of 46 packed lines, so the rise at step 208 may be noise.
  • Forgetting: hold-out loss 3.1241, perplexity 22.74, against 20.97 before SFT: +8.4%.
  • Balance: the experts stayed even under quantile balancing; MaxVio was 0.062 at step 26 and 0.039 at step 104 of the three-epoch run.

The after-SFT evaluation of step 175 (subsets of 200 problems unless marked whole):

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

pass@8 is the share of problems with at least one right answer among 8 samples at temperature 1.

The gate on step 175: GSM8K 2.0%, recorded; format 74.5% on 200 dev answers, a PASS; group signal 1.6% at the easy tier, a FAIL. The answers show why. The model writes the format exactly but copies the question’s first number: “What is 96 + 83?” gets <answer>96</answer>. More epochs gave a better fit, not the RL signal. The fix that worked was the medium tier with 32 answers per problem, on the RL page.

// § 06

Check that it worked

  • The loss falls, with no assertion about masks or reset flags.

  • Format compliance on the dev split clears 50%, the gate, and ideally 80%, the target after SFT.

    Ours read 91% at the second epoch of the three-epoch run, on 100 answers, but 74.5% for the kept step 175 on the gate’s 200 answers.

  • No expert is starved, and MaxVio stays level.

  • latest_checkpointed_iteration.txt names the step you chose.

  • The hold-out perplexity rises only a little; compare it with the value before SFT.

// § 07

Common problems

Symptom Cause Fix
SFT stops before step 1 on an attention-mask assertion the data loader builds a mask the SFT dataset refuses --no-create-attention-mask-in-dataloader (in sft_common.sh)
a crash at the first padding, or a token silently left out of the loss Megatron’s pad is <unk>, which Llama 3.2 lacks our patch falls back to <|finetune_right_pad_id|> and refuses a pad equal to the end token
SFT takes thousands of steps one example per line is about 96% padding pack the lines (make_megatron_sft.py)
SFT stops at 0 steps the restored iteration counter of the pretraining checkpoint --finetune (in sft.sh)
a short run stops in the scheduler the warm-up is not shorter than the decay the warm-up is 320 samples or a quarter of the run, whichever is smaller
the gate’s group signal fails the model writes the format but rarely the right number a harder-but-learnable tier and more answers per problem (RL)

More are in the troubleshooting table.

// § 08

Read more