Megatron-LM to Megatron Bridge Guide#
Megatron Bridge is Python-first: configure models, data, and training via typed Python APIs. All configuration lives in a structured ConfigContainer (see Configuration overview). Any field can be overridden from the command line using Hydra/OmegaConf syntax in the example training scripts.
Automated config translation script#
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.
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.
MLM → Bridge (default direction)#
# From a YAML config file (MODEL_ARGS section)
uv run python scripts/translate_mlm_to_bridge.py --yaml model_configs/DeepSeek-V3.yaml
# From inline CLI args
uv run python scripts/translate_mlm_to_bridge.py \
--args "--num-layers 32 --hidden-size 4096 --num-attention-heads 32 --bf16 --swiglu"
# Emit a standalone Bridge recipe Python file (output goes to stdout; use -o to write to a file)
uv run python scripts/translate_mlm_to_bridge.py \
--yaml DeepSeek-V3.yaml --emit recipe --recipe-name deepseek_v3
# Write output to a file instead of stdout
uv run python scripts/translate_mlm_to_bridge.py \
--yaml DeepSeek-V3.yaml -o bridge_overrides.txt
Bridge → MLM (reverse direction)#
# From a Bridge recipe name (defaults exported as MLM args)
uv run python scripts/translate_mlm_to_bridge.py --reverse \
--recipe llama32_1b_pretrain_1gpu_h100_bf16_config
# From a recipe plus inline overrides
uv run python scripts/translate_mlm_to_bridge.py --reverse \
--recipe llama32_1b_pretrain_1gpu_h100_bf16_config \
--args "train.train_iters=1000 model.tensor_model_parallel_size=2"
# From Bridge overrides only (no recipe)
uv run python scripts/translate_mlm_to_bridge.py --reverse \
--args "model.num_layers=32 model.activation_func=silu model.gated_linear_unit=true"
# From a Bridge YAML/OmegaConf config file (e.g. exported ConfigContainer)
uv run python scripts/translate_mlm_to_bridge.py --reverse \
--yaml bridge_config.yaml
Key mappings#
MLM flag |
Bridge override |
Notes |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Dual mapping |
|
|
Expanded to two keys |
|
|
|
|
|
Space-separated paths (and optional weights) |
|
|
|
|
|
|
|
|
Inverted flag |
|
|
Inverted flag |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Selects |
|
|
Migrates the deprecated MLM field |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Separate MLM MTP pattern |
|
|
One physical MTP layer reused across prediction depths |
|
|
Bridge exposes the MCore SFT compatibility alias at load time |
|
|
Use synthetic data (no files needed) |
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.
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.
Activation function CLI overrides:
model.activation_funccan 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 inTransformerConfig.finalize(). This makes--swiglu→model.gated_linear_unit=true model.activation_func=siluround-trippable from the CLI.
Quick start#
Run the generic recipe launcher and override config keys directly:
uv run python scripts/training/run_recipe.py \
--recipe llama3_8b_pretrain_2gpu_h100_bf16_config \
--mode pretrain \
--dataset mock \
train.micro_batch_size=2 \
train.global_batch_size=128 \
model.num_layers=32 model.hidden_size=4096 model.num_attention_heads=32 \
model.max_position_embeddings=4096 \
dataset.seq_length=4096 \
checkpoint.save=/workspace/ckpts checkpoint.save_interval=1000 \
logger.wandb_project=my_proj logger.wandb_exp_name=exp1
Notes:
Config groups are nested:
rng,train,model,optimizer,ddp,scheduler,dataset,logger,tokenizer,checkpoint,dist,profiling,peft,comm_overlap,mixed_precision,inprocess_restart.After overrides are applied, runtime validation computes any dependent fields (e.g., data-parallel size, scheduler steps) and checks consistency.
Best-effort export of an existing Megatron-LM checkpoint#
Megatron-LM checkpoints save their training arguments in common.pt; they do
not normally contain the run_config.yaml written by Megatron Bridge. The
Bridge checkpoint export launcher currently needs that file to reconstruct a
model provider before loading the distributed weights.
Training with Megatron-LM and later relying on Megatron Bridge for Hugging Face export is not recommended. This procedure is a best-effort recovery path for an existing checkpoint, not a supported general MLM-to-Hugging-Face conversion workflow. Use it only with a checkpoint and immutable local Hugging Face snapshot that you trust. Loading MLM common checkpoint state may deserialize Python objects; an allowlisted package prefix or audited Hugging Face code does not make an untrusted checkpoint safe.
Use this procedure only when all of the following are true:
the iteration directory contains
common.ptand the distributed checkpoint metadata and shards;the checkpoint architecture has an existing Megatron Bridge implementation;
--hf-modelidentifies an immutable local snapshot of the exact Hugging Face architecture used to create the checkpoint; fine-tuned weights may differ, but all architecture- and behavior-bearing configuration must match; andMegatron Bridge, Megatron Core, and Transformer Engine are compatible with the versions that wrote the checkpoint.
This procedure generates only run_config.yaml in the checkpoint directory.
It does not migrate legacy checkpoint keys or metadata, translate a custom
Megatron-LM model spec into a Bridge provider, or prove that the checkpoint and
reference are semantically equivalent. Work on a copy if the checkpoint
directory must remain pristine.
Generate run_config.yaml#
Set MB_CKPT to the checkpoint iteration directory, not its parent. The
Hugging Face reference is used only for configuration and provider selection;
this generation step does not download its weights.
MB_CKPT=/workspace/checkpoints/model/iter_0001000
MB_HF_REF=/workspace/hf-snapshots/model-at-immutable-revision
uv run python - "$MB_CKPT" "$MB_HF_REF" --trust-remote-code <<'PY'
from dataclasses import fields
import logging
from pathlib import Path
import sys
from megatron.core.ssm.mamba_hybrid_layer_allocation import Symbols
from megatron.bridge import AutoBridge
from megatron.bridge.training.config import ConfigContainer
from megatron.bridge.training.model_load_save import load_model_config
from megatron.bridge.utils.yaml_utils import dump_dataclass_to_yaml
from transformers import AutoConfig
logging.basicConfig(level=logging.INFO, format="%(message)s")
logger = logging.getLogger(__name__)
checkpoint = Path(sys.argv[1])
hf_reference = sys.argv[2]
trust_remote_code = "--trust-remote-code" in sys.argv[3:]
output = checkpoint / "run_config.yaml"
if not (checkpoint / "common.pt").is_file():
raise FileNotFoundError(f"common.pt not found in {checkpoint}")
if output.exists():
raise FileExistsError(f"Refusing to overwrite {output}")
# Without run_config.yaml, this reads the Megatron-LM args from common.pt.
checkpoint_config, megatron_args = load_model_config(str(checkpoint))
if megatron_args is None:
raise RuntimeError("Expected a Megatron-LM checkpoint with args in common.pt")
hf_config = AutoConfig.from_pretrained(
hf_reference,
trust_remote_code=trust_remote_code,
)
bridge = AutoBridge.from_hf_config(hf_config)
provider = bridge.to_megatron_provider(load_weights=False)
# Overlay the checkpoint's TransformerConfig, including FP8/MXFP8 fields, on
# the architecture-specific provider derived from the HF reference.
for field in fields(checkpoint_config):
if hasattr(provider, field.name):
setattr(provider, field.name, getattr(checkpoint_config, field.name))
# Hybrid layer patterns are stored in the Megatron-LM Namespace rather than
# its TransformerConfig. Preserve separate and already-unified MTP layouts.
pattern = (
getattr(megatron_args, "hybrid_layer_pattern", None)
or getattr(megatron_args, "hybrid_override_pattern", None)
)
if pattern and hasattr(provider, "hybrid_layer_pattern"):
provider.hybrid_override_pattern = None
provider.hybrid_layer_pattern = pattern
for name in (
"mtp_num_layers",
"mtp_hybrid_override_pattern",
"mtp_use_repeated_layer",
"keep_mtp_spec_in_bf16",
"seq_length",
):
value = getattr(megatron_args, name, None)
if value is not None and hasattr(provider, name):
setattr(provider, name, value)
if pattern and Symbols.MTP_SEPARATOR in pattern:
provider.mtp_hybrid_override_pattern = None
if hasattr(provider, "hf_model_id"):
provider.hf_model_id = hf_reference
provider.finalize()
# Serializing the provider directly omits its dataclass fields. Convert it
# through ConfigContainer so load_model_config() can instantiate it correctly.
model_dict = ConfigContainer._convert_value_to_dict(provider)
dump_dataclass_to_yaml({"model": model_dict}, str(output))
logger.info("Wrote %s", output)
PY
Omit --trust-remote-code unless the reference model requires custom code and
you trust its repository.
Validate the generated provider#
Validate the YAML before allocating GPUs for conversion:
uv run python - "$MB_CKPT" <<'PY'
import logging
import sys
from megatron.bridge.training.model_load_save import load_model_config
logging.basicConfig(level=logging.INFO, format="%(message)s")
logger = logging.getLogger(__name__)
config, megatron_args = load_model_config(sys.argv[1])
if megatron_args is not None:
raise RuntimeError("run_config.yaml was not loaded")
for name in (
"num_layers",
"hidden_size",
"ffn_hidden_size",
"num_moe_experts",
"hybrid_layer_pattern",
"mtp_num_layers",
"fp8",
"fp8_recipe",
"fp8_param",
"first_last_layers_bf16",
"num_layers_at_start_in_bf16",
"num_layers_at_end_in_bf16",
):
logger.info("%s=%r", name, getattr(config, name, None))
PY
The printed fields are only a starting diagnostic. Compare every architecture- and behavior-bearing field with the original training configuration, including position and RoPE behavior, vocabulary and tokenizer IDs, tied weights, expert and router behavior, attention, Mamba, and physical/repeated-MTP layout. Parallel degrees may differ only for a valid resharding topology. Treat any unclassified difference as an incompatibility and do not continue.
Run the normal export after validation. Adapt the parallel topology to the checkpoint and available GPUs:
./scripts/conversion/convert.sh export \
--executor local \
--device gpu \
--gpus-per-node 8 \
--hf-model "$MB_HF_REF" \
--megatron-path "$MB_CKPT" \
--hf-path /workspace/exports/model-hf \
--tp 1 --pp 1 --ep 8 --etp 1 \
--torch-dtype bfloat16 \
--trust-remote-code
Keep strict conversion enabled for the first export. Do not use
--not-strict to bypass missing MTP, expert, or quantized parameters.
Verify the emitted HF config, shard index, expected tensor keys, strict
from_pretrained() loading, and at least one forward pass. These are structural
and runtime checks, not numerical-parity evidence. Compare source and exported
logits when a source-model baseline is available.
For MXFP8 parameter checkpoints, use hardware supported by the saved recipe
(normally Blackwell). The default BF16 export dequantizes Transformer Engine
quantized parameters. Do not request --export-weight-dtype fp8 for MXFP8;
native FP8 Hugging Face export currently supports blockwise FP8 parameters.
Mapping Megatron-LM arguments to Megatron Bridge config#
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.
Model topology and parallelisms#
megatron-lm arguments |
Megatron Bridge config |
Description |
|---|---|---|
|
|
TP degree. |
|
|
PP degree. |
|
|
CP degree. |
|
|
EP degree. |
|
|
Expert TP degree. |
|
|
Enable sequence parallelism. |
|
|
Asymmetric PP: embeddings. |
|
|
Asymmetric PP: loss. |
Model architecture knobs#
megatron-lm arguments |
Megatron Bridge config |
Description |
|---|---|---|
|
|
Untie embeddings/output. |
|
|
|
|
|
Fraction of rotary dims. |
|
|
RoPE base. |
|
|
RoPE interpolation factor. |
|
|
LayerNorm/RMSNorm, etc. |
|
|
Enable SwiGLU MLP. |
|
|
Epsilon for norm layers. |
|
|
Number of transformer layers. |
|
|
Model hidden size. |
|
|
MLP expansion size. |
|
|
Attention heads. |
|
|
Key/Value channels per head. |
|
|
Set groups (enable GQA). |
|
|
Number of query groups. |
|
|
Enable QK LayerNorm. |
|
|
Max model sequence length. |
|
|
Alias used by HF conversions. |
|
|
TP padding multiple. |
|
|
Disable linear bias. |
|
|
Use FlashAttention backend. |
|
|
Weight init standard deviation. |
|
|
Attention dropout. |
|
|
Hidden dropout. |
MoE#
megatron-lm arguments |
Megatron Bridge config |
Description |
|---|---|---|
|
|
Experts per MoE layer. |
|
|
Expert MLP hidden size. |
|
|
e.g., aux_loss or seq_aux_loss. |
|
|
Top-k experts per token. |
|
|
Pre-softmax routing. |
|
|
Grouped GEMM for MoE. |
|
|
Aux loss coefficient. |
|
|
Token dispatcher: alltoall or flex. |
|
|
MoE token dispatcher: deepep or hybridep |
|
|
Enable MoE permute fusion. |
|
|
Enable MoE router fusion. |
|
|
Router dtype (e.g., fp32). |
Mixed precision#
megatron-lm arguments |
Megatron Bridge config |
Description |
|---|---|---|
|
|
Select a mixed-precision recipe; sets |
Mixed precision is selected via the mixed_precision config key (e.g., preset names like bf16_mixed, bf16, or fp16, depending on your codebase) and is applied to model, optimizer, and ddp during runtime_config_update.
Training#
megatron-lm arguments |
Megatron Bridge config |
Description |
|---|---|---|
|
|
Per-rank batch size before gradient accumulation. |
|
|
Total batch across DP and micro-batches. |
|
|
Total training samples (sample-based mode). |
|
|
Start size, increment, and sample count for linear batch ramp-up. |
|
|
Adjust GBS to remain divisible when DP changes. |
|
|
PyTorch CUDA empty_cache cadence (0, 1, or 2). |
|
|
Interval to validate DP weight consistency. |
|
|
Number of training iterations. |
|
|
Exit when iteration % interval == 0. |
|
|
Exit after N minutes. |
|
|
Save and shut down on SIGTERM. |
|
|
Enable manual Python GC scheduling. |
|
|
Steps between manual GC runs. |
|
|
Disable GC at eval boundaries. |
|
|
Eval iterations per validation run. |
|
|
Steps between validations. |
|
|
Skip training loop (eval-only). |
Scheduler / Regularization#
megatron-lm arguments |
Megatron Bridge config |
Description |
|---|---|---|
|
|
LR schedule: constant/linear/cosine/ISR/WSD. |
|
|
Iterations over which to decay LR. |
|
|
WSD anneal style. |
|
|
Iterations for WSD anneal phase. |
|
|
Warmup as fraction of decay span. |
|
|
Warmup iterations (absolute). |
|
|
Initial LR at start of warmup. |
|
|
Samples over which to decay LR (sample-based training). |
|
|
Warmup samples (sample-based training). |
|
|
Base learning rate. |
|
|
Minimum learning rate. |
|
|
Gradient clipping value. |
|
|
Weight decay. |
|
|
Adam beta1. |
|
|
Adam beta2. |
|
|
Ignore ckpt scheduler and use config. |
|
|
Load scheduler from checkpoint. |
|
|
WD at start (non-constant modes). |
|
|
WD at end (non-constant modes). |
|
|
WD schedule: constant/linear/cosine. |
Checkpointing#
megatron-lm arguments |
Megatron Bridge config |
Description |
|---|---|---|
|
|
Directory to write checkpoints. |
|
|
Iterations between persistent saves. |
|
|
Do not save optimizer state. |
|
|
Do not save RNG state. |
|
|
Directory to load from. |
|
|
Do not load optimizer state. |
|
|
Load FP32 main params directly. |
|
|
Do not load RNG state. |
|
|
Frequency for ephemeral saves. |
|
|
Kind of ephemeral checkpoint (global/local/memory). |
|
|
Dir for global ephemeral saves. |
|
|
Dir for local-per-rank ephemeral saves. |
|
|
Local save algorithm selection. |
|
|
Load weights, reset iters, no optim/rng. |
|
|
Path to pretrained weights for finetune/SFT. |
|
|
Explicit step to load. |
|
|
Override model args from checkpoint metadata. |
|
|
Exit if |
|
|
Format: torch_dist/zarr/fsdp_dtensor. |
|
|
Conversion target format. |
|
|
Output dir for converted ckpt. |
|
|
Disable DP-parallel save. |
|
|
Enable async saves (torch_dist only). |
|
|
Background worker for async saves. |
|
|
Enable DP-parallel load. |
|
|
Optimize for fixed structure. |
|
|
Handling of key mismatches on load. |
|
|
Auto-detect checkpoint format on load. |
|
|
Enable replication of local checkpoints. |
|
|
Spacing between replica ranks. |
|
|
Number of replicas. |
|
|
Relax FSDP-DTensor strict load. |
Logging#
megatron-lm arguments |
Megatron Bridge config |
Description |
|---|---|---|
|
|
Steps between console logs. |
|
|
Compute and log parameter L2 norm. |
|
|
Log tokens/sec per GPU. |
|
|
Write progress.txt with tokens and FLOPs. |
|
|
0=min; 1=coarse ops; 2=many ops. |
|
|
max/minmax/all across ranks. |
|
|
TensorBoard log directory. |
|
|
Steps between TB events. |
|
|
Pending TB event queue size. |
|
|
Write timers to TB. |
|
|
Disable loss-scale TB logs. |
|
|
Write validation perplexity (ppl) to TB. |
|
|
Enable memory stats in TB. |
|
|
Log world size in TB. |
|
|
Weights & Biases project. |
|
|
Weights & Biases entity/team. |
|
|
Run name in W&B. |
|
|
Local directory for W&B artifacts. |
|
|
Python logging level (e.g., 20=INFO). |
|
|
Log energy in Joules (if available). |
RNG / Initialization#
megatron-lm arguments |
Megatron Bridge config |
Description |
|---|---|---|
|
|
Global random seed. |
|
|
Enable per-DP-rank random init. |
|
|
Use TE RNG (needed for CUDA graphs). |
|
|
RNG tuned for inference stability. |
Distributed init and topology#
megatron-lm arguments |
Megatron Bridge config |
Description |
|---|---|---|
|
|
Process group backend (nccl/gloo). |
|
|
PG init and collective timeout. |
|
|
Launch DP reduces independently per PP stage. |
|
|
Disable auxiliary Gloo PG creation. |
|
|
Enable SHARP collectives for DP PG. |
|
|
Which DP group enables SHARP. |
|
|
Use high-priority comm streams for groups. |
|
|
Use TP-PP-DP rank ordering at init. |
Additional distributed/optimizer overlap settings:
megatron-lm arguments |
Megatron Bridge config |
Description |
|---|---|---|
|
|
Enable distributed optimizer; settings are synchronized. |
|
|
Overlap DP gradient reduce-scatter. |
|
|
Overlap parameter all-gather with fprop. |
Profiling#
megatron-lm arguments |
Megatron Bridge config |
Description |
|---|---|---|
|
|
Enable nsys profiling (capture is controlled via external CLI). |
|
|
Enable PyTorch profiler (TB-friendly). |
|
|
Global step to start profiling. |
|
|
Global step to stop profiling. |
|
|
Global ranks to profile. |
|
|
Track memory history. |
|
|
Output path for memory snapshot. |
(shapes) |
|
Record tensor shapes (overhead). |
In-process restart#
megatron-lm arguments |
Megatron Bridge config |
Description |
|---|---|---|
|
|
Enable nvrx in-process restart. |
|
|
Max restart attempts. |
|
|
Monitor thread polling interval. |
|
|
Monitor process polling interval. |
|
|
Auto progress timestamp update cadence. |
|
|
Unresponsive-rank heartbeat cadence. |
|
|
Soft progress timeout. |
|
|
Hard timeout until kill. |
|
|
Missing heartbeat timeout. |
|
|
Timeout for internal barriers. |
|
|
Timeout for completion barrier. |
|
|
Delay to collect terminal failures. |
|
|
SIGTERM→SIGKILL grace period. |
|
|
Restart granularity (node/rank). |
|
|
Active ranks count; rest are reserve. |
|
|
Empty CUDA cache on restart finalize. |
Straggler detection#
megatron-lm arguments |
Megatron Bridge config |
Description |
|---|---|---|
|
|
Track and log straggler GPUs. |
|
|
Start with straggler detector disabled. |
|
|
Controller port for toggling. |
|
|
Num ranks to report for min/max throughput. |
Rerun state machine#
megatron-lm arguments |
Megatron Bridge config |
Description |
|---|---|---|
|
|
Frequency of injected validation perturbations. |
|
|
Kind of injection (correct/transient/persistent). |
|
|
Disabled/validate_results/report_determinism_stats. |
Data / Tokenizer args#
megatron-lm arguments |
Megatron Bridge config |
Description |
|---|---|---|
|
|
Tokenizer implementation (e.g., HuggingFaceTokenizer). |
|
|
Model name/path for tokenizer. |
|
|
DataLoader workers. |
|
|
Use backend-generated masks. |