nvidia-nemo/megatron-bridge/adding-model-support
Claude Code and agent skill by nvidia-nemo/megatron-bridge
- community
- ext:[{"type":"config","description":"Configuration overrides"}]
Checking that the SKILL.md file is still in the repository.
Guide for adding support for new LLM or VLM models in Megatron-Bridge. Covers bridge, builder-backed model config, recipe, tests, docs, and examples.
Install
npx vskill@latest install nvidia-nemo/megatron-bridge/adding-model-supportSemi-extensibleMentions customization, but needs skill-specific knowledge. Read the extensible skills standard
SKILL.md
The same SKILL.md was published earlier as nvidia-nemo/megatron-bridge/adding-model-support.
Adding New Model Support in Megatron-Bridge
Implementation boundaries
- Keep model-support changes in Megatron-Bridge. Do not modify Megatron-Core
or its submodule to implement a model. Use existing module specs, builders, conversion hooks, and narrow Bridge subclasses or compositions.
- Before adding a block, inspect both MCore and existing Bridge implementations.
Reuse an existing block when it represents the same computation. Differences in accumulation precision, rounding, fused kernels, or mathematically equivalent LayerNorm/RMSNorm operation ordering alone do not justify a replacement implementation.
- Add model-specific code under the family's
modeling_<model>/directory only
for genuinely missing computation or composition. For example, normalizing each expert before weighted summation differs mathematically from normalizing the combined result. Compose existing normalization and linear operations wherever possible instead of copying their kernels.
- Invoke Hugging Face vision/video and audio encoders directly; do not port
their internals into Bridge. Bridge owns their construction, checkpoint mapping, modality insertion, placement, freezing, and gradient synchronization. Existing native encoder ports are references for previously supported models, not a requirement for new support. Follow an explicit request for a different encoder implementation when the user provides one.
- Verify support through the requested model API, not only a shared config.
For HybridModel, trace the actual layer specs and expand per-layer schedules to Hybrid positions: *E repeated N times has 2N positions. Configure RoPE explicitly, since HybridModel defaults to no positional embedding.
- Separate weight-independent checks from checkpoint validation. A checkpoint
download need not block implementation or small config/block tests; record full conversion, logits, and training validation as pending until they run.
Phase 1: Discovery
Step 1 — Get the HF model link
Ask the user for the HuggingFace model link (e.g. https://huggingface.co/Qwen/Qwen3.5-VL-27B).
If the model is not public, ask the user to provide the config.json file directly.
Step 2 — Fetch and analyze config.json
Read the model's config.json from HuggingFace (or from the user-provided file). Key fields to extract:
model_type— used for@register_bridge(model_type=...)architectures— the HF model class name (used forsource=...in registration)tie_word_embeddings— critical for weight tying- Architecture fields:
num_hidden_layers,hidden_size,intermediate_size,num_attention_heads,num_key_value_heads,vocab_size,max_position_embeddings,rope_theta, etc. - MoE fields (if present):
num_local_experts,num_experts_per_tok,moe_intermediate_size - MLA fields (if present):
q_lora_rank,kv_lora_rank,qk_nope_head_dim,qk_rope_head_dim
For unfamiliar config fields, inspect the supplied Hugging Face modeling_*.py implementation and check existing MCore and Bridge components before concluding that a new block is needed. Ask for missing source only when it is not already available through the user's supplied artifacts or authorized locations.
Step 3 — Identify supported modalities
Inspect the config, HF model, and processor for vision/video and audio inputs. Perception configs commonly appear as vision_config or audio_config alongside text_config, but names and nesting vary. Route models with either type of perception encoder through the multimodal wrapper path, including audio-only language models. A text-only model has no perception integration; its language config may be flat or nested.
This distinction determines where to read language config fields, whether a wrapper must combine perception with the language model, and which modality inputs the functional checks must exercise.
Step 4 — Check for quantized weights (FP8 / FP4)
Inspect the HF checkpoint's model.safetensors (or model.safetensors.index.json) for quantized weight dtypes such as float8_e4m3fn (FP8) or uint8/uint4 with accompanying *_scale_inv or *_scale tensors. Common signs:
config.jsonmentionsquantization_configor dtype fields like"torch_dtype": "float8_e4m3fn"- Safetensors contain
weight_scale_invkeys alongside the main weight keys - The model card mentions FP8/FP4/INT4 weights
Why this matters: Apart from fine-grained FP8 (below), the bridge's import_ckpt path does not automatically dequantize — it loads raw quantized values as-is. This produces a silently broken model (random-level loss, huge grad norms) instead of raising an error.
Fine-grained FP8 needs no bridge code. Checkpoints with quant_method: "fp8" store FP8 weights with a <name>_scale_inv block-scale companion, as DeepSeek-V3 does. The base _load_hf_weights dequantizes them with the checkpoint's quantization_config.weight_block_size. Do not dequantize them in maybe_modify_loaded_hf_weight(): that hook runs first, so a fixed 128x128 block there ignores a different declared block size.
Other formats: Dequantize before or during conversion. The current in-repo pattern is to use a bridge hook plus the shared helpers in src/megatron/bridge/models/conversion/quantization_utils.py. For example, src/megatron/bridge/models/gpt_oss/gpt_oss_bridge.py dequantizes its MXFP4 experts, stored as <name>_blocks and <name>_scales, on the fly during import:
``python def maybe_modify_loaded_hf_weight(self, hf_param, hf_state_dict): if isinstance(hf_param, str) and hf_param not in hf_state_dict: return quantization_utils.dequantize_mxfp4( hf_state_dict[hf_param + "_blocks"], hf_state_dict[hf_param + "_scales"] ) return super().maybe_modify_loaded_hf_weight(hf_param, hf_state_dict) ``
Always add a sanity check in the verification workflow (e.g., print std of a weight tensor — quantized models typically have std ≈ 13 before dequantization vs std ≈ 0.006 after). Also add or update focused tests when touching export/import quantization paths; see tests/unit_tests/models/test_fp8_param_export.py for current FP8 export coverage.
Phase 2: Bridge Support
File structure
LLM — Reference: Qwen3 (src/megatron/bridge/models/qwen/qwen3_bridge.py)
VLM / audio-language model — Use HF perception encoders and a Bridge wrapper. Reference: Gemma3-VL (src/megatron/bridge/models/gemma_vl/).
For a small wrapper, an existing single-file layout can also be followed:
Model-specific modeling code: If the model requires custom nn.Module implementations (e.g. a custom RoPE variant, non-standard transformer config, custom thinker/talker architecture), place them in a modeling_<model>/ directory or a single modeling_<model>.py file inside the model family folder. Use a directory when there are multiple files (model, transformer config, custom ops); use a single file when one module suffices. Never put model-specific modeling code in shared directories or as loose files in the bridge family directory — keep them namespaced under the modeling_<model> prefix.
Implementation order
LLM:
- Bridge only — Register bridge, implement
hf_config_to_model_config_kwargs()and
mapping_registry(). The bridge calls super().hf_config_to_model_config_kwargs(hf_config) to get the fields derived from CONFIG_MAPPING, then update()s the model-specific fields. AutoBridge.get_model_config() turns these kwargs into a builder-backed ModelConfig (BridgeGPTModelConfig by default) that Megatron Core's ModelBuilder constructs. Set USE_MODEL_CONFIG_FOR_CONVERSION = True so checkpoint conversion builds the model through the same config, and have hf_config_to_provider_kwargs() return the same kwargs so the deprecated provider API stays consistent. Do not override `provider_bridge()` or create a provider or config file — BridgeGPTModelConfig is usually sufficient for LLMs. Do not add size-specific provider or config classes whose names combine ModelProvider or ModelConfig with a model-size suffix. Examples of forbidden suffixes include 7B, 200M, and A3B. Model size and architecture fields should come from the Hugging Face config through AutoBridge / MegatronModelBridge config mapping. If a recipe needs a fixed architecture, build the config from a Hugging Face config inside the recipe function (AutoBridge.from_hf_config(hf_config).get_model_config()) instead of exporting a subclass.
VLM:
- Bridge — Register bridge, implement config and weight mappings.
- Model config and builder — A combined vision+language model cannot be represented by
BridgeGPTModelConfig. Define a ModelConfig subclass and a ModelBuilder in the family directory, select the config with MODEL_CONFIG_CLASS, and override hf_config_to_model_config(). Reference: Muse Glimmer (src/megatron/bridge/models/muse_glimmer/). Older VLMs use a provider subclass with a custom provide() instead; see @skills/adding-model-support/vlm-patterns.md.
- Model class — Combine vision encoder + language decoder.
For detailed patterns, see:
- VLM: @skills/adding-model-support/vlm-patterns.md
- LLM: @skills/adding-model-support/llm-patterns.md
Critical: tie_word_embeddings for VLMs
For VLMs, tie_word_embeddings lives on the top-level HF config, NOT on text_config. Always read from the parent config:
Critical: Config field location for VLMs
When reading HF config for VLMs, check whether each field is in:
hf_config(top-level) — e.g.tie_word_embeddings,image_token_id,video_token_idhf_config.text_config— e.g.num_hidden_layers,hidden_size, etc.hf_config.vision_config— e.g. vision encoder dimensions
Encapsulating model-specific layers
When a new model introduces custom or non-standard layers (novel attention variants, custom normalization, fused expert layouts, MTP heads, etc.), keep all model-specific logic inside the model family directory. Do not modify shared files in src/megatron/bridge/models/conversion/ (e.g. param_mapping.py, model_bridge.py, quant_mapping.py) unless the change is genuinely reusable across multiple model families.
Principle: The bridge and provider files for a model family are your primary extension surface. Shared conversion infrastructure provides hooks and base classes — subclass them locally rather than adding conditionals to shared code.
Prefer Transformer Engine normalization
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 100 of 100Pattern checks on the skill's files.
- Model reviewNot runA model review is scheduled for the next rescan.
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/adding-model-support/SKILL.md
Popularity
- Repository stars
- 1,009
- Repository forks
- 601
- 7-day trend score
- 33
Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.
Extension points
configConfiguration overrides
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/nvidia-nemo/megatron-bridge/adding-model-support)