pytorch/torchtitan/add-moe-model
Claude Code and agent skill by pytorch/torchtitan
- community
- ext:[{"type":"hook","description":"Pre/post lifecycle hooks"}]
Checking that the SKILL.md file is still in the repository.
Add a new HF MoE model to the transformers_modeling_backend experiment. Use when the user provides a HuggingFace model ID and wants to integrate it with Titan's MoE, or invokes /add_moe_model.
Install
npx vskill@latest install pytorch/torchtitan/add-moe-modelSemi-extensibleMentions customization, but needs skill-specific knowledge. Read the extensible skills standard
SKILL.md
The same SKILL.md was published earlier as pytorch/torchtitan/add-moe-model.
Add HF MoE Model to Transformers Backend
Add support for a new HuggingFace MoE model in the torchtitan/experiments/transformers_modeling_backend/ experiment.
Scope of changes
ONLY modify code under `torchtitan/experiments/transformers_modeling_backend/`. If supporting the new model appears to require a change outside this folder (e.g. in torchtitan/models/, torchtitan/distributed/, torchtitan/components/, or any other core path), STOP and escalate to the user — describe the change you believe is needed and why, and wait for their decision instead of editing core yourself.
The one exception is the temporary, must-be-reverted diagnostic patches in Phase 3c (numerical-gap analysis): those edit core only to measure where titan diverges from HF, are reverted before the change is done, and are never committed. Any permanent change outside the experiment folder still requires escalation.
DO modify experiment code to support the new model. The experiment folder (torchtitan/experiments/transformers_modeling_backend/) is designed to be extended for new models. Expected changes include:
state_dict_adapter.py— add regex patterns for new key naming conventions,
handle transposed weight layouts, fix round-trip mappings
moe_replacement.py— add detection logic for new scoring functions, router
types, expert layouts, or shared expert patterns in _probe_hf_moe_block and its helper functions
hf_sharding.py— give every parameter/buffer-bearing module the model
introduces a sharding config. This is not limited to attention projections: set_hf_sharding_configs covers the root-level tok_embeddings, norm, lm_head, and rotary_emb (and their buffers), and _set_layer_sharding_configs covers per-layer norms, the attention block, and the dense MLP. A module with params/buffers but no config will mix a plain tensor with a DTensor and crash under TP (the _assert_all_states_sharded backstop now makes that a loud setup-time error for any param/buffer-bearing dense-path module — root modules and every decoder layer, excluding the Titan-swapped MoE). For a genuinely new module, shard it (colwise_sharding_config/rowwise_sharding_config) if it has a clear TP layout, otherwise default to _replicate_sharding_config(module) (replicate weights, no TP). If a new module type doesn't fit any existing helper, that's a signal to stop and think (or escalate) rather than leave it unconfigured.
model.py— handle alternative submodule names: HF models name the same
component differently (feed-forward mlp vs feed_forward, final norm norm vs final_layernorm). Add a new model's variant to the relevant lookup (_get_moe_attr_name, the HFTransformerModel accessor properties).
scripts/numerical_equivalence.py— add the model's synthetic test config
When blockers are found in Phase 1, fix them in the experiment code before proceeding to Phase 2. Do NOT stop and ask — implement the fixes, then continue the workflow.
Input
The user provides a HuggingFace model ID (e.g. Qwen/Qwen3-30B-A3B). Optionally, a local path to downloaded weights for pretrained testing.
Before starting, ask the user (if not already specified):
- Which branch to work on — should changes go on the current branch,
or a new branch? If running in a worktree, clarify whether the commit should target the main feature branch or stay on the worktree branch.
- Whether to commit — after all tests pass, should the changes be
committed automatically, or left as uncommitted changes for the user to review first?
Phase 1: Compatibility Probe
Load the model config and a single MoE layer on meta device to verify titan compatibility. No file changes in this phase — but record all issues found. After the probe, fix any blockers in the experiment code before moving to Phase 2.
1a. Load and inspect config
Record: model_type, hidden_size, intermediate_size, moe_intermediate_size, num_attention_heads, num_key_value_heads, num_hidden_layers.
1b. Instantiate on meta device
1c. Find MoE layers
Scan model.model.layers for layers where hasattr(mlp, "gate") or hasattr(mlp, "router") AND hasattr(mlp, "experts").
Record:
- Which layer indices are MoE vs dense
- The mechanism:
first_k_dense_replace,decoder_sparse_step, or
mlp_layer_types
- Minimum
num_hidden_layersneeded to have at least one MoE layer
1d. Probe MoE block
Call _probe_hf_moe_block(moe_block, config) from torchtitan/experiments/transformers_modeling_backend/moe_replacement.py.
Check each field succeeds without error:
| Field | How it's resolved | Blocker if missing | |
|---|---|---|---|
num_experts | experts.num_experts, gate.weight.shape[0], or config attrs | Yes | |
dim | config.hidden_size | Yes | |
moe_intermediate_size | experts.gate_up_proj.shape[1] // 2 or config | Yes | |
top_k | moe_block.top_k, config.num_experts_per_tok | Yes | |
score_func | sigmoid if e_score_correction_bias exists, else softmax | Blocker if neither | |
route_norm | config.norm_topk_prob or default True | No | |
route_scale | config.routed_scaling_factor or 1.0 | No | |
num_expert_groups | config.n_group or None | No | |
shared_expert_info | Probes shared_expert/shared_experts/shared_mlp | No |
Issues to detect and fix in experiment code:
- Expert weight layout transposed (e.g.
(E, H, 2*I)instead of
(E, 2*I, H)) — fix state_dict_adapter.py to transpose during conversion, and moe_replacement.py to detect the layout
- Experts stored as
nn.ModuleListof individual MLPs instead of fused
3D tensors — this is a true blocker (needs HF upstream change), report to user and stop
- Scoring function not
softmax/sigmoidbut detectable from the model
code (e.g. torch.sigmoid call without e_score_correction_bias) — fix _resolve_score_func() in moe_replacement.py
- Router uses
nn.Lineardirectly (key isrouter.weightnot
gate.weight) — add pattern to state_dict_adapter.py
- MoE layer attribute is not
mlp(e.g.feed_forward) — fix
model.py and moe_replacement.py to handle the alternative name
- Shared expert round-trip fails (singular/plural mismatch) — fix
reverse patterns in state_dict_adapter.py
- Model doesn't support
grouped_mmexpert implementation — adjust
the numerical test to skip the grouped_mm alignment for this model
- Layer-level MoE: router and experts are siblings of the dense MLP
at the decoder layer level, not nested inside layer.mlp (e.g. Gemma4 has layer.mlp + layer.router + layer.experts). In this case the dense MLP is functionally a shared expert — it runs on every token and its output is summed with the routed expert output. The correct mapping is to treat the dense MLP as shared_experts inside Titan's MoE module and replace layer.mlp with the full Titan MoE (router + experts + shared_experts). This way the entire block has a single ShardingConfig and TP/EP work correctly. Fix in moe_replacement.py: when probing, detect that the dense MLP is a shared expert, include it in shared_expert_info, and when swapping, replace layer.mlp with the Titan MoE that includes the dense MLP as its shared expert. Wire the router and expert weights from the layer-level attributes into the Titan MoE.
1e. Probe attention for ShardingConfig
Check which sharding configs _set_layer_sharding_configs (in hf_sharding.py) needs:
Q and KV are detected independently, so any mix of full-rank/low-rank works (e.g. DeepSeek-V2-Lite has full-rank q_proj + low-rank KV):
| Pattern | Projections | Already supported? | |
|---|---|---|---|
| Full-rank Q | q_proj | Yes (colwise_sharding_config) | |
| Low-rank Q (MLA) | q_a_proj, q_b_proj | Yes (_replicate_sharding_config/colwise_sharding_config) | |
| Standard KV (GQA) | k_proj, v_proj | Yes (colwise_sharding_config) | |
| Low-rank KV (MLA) | kv_a_proj_with_mqa, kv_b_proj | Yes (_replicate_sharding_config/colwise_sharding_config) | |
| Output | o_proj or dense | Yes (rowwise_sharding_config) | |
| Q/K norms | q_norm, k_norm | Yes (_replicate_sharding_config, each independent) | |
| V-norm | v_norm | Yes (_replicate_sharding_config) | |
| DSA indexer | indexer | FSDP/EP only — NOT under TP (fails loud; the indexer's scatter_/index ops need the spmd_types backend, see hf_sharding.py) |
The _assert_all_states_sharded backstop will fail loud at setup if any param/buffer-bearing attention (or other dense-path) module is left without a config, so an unhandled projection surfaces immediately. If found, report: "attention has unsupported projection <name>, needs _set_layer_sharding_configs update in hf_sharding.py."
Also check: does the layer have post_attention_layernorm? (Some models omit it — already handled.) Does the embedding have extra buffers (e.g. Gemma4's embed_scale)? (Already handled — buffers are enumerated dynamically.)
1f. State dict adapter round-trip
Verify: all original keys present, no extra keys, values match. If keys are missing, the adapter needs new patterns for this model's key naming convention.
1g. Report
Print a compatibility summary table:
1h. Fix issues
If issues were found, fix them in the experiment code now. Consult the "Issue Resolution Reference" at the bottom of this document for where each fix goes. The only true blocker is nn.ModuleList experts — for everything else, implement the fix and re-run the probe to verify.
After all issues are resolved and the probe passes cleanly, proceed to Phase 2.
Phase 2: Add Synthetic Test Config
Add an entry to _MODEL_CONFIGS in torchtitan/experiments/transformers_modeling_backend/.claude/skills/add_moe_model/scripts/numerical_equivalence.py.
Config rules
Use production-scale hidden_size and moe_intermediate_size from the real config. Override everything else for a small single-GPU test:
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 repositoryCheckingtorchtitan/experiments/transformers_modeling_backend/.claude/skills/add_moe_model/SKILL.md
Popularity
- 7-day trend score
- 0
Not refreshed yet.
Extension points
hookPre/post lifecycle hooks
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/pytorch/torchtitan/add-moe-model)