Skip to content

Commit fbb7570

Browse files
authored
fix(conversion): improve Megatron-LM checkpoint compatibility (#5354)
Signed-off-by: Chen Cui <chcui@nvidia.com>
1 parent 8e2e25e commit fbb7570

13 files changed

Lines changed: 463 additions & 44 deletions

File tree

‎docs/bridge-guide.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,7 @@ Or with a helper script:
292292

293293
Megatron-LM training checkpoints do not normally contain the Bridge
294294
`run_config.yaml` required by this export command. See
295-
[Export Megatron-LM checkpoints without a Bridge run config](megatron-lm-to-megatron-bridge.md#export-megatron-lm-checkpoints-without-a-bridge-run-config)
295+
[Best-effort export of an existing Megatron-LM checkpoint](megatron-lm-to-megatron-bridge.md#best-effort-export-of-an-existing-megatron-lm-checkpoint)
296296
for the configuration generation and validation workflow.
297297

298298
### Create Megatron models and run locally

‎docs/fern/versions/nightly/pages/bridge-guide.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -260,7 +260,7 @@ Or with a helper script:
260260

261261
Megatron-LM training checkpoints do not normally contain the Bridge
262262
`run_config.yaml` required by this export command. See
263-
[Export Megatron-LM checkpoints without a Bridge run config](megatron-lm-to-megatron-bridge.md#export-megatron-lm-checkpoints-without-a-bridge-run-config)
263+
[Best-effort export of an existing Megatron-LM checkpoint](megatron-lm-to-megatron-bridge.md#best-effort-export-of-an-existing-megatron-lm-checkpoint)
264264
for the configuration generation and validation workflow.
265265

266266
### Create Megatron models and run locally

‎docs/fern/versions/nightly/pages/megatron-lm-to-megatron-bridge.mdx‎

Lines changed: 42 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ Megatron Bridge is Python-first: configure models, data, and training via typed
66

77
`scripts/translate_mlm_to_bridge.py` translates bidirectionally between Megatron-LM `pretrain_gpt.py` CLI arguments and Megatron Bridge `run_recipe.py` Hydra overrides. It is useful for running loss-correlation experiments between the two frameworks and for migrating existing MLM configs.
88

9+
This script provides best-effort configuration translation only. It does not establish semantic equivalence, convert checkpoint weights, or emit the serialized `run_config.yaml` stored in a Bridge-native checkpoint. Do not rename its output to `run_config.yaml` or place it in an MLM checkpoint: the generated overrides or Python recipe are starting points for a new Bridge run, not checkpoint metadata. Review every skipped and unknown argument before using the output.
10+
911
### MLM → Bridge (default direction)
1012

1113
```bash
@@ -87,9 +89,20 @@ uv run python scripts/translate_mlm_to_bridge.py --reverse \
8789
| `--rotary-base N` | `model.rotary_base=N` | |
8890
| `--num-experts N` | `model.num_moe_experts=N` | |
8991
| `--moe-router-topk K` | `model.moe_router_topk=K` | |
92+
| `--hybrid-layer-pattern P` | `model.hybrid_layer_pattern=P` | Selects `HybridModelProvider` in generated recipes |
93+
| `--hybrid-override-pattern P` | `model.hybrid_layer_pattern=P` | Migrates the deprecated MLM field |
94+
| `--mamba-state-dim N` | `model.mamba_state_dim=N` | |
95+
| `--mamba-head-dim N` | `model.mamba_head_dim=N` | |
96+
| `--mamba-num-groups N` | `model.mamba_num_groups=N` | |
97+
| `--mamba-num-heads N` | `model.mamba_num_heads=N` | |
98+
| `--mtp-hybrid-override-pattern P` | `model.mtp_hybrid_override_pattern=P` | Separate MLM MTP pattern |
99+
| `--mtp-use-repeated-layer` | `model.mtp_use_repeated_layer=true` | One physical MTP layer reused across prediction depths |
100+
| `--sft-tokenizer-prompt-format P` | `tokenizer.tokenizer_prompt_format=P` | Bridge exposes the MCore SFT compatibility alias at load time |
90101
| `--mock-data` | `dataset.mock=true` | Use synthetic data (no files needed) |
91102

92-
Flags not present in Bridge (e.g., `--use-mcore-models`, `--use-flash-attn`) are silently skipped with a comment. `--mock-data` translates to `dataset.mock=true`. Unknown flags are listed in a separate section so you can handle them manually.
103+
Flags not present in Bridge (e.g., `--use-mcore-models`, `--use-flash-attn`) are omitted and listed in a comment. `--mock-data` translates to `dataset.mock=true`. Unknown flags are listed separately so you can handle them manually.
104+
105+
Megatron-LM `--spec` values are intentionally not copied into generated configuration as arbitrary import targets. A recognized Mamba or Hybrid spec helps the translator identify the provider family, but a standalone Hybrid recipe still requires an explicit layer pattern. Review and select any Bridge stack specification in trusted Python code.
93106

94107
> **Activation function CLI overrides**: `model.activation_func` can now be set via Hydra CLI string override (e.g. `model.activation_func=silu`, `model.activation_func=gelu`). The string is resolved to the callable in `TransformerConfig.finalize()`. This makes `--swiglu` → `model.gated_linear_unit=true model.activation_func=silu` round-trippable from the CLI.
95108
@@ -115,27 +128,37 @@ Notes:
115128
- Config groups are nested: `rng`, `train`, `model`, `optimizer`, `ddp`, `scheduler`, `dataset`, `logger`, `tokenizer`, `checkpoint`, `dist`, `profiling`, `peft`, `comm_overlap`, `mixed_precision`, `inprocess_restart`.
116129
- After overrides are applied, runtime validation computes any dependent fields (e.g., data-parallel size, scheduler steps) and checks consistency.
117130

118-
## Export Megatron-LM checkpoints without a Bridge run config
131+
## Best-effort export of an existing Megatron-LM checkpoint
119132

120133
Megatron-LM checkpoints save their training arguments in `common.pt`; they do
121134
not normally contain the `run_config.yaml` written by Megatron Bridge. The
122135
Bridge checkpoint export launcher currently needs that file to reconstruct a
123136
model provider before loading the distributed weights.
124137

138+
Training with Megatron-LM and later relying on Megatron Bridge for Hugging Face
139+
export is **not recommended**. This procedure is a best-effort recovery path for
140+
an existing checkpoint, not a supported general MLM-to-Hugging-Face conversion
141+
workflow. Use it only with a checkpoint and immutable local Hugging Face
142+
snapshot that you trust. Loading MLM common checkpoint state may deserialize
143+
Python objects; an allowlisted package prefix or audited Hugging Face code does
144+
not make an untrusted checkpoint safe.
145+
125146
Use this procedure only when all of the following are true:
126147

127148
- the iteration directory contains `common.pt` and the distributed checkpoint
128149
metadata and shards;
129150
- the checkpoint architecture has an existing Megatron Bridge implementation;
130-
- `--hf-model` identifies the exact Hugging Face architecture used to create
131-
the checkpoint; fine-tuned weights may differ, but model dimensions, layer
132-
patterns, vocabulary configuration, and MTP structure must match; and
151+
- `--hf-model` identifies an immutable local snapshot of the exact Hugging Face
152+
architecture used to create the checkpoint; fine-tuned weights may differ,
153+
but all architecture- and behavior-bearing configuration must match; and
133154
- Megatron Bridge, Megatron Core, and Transformer Engine are compatible with
134155
the versions that wrote the checkpoint.
135156

136-
This procedure generates only `run_config.yaml`. It does not migrate legacy
137-
checkpoint keys or metadata, and it does not translate a custom Megatron-LM
138-
model spec into a Bridge provider.
157+
This procedure generates only `run_config.yaml` in the checkpoint directory.
158+
It does not migrate legacy checkpoint keys or metadata, translate a custom
159+
Megatron-LM model spec into a Bridge provider, or prove that the checkpoint and
160+
reference are semantically equivalent. Work on a copy if the checkpoint
161+
directory must remain pristine.
139162

140163
### Generate `run_config.yaml`
141164

@@ -145,7 +168,7 @@ this generation step does not download its weights.
145168

146169
```bash
147170
MB_CKPT=/workspace/checkpoints/model/iter_0001000
148-
MB_HF_REF=organization/model-reference
171+
MB_HF_REF=/workspace/hf-snapshots/model-at-immutable-revision
149172

150173
uv run python - "$MB_CKPT" "$MB_HF_REF" --trust-remote-code <<'PY'
151174
from dataclasses import fields
@@ -269,8 +292,12 @@ for name in (
269292
PY
270293
```
271294

272-
Compare the reported architecture, hybrid/MTP layout, and precision fields
273-
with the original training configuration. Do not continue if they differ.
295+
The printed fields are only a starting diagnostic. Compare every architecture-
296+
and behavior-bearing field with the original training configuration, including
297+
position and RoPE behavior, vocabulary and tokenizer IDs, tied weights, expert
298+
and router behavior, attention, Mamba, and physical/repeated-MTP layout.
299+
Parallel degrees may differ only for a valid resharding topology. Treat any
300+
unclassified difference as an incompatibility and do not continue.
274301

275302
Run the normal export after validation. Adapt the parallel topology to the
276303
checkpoint and available GPUs:
@@ -290,6 +317,10 @@ checkpoint and available GPUs:
290317

291318
Keep strict conversion enabled for the first export. Do not use
292319
`--not-strict` to bypass missing MTP, expert, or quantized parameters.
320+
Verify the emitted HF config, shard index, expected tensor keys, strict
321+
`from_pretrained()` loading, and at least one forward pass. These are structural
322+
and runtime checks, not numerical-parity evidence. Compare source and exported
323+
logits when a source-model baseline is available.
293324

294325
For MXFP8 parameter checkpoints, use hardware supported by the saved recipe
295326
(normally Blackwell). The default BF16 export dequantizes Transformer Engine

‎docs/megatron-lm-to-megatron-bridge.md‎

Lines changed: 42 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ Megatron Bridge is Python-first: configure models, data, and training via typed
66

77
`scripts/translate_mlm_to_bridge.py` translates bidirectionally between Megatron-LM `pretrain_gpt.py` CLI arguments and Megatron Bridge `run_recipe.py` Hydra overrides. It is useful for running loss-correlation experiments between the two frameworks and for migrating existing MLM configs.
88

9+
This script provides best-effort configuration translation only. It does not establish semantic equivalence, convert checkpoint weights, or emit the serialized `run_config.yaml` stored in a Bridge-native checkpoint. Do not rename its output to `run_config.yaml` or place it in an MLM checkpoint: the generated overrides or Python recipe are starting points for a new Bridge run, not checkpoint metadata. Review every skipped and unknown argument before using the output.
10+
911
### MLM → Bridge (default direction)
1012

1113
```bash
@@ -87,9 +89,20 @@ uv run python scripts/translate_mlm_to_bridge.py --reverse \
8789
| `--rotary-base N` | `model.rotary_base=N` | |
8890
| `--num-experts N` | `model.num_moe_experts=N` | |
8991
| `--moe-router-topk K` | `model.moe_router_topk=K` | |
92+
| `--hybrid-layer-pattern P` | `model.hybrid_layer_pattern=P` | Selects `HybridModelProvider` in generated recipes |
93+
| `--hybrid-override-pattern P` | `model.hybrid_layer_pattern=P` | Migrates the deprecated MLM field |
94+
| `--mamba-state-dim N` | `model.mamba_state_dim=N` | |
95+
| `--mamba-head-dim N` | `model.mamba_head_dim=N` | |
96+
| `--mamba-num-groups N` | `model.mamba_num_groups=N` | |
97+
| `--mamba-num-heads N` | `model.mamba_num_heads=N` | |
98+
| `--mtp-hybrid-override-pattern P` | `model.mtp_hybrid_override_pattern=P` | Separate MLM MTP pattern |
99+
| `--mtp-use-repeated-layer` | `model.mtp_use_repeated_layer=true` | One physical MTP layer reused across prediction depths |
100+
| `--sft-tokenizer-prompt-format P` | `tokenizer.tokenizer_prompt_format=P` | Bridge exposes the MCore SFT compatibility alias at load time |
90101
| `--mock-data` | `dataset.mock=true` | Use synthetic data (no files needed) |
91102

92-
Flags not present in Bridge (e.g., `--use-mcore-models`, `--use-flash-attn`) are silently skipped with a comment. `--mock-data` translates to `dataset.mock=true`. Unknown flags are listed in a separate section so you can handle them manually.
103+
Flags not present in Bridge (e.g., `--use-mcore-models`, `--use-flash-attn`) are omitted and listed in a comment. `--mock-data` translates to `dataset.mock=true`. Unknown flags are listed separately so you can handle them manually.
104+
105+
Megatron-LM `--spec` values are intentionally not copied into generated configuration as arbitrary import targets. A recognized Mamba or Hybrid spec helps the translator identify the provider family, but a standalone Hybrid recipe still requires an explicit layer pattern. Review and select any Bridge stack specification in trusted Python code.
93106

94107
> **Activation function CLI overrides**: `model.activation_func` can now be set via Hydra CLI string override (e.g. `model.activation_func=silu`, `model.activation_func=gelu`). The string is resolved to the callable in `TransformerConfig.finalize()`. This makes `--swiglu` → `model.gated_linear_unit=true model.activation_func=silu` round-trippable from the CLI.
95108
@@ -115,27 +128,37 @@ Notes:
115128
- Config groups are nested: `rng`, `train`, `model`, `optimizer`, `ddp`, `scheduler`, `dataset`, `logger`, `tokenizer`, `checkpoint`, `dist`, `profiling`, `peft`, `comm_overlap`, `mixed_precision`, `inprocess_restart`.
116129
- After overrides are applied, runtime validation computes any dependent fields (e.g., data-parallel size, scheduler steps) and checks consistency.
117130

118-
## Export Megatron-LM checkpoints without a Bridge run config
131+
## Best-effort export of an existing Megatron-LM checkpoint
119132

120133
Megatron-LM checkpoints save their training arguments in `common.pt`; they do
121134
not normally contain the `run_config.yaml` written by Megatron Bridge. The
122135
Bridge checkpoint export launcher currently needs that file to reconstruct a
123136
model provider before loading the distributed weights.
124137

138+
Training with Megatron-LM and later relying on Megatron Bridge for Hugging Face
139+
export is **not recommended**. This procedure is a best-effort recovery path for
140+
an existing checkpoint, not a supported general MLM-to-Hugging-Face conversion
141+
workflow. Use it only with a checkpoint and immutable local Hugging Face
142+
snapshot that you trust. Loading MLM common checkpoint state may deserialize
143+
Python objects; an allowlisted package prefix or audited Hugging Face code does
144+
not make an untrusted checkpoint safe.
145+
125146
Use this procedure only when all of the following are true:
126147

127148
- the iteration directory contains `common.pt` and the distributed checkpoint
128149
metadata and shards;
129150
- the checkpoint architecture has an existing Megatron Bridge implementation;
130-
- `--hf-model` identifies the exact Hugging Face architecture used to create
131-
the checkpoint; fine-tuned weights may differ, but model dimensions, layer
132-
patterns, vocabulary configuration, and MTP structure must match; and
151+
- `--hf-model` identifies an immutable local snapshot of the exact Hugging Face
152+
architecture used to create the checkpoint; fine-tuned weights may differ,
153+
but all architecture- and behavior-bearing configuration must match; and
133154
- Megatron Bridge, Megatron Core, and Transformer Engine are compatible with
134155
the versions that wrote the checkpoint.
135156

136-
This procedure generates only `run_config.yaml`. It does not migrate legacy
137-
checkpoint keys or metadata, and it does not translate a custom Megatron-LM
138-
model spec into a Bridge provider.
157+
This procedure generates only `run_config.yaml` in the checkpoint directory.
158+
It does not migrate legacy checkpoint keys or metadata, translate a custom
159+
Megatron-LM model spec into a Bridge provider, or prove that the checkpoint and
160+
reference are semantically equivalent. Work on a copy if the checkpoint
161+
directory must remain pristine.
139162

140163
### Generate `run_config.yaml`
141164

@@ -145,7 +168,7 @@ this generation step does not download its weights.
145168

146169
```bash
147170
MB_CKPT=/workspace/checkpoints/model/iter_0001000
148-
MB_HF_REF=organization/model-reference
171+
MB_HF_REF=/workspace/hf-snapshots/model-at-immutable-revision
149172

150173
uv run python - "$MB_CKPT" "$MB_HF_REF" --trust-remote-code <<'PY'
151174
from dataclasses import fields
@@ -269,8 +292,12 @@ for name in (
269292
PY
270293
```
271294

272-
Compare the reported architecture, hybrid/MTP layout, and precision fields
273-
with the original training configuration. Do not continue if they differ.
295+
The printed fields are only a starting diagnostic. Compare every architecture-
296+
and behavior-bearing field with the original training configuration, including
297+
position and RoPE behavior, vocabulary and tokenizer IDs, tied weights, expert
298+
and router behavior, attention, Mamba, and physical/repeated-MTP layout.
299+
Parallel degrees may differ only for a valid resharding topology. Treat any
300+
unclassified difference as an incompatibility and do not continue.
274301

275302
Run the normal export after validation. Adapt the parallel topology to the
276303
checkpoint and available GPUs:
@@ -290,6 +317,10 @@ checkpoint and available GPUs:
290317

291318
Keep strict conversion enabled for the first export. Do not use
292319
`--not-strict` to bypass missing MTP, expert, or quantized parameters.
320+
Verify the emitted HF config, shard index, expected tensor keys, strict
321+
`from_pretrained()` loading, and at least one forward pass. These are structural
322+
and runtime checks, not numerical-parity evidence. Compare source and exported
323+
logits when a source-model baseline is available.
293324

294325
For MXFP8 parameter checkpoints, use hardware supported by the saved recipe
295326
(normally Blackwell). The default BF16 export dequantizes Transformer Engine
@@ -300,7 +331,6 @@ native FP8 Hugging Face export currently supports blockwise FP8 parameters.
300331

301332
Below is a concise mapping from common `megatron-lm/megatron/training/arguments.py` flags to the new dataclass fields. If a field is not listed here (e.g., highly model-specific knobs), it typically lives under `model.*`, `optimizer.*`, `dataset.*`, or `tokenizer.*` with similar names.
302333

303-
304334
### Model topology and parallelisms
305335

306336
| megatron-lm arguments | Megatron Bridge config | Description |

‎scripts/conversion/README.md‎

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,21 @@ Run `./scripts/conversion/convert.sh import --help`,
1313
`./scripts/conversion/convert.sh export --help`, or
1414
`./scripts/conversion/convert.sh roundtrip --help` for the complete CLI.
1515

16-
Megatron-LM training checkpoints normally store their arguments in `common.pt`
17-
instead of the Megatron Bridge `run_config.yaml` required by the export path.
18-
Before exporting such a checkpoint, follow
19-
[Export Megatron-LM checkpoints without a Bridge run config](../../docs/megatron-lm-to-megatron-bridge.md#export-megatron-lm-checkpoints-without-a-bridge-run-config)
20-
to generate and validate the provider configuration. Do not create an empty or
21-
hand-written YAML file; missing hybrid, MTP, MoE, or FP8 fields can construct a
22-
different model while appearing to load successfully.
16+
### Megatron-LM checkpoint compatibility
17+
18+
Training with Megatron-LM and later relying on Megatron Bridge for Hugging Face
19+
export is **not recommended**. Megatron-LM checkpoints normally store their
20+
arguments in `common.pt` instead of the `run_config.yaml` used by the supported
21+
Bridge export launcher, so the launcher cannot consume them directly. For an
22+
existing trusted checkpoint, the
23+
[best-effort compatibility guidance](../../docs/megatron-lm-to-megatron-bridge.md#best-effort-export-of-an-existing-megatron-lm-checkpoint)
24+
describes how to generate and validate the required provider configuration. It
25+
does not guarantee compatibility, and any unclassified metadata mismatch must
26+
stop the export.
27+
28+
Output from `scripts/translate_mlm_to_bridge.py` is best-effort configuration
29+
guidance for a new Bridge run. It is not checkpoint metadata and must not be
30+
renamed or inserted as `run_config.yaml`.
2331

2432
## Local CPU conversion
2533

0 commit comments

Comments
 (0)