Prince Osei Aboagye
Reference

Configs and flags

The key Megatron-LM settings of every stage, each with a one-line meaning: model shape, parallelism, optimizer and precision, the MoE router, SFT, GSPO, evaluation and serving, plus the overrides the main and control runs used.

All launch scripts live in code/scripts/megatron/. common.sh defines the shared flag arrays, and each stage script composes them and starts torchrun. Megatron-LM is pinned at commit d6316eb45, with my patch code/patches/megatron-d6316eb45.patch. DRY_RUN=1 prints a script’s arguments instead of launching, and check_flags.py builds each launch’s config before any GPU time is used.

The base recipe is the HF MoE handbook’s tested launch script, with DeepSeek V4’s router flags on top. Exact commands for every stage are in the Guide.

// § 01

Which script runs which stage

Script Stage Notes
moe_pretrain.sh Main pretraining The router of MAIN_ROUTER; checkpoints every 200 steps; the profiler on steps 50–53
dense_baseline.sh, moe_forced_even.sh, moe_aux.sh, moe_v4router.sh, moe_v4_qb.sh, moe_overlap_test.sh, moe_nvlink_off.sh The balancing study 40 iterations per MoE arm, 120 for the dense baseline
sft.sh with sft_common.sh Supervised fine-tuning From the final pretraining checkpoint
gspo.sh with rl_common.sh GSPO Megatron’s own RL loop (train_rl.py) with my patch and curriculum agent
eval.sh with rl_common.sh Held-out evaluations Megatron’s RL inference-only mode
lm_eval.sh Hold-out perplexity One validation pass, no training
serve_bench.sh Serving benchmark Megatron’s own inference examples
distill.sh, qat_4bit.sh Distillation and 4-bit Run in the rehearsal only; cut from the main run
qwen_skeleton.sh, convert_qwen2_hf.py Control-run conversion A Megatron checkpoint of Qwen’s shape, then the weight swap
rogue_experts.sh Expert output norms One iteration with Megatron’s activation dump
// § 02

Environment variables

Variable Value Meaning
CUDA_DEVICE_MAX_CONNECTIONS 1 One hardware work queue per GPU, so kernels start in the order they are issued
NVTE_ALLOW_NONDETERMINISTIC_ALGO 1 Lets Transformer Engine pick faster, non-deterministic kernels
PYTORCH_CUDA_ALLOC_CONF expandable_segments:True The allocator grows memory segments in place, which cuts fragmentation
NCCL_NVLS_ENABLE 0 Turns off NCCL’s NVLink SHARP algorithms

These four come from the handbook’s tested environment. On the laptop, without expandable segments, even the MoE’s first update failed with 1.2 GB idle in the allocator.

// § 03

Model shape

Flag Value Meaning
--num-layers 16 Transformer blocks
--hidden-size 2048 Width of the residual stream
--num-attention-heads 32 Query heads per layer
--group-query-attention, --num-query-groups 4 Grouped-query attention: 4 key-value heads shared by the 32 query heads
--kv-channels 64 Dimension of each head
--qk-layernorm on RMSNorm on queries and keys before attention
--position-embedding-type, --rotary-base, --rotary-percent rope, 500,000, 1.0 Rotary position embeddings on the whole head, base 500,000
--normalization, --norm-epsilon RMSNorm, 1e-5 Pre-norm with RMSNorm
--swiglu on SwiGLU feed-forward blocks
--seq-length, --max-position-embeddings 4096 Training context of 4,096 tokens
--ffn-hidden-size 8192 Dense FFN width; only the dense baseline uses it, since every MoE layer is an expert layer
--disable-bias-linear on No bias terms in linear layers
--attention-dropout, --hidden-dropout 0, 0 No dropout
--init-method-std 0.02 Standard deviation of the initial weights
--transformer-impl, --use-flash-attn transformer_engine, on Transformer Engine layers with FlashAttention
(no untie flag) tied Input embedding and output layer share one matrix

The vocabulary is the Llama 3.2 tokenizer’s 128,256 tokens. The model has 6.86B parameters in total and 1.22B active per token.

// § 04

Mixture of experts

Flag Value Meaning
--num-experts 64 Routed experts per layer, in every layer
--moe-ffn-hidden-size 1024 Width of each expert’s FFN
--moe-router-topk 8 Experts each token is sent to
(no shared-expert flag) none No always-on shared expert
--moe-token-dispatcher-type alltoall Tokens travel to their experts’ GPUs by all-to-all
--moe-grouped-gemm on One grouped matrix multiply for a GPU’s local experts
--moe-router-dtype fp32 The router in fp32 (logits, scores and gate weights). Megatron’s help calls it the “data type for routing and expert output weighted averaging”, but at d6316eb45 the all-to-all path sums the experts’ outputs in bf16
--moe-per-layer-logging on Router losses logged per layer
--activation-func-clamp-value 10 DeepSeek V4’s SwiGLU clamp: the gate input is capped at 10 and the linear input clipped to [−10, 10]
// § 05

The router

The plan was DeepSeek V4’s router. In the main run every recipe router collapsed at the start, so pretraining used V4’s scores with quantile balancing (MAIN_ROUTER=qb). Every later stage loads those weights, so every later stage routes the same way.

Scores. Both V4 arrays score each expert with the square root of the softplus of its router logit:

\[s_{t,e} = \sqrt{\operatorname{softplus}(\ell_{t,e})} = \sqrt{\ln\left(1 + e^{\ell_{t,e}}\right)} \tag{1}\]

Here \(\ell_{t,e}\) is the router logit of token \(t\) for expert \(e\), and \(s_{t,e}\) is its score.

In words: a smooth, always-positive score that grows like the square root of the logit for large logits.

Selection with V4’s expert bias. V4 picks the top 8 experts on the score plus a per-expert bias, and nudges that bias by a fixed step after each update:

\[\mathcal{T}_t = \operatorname{TopK}_{8}\left(s_{t,e} + b_e\right), \qquad b_e \leftarrow b_e + \gamma \cdot \operatorname{sign}\left(\bar{c} - c_e\right) \tag{2}\]

Here \(\mathcal{T}_t\) is the set of experts chosen for token \(t\), \(b_e\) is expert \(e\)’s bias, \(\gamma\) is the bias update rate (--moe-router-bias-update-rate, 1e-3), \(c_e\) is the number of tokens expert \(e\) received, and \(\bar{c}\) is the mean over experts.

In words: an expert that got fewer tokens than average has its bias raised by \(\gamma\), so it wins more tokens next time.

Selection with quantile balancing. Quantile balancing picks the top 8 experts on the logit minus a per-expert bias, and solves that bias from the batch’s logit quantiles instead of stepping it:

\[\mathcal{T}_t = \operatorname{TopK}_{8}\left(\ell_{t,e} - \beta_e\right), \qquad \beta_e \leftarrow \rho\,\beta_e + (1-\rho)\,q_e \tag{3}\]

Here \(\beta_e\) is expert \(e\)’s bias (qb_beta), \(q_e\) is the quantile solved from the current global batch, and \(\rho\) is the exponential moving average (--moe-router-quantile-balancing-ema). Megatron then centres the biases. They are updated during training only, and \(\rho = 1.0\) keeps them exactly fixed.

In words: each expert’s bias moves toward the logit threshold that would hand it exactly its fair share of the batch’s tokens.

Gate weights. The chosen experts’ outputs are mixed with their scores, renormalised over the 8 chosen experts and scaled by the routed scaling factor:

\[g_{t,e} = \lambda \, \frac{s_{t,e}}{\sum_{j \in \mathcal{T}_t} s_{t,j}} \quad (e \in \mathcal{T}_t) \tag{4}\]

Here \(g_{t,e}\) is the weight of expert \(e\)’s output for token \(t\), and \(\lambda = 2.5\) (--moe-router-topk-scaling-factor).

In words: the 8 weights of a token are proportional to the chosen experts’ scores and sum to the scaling factor.

Array (common.sh) Flags Where it ran
ROUTER_V4 sqrtsoftplus scores; expert bias at rate 1e-3; sequence-level aux loss 1e-4; scaling 2.5 The planned router; collapsed in the balancing study
ROUTER_AUX softmax scores; aux loss 1e-3 The handbook’s tested router; collapsed the same way
ROUTER_V4_QB sqrtsoftplus scores; quantile balancing; aux loss 0; scaling 2.5 The main run: pretraining, SFT, evaluations, serving
ROUTER_MAIN_FROZEN (qb) as above, plus EMA 1.0 QAT: the bias kept exactly
ROUTER_MAIN_RL (qb) as above, plus EMA 1.0 GSPO: the bias kept exactly
ROUTER_V4_FROZEN, ROUTER_V4_RL V4 with the bias rate 0; for RL also no balance loss The rehearsal’s QAT and GSPO; replaced by the qb arrays in the main run

Megatron refuses any aux loss beside quantile balancing, so that array sets the aux-loss coefficient to 0. In the rehearsal, with every advantage 0, the V4 bias rule alone moved the GSPO policy to a KL of about 4.6e-4 after one update. The sequence-level balance loss alone moved it to a KL of 0.079 in 64 updates at 1e-5; with both off, the gradient was exactly 0. That is why GSPO’s router updates neither.

// § 06

Parallelism

Flag Value Meaning
--tensor-model-parallel-size 1 No layer is split across GPUs
--pipeline-model-parallel-size 1 No layer-wise pipeline
--context-parallel-size 1 No splitting of the sequence
--expert-model-parallel-size 8 Each GPU holds 8 of every layer’s 64 experts
--expert-tensor-parallel-size 1 No expert is split across GPUs
--use-distributed-optimizer on Optimizer state sharded across the 8 data-parallel ranks
--overlap-grad-reduce, --overlap-param-gather on Gradient reduction and parameter gathers overlap with compute

The attention and the router are replicated on every GPU; the experts are not. Communication overlap for the experts (--overlap-moe-expert-parallel-comm) needs selective recomputation, and that arm ran out of memory at its first step (78.8 of 79.2 GiB).

// § 07

Optimizer, schedule and precision (pretraining)

Flag Value Meaning
--micro-batch-size 8 Sequences per GPU per forward pass
--global-batch-size 512 Sequences per optimizer step: 512 × 4,096 = 2,097,152 tokens
--train-samples 634,880 1,240 steps, all 2.60B tokens
--optimizer, --adam-beta1, --adam-beta2 adam, 0.9, 0.95 Adam with decoupled weight decay
--weight-decay 0.1 Weight decay
--clip-grad 1 Gradient-norm clipping at 1.0
--lr, --min-lr 5e-4, 0 Peak and final learning rate
--lr-warmup-samples 2,000 About 4 steps of linear warm-up
--lr-decay-style, --lr-wsd-decay-style, --lr-wsd-decay-samples WSD, linear, 126,976 (634,880 / 5) Warm-up, stable, then linear decay over the last 20%
--bf16 on bf16 weights and activations; fp32 master weights in the optimizer
--cross-entropy-loss-fusion, --cross-entropy-fusion-impl on, native Fused cross-entropy over the 128,256-token vocabulary
--recompute-granularity, --recompute-method, --recompute-num-layers full, uniform, 1 Recompute every layer’s activations in the backward pass

The schedule, with \(n\) the number of training samples seen so far:

\[\eta(n) = \begin{cases} \eta_{\max}\, n / n_w & n < n_w \\ \eta_{\max} & n_w \le n < N - n_d \\ \eta_{\max}\,(N - n)/n_d & n \ge N - n_d \end{cases} \tag{5}\]

Here \(\eta_{\max} = 5 \times 10^{-4}\), \(n_w = 2{,}000\) warm-up samples, \(N = 634{,}880\) samples in all, and \(n_d = N/5 = 126{,}976\) decay samples, so the decay starts at step 992. The logged rates at steps 1–4 were 1.28e-4, 2.56e-4, 3.84e-4 and 5e-4, as the formula gives.

In words: a short linear ramp, a long flat stretch at the peak, then a straight line down to zero over the last fifth.

// § 08

Data, logging and checkpoints (pretraining)

Flag Value Meaning
--tokenizer-type, --tokenizer-model HuggingFaceTokenizer, Llama 3.2 The tokenizer files
--train-data-path, --valid-data-path FineWeb-Edu train and 1% hold-out Separate files, so no --split
--reset-attention-mask, --reset-position-ids on Document masking: no attention across documents, positions restart per document
--no-mmap-bin-files, --num-workers on, 6 The tested data-loader settings
--eval-interval, --eval-iters 100, 5 Validation every 100 steps on 5 batches
--save-tokens-per-expert-interval 100 Expert token counts for MaxVio and dead experts (10 in the study arms)
--save-interval, --exit-duration-in-mins 200, 435 Checkpoints every 200 steps; a time cap (373 in the main run)
--log-throughput, --log-timers-to-tensorboard on TFLOP/s and step time in the logged scalars
--log-memory-interval 10 The full memory line every 10 iterations
--log-num-zeros-in-grad, --log-params-norm, --log-max-attention-logit on Underflow, weight norms and attention-logit stability
--check-for-spiky-loss, --check-for-large-grads, --rerun-mode on, on, validate_results Re-run a flagged step to tell a hardware fault from a data cause
--manual-gc, --manual-gc-interval on, 5 Python garbage collection every 5 steps
--profile --use-pytorch-profiler steps 50–53, rank 0 One PyTorch Profiler trace in the main run
--seed 1234 Every run’s seed

--no-mmap-bin-files opens and closes the data file for every read. On network storage that stalled the GPUs, so the main run read its data from RAM. Every run that must start from a checkpoint also carries --exit-on-missing-checkpoint. Without it, a wrong path trains or evaluates random weights and exits 0.

// § 09

Supervised fine-tuning

Flag Value Meaning
--sft, --tokenizer-type, --sft-tokenizer-prompt-format on, SFTTokenizer, identity The prompt is the question as it is; the response is the <think>/<answer> answer
--no-create-attention-mask-in-dataloader on Required by Megatron’s SFT dataset, which packs examples itself
Training data packed JSONL lines About 24 examples per 4,096-token line; 2,210 lines
--micro-batch-size, --global-batch-size 8, 64 64 packed rows per step
--lr, --min-lr, --lr-decay-style 1e-5, 1e-6, cosine The SFT rate, cosine decay
--lr-warmup-samples 320 5 steps of warm-up
--train-samples 6,656 by default 3 epochs, 104 steps
--eval-interval, --eval-iters 35, 1 One batch covers all 46 validation lines
--finetune --load the pretraining checkpoint Weights only: iteration 0 and a fresh optimizer
--save-interval 35 A weights-only save at about each epoch

Main-run override. SFT_SAMPLES=13312: 6 epochs in one cosine schedule over 208 steps. The save with the lowest validation loss, step 175 (0.748), was kept.

// § 10

RL settings shared by GSPO and the evaluations

Flag Value Meaning
--seq-length (RL_SEQ) 1,536 Prompt + answer hard stop; Megatron’s RL engine has no per-answer limit
--chat-template identity The prompt is the SFT user turn, nothing added
--rl-default-temperature, --rl-default-top-k, --rl-default-top-p 1.0, -1, 1.0 Sampling at temperature 1 with no truncation
--rl-skip-bos-token on No BOS token: pretraining and SFT never had one
--no-rl-use-sequence-packing on One answer per row; the sequence ratio refuses packing
--inference-dynamic-batching-max-requests, --inference-dynamic-batching-max-tokens 128, 8,192 The inference engine’s admission limits
--inference-dynamic-batching-buffer-size-gb 20 KV-cache buffer
--moe-pad-experts-for-cuda-graph-inference on (MoE only) Fixed expert shapes at decode; required at expert parallelism 8
RL_CUDA_GRAPHS=1 off in the main run, on in the control run Adds --cuda-graph-impl local --inference-dynamic-batching-num-cuda-graphs 1 --te-rng-tracker
// § 11

GSPO

The loss is GSPO’s clipped objective with a K3 KL penalty to the SFT model. With the symbols defined in the metrics glossary:

\[\mathcal{L} = -\frac{1}{M}\sum_{i=1}^{M} \min\Big(s_i A_i,\ \operatorname{clip}\left(s_i,\, 1-\varepsilon_{\text{lo}},\, 1+\varepsilon_{\text{hi}}\right) A_i\Big) + \beta\, \overline{\mathrm{KL}} \tag{6}\]

Here \(M\) is the number of answers in the update, \(s_i\) is answer \(i\)’s length-normalised sequence ratio, \(A_i\) its group advantage, \(\varepsilon_{\text{lo}}\) and \(\varepsilon_{\text{hi}}\) the clip bounds, \(\beta\) the KL weight, and \(\overline{\mathrm{KL}}\) the mean per-token K3 estimate.

In words: raise answers that beat their group, lower the others, stop once a ratio passes the clip, and stay near the SFT model.

The optimizer’s batch is the step’s rollouts divided by the number of updates per step:

\[B = \frac{P \times G}{U} \tag{7}\]

Here \(B\) is --global-batch-size in answers, \(P\) the prompts per step, \(G\) the answers per prompt, and \(U\) the updates per step. Both the main run (\(16 \times 32 / 4\)) and the control run (\(16 \times 8 / 1\)) give \(B = 128\).

In words: each rollout batch is cut into \(U\) equal optimizer updates.

Setting (flag or variable) Default GSPO-A and GSPO-B (main run) Control run Meaning
GROUP_SIZE (--grpo-group-size) 8 32 8 Answers sampled per prompt
PROMPTS_PER_STEP 64 16 16 Prompts per rollout batch
UPDATES_PER_STEP 4 4 1 Optimizer updates per rollout batch
--grpo-importance-sampling-level sequence sequence sequence GSPO’s length-normalised sequence ratio
--grpo-clamp-eps-lower, --grpo-clamp-eps-upper 3e-4, 4e-4 2e-2, 2.7e-2 3e-4, 4e-4 Clip bounds on the sequence ratio
--grpo-kl-beta 0.01 0.01 0.01 Weight of the K3 KL to the SFT model
--grpo-entropy-term-weight 0 0 0 No entropy bonus
--grpo-filter-groups-by-correctness on on on All-right and all-wrong groups get advantage 0
GSPO_LR (--lr, constant) set by the calibration 1e-6 1e-6 Learning rate after a 5-update warm-up
--micro-batch-size 1 1 1 Megatron’s RL forward holds one row
--adam-beta2, --adam-eps, --clip-grad, --weight-decay 0.95, 1e-8, 1, 0.1 same same Adam and clipping as in pretraining
--calculate-per-token-loss, --accumulate-allreduce-grads-in-fp32 on on on Per-token loss; fp32 gradient reduction
RL_ENV_CONFIG curriculum_env.yaml curriculum_env_medium.yaml control_env.yaml Which problems, prompt and reward
RL_SEQ 1,536 1,536 3,584 Prompt + answer hard stop
Time cap or length 80 min 85 min 12,800 samples (100 updates) How the run ends
  • The medium tier, held fixed. curriculum_env_medium.yaml starts on the medium tier and never moves (steps_per_adjust 1,000,000).
  • Why the clip was raised. At expert parallelism 8 the first update’s ratio was not exactly 1 (median absolute log-ratio 4.9e-3), so noise alone clipped 4–20% of answers per update at the paper’s clip.
  • The reference model is the SFT checkpoint, loaded once with --pretrained-checkpoint and kept for the whole run.
  • GSPO-B used GSPO-A’s settings on the 418 learnable medium-tier problems.
  • Evaluation and saves run every 50 GSPO steps: 200 Megatron iterations in the main run, 50 in the control run.

The reward

For my model, the reward adds a format bonus and a soft length penalty to correctness:

\[r = \mathbf{1}[\text{correct}] + 0.1 \cdot \mathbf{1}[\text{format}] + p(n), \qquad p(n) = \begin{cases} 0 & n \le 768 \\ -(n - 768)/256 & 768 < n \le 1024 \\ -1 & n > 1024 \end{cases} \tag{8}\]

Here \(\mathbf{1}[\cdot]\) is 1 when its condition holds and 0 otherwise, and \(n\) is the answer’s length in tokens. The control run used PocketRL’s reward instead: 1 when the last \boxed{} answer matches under the Dr. GRPO grader, else 0, and 0 for an answer that has not ended within 3,000 tokens.

In words: one point for the right answer, a tenth of a point for the exact <think>/<answer> format, and a penalty that grows from 0 at 768 tokens to −1 at 1,024.

// § 12

Evaluation

Setting Value Meaning
Mode (eval.sh) --skip-train --perform-rl-step Megatron’s RL loop with no update and no save
Samples greedy plus 8 at temperature 1 Greedy accuracy, pass@1–8 and avg@8 from one pass
EVAL_PROMPTS 200 or 5,000 200 per set by a fixed hash order (all 180 of MultiArith), or every set in full
Time limit per evaluation 10 / 15 / 15 min Before SFT, after SFT, after GSPO: the subset first, then whole sets that fit
In-run evaluation every 50 GSPO steps Greedy on 200 per set, plus pass@1–8 on GSM8K’s first 50 problems
lm_eval.sh 12 batches of 512 × 4,096 Hold-out perplexity, about the whole 26M-token hold-out once
Control run EVAL_PROMPTS=500, then 675 All of MATH-500, then PocketRL’s five other sets

The 4-bit models are refused by eval.sh: ModelOpt’s attention wrapper cannot run in Megatron’s dynamic inference engine.

// § 13

Serving

Setting Value Meaning
Precision, decoding bf16 weights and KV cache, greedy (--top_k 1) Always the most likely token
SERVE_TOKENS, --termination-id -1 256, EOS off Every answer exactly 256 tokens, so runs compare
Prompts 512 GSM8K test questions A fixed prompt file
SERVE_MODE=concurrent 8 GPUs, expert parallel 8 All 512 requests submitted at once
SERVE_MODE=batch1 one GPU, expert parallel 1 16 requests one at a time, two passes (the first is warm-up)
Dynamic batching limits 512 requests, 16,384 tokens, 20 GB buffer The engine’s admission limits
CUDA graphs off Eager mode, as the RL rollouts ran
// § 14

Distillation and 4-bit (scripted; run in the rehearsal only)

Distillation (distill.sh) trains a 314M dense student (12 layers, hidden 1,024, FFN 4,096, 16 heads) from scratch for 400 steps of 256 × 4,096 tokens, about 420M tokens, at a peak rate of 1e-3. The teacher arm’s loss, in ModelOpt’s form:

\[\mathcal{L}_{\text{KD}} = (1 - \alpha)\,\mathrm{CE} + \alpha\,\mathrm{KL}\left(p_{\text{teacher}} \,\|\, p_{\text{student}}\right) \tag{9}\]

Here \(\alpha = 0.5\), both terms are taken on the output logits at temperature 1, and the teacher is the pretrained MoE. Adam ignores a constant factor on the loss except through clipping, so this arm halves the clip threshold to 0.5.

In words: half next-token cross-entropy and half the divergence from the teacher’s next-token distribution.

4-bit (qat_4bit.sh) quantizes only the routed experts’ weights to INT4, one scale per block of 128 weights, with activations in bf16 (W4A16). That is 2,048 quantizers: 16 layers × 64 experts × 2. Quantization-aware distillation then trains the 4-bit model against the bf16 GSPO model with KL only, for one epoch of the SFT lines (35 steps).

// § 15

The control run’s model family

MODEL_FAMILY=qwen2p5_math_1p5b swaps the model arrays and keeps the pipeline.

Setting Value
Shape 28 layers, hidden 1,536, FFN 8,960, 12 heads in 2 key-value groups of 128 dims
Positions and norms RoPE base 10,000; RMSNorm 1e-6; QKV bias on; tied embeddings
Parallelism One GPU; no expert, tensor or pipeline parallelism
MoE, router, recomputation none
Checkpoint format --ckpt-format torch, Megatron’s single-file format
Vocabulary 151,665 tokens, padded to 151,680
// § 16

Guards in check_flags.py

check_flags.py refuses, before launch:

  • a load without --exit-on-missing-checkpoint;
  • a GSPO launch with micro-batch above 1;
  • an RL restart with --finetune, which would start over;
  • an expert-parallel RL launch without the expert padding flag.