Pretraining
How to run the router study and the main pretraining of the 6.86B-parameter mixture of experts on 8×H100 with Megatron-LM, size it before launch, watch it, and check the result against our numbers.
What you will do
- Check the model’s size and memory before you launch.
- Optionally, run the balancing study: a dense baseline and 40-step mixture-of-experts (MoE) arms that differ only in the router.
- Run the main pretraining: 1,240 steps of 512 sequences of 4,096 tokens, with DeepSeek V4’s router scores and quantile balancing.
- Watch loss, speed and expert balance while it runs, then check the end state and measure the base model.
Two terms first. In an MoE layer, a small network called the router sends each token to 8 of 64 expert networks. MaxVio measures how unevenly the experts are loaded: 0 is perfectly even, and 7 means every token went to the same 8 experts. The monitoring guide defines it exactly.
Hardware and time
The full model needs 8×H100 SXM. Our main run took 14,715 s, or 4.09 h, for all 1,240 steps.
Each 40-step study arm took 651 s (forced-even routing) to 949 s (a collapsed router); I sized the main run after the study.
On one H100 you can rehearse every command with a shrunk model (see Rehearse on one H100). It tests the plumbing, not the model.
The configuration
All pretraining flags live in code/scripts/megatron/common.sh, built from the Hugging Face MoE handbook’s tested launch script, with V4’s router flags on top.
| Group | Settings |
|---|---|
| Parallel layout | tensor 1, pipeline 1, context 1; expert parallelism 8; expert-tensor parallelism 1 |
| Shape | 16 layers; hidden size 2,048; 32 attention heads in 4 query groups of 64 channels; RMSNorm on Q and K; sequence 4,096; RoPE base 500,000 |
| Experts | 64 routed, top-8, expert FFN width 1,024; all-to-all token dispatcher; grouped GEMM; router in fp32; SwiGLU clamped at 10 |
| Optimizer | distributed Adam (0.9, 0.95); micro-batch 8, global batch 512; learning rate 5e-4 after 2,000 warm-up samples; warmup-stable-decay (WSD), decaying over the last 20%; gradient clip 1; weight decay 0.1; bf16 |
| Memory | full activation recomputation, one layer at a time |
| Logging | validation every 100 steps on 5 batches; expert counts every 100 steps; full checkpoints every 200 steps; PyTorch Profiler on steps 50–53 |
The router. MAIN_ROUTER=qb selects V4’s square-root-softplus scores with quantile balancing, no auxiliary loss,
and a routed scaling of 2.5.
The default in common.sh is still v4, the sign-rule router that collapsed.
On our node /workspace/env.sh exported MAIN_ROUTER=qb for every later stage. Export it yourself before every
launch, or add it to env.sh as the setup guide shows, because SFT, evaluation, serving and RL must
route the same way as the weights were trained.
Size it before you launch
Parameters
Most of the parameters sit in the experts. One SwiGLU expert has three matrices of \(d \times f\):
where \(P_{\text{shared}}\) is everything outside the experts (embedding, attention, routers, norms), \(n_{\text{L}}\) the number of layers, \(E\) the experts per layer, \(k\) the experts each token uses, \(d\) the hidden size and \(f\) the expert FFN width.
In words: the experts multiply the parameter count, but each token only pays for the \(k\) it uses.
With \(d = 2{,}048\) and \(f = 1{,}024\), one expert has 6.29M parameters, so the 1,024 experts hold 6.44B. A token uses \(16 \times 8\) of them, 0.81B. The shared part is about 0.42B, most of it the 128,256 × 2,048 embedding. That gives 6.86B in total and 1.22B active, the sizes we report.
Memory per GPU
With expert parallelism 8, each GPU holds the shared part and 8 of the 64 experts in every layer. The distributed optimizer splits the shared part’s optimizer state 8 ways. The experts’ state is not split further: each expert lives on one GPU only.
where \(P_{\text{local}}\) is the parameters on one GPU, \(P_{\text{opt}}\) the parameters whose optimizer state that GPU owns, 2 bytes the bf16 weight, 4 bytes the fp32 gradient, and 12 bytes the fp32 master weight and Adam’s two moments.
In words: before any activation, each GPU stores its weights, their gradients, and its share of the optimizer state.
Here \(P_{\text{local}} \approx 0.42\text{B} + 0.81\text{B} = 1.22\text{B}\) and $P_{\text{opt}} \approx 0.42\text{B}/8 + 0.81\text{B} \approx 0.86\text{B}$, so about 7.3 GB plus 10.3 GB. The metrics reference’s own estimate is about 18 GB per GPU. Activations take the rest: the MoE study arms peaked at 58.8 GiB allocated with full recomputation, inside an 80 GB H100. Keep peak allocated memory under 70 GB for headroom.
Tokens and time
where \(S\) is the number of steps, \(B\) the global batch in sequences, \(L\) the sequence length, \(t_{\text{step}}\) the time of one step, and \(N_{\text{save}}, t_{\text{save}}, N_{\text{eval}}, t_{\text{eval}}\) the number and time of checkpoint saves and validation passes.
In words: the token target fixes the steps, and the run takes the steps’ time plus the saves and the evaluations.
Ours: \(1{,}240 \times 512 \times 4{,}096 \approx 2.60 \times 10^9\) tokens, written in common.sh as 634,880 samples.
At the measured median of 10.93 s per step, the steps alone take 13,553 s; the run took 14,715 s.
The difference is the collapsed start (17.3 s per step for the first 50 steps), 7 saves and the evaluations.
Size from a measured step time, not from the first steps. The router study’s 40-step rate was the collapsed one, so I started all 1,240 steps and re-sized at step 200. There the remaining 964 steps at 11.05 s, five saves and the evaluations came to about 3.0 h, which fit the cap.
Steps
0. Before you start
Finish the setup, so env.sh, the run helper, M and RW exist. Then, in the shell you launch
from:
source /workspace/env.sh
unset NPROC EXTRA_ARGS
export MAIN_ROUTER=qb
1. The balancing study (optional)
This repeats our router decision. Each arm runs 40 steps on the same model, data order, optimizer and seed, and saves weights only.
run dense bash $M/dense_baseline.sh
run forced_even bash $M/moe_forced_even.sh
run aux_loss bash $M/moe_aux.sh # not "aux": our network volume refused that folder name
LAUNCH_PREFIX="env -u BASH_ENV nsys profile -t cuda,nvtx,osrt -s none --capture-range=cudaProfilerApi \
--capture-range-end=stop -o /workspace/runs/v4router/nsys --force-overwrite true" \
EXTRA_ARGS="--profile --profile-step-start 36 --profile-step-end 38 --profile-ranks 0" \
run v4router bash $M/moe_v4router.sh # the nsys capture; the arm's throughput: iterations 10-35
unset LAUNCH_PREFIX EXTRA_ARGS
run nvlink_off bash $M/moe_nvlink_off.sh
run overlap bash $M/moe_overlap_test.sh
for arm in forced_even aux_loss v4router nvlink_off overlap; do
python $GIST_DIR/router_watch.py counts /workspace/runs/$arm/save/tokens_per_expert --num-experts 64 \
--ranks 0 1 2 3 4 5 6 7 --expert-map $M/expert_map_ep8.json --pool-ranks > /workspace/runs/$arm/maxvio.jsonl
rm -rf /workspace/runs/$arm/save/iter_* # keep tokens_per_expert/, drop the weights-only checkpoint
done
The arm that won, V4’s scores with quantile balancing, is
code/scripts/megatron/moe_v4_qb.sh. Run it the same way, as
run v4_qb bash $M/moe_v4_qb.sh, and add v4_qb to the loop.
The study’s reports, from the run folders and the GPU log:
python -I code/scripts/run_report.py --run dense=/workspace/runs/dense --run forced_even=/workspace/runs/forced_even \
--run aux=/workspace/runs/aux_loss --run v4router=/workspace/runs/v4router --run nvlink_off=/workspace/runs/nvlink_off \
--run overlap=/workspace/runs/overlap --gpu-csv /workspace/gpu.csv --nccl /workspace/nccl_alltoall.txt \
--nccl /workspace/nccl_alltoall_p2p_off.txt --json /workspace/runs/study_report.json > /workspace/runs/study_report.md
nsys stats --report cuda_gpu_kern_sum --format csv --output /workspace/runs/v4router/nsys /workspace/runs/v4router/nsys.nsys-rep
python -I code/scripts/profile_report.py --compare forced_even=/workspace/runs/forced_even --compare aux=/workspace/runs/aux_loss \
--compare nvlink_off=/workspace/runs/nvlink_off --compare overlap=/workspace/runs/overlap \
--compare v4router_nsys=/workspace/runs/v4router/nsys_cuda_gpu_kern_sum.csv > /workspace/runs/study_profile.md
Our study (medians over iterations 11–40; the dense baseline over 11–120):
| Arm | Step time | TFLOP/s per GPU | Loss, last 10 steps | MaxVio at step 40 | Peak allocated |
|---|---|---|---|---|---|
| Dense baseline | 5.70 s | 373.1 | 6.900 | — | 50.9 GiB |
| MoE, forced-even routing (the speed ceiling) | 10.69 s | 199.0 | 7.756 | 0.011 | 58.8 GiB |
| MoE, auxiliary-loss router | 17.63 s | 120.7 | 7.771 | 7.000 | 58.8 GiB |
| MoE, V4 sign rule at 1e-3 | 17.80 s | 119.6 | 7.621 | 7.000 | 58.8 GiB |
| MoE, V4 sign rule at 1e-2 | 17.37 s | 122.5 | 7.664 | 7.000 | — |
| MoE, V4 scores + quantile balancing | 17.04 s | 124.9 | 7.667 | 5.186, falling | — |
| MoE, communication overlap | out of memory at step 1 |
Forced-even routing sends every expert the same share of tokens. Its loss means nothing, but its speed is the ceiling the real routers are measured against. The sign-rule and auxiliary-loss routers were at MaxVio 7.000, the maximum, in all 16 layers at step 10 and again at step 40. Only the sign rule at 1e-2 dipped once, to a layer mean of 6.870 at step 30.
The quantile arm started there too (6.999 at step 10), but fell to 5.186 by step 40, with 15 of 16 layers below 7.
I did not run the NVLink-off training arm in the end; nccl-tests measured the bandwidth without NVLink instead.
2. The main pretraining
CKPT_DIR=/workspace/ckpt/pretrain run pretrain bash $M/moe_pretrain.sh # [TRAIN_SAMPLES=...] if capped
EXIT_MINS sets the safety net: Megatron saves and exits after that many minutes. The default is 435; our run used 373,
my time cap plus 15 minutes.
If your projection at step 200 passes your cap, restart from the step-200 checkpoint with a lower TRAIN_SAMPLES and
--override-opt_param-scheduler. WSD is flat until its last 20%, so only the decay moves.
Check the first lines of the log. Ours showed moe_router_load_balancing_type = quantile_balancing,
moe_router_score_function = sqrtsoftplus, moe_router_topk_scaling_factor = 2.5, moe_aux_loss_coeff = 0.0 and
train_samples = 634880.
If the load-balancing type reads anything else, stop: MAIN_ROUTER was not exported.
3. Watch it
- Loss, validation loss, gradient norm and throughput in W&B or TensorBoard (
$RUN_DIR/tb), andgpu.csv. - MaxVio from the expert counts, every 100 steps. The command re-reads the whole file, so run it at any time:
RW="--num-experts 64 --ranks 0 1 2 3 4 5 6 7 --expert-map $M/expert_map_ep8.json --pool-ranks"
python $GIST_DIR/router_watch.py counts /workspace/ckpt/pretrain/tokens_per_expert $RW > /workspace/runs/pretrain/maxvio.jsonl
The rule for pretraining: investigate MaxVio above 2. The in-run check I set before the main run: MaxVio at most 2 by step 200, the second count.
The monitoring guide lists every other alarm.
4. After it ends
The checks fixed before the run, from its log:
python3 code/scripts/pretrain_checks.py /workspace/runs/pretrain.log
The run’s report and its profile of steps 50–52:
python -I code/scripts/run_report.py --run pretrain=/workspace/runs/pretrain --run dense=/workspace/runs/dense \
--gpu-csv /workspace/gpu.csv --sizes --json /workspace/runs/pretrain_report.json > /workspace/runs/pretrain_report.md
python -I code/scripts/profile_report.py /workspace/runs/pretrain --json /workspace/runs/pretrain/profile.json \
> /workspace/runs/pretrain/profile.md
Before you delete old checkpoints to free disk, keep what lives only in them: the router’s bias at every save, and the expert counts.
python -I code/scripts/checkpoint_router_bias.py "$MEGATRON_PATH" /workspace/ckpt/pretrain --all \
> /workspace/runs/pretrain/router_bias.jsonl
cp -r /workspace/ckpt/pretrain/tokens_per_expert /workspace/runs/pretrain/
Then keep the last checkpoint and delete the older ones. The checkpoints guide shows how to make a weights-only copy and check it.
The base model’s hold-out perplexity (the baseline for measuring forgetting later), and the rogue-expert check:
LM_EVAL_CKPT=/workspace/ckpt/pretrain run lm_pretrain bash $M/lm_eval.sh
ROGUE_CKPT=/workspace/ckpt/pretrain run rogue bash $M/rogue_experts.sh
python $GIST_DIR/expert_watch.py --unpadded --expert-tp-size 1 /workspace/runs/rogue/save/activations/iter_0000001/* \
> /workspace/runs/rogue/expert_norms.jsonl
rm -rf /workspace/runs/rogue/save
The activation dump is about 10 GB per GPU, so read it and delete it.
What to expect
| Step | 100 | 200 | 400 | 600 | 800 | 1,000 | 1,200 | 1,240 |
|---|---|---|---|---|---|---|---|---|
| Validation loss | 6.722 | 5.863 | 4.459 | 3.718 | 3.389 | 3.222 | 3.061 | 3.046 |
| MaxVio, mean over layers | 0.737 | 0.437 | 0.240 | 0.224 | 0.262 | 0.171 | — | — |
-
The end: validation loss 3.046, a perplexity of 21.0, with every step of the plan run.
-
Speed: a median of 10.93 s per step, 194.7 TFLOP/s per GPU, and 1.92×10⁵ tokens/s on the 8 GPUs. Steps after 100 ran at about 97% of the forced-even ceiling.
-
Stability: no NaN and no skipped step; the gradient norm fell from 4.76 to 0.10–0.26.
-
Checkpoints: 7 full saves of 89.46 GiB each, 44.6 s to 54.3 s per save.
-
GPUs: peak temperatures of 60–67 °C, one-second power peaks of 700.6–714.9 W at the 700 W cap, and no ECC errors.
-
After the run: hold-out loss 3.0430, a perplexity of 20.97. No rogue expert: the largest expert’s mean output norm was 3.47× its layer’s median, against a threshold of 10×.
A check on the speed: model FLOPs utilization (MFU).
where \(6\,P_{\text{active}}\) is the training FLOPs per token (forward and backward), \(B\,L\) the tokens per step, \(n_{\text{GPU}}\) the number of GPUs, \(F_{\text{peak}}\) one GPU’s peak bf16 FLOP/s, and \(t_{\text{step}}\) the step time.
In words: the share of the GPUs’ peak that went into the model’s own arithmetic.
$6 \times 1.22 \times 10^9 \times 512 \times 4{,}096 ,/, (8 \times 989 \times 10^{12} \times 10.93,\text{s}) \approx 17.7%$, as our report gives. Megatron’s own FLOP count gives 19.7%. The handbook measured 13–15% for its MoE on H100.
The base model answers nothing. Scored before SFT, it gets 0 on every test set and loops to the length limit. That is expected: pretraining teaches neither the answer format nor when to stop. The evaluation guide runs that measurement.
Check that it worked
-
pretrain_checks.pypasses all three checks: validation loss below its value 500 steps earlier, no NaN or unrecovered spike, and the run ended by its schedule. Ours read PASS, PASS, ended at step 1,240 of 1,240. -
MaxVio is at most 2 by step 200, and no expert gets under 1% of an even share.
-
The validation loss tracks the training loss.
-
The hold-out perplexity is close to the run’s last validation perplexity.
Rehearse on one H100
The full model does not fit one GPU, so the rehearsal shrinks it and runs every script for a few dozen steps.
SHRINK="--num-layers 2 --hidden-size 512 --ffn-hidden-size 2048 --num-attention-heads 8 --num-query-groups 2"
export NPROC=1 EXTRA_ARGS="$SHRINK --num-experts 8 --moe-ffn-hidden-size 256 --moe-router-topk 2 \
--expert-model-parallel-size 1 --micro-batch-size 2 --global-batch-size 16" # MoE runs
DENSE_EXTRA="$SHRINK --micro-batch-size 1 --global-batch-size 16" # dense runs
EXTRA_ARGS="$DENSE_EXTRA" run r_dense bash $M/dense_baseline.sh
EXTRA_ARGS comes last on the command line, and Megatron keeps a flag’s last value, so it overrides the full shape.
Expect a first loss near \(\ln 128{,}256 = 11.76\), what an untrained model gives. Our shrunk dense run went from 11.87
to 6.75 in 120 iterations.
Unset NPROC and EXTRA_ARGS before the real run.
Common problems
| Symptom | Cause | Fix |
|---|---|---|
| MaxVio 7.0 in every layer by step 10; ~55 of 64 experts starved | the sign-rule bias moves at most 1e-3 per step, while balance needed biases of ±4–6 logits | MAIN_ROUTER=qb: quantile balancing solves the bias each step |
| step time 3× too long, GPUs at 0% | data files on network storage | stage the data in /dev/shm (setup) |
ValueError: Path is not a file: .../latest_checkpointed_iteration.txt after a save |
Megatron’s W&B hook raced the tracker file across ranks | our patch waits for the file and never stops training |
the nsys run sits for minutes in make |
BASH_ENV makes every shell under nsys slow to start |
start the prefix with env -u BASH_ENV |
| the overlap arm runs out of memory at step 1 | overlap needs selective recomputation, about 19 GB more here | keep full recomputation without overlap |
a 40-step arm has no tokens_per_expert/ |
counts are written only on multiples of the interval (100) | the study arms count every 10 steps |
| no TFLOP/s or step time in W&B | Megatron sends them only with --log-timers-to-tensorboard |
the flag is in the shared logging array |
| a resumed run profiles the wrong steps | the profiler counts steps from each launch | set the profiler window per launch |
Two identical launches do not give identical losses: without deterministic mode, GPU reductions sum in varying order. Ours differed by up to about 0.3% by iteration 37. More problems, and where each was caught, are in the troubleshooting table.
Read more
- Part 6: pretraining, and the router that collapsed tells the story of the router decision.
- Part 2: the model and Part 4: the training system explain the architecture and the parallel layout.
- Code: code/scripts/megatron/common.sh, code/scripts/megatron/moe_pretrain.sh, code/scripts/megatron/moe_v4_qb.sh, code/scripts/pretrain_checks.py, code/scripts/run_report.py, code/scripts/checkpoint_router_bias.py.