Converting checkpoints
How we converted Qwen2.5-Math-1.5B from Hugging Face into Megatron's format for the control run, how we checked the conversion, and what exists, and does not, for converting our own model the other way.
What you will do
- Make a tokenizer copy that Megatron can use safely.
- Build a “skeleton”: a Megatron checkpoint of the target model’s shape, with random weights.
- Fill the skeleton with the Hugging Face weights, tensor by tensor, refusing anything that does not map.
- Check the converted model against Hugging Face’s: a log-probability gate, and a greedy-text report.
This is the path we built and used, for the control run’s dense Qwen2.5-Math-1.5B. The other direction, from our own mixture of experts to Hugging Face, is not built; the last section says what exists.
Hardware and time
The skeleton and the checks need one GPU; the conversion itself runs on the CPU in about a minute.
On our H100 the skeleton saved in 46 s, and the conversion took 23 s. The converter’s unit tests need no GPU.
Why a skeleton
Megatron-LM at d6316eb45 has no Hugging Face loader for Qwen; its checkpoint tools hold Mixtral’s only.
Building Megatron’s model outside its own entry points would mean its new run-config start-up, which I could not test on the laptop. So the work splits in two:
- one iteration of Megatron’s own
pretrain_gpt.pyat the Qwen shape saves a checkpoint with exactly the keys, shapes, dtypes and metadata thatgspo.shandeval.shload; - a plain-PyTorch script then replaces every tensor with the mapped Hugging Face weight.
I chose this over NVIDIA’s Megatron-Bridge, a separate install that ships its own Megatron and might clash with our pinned commit.
Steps
1. The tokenizer copy
hf download Qwen/Qwen2.5-Math-1.5B --revision 4a83ca6e4526a4f2da3aa259ec36c259f66b2ab2 --local-dir "$QWEN_HF_DIR"
python -I code/scripts/make_qwen_tokenizer.py "$QWEN_HF_DIR" "$TOKENIZER_DIR"
code/scripts/make_qwen_tokenizer.py changes two things and nothing else:
- The pad token. Qwen’s pad token is its end token,
<|endoftext|>(151643). Megatron’s SFT dataset masks every label equal to the pad, so the end-of-text label would never be learned. Our patch refuses that, and the copy uses<|vision_pad|>(151654), a special token that text never contains. - No
generation_config.json. Megatron’s chat endpoint fills any sampling setting a request leaves out from that file, and Qwen’s saysdo_sample: false. Megatron read that as greedy decoding.
Every text still tokenizes to the same ids as with the original.
2. The skeleton
RUN_DIR=/workspace/runs/qwen_skeleton bash code/scripts/megatron/qwen_skeleton.sh > /workspace/runs/qwen_skeleton.log 2>&1
It runs one step on mock data at learning rate 0, and saves the weights in Megatron’s single-file torch format,
without optimizer state.
The step itself does not matter: every weight is replaced next.
3. The conversion
PYTHONPATH="$MEGATRON_PATH" python code/scripts/megatron/convert_qwen2_hf.py /workspace/runs/qwen_skeleton/skeleton \
"$QWEN_HF_DIR" /workspace/qwen/megatron
The mapping, from Megatron’s Transformer Engine names to Hugging Face’s Qwen2ForCausalLM:
| Megatron | Hugging Face |
|---|---|
embedding.word_embeddings.weight |
model.embed_tokens.weight, the first rows |
decoder.layers.i.self_attention.linear_qkv.layer_norm_weight |
model.layers.i.input_layernorm.weight |
decoder.layers.i.self_attention.linear_qkv.weight and .bias |
the q, k and v projections, fused per key-value group |
decoder.layers.i.self_attention.linear_proj.weight |
self_attn.o_proj.weight |
decoder.layers.i.mlp.linear_fc1.layer_norm_weight |
post_attention_layernorm.weight |
decoder.layers.i.mlp.linear_fc1.weight |
[mlp.gate_proj.weight; mlp.up_proj.weight] |
decoder.layers.i.mlp.linear_fc2.weight |
mlp.down_proj.weight |
decoder.final_layernorm.weight |
model.norm.weight |
The fused QKV layout is the one place a conversion goes quietly wrong. Megatron stores each key-value group’s query heads, then its key head, then its value head, as “q1 q2 k1 v1 | q3 q4 k2 v2”.
where \(R_{\text{qkv}}\) is the rows of the fused weight, \(n_{\text{KV}}\) the key-value heads, \(n_{\text{heads}}\) the query heads, and \(d_{\text{head}}\) the head dimension.
In words: each key-value group carries its share of query heads plus one key head and one value head.
For Qwen2.5-Math-1.5B, with 12 query heads in 2 groups of 128 dimensions: \(2 \times (6 + 2) \times 128 = 2{,}048\) rows.
The other rules:
- SwiGLU: Megatron’s
linear_fc1output is split in two; the first half (the gate) goes through the activation, the second (up) multiplies it. So the gate’s rows come first. - Tied embeddings: the output layer is the embedding. If the file has
lm_head.weight, it must equal the embedding. - The vocabulary: Megatron pads the tokenizer’s vocabulary up to a multiple of 128.
where \(V_{\text{tokenizer}}\) is the tokenizer’s vocabulary and \(V_{\text{Megatron}}\) the embedding rows Megatron builds.
In words: round the vocabulary up to the next multiple of 128.
Qwen’s tokenizer has 151,665 tokens, so Megatron builds 151,680 rows. The model’s embedding has 151,936 rows, and the converter keeps the first 151,680.
What it refuses: a key missing on either side, or a shape that differs. It also refuses model dimensions that differ from the skeleton’s own arguments, untied embeddings, and an output folder that already exists.
Loading the skeleton unpickles Megatron’s arguments, so Megatron must be on PYTHONPATH, and the file must be one you
made.
It writes the converted checkpoint and conversion.json: the model’s config, the SHA-256 of each weights file, and
the counts.
Ours: 198 tensors replaced, which is 2 plus 7 per layer over 28 layers. It kept 142 Transformer Engine
_extra_state entries, and the embedding’s first 151,680 of 151,936 rows.
The strict key and shape check passed on the first try.
4. Check the converted model
First evaluate the converted base model, as stage C6 of the control run does. That gives a score to compare with the published one, and the sampled tokens with Megatron’s log-probabilities. Then the gate:
python code/scripts/qwen_logprob_parity.py "$QWEN_HF_DIR" "$TOKENIZER_DIR" /workspace/runs/control_base/rollouts.jsonl \
/workspace/runs/control_base/rollout_logprobs.jsonl --n 64 --out /workspace/runs/control_base/logprob_parity.json
It scores the same tokens in the same context with Hugging Face (teacher forcing) and compares:
where \(T\) is the number of tokens compared, \(x_t\) a sampled token, \(x_{<t}\) everything before it, and \(p\) each implementation’s probability.
In words: the average disagreement, in nats, between the two implementations about the same token in the same context.
The thresholds were fixed before the first run. PASS needs \(\overline{|\Delta|}\) of at most 0.05 nats per token, and at most 1% of tokens differing by more than 0.5. Rounding in bf16 gives differences of hundredths of a nat. A wrong mapping of heads, of gate and up, or of the vocabulary gives whole nats.
The greedy-text comparison is a report, not a gate. Its usage, with our files:
python code/scripts/qwen_greedy_parity.py "$QWEN_HF_DIR" "$TOKENIZER_DIR" /workspace/runs/control_base/eval_results.jsonl \
"$CURRICULUM_DIR" --n 20
A base model’s greedy answers often start at a near-tie, which bf16 rounding flips, so two correct implementations can part early.
What to expect
- The base reading: MATH-500 avg@8 21.8% through our converted model, against PocketRL’s published 21.9% for the same base model.
- The log-prob gate: PASS. It compared 63,278 tokens of 64 answers. The mean \(|\Delta|\) was 0.034 nats per token, and 0.92% of tokens were over 0.5. The p99 was 0.42, and the Pearson correlation 0.96.
- The greedy-text report: 11 of 20 MATH-500 openings agreed on their first 200 characters, where the check as first written wanted 16. Nine of the pairs agreed for 300–1,363 characters, odd repetitions included, which no wrong mapping would produce.
The same weights evaluated twice gave identical greedy texts for only 198 of 500 problems, so the greedy-text failure fits ordinary bf16 noise. Nine answers were skipped because their re-tokenized text did not line up with the engine’s token ids. The check should compare the engine’s own ids; that improvement is open.
Check that it worked
conversion.jsonshows every tensor replaced, and the embedding rows kept.- The log-prob gate passes before any training.
- The converted base model’s score lands near the published base score.
- The evaluation log’s
Sampling defaultsline showstop_k=0: the tokenizer copy leftgeneration_config.jsonout.
The other direction: Megatron to Hugging Face
Not built for our model. At d6316eb45, Megatron’s checkpoint tools convert only two models. They hold a Hugging Face → Megatron loader for Mixtral, and a Megatron → Hugging Face saver for LLaVA. I decided against a Hugging Face conversion for the main run. What I found for later:
- NVIDIA’s Megatron-Bridge converts both ways for standard architectures, DeepSeek V3 and V4 and Qwen3-MoE among them.
- For a custom model, its
AutoBridge.from_auto_configbuilds a Hugging Face config from therun_config.yamlinside a Megatron checkpoint, and ours has one. A custom architecture still needs aMegatronModelBridgesubclass for the weight mapping. - Our model is, in effect, Qwen3-MoE with our router. Its attention is grouped-query attention with QK normalization and RoPE base 500,000. Its router picks the top 8 on the logits plus a quantile bias, with square-root-softplus weights scaled by 2.5, and its SwiGLU is clamped. Neither vLLM nor SGLang loads it as is.
Inside Megatron, one conversion does exist and we used it: the weights-only copy, which turns a full checkpoint into the bf16 weights alone. The checkpoints guide shows it.
Common problems
| Symptom | Cause | Fix |
|---|---|---|
| Qwen’s tokenizer is refused at launch | its pad token equals its end token | the tokenizer copy’s pad, <|vision_pad|> |
| every “sample” in a group is the same text | generation_config.json in the folder Megatron loads |
the copy never includes that file |
| the skeleton stops after 44 s | Megatron divides by --eval-interval even with no evaluation |
--eval-interval 1000 in qwen_skeleton.sh |
| the greedy-text check fails | near-tie openings flip under bf16 | gate on log-probabilities instead |
| the converter stops on a key or shape | the skeleton and the model disagree, or the embeddings are untied | rebuild the skeleton from the model’s config.json values |
The tests
The conversion’s tests run on a laptop without a GPU. code/tests/test_convert_qwen2_hf.py has 8. Two of them check that Megatron reads the fused QKV as Hugging Face’s heads, and that its SwiGLU on the stacked weights is Hugging Face’s MLP.
The log-prob check has 5 tests, the tokenizer copy 6, and the greedy-text report 4.
Read more
- Part 14: the control run explains why the conversion had to be exact.
- Code: code/scripts/megatron/convert_qwen2_hf.py, code/scripts/megatron/qwen_skeleton.sh, code/scripts/make_qwen_tokenizer.py, code/scripts/qwen_logprob_parity.py, code/scripts/qwen_greedy_parity.py.