Prince Osei Aboagye
Guide

Reinforcement learning with GSPO

How to run GSPO with Megatron-LM's own RL loop on 8×H100: the rate calibration, the first-update checks, the run and what to watch, the optional difficulty filter, and the laptop experiments that came first.

// § 01

What you will do

  • On the laptop: reproduce the Phase 0 GSPO experiments on MiniMind’s 64M dense model.
  • On 8×H100: calibrate the learning rate with three one-step runs, and check the first update.
  • Run GSPO from the SFT model, watch its signals, and evaluate the result.
  • Optionally: keep only the problems the SFT model can sometimes solve, and run GSPO on those.

GSPO in one paragraph. For each prompt, the model samples a group of \(G\) answers, and a grader scores them. Each answer’s advantage is its reward relative to its group. The update raises the probability of the better answers, and a clip stops any answer’s probability from moving too far in one update. GSPO (group sequence policy optimization) applies that clip to a whole answer’s probability ratio, not to each token’s.

\[s_i(\theta) = \left( \frac{\pi_\theta(o_i \mid q)}{\pi_{\text{old}}(o_i \mid q)} \right)^{1/|o_i|}\]

where \(q\) is the prompt, \(o_i\) the \(i\)-th sampled answer, \(|o_i|\) its length in tokens, \(\pi_\theta\) the model being updated, and \(\pi_{\text{old}}\) the model that sampled the answers.

In words: \(s_i\) is how much the answer’s probability has changed since it was sampled, per token on average.

The clip keeps \(s_i\) within \([1 - \varepsilon_{\text{low}},\, 1 + \varepsilon_{\text{high}}]\), which the GSPO paper sets to \(3 \times 10^{-4}\) and \(4 \times 10^{-4}\). Before the first update nothing has changed, so \(s_i\) must be exactly 1. That is the most useful check in this guide.

// § 02

Hardware and time

Level What runs Time
A laptop RTX 3060 (6 GB) GSPO on MiniMind’s 64M dense model, 300 steps about 75 min for Run 3b; about 5 h for the three-seed batch
One H100 the rehearsal: GSPO on the shrunk model, 64 answers per step 10 minutes of training per test
8×H100 GSPO on the full model, 512 answers per step 85 minutes of training per arm

The mixture of experts does not fit RL on the 6 GB card: its rollout runs out of memory, not its update.

// § 03

Phase 0 on the laptop

The laptop experiments found the numerical bugs that shaped everything after them. From code/, after the laptop setup:

bash scripts/run3b.sh                 # Run 3b: GSPO on MiniMind's 64M dense SFT model, 300 steps, about 75 min
bash scripts/step3.sh ab              # on-policy GSPO: arm A (1e-7, seeds 0 1 2) and arm B (3e-7); about 5 h

What the public repository lacks. Both scripts check their runs against our own saved Phase 0 logs, and those logs are not in the public repository. run3b.sh first runs 10 steps and compares them with our Run 2 log (logs/minimind_gspo_lr_sweep_1e-6.jsonl); without that file it stops there. Its final analysis also reads our Run 3 log. To train Run 3b without those comparisons, run its training line yourself, from code/:

../.venv/bin/python -u rl/minimind_gspo.py --tag run3b_1e-6 --from_weight full_sft --batch_size 16 --lr_warmup_updates 5 \
    --learning_rate 1e-6 --adjust_every 20 --start_tier warmup --steps 300 --seed 1 --eval_every 50 --eval_n 200 \
    --eval_samples 8 --save_eval_answers --save_eval_weights --save_weight gspo_run3b --deterministic on

It writes logs/minimind_gspo_run3b_1e-6.jsonl and the held-out answers beside it. step3.sh needs no saved log of ours to train, but its final analysis compares with that Run 3b log, so run this first.

  • What to expect. On-policy GSPO at 1e-7 raised held-out final-answer accuracy in 3 of 3 seeds, from 0.81% to 5.9%, 5.9% and 5.4%.

  • Read it carefully. The grader reads only the final number, and the three seeds share one held-out set.

  • What it taught. Old, new and reference log-probabilities must come from identical mini-batches; otherwise the ratio moves with no learning at all. The sampler must also be the untruncated policy at temperature 1, or every update is off-policy.

The rest of this page runs the full model.

// § 04

On 8×H100

The settings

code/scripts/megatron/gspo.sh runs Megatron’s own RL loop (train_rl.py) with our patch and our curriculum agent.

Setting Value
Ratio sequence level, clipped per answer; KL penalty β = 0.01 to the SFT model; no entropy term
Groups groups whose answers are all right or all wrong get advantage 0 (the correctness filter)
Sampling temperature 1, no top-k, no top-p, no BOS token, no sequence packing
Length a hard stop at 1,536 tokens for prompt plus answer; the reward’s penalty starts at 768 tokens and reaches −1 at 1,024
Optimizer Adam, constant rate after a 5-update warm-up; micro-batch 1; gradient clip 1
Router the main run’s router with its balancing frozen (ROUTER_MAIN_RL)
Saves full checkpoints with the optimizer state every 50 GSPO steps; the curriculum state every step

The reference model is the SFT checkpoint. Megatron loads it at the start and keeps it fixed for the whole run, also after a restart. Micro-batch 1 is not a choice: Megatron’s RL forward pass holds exactly one answer, and check_flags.py refuses more.

Batch sizes. Megatron counts RL iterations in optimizer updates, so every interval is a multiple of the updates per step:

\[B_{\text{global}} = \frac{P \times G}{U}\]

where \(P\) is the prompts per GSPO step, \(G\) the answers per prompt, \(U\) the optimizer updates per step, and \(B_{\text{global}}\) the answers in one update.

In words: one step’s rollouts are split evenly across its updates.

Our main run used \(P = 16\), \(G = 32\) and \(U = 4\): 512 rollouts per step and 128 answers per update.

So “every 50 GSPO steps” is every 200 iterations, for saves and in-run evaluations alike.

1. Calibrate the learning rate

Each calibration run is one GSPO step, its 4 updates, from the SFT weights. Nothing is saved.

Set our main run’s group settings first; they stay set for every step below:

export GROUP_SIZE=32 PROMPTS_PER_STEP=16 RL_ENV_CONFIG=code/rl/curriculum_env_medium.yaml
for lr in 1e-7 3e-7 1e-6; do
  CALIBRATION=1 GSPO_LR=$lr SFT_CKPT=/workspace/ckpt/sft run cal_$lr bash $M/gspo.sh
done
python -I code/scripts/gspo_calibration_report.py --run 1e-7=/workspace/runs/cal_1e-7 \
    --run 3e-7=/workspace/runs/cal_3e-7 --run 1e-6=/workspace/runs/cal_1e-6        # prints the chosen GSPO_LR

curriculum_env_medium.yaml starts at the medium tier and holds it there. The default tier, easy, gave our SFT model almost no mixed groups (see the SFT gate). The report’s rule picks the highest rate whose clipped share \(C\) stays at or below 0.30. \(C\) counts answers clipped in the direction their advantage pushes, on the updates after the first.

Our calibration. The three runs took 375 s, 357 s and 421 s. \(C\) was 13.0%, 12.0% and 4.2% at 1e-7, 3e-7 and 1e-6. It fell as the rate rose tenfold, so it measured noise, not the rate. The rule chose 1e-6.

2. Check the gate and the first update

Read the first calibration run before anything else:

python -I code/scripts/gspo_run_report.py /workspace/runs/cal_1e-7
  • Group signal: at least 30% of the step’s groups must be mixed (step_stats.jsonl). Ours read 43.8% of 16 groups on the first calibration run, with a solve rate of 2.73%: PASS. The other two runs’ first steps, sampled from the same SFT weights, read 31.3% and 12.5%. One batch of 16 groups is a noisy gate, and the third draw alone would have failed it, so read all three.

  • Loss and gradients finite: ours passed.

  • The first update’s ratio: exactly 1, and the KL to the reference about 0. On one GPU both held exactly, in the rehearsal and in the control run. On 8 GPUs they did not: before any weight change, the median \(|\log s_i|\) was 0.0049 (p99 0.034), and the KL was 0.0027.

The cause is numerical: Megatron’s no-gradient log-prob pass and its training pass differ slightly at expert parallelism 8. Routing, batch composition and dropout were ruled out from the code. Megatron’s batch-invariant mode would fix it, but it needs FlashAttention 3 or 4, which our image lacked.

That noise is 16× the paper’s clip. At the paper’s clip it alone clipped 19.5%, 13.3% and 3.9% of the first update’s answers in the three runs. So I set the clip just above it: GSPO_CLIP_LOW=2e-2 GSPO_CLIP_HIGH=2.7e-2, which noise clipped 0% of the time.

On 8 GPUs, measure your own noise first and set the clip above it.

3. Run GSPO

export GROUP_SIZE=32 PROMPTS_PER_STEP=16 RL_ENV_CONFIG=code/rl/curriculum_env_medium.yaml \
       GSPO_CLIP_LOW=2e-2 GSPO_CLIP_HIGH=2.7e-2
EXTRA_ARGS="--moe-routing-trace-path /workspace/runs/gspo/trace --moe-routing-trace-max-training-iters 5 \
  --moe-routing-trace-capture-logits" GSPO_LR=1e-6 SFT_CKPT=/workspace/ckpt/sft CKPT_DIR=/workspace/ckpt/gspo \
  EXIT_MINS=85 run gspo bash $M/gspo.sh
unset EXTRA_ARGS

GSPO_LR=1e-6 and EXIT_MINS=85 were our calibrated rate and time limit; use yours. With --load empty at the first launch, Megatron starts from the SFT checkpoint by itself. Do not add --finetune, or a restart starts over.

4. Watch it

  • The agent’s line every step: solve rate, mixed groups, answer length, tier. The same numbers go to step_stats.jsonl.
  • In W&B: rl/clipped_sequences, rl/seq_kl, rl/sampler_learner_gap, Megatron’s own mean_inf_train_prob_abs_diff, and the timers.
  • The run report, at any time (KL mean, median and p99; clipping by mini-batch; the alarms):
python -I code/scripts/gspo_run_report.py /workspace/runs/gspo
python $GIST_DIR/router_watch.py counts /workspace/ckpt/gspo/tokens_per_expert $RW > /workspace/runs/gspo/maxvio.jsonl

The second line reads MaxVio every GSPO step, with step 1 as the baseline. Nothing rebalances the experts during RL, so the alarm is MaxVio above twice its step-1 value. If it fires, raise β from 0.01 to 0.05, then halve the rate. Our MaxVio read 6.29–6.41 at every step, flat. That level is padding: rows are padded to 1,536 tokens, and the RL training forward routes the padding too. At step 50 (iteration 200), compare the dev split’s greedy solve rate with step 0, and read the KL’s median and p99.

How long a step takes. In synchronous RL the trainer waits while the model generates, so:

\[t_{\text{step}} \approx t_{\text{rollout}} + t_{\text{logprob}} + n_{\text{upd}} \, t_{\text{update}}\]

where \(t_{\text{rollout}}\) is the time to generate all \(P \times G\) answers (set by the longest one), \(t_{\text{logprob}}\) the old and reference log-probability passes, \(n_{\text{upd}}\) the timed updates, and \(t_{\text{update}}\) one update.

In words: generation dominates, and it lasts as long as the longest answer in the batch.

Our first step was the slowest, at 346 s. Over the 44 complete steps the median step took 111 s: one rollout iteration (generation, grading, scoring and the first update), then three more updates of about 8.5 s each. Generation and grading took 57.5% of the logged time, scoring 11.8% and the four updates 30.7%. Over the whole run, 45 steps took 5,277 s, an average of about 117 s per step. To plan a run, divide your time limit by a step time measured on your own first steps.

5. After GSPO

The router’s change during RL, the counts, the routing at the end of RL, the forgetting check, and the after-GSPO evaluation:

python -I code/scripts/checkpoint_router_bias.py "$MEGATRON_PATH" /workspace/ckpt/gspo --all \
    --base /workspace/ckpt/sft > /workspace/runs/gspo/router_bias.jsonl
cp -r /workspace/ckpt/gspo/tokens_per_expert /workspace/runs/gspo/
python $GIST_DIR/router_watch.py trace /workspace/runs/gspo/trace --num-experts 64 --ranks 0 --score sqrtsoftplus \
    --scale 2.5 > /workspace/runs/gspo/routing.jsonl
CALIBRATION=1 GSPO_LR=1e-6 SFT_CKPT=/workspace/ckpt/gspo EXTRA_ARGS="--moe-routing-trace-path /workspace/runs/gspo_end/trace \
    --moe-routing-trace-max-training-iters 5 --moe-routing-trace-capture-logits" run gspo_end bash $M/gspo.sh
python $GIST_DIR/router_watch.py trace /workspace/runs/gspo_end/trace --num-experts 64 --ranks 0 --score sqrtsoftplus \
    --scale 2.5 > /workspace/runs/gspo_end/routing.jsonl
for t in gspo gspo_end; do python -I code/scripts/router_zloss.py $GIST_DIR /workspace/runs/$t/trace --num-experts 64 \
    --json /workspace/runs/$t/zloss.jsonl; done
python -I code/scripts/gspo_run_report.py /workspace/runs/gspo
LM_EVAL_CKPT=/workspace/ckpt/gspo run lm_gspo bash $M/lm_eval.sh
python -I code/scripts/eval_budget.py --name eval_gspo --ckpt /workspace/ckpt/gspo \
    --config code/rl/heldout_eval_env.yaml --budget-min 15

The gspo_end run is one calibration step from the final weights, only to record their routing.

With the balancing frozen, expect the router-bias report to show no change.

6. Optional: train only on learnable problems

GSPO learns nothing from a problem whose answers are all wrong. Our GSPO-B run first asked the SFT model each medium-tier problem 16 times, kept the problems with between 1 and 15 right answers, and ran GSPO on those.

STALL_MIN=30 EVAL_CKPT=/workspace/ckpt/sft EVAL_CONFIG=code/rl/medium_filter_env.yaml EVAL_PROMPTS=5000 \
    run medium_filter bash $M/eval.sh
LEARN=/dev/shm/data/curriculum_learnable
python -I code/scripts/build_learnable_tier.py /workspace/runs/medium_filter/eval_results.jsonl "$CURRICULUM_DIR" $LEARN
CURRICULUM_DIR=$LEARN GSPO_LR=1e-6 EXIT_MINS=85 SFT_CKPT=/workspace/ckpt/sft CKPT_DIR=/workspace/ckpt/gspo_filtered \
    run gspo_filtered bash $M/gspo.sh

build_learnable_tier.py copies every other file of the curriculum unchanged. Specific to our machines: LEARN was a folder in RAM beside our staged data; any folder works.

// § 05

What to expect

GSPO-A (the main run): 45 GSPO steps, 177 updates, stopped by the 85-minute limit.

  • Training. The solve rate went from 2.25% (first 22 steps) to 2.79% (last 23): suggestive, not significant (Welch t 1.68).
  • The policy moved steadily. The KL to SFT rose from 0.0024, the noise floor, to 0.028 by step 39; 0–1.6% of answers were clipped per update; 97–99% of answers kept the format.
  • No forgetting. Hold-out perplexity 22.76, against 22.74 after SFT.

The held-out evaluation, paired on the same 1,178 problems as after SFT:

Measure SFT GSPO-A Paired p
Greedy accuracy, pooled 1.9% 2.6% 0.24
pass@8, pooled 10.5% 13.2% 0.038
pass@8, SVAMP subset 11.0% 21.5% 0.0025
pass@8, whole SVAMP (300) 12.0% 18.0% 0.04

In avg@8, the share of right answers among 8 samples, the six-set mean went from 1.46% to 2.04%, a paired +0.58 points with p = 0.002. GSPO-A improved the sets nearest its training tier, while GSM8K and MATH did not move.

GSPO-B (learnable problems only): 418 of 1,905 medium-tier problems were learnable, 22%; it ran 46 steps in 5,182 s. It learned its own pool much faster, a solve rate of 4.89% → 7.31% (t 4.24), but on the held-out tests it could not be told apart from GSPO-A (greedy p = 0.31, pass@8 p = 0.22).

The router through RL: the mean router z-loss went from 25.3 to 25.9 (+2.4%), and the entropy of the 8 selected weights from 1.996 to 1.989 nats. The routing did not drift.

Our model’s gain was small, and the control run shows why: the same pipeline on a stronger base model matched a published result.

// § 06

Check that it worked

  • On one GPU, the first update’s ratio is exactly 1 and the KL 0. On 8 GPUs, record the noise and set the clip above it.
  • The KL to SFT rises slowly; the 10-step mean stays under 0.1.
  • On updates 2–4, the clipped share stays under 0.30.
  • At least 30% of groups stay mixed, and format compliance stays above 90%.
  • MaxVio stays under twice its step-1 value.
  • The held-out evaluation is compared with SFT’s on the same problems, with a paired test.
// § 07

Common problems

Symptom Cause Fix
RuntimeError: expected 3D tensor in Transformer Engine’s fused RoPE after the rollouts micro-batch above 1: Megatron’s RL forward holds one row micro-batch 1; check_flags.py refuses more
a crashed run sits at 0% GPU holding memory the inference coordinator was not a daemon process our patch makes it one; the stall guard stops any quiet run
AttributeError at the first update --check-for-spiky-loss calls a method Megatron lacks off for RL runs (LOG_RL)
ModuleNotFoundError: openai, or no web backend the image lacks the RL loop’s packages the setup script installs them at Megatron’s lock versions
the restart loads its own checkpoint “at iteration 0” --finetune on a restart leave it out; Megatron starts from the SFT checkpoint by itself
“–moe-pad-experts-for-cuda-graph-inference must be set” on 8 GPUs Megatron’s RL inference always uses CUDA graphs with expert parallelism rl_common.sh adds the flag to every RL launch
the policy drifts with every advantage 0 the router’s bias rule and balance loss still produce gradients ROUTER_MAIN_RL freezes both
the gate’s group signal fails the tier is too hard for the model at 8 answers a learnable tier and 32 answers per problem
the first update’s ratio is not 1 on 8 GPUs numerical noise between two passes at expert parallelism 8 measure it, set the clip above it

Every RL bug, with where it was caught, is in the troubleshooting table.

// § 08

Read more