Prince Osei Aboagye
Guide

Distillation and 4-bit training

How to distil the pretrained mixture of experts into a 314M dense student, and quantize the experts to 4 bits with NVIDIA Model Optimizer, with the commands, the checks, and what the rehearsal and the laptop measured.

// § 01

What you will do

  • Distillation: train a 314M-parameter dense student from scratch twice, on the same data in the same order: once with the plain next-token loss, once also matching the frozen pretrained model’s predictions. Then compare their held-out losses.
  • 4-bit: quantize the routed experts’ weights to 4 bits (post-training quantization, PTQ). Then let the 4-bit model train against the bf16 model for a short while (quantization-aware distillation, QAD), and compare all three.
  • On the laptop: the Phase 0 distillation study on MiniMind’s models.

Read this first. On the 8×H100 run I cut both stages for time, and ran serving instead.

So the numbers below come from the rehearsal’s shrunk models on one H100, and from the laptop. They show that every step runs and records its metrics, not how well the methods work on our model.

The 4-bit models’ math accuracy was never measured, for a reason given below.

// § 02

Hardware and time

Level What runs Time
A laptop RTX 3060 (6 GB) MiniMind distillation: 3 arms × 3 seeds about 2 h with the MoE-versus-dense slices
One H100 the rehearsal’s distillation and 4-bit stages, shrunk models 44–244 s per run
8×H100 the planned full stages planned at about 30 min (distillation) and 25 min (4-bit); not run

Both stages use NVIDIA Model Optimizer (ModelOpt) 0.48.0, which the setup script installs.

// § 03

Distillation

The method

The student has 12 layers, hidden size 1,024, an FFN width of 4,096, and 16 attention heads of 64 dimensions in 4 key-value groups: 314M parameters, 131M of them the tied embedding. Both arms train 400 steps of 256 rows × 4,096 tokens, 420M tokens, from the same initial weights in the same data order. The teacher is the frozen pretrained model, not the RL model.

\[\mathcal{L}_{\text{kd}} = \tfrac{1}{2}\left( \mathrm{CE}(y, p_S) + \mathrm{KL}(p_T \,\|\, p_S) \right)\]

where \(y\) is the true next token, \(p_S\) the student’s next-token distribution, \(p_T\) the teacher’s, \(\mathrm{CE}\) the cross-entropy, and \(\mathrm{KL}(p_T \| p_S)\) how far the student’s distribution is from the teacher’s. Both use temperature 1.

In words: the student learns from the real next token and from the teacher’s whole distribution, half and half.

The control arm uses cross-entropy alone. Because ModelOpt halves the sum, the teacher arm’s gradient-clip threshold is halved too, so both arms clip alike.

Commands (8×H100)

export DISTILL_DIR=/workspace/distill TEACHER_CKPT=/workspace/ckpt/pretrain
DISTILL_ARM=ce run distill_ce bash $M/distill.sh
DISTILL_ARM=kd run distill_kd bash $M/distill.sh
for a in ce kd teacher; do DISTILL_STAGE=eval DISTILL_ARM=$a run distill_eval_$a bash $M/distill.sh; done
grep -h "validation loss" /workspace/runs/distill_eval_*.log

Look for: both arms finish all 400 steps. If the teacher arm stops at its 25-minute limit first, compare at its last step, using the control arm’s validation curve. Compare: each student’s “lm loss” (cross-entropy at temperature 1) and “logits distillation loss” (KL(teacher ‖ student)), and the teacher’s own cross-entropy.

Memory. The teacher arm holds full-vocabulary logits in fp32, so it runs at micro-batch 2:

\[M_{\text{logits}} = L \times V \times 4\ \text{bytes}\]

where \(L\) is the sequence length, \(V\) the vocabulary size, and 4 bytes one fp32 number.

In words: one row’s logits over the whole vocabulary, for every position.

\(4{,}096 \times 128{,}256 \times 4\) bytes is 2.1 GB per row and per tensor.

// § 04

4-bit: PTQ, then QAD

The method

  • PTQ uses Megatron’s own ModelOpt example, quantize.py. It stores the routed experts’ weights as 4-bit integers, with one scale per block of 128 weights (W4A16: 4-bit weights, 16-bit activations). Only the routed experts are quantized.

  • QAD trains the 4-bit model with a quantize-dequantize forward pass and a straight-through backward pass, against the frozen bf16 RL model as teacher. Its loss is the KL divergence alone, on the SFT lines.

    Cross-entropy on the SFT answers would pull the RL model back toward the SFT model.

  • The evaluation runs one validation pass of each model over the 46 SFT validation lines, with the bf16 model attached as teacher. It reports each model’s loss and its KL to bf16.

The router’s balancing stays frozen in both stages (ROUTER_MAIN_FROZEN).

Commands (8×H100)

export GSPO_CKPT=/workspace/ckpt/gspo QAT_DIR=/workspace/qat
QAT_STAGE=ptq run qat_ptq bash $M/qat_4bit.sh
QAT_STAGE=qad run qat_qad bash $M/qat_4bit.sh       # saves at its 15-min limit (EXIT_MINS) or after 35 steps
for m in bf16 ptq qad; do QAT_STAGE=eval QAT_MODEL=$m run qat_eval_$m bash $M/qat_4bit.sh; done
grep -h "validation loss" /workspace/runs/qat_eval_*.log
for m in ptq qad; do
  python -I code/scripts/qat_weights_report.py "$MEGATRON_PATH" /workspace/qat/$m --name $m \
      --json /workspace/runs/qat_weights_$m.json
done

A count to check in the PTQ log. Each expert has two linear layers to quantize, so:

\[n_{\text{quantizers}} = n_{\text{L}} \times E \times 2\]

where \(n_{\text{L}}\) is the number of layers and \(E\) the experts per layer.

In words: one weight quantizer for each of every expert’s two matrices, and nothing else.

The full model should print 2,048 enabled expert weight quantizers (\(16 \times 64 \times 2\)), as StaticBlockScaleQuantizer(4 bit ...) lines that the log prints twice. The shrunk rehearsal model printed 32 (\(2 \times 8 \times 2\)). In the QAD log, the KL (“logits distillation loss”) should fall, and its “lm loss” reads 0, since QAD trains on the KL alone. From the evaluations, bf16’s KL reads 0, and plain 4-bit’s KL should sit above QAD’s.

Why there is no 4-bit math accuracy

The 4-bit checkpoint loads into Megatron’s RL loop with our patch. But ModelOpt’s attention wrapper raises an error in flash_decode_and_prefill, the only attention path of the inference engine that loop uses, and the run then hangs.

So the 4-bit models are judged by held-out loss and KL to bf16, and eval.sh refuses EVAL_MODELOPT=1 with that reason.

// § 05

What the rehearsal measured (one H100, shrunk models)

Stage Result
Distillation, teacher arm student cross-entropy 7.808, KL to the teacher 0.215
Distillation, control arm student cross-entropy 7.828, KL to the teacher 0.293
Distillation, the teacher itself cross-entropy 7.480
4-bit, bf16 (the reference) KL 0, as expected
4-bit, PTQ KL 1.815e-3
4-bit, QAD with the expert-bias rule on KL 2.826e-3, worse than PTQ
4-bit, QAD with the expert bias frozen KL 1.800e-3

The teacher arm ended closer to the teacher than the control arm did. That is what the plumbing should show on any model; it is not evidence that distillation helps ours. The expert-bias rule moved QAD’s model on its own, which is why the bias is frozen in the 4-bit stages.

The 4-bit weights, read by qat_weights_report.py: the quantization error was 11.7%, and the 4-bit codes were symmetric. Rebuilding the weights from the codes ModelOpt’s own fake quantization implies reproduces the QAT forward exactly. Recomputing the codes from the weights instead agrees on 99.94% of them, and the layer outputs then differ by up to about 4%. So a deployment kernel should take its codes from the QAT model, not recompute them.

// § 06

What the laptop measured

From the repository’s code/ folder, bash scripts/moe_distill.sh runs the Phase 0 study: MoE against dense slices, then distillation into a dense student from scratch, in 3 arms of 3 seeds.

  • With MiniMind’s default settings, distillation made the from-scratch student worse. Held-out cross-entropy was 2.978 with either teacher, against 2.940 with none.

  • The no-teacher arm also had the full cross-entropy weight (1.0 against 0.5), the likely cause; that was not tested.

  • The distilled students matched the teacher at the training temperature, 1.5, in 6 of 6 seed-teacher pairs, but at temperature 1 in only 1 of 6.

On the H100 stages, halving both the loss and the clip threshold leaves Adam following cross-entropy plus the full KL: Adam ignores a constant loss factor except through clipping.

// § 07

Check that it worked

  • Both student arms run the same number of steps from the same initial weights.
  • The PTQ log shows exactly the expected number of enabled expert weight quantizers, and nothing else quantized.
  • The bf16 evaluation’s KL reads 0: the three models differ only in their weights.
  • The checkpoint loads into ModelOpt’s layout with no missing keys and no _extra_state error.
// § 08

Common problems

Symptom Cause Fix
PTQ stops building its calibration loader quantize.py builds one even for weight-only, and its default dataset is gated a local file of 64 training-curriculum questions
QAD stops in the learning-rate scheduler the warm-up was not shorter than the decay of a short run the warm-up is a quarter of the run at most
ModelOpt refuses the launch ModelOpt distillation refuses --manual-gc the logging array without it (LOG_NO_GC)
Megatron’s own distillation config fails two of its keys were removed in ModelOpt 0.48 our distill_alpha05.yaml
out of memory with a teacher attached full-vocabulary fp32 logits, 2.1 GB per row micro-batch 1–2
“Missing key … final_layernorm._extra_state” when an RL run loads a 4-bit checkpoint train_rl.py built the plain model config our patch detects ModelOpt first
an evaluation of a missing checkpoint reports loss 11.85 and exits 0 Megatron started from random weights --exit-on-missing-checkpoint
// § 09

Read more