Skip to content

Build sharded model configs; separate RL trainer and generator models - #5280

Merged
tianyu-l merged 6 commits into
mainfrom
rl-separate-model-configs
Oct 11, 2026
Merged

tianyu-l merged 6 commits into
mainfrom
rl-separate-model-configs

Conversation

@tianyu-l

@tianyu-l tianyu-l commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Why

The RL trainer and generator shared one model config, and each actor re-derived sharding from its own parallelism with a public set_sharding_() before building. That forced three workarounds:

  • Model configs were built without a parallelism, so sharding was attached afterwards by per-model walkers that mutate a finished tree, and transforms ran before sharding existed.
  • SharedExpertRowParallelLinear existed only because the shared-expert output layout (TP-Partial vs. reduced) could not be fixed at build time.
  • Role-specific settings (e.g. a CUDA-graph-compatible MoE dispatcher for the generator) needed per-actor overrides (torchtitan_recipes/overrides/moe_token_dispatcher.py).

This PR builds each model config for a known parallelism, bottom-up, and gives the RL trainer and generator their own model configs.

What changed

Sharding is part of model config construction

  • build_model_config(flavor, *, parallelism) builds a sharded config; parallelism is required so a model config cannot be built without choosing its layout. Each component gets its sharding_config where it is constructed; the shared make_* factories take enable_sp/enable_ep. Sequence and expert parallelism are the only settings that change declared layouts; mesh degrees are still resolved at runtime.
  • Removed: BaseModel.Config.set_sharding_(), the per-model set_*_sharding_config walkers, decoder_sharding.set_*/moe_sharding.set_*/set_vision_transformer_block_sharding_config, and the runtime re-shard in the trainers and the vLLM wrapper. Model sharding.py files now hold pure constructors returning ShardingConfig/SpmdType (deleted for llama3 and qwen3, which need none beyond common/).
  • SharedExpertRowParallelLinear is removed: the shared-expert w2 is chosen at construction -- a RowParallelLinear (reduce-scatter) with SP, and a plain Linear that keeps its TP-Partial output without SP, so the MoE reduces routed + shared once. RowParallelLinear is unchanged and transforms such as async TP apply as-is.
  • Transforms and overrides assume the config is already sharded and keep (or explicitly set) the sharding of configs they replace; apply_transforms never re-derives sharding.

RL: one model config per role

  • Controller.Config.model is removed; Trainer.Config.model and VLLMGenerator.Config.model replace it, each built for that role's parallelism (build_rl_model_configs builds both from one call). The controller requires the same model class; keeping them otherwise aligned is the recipe's job.
  • Per-role differences are model config transforms on one role, e.g. apply_transforms(config.generator, [TokenDispatcherTransform(DeepEPTokenDispatcher, num_max_tokens_per_rank=..., kwargs={"cuda_graph_compatible": True})]).
  • Transforms take only the model config (ModelConfigTransformContext is removed) and apply_transforms works on any config that owns a model. TokenDispatcherTransform takes the EP buffer capacity explicitly: a trainer passes its microbatch / (CP x TP), the generator its per-step token budget / TP.
  • override moves from TrainingEngine.Config to the top-level configs: core Trainer.Config.override and a new Controller.Config.override, applied to the whole RL tree (both models) before actors spawn. VLLMGenerator.Config.override and moe_token_dispatcher.py are removed. The CLI --override extends the top-level config's override.

Recipes

  • Recipes declare their parallelism before building the model. Base recipes that derived recipes reshape (EP 1 vs. >1, SP on/off) take a parallelism= keyword; derived recipes that only change degrees are unchanged.
  • Base MoE test recipes that accept an EP parallelism disable CUDA graphs for the stock all-to-all dispatcher (it syncs with the CPU); derived recipes that install a capturable dispatcher (HybridEP non-blocking, Dist-MoE) re-enable them. Every non-RL recipe's final config and runtime model config is unchanged vs. Reorganize repo structure, dependencies, docs, and tests #5277 (checked for all recipes, with the shared-expert class rename normalized).

Cleanups

  • Sharding constructors are named *_sharding_config (e.g. sharding_config=router_gate_sharding_config()), so call sites do not read like module configs.
  • The vLLM wrapper's FSDP storage transitions are private module functions named for what they do: _restore_sharded_params / _unshard_and_free_sharded_params (matching the upstream APIs they stand in for).
  • scripts/install_rl_env.sh installs FA3 from the same nightly/${cuda} index as torch (FA3 ships one CUDA 13.0 stable-ABI wheel that every CUDA 13 index serves).

Fixes found along the way

  • kimi_k2_7 and muse_glimmer build_model_config dropped a converter's returned root config (now covered for every model by test_build_model_config.py).
  • graph_trainer's SDPA test backend swap kept the inner attention's sharding.

Behavior changes

  • Recipes that set the fused_swiglu perf override now set it on Controller.Config.override, so it applies to both RL models (previously the DeepEP perf recipes applied it to the generator only).
  • The RL generator's DeepEP dispatch buffers are sized from its own per-step token budget instead of the trainer's microbatch.
  • The routed-expert "sharding does not match expert_parallel_degree" validation is removed along with the runtime re-shard; a mismatched build is caught by SPMD typechecking (debug.spmd_typechecking).

Numerics

Every model flavor's config tree (llama3, qwen3, qwen3_5/6/8, deepseek_v3/v4, gpt_oss, kimi_k2_7, kimi_k3, muse_glimmer, flux) x {SP on, off} x {EP 1, 2} is byte-identical to the tree the previous walkers produced, including every sharding_config and parameter initializer.

Bitwise comparison against #5277 with scripts/loss_compare.py (seed 42, deterministic, --metrics loss,grad_norm --assert-equal, 20 steps, 4x GB300):

Config Layout Result
Llama 3 debugmodel FSDP2 TP2, no SP loss and grad_norm identical
DeepSeek V3 debugmodel (MLA, MoE with shared experts) FSDP2 TP2 EP2, SP loss and grad_norm identical
DeepSeek V3 debugmodel FSDP2 TP2 EP2, no SP (plain Linear shared-expert w2) loss and grad_norm identical
Qwen3.5 debugmodel_moe (GDN, sigmoid-gated shared experts) FSDP2 TP2 EP2, SP loss and grad_norm identical
Qwen3.5 debugmodel_moe FSDP2 TP2 EP2, no SP loss and grad_norm identical
Kimi K3 multimodal DistMuon (kimi_k3_mm_muon) FSDP2 EP2, seeded from kimi_k3_debugmodel_mm loss identical, both with a shared seed checkpoint and with each commit creating its own

Beyond loss runs, every recipe in torchtitan_recipes and the integration suites was built on both commits: the final configs (models excluded) are identical for every non-RL recipe, and every runtime model config (this PR's built config vs. #5277's config after set_sharding_(parallelism)) is identical once the shared-expert class rename is normalized. The only intended differences are the RL changes listed above.

Testing

  • pre-commit run --all-files clean (pyrefly 0 errors).
  • CPU unit tests (core, RL, graph_trainer passes): all pass except failures that reproduce on Reorganize repo structure, dependencies, docs, and tests #5277: 4 aarch64-only Inductor CPU flex-attention failures, and 2 Dist-MoE tests that need a visible GPU (they pass with one).
  • GPU unit tests touched by this change pass on 4x GB300: test_tensor_parallel_feed_forward, test_async_linear, test_fsdp_cpu_offload, test_fused_swiglu, test_fsdp_moe_sharding (one failure also fails on Reorganize repo structure, dependencies, docs, and tests #5277).
  • Every recipe in torchtitan_recipes and the integration suites builds, and its model's SP/EP layout matches its parallelism (both RL roles included), except hardware-gated MXFP8/NVFP4/flash recipes on this machine.

@tianyu-l
tianyu-l added this pull request to stack #5281 October 11, 2026 08:37
@pytorch-bot pytorch-bot Bot added ciflow/b200 Trigger B200 CI ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Oct 11, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 11, 2026
@tianyu-l tianyu-l changed the title Build sharded model configs per role; separate RL trainer/generator models Build sharded model configs; separate RL trainer and generator models Oct 11, 2026
from torchtitan.rl.distributed.parallelism import InferenceParallelismConfig


def build_rl_model_configs(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@felipemello1 this could be the central entry for RL models, where we can apply lm_head fp32 transform, router freezing, etc. Wdyt?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function is about transforms that every rl model need. So yeah fp32 lm head, router freezing goes here.

Base automatically changed from repo-structure-cleanup to main October 11, 2026 18:23
@tianyu-l
tianyu-l force-pushed the rl-separate-model-configs branch from ee7c954 to 2ee95ab Compare October 11, 2026 18:23
…odels

Sharding is now part of model config construction:
build_model_config(flavor, parallelism=...) sets each component's
sharding_config where it is built, and the shared make_* factories take
enable_sp/enable_ep. This removes BaseModel.Config.set_sharding_(), the
per-model set_*_sharding_config walkers, the runtime re-shard in the
trainers and the vLLM wrapper, and SharedExpertRowParallelLinear (a
RowParallelLinear with a declared TP-Partial output skips its reduction).
Transforms and overrides keep the sharding of the configs they replace.

The RL trainer and generator each own a model config built for their own
parallelism (Controller.Config.model is removed), and must use the same
model class. Per-role differences are model config transforms on one role;
apply_transforms takes its context from config.transform_context().
override moves to the top-level configs (Trainer.Config and a new
Controller.Config.override applied to both RL models); the generator
override and the per-actor MoE token dispatcher override are removed.

Recipes declare parallelism before building their models. Also fixes
kimi_k2_7 and muse_glimmer dropping a converter's returned root config.
…ithout SP, no transform context

- build_model_config requires parallelism, so a model config cannot be built
  without choosing the layout it is sharded for. Recipes pass their own
  parallelism; tests and scripts pass an explicit ParallelismConfig().
- The shared-expert down projection is a RowParallelLinear with SP and a plain
  Linear without SP (selected at construction), so RowParallelLinear always
  reduces and transforms such as async TP apply unchanged.
- Remove ModelConfigTransformContext and transform_context(): transforms take
  only the model config, apply_transforms works on any config with a model,
  and TokenDispatcherTransform takes num_max_tokens_per_rank explicitly.
- Base recipes that accept an EP parallelism disable CUDA graphs for the stock
  all-to-all dispatcher; derived recipes that install a capturable dispatcher
  re-enable them, keeping every recipe's final config unchanged.
- Fix a stale doc link to the removed llama3/sharding.py and the Kimi K3 GPU
  test's direct flavor call.
VLLMGenerator.Config.max_num_batched_tokens is optional, so dividing the
field fails type checking; use the recipe's budget variable instead.
FA3 ships one CUDA 13.0 wheel on the torch stable ABI, and every CUDA 13
PyTorch index (including nightly/cu132) serves that same file. Use the
--cuda nightly index instead of a hardcoded test/cu130 one.
Call sites read sharding_config=router_gate_sharding_config() instead of
sharding_config=router_gate_config(), which looked like a module config.
Applies to every ShardingConfig constructor in the sharding modules (common,
per-model, and the HF backend's private helpers); local variables with the
old names are untouched.
prepare_for_state_dict_load and prepare_for_forward used no wrapper state;
they are now private module functions named for what they do to the FSDP
group's storage, matching the upstream APIs they stand in for:
_restore_sharded_params and _unshard_and_free_sharded_params, with a shared
_sharded_param_storages helper.
@tianyu-l
tianyu-l force-pushed the rl-separate-model-configs branch from 2ee95ab to c4ed6e1 Compare October 11, 2026 19:04

@wwwjn wwwjn left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The idea looks good, approve to unblock

@tianyu-l
tianyu-l merged commit b81852f into main Oct 11, 2026
@tianyu-l
tianyu-l deleted the rl-separate-model-configs branch October 11, 2026 20:32
acisseJZhong added a commit that referenced this pull request Oct 15, 2026
… parallelism (#5426)

GraphTrainer's DeepSeek integration recipes enable EP after building a
model with EP disabled. Routed-expert weights consequently retain the
dense placement instead of sharding the expert dimension on the sparse
mesh. Pass `expert_parallel_degree` into the base recipe at construction
time; retain the existing runtime mesh degrees and schedules.

This fixes the stale sharding configuration behind these five failures
in the [main H100
job](https://github.com/pytorch/torchtitan/actions/runs/38781348820/job/116582123654):

| Integration test | Observed failure |
| --- | --- |
| `aot_fx_trace_deepseek_v3_hsdp_edp_shard_ep` | `KeyError: mesh_ep` |
| `aot_fx_trace_deepseek_v3_graph_pp_dual_pipe_v_full_inductor` |
`KeyError: mesh_ep` |
| `aot_fx_trace_deepseek_v3_graph_pp_zbv_zero_bubble_full_inductor` |
`KeyError: mesh_ep` |
| `aot_fx_trace_deepseek_v3_graph_pp_interleaved_1f1b_full_inductor` |
`KeyError: mesh_ep` |
| `aot_fx_trace_deepseek_v3_fused_mla_swiglu_fsdp_tp_ep` |
`RuntimeError: matrix batch sizes have to match` |

Root cause: #5280 (`b81852f007`) moved sharding to model-config
construction and removed the runtime re-sharding step, but missed these
derived integration recipes. Its [direct parent's H100
run](https://github.com/pytorch/torchtitan/actions/runs/38163639527/job/114541631402)
passed the integration stage; the [run at
#5280](https://github.com/pytorch/torchtitan/actions/runs/38172622630/job/114568343559)
first failed all five integrations. Both used
`torch==2.16.0.dev20261011+cu132`. The fused test initially reported an
ambient-mesh error and now reaches the grouped-matmul shape error. The
missing EP placement was reproduced with a local CPU configuration
check.

Pass EP at construction time in all seven affected callers of the
default DeepSeek GraphTrainer recipe in `integration_tests.py`, covering
15 derived recipes. Existing integration tests exercise the fix. Other
recipe families already build with the required EP-enabled layout or
only change mesh degrees.

Validation:
- Local CPU configuration check (kept outside the PR): expert-weight
placement is incorrect in all 15 derived recipes before the fix and
correct in all 15 after it.
- The CPU check used isolated `torch==2.16.0.dev20261015+cpu`, with the
shared environment's incompatible optional CUDA-only `torchcomms`
package hidden from import. No model/sharding code was mocked.
- Ran `pre-commit run --all-files`: all hooks except Pyrefly pass;
Pyrefly reports 54 existing dependency/type errors outside this change.
Restored unrelated automatic edits. Scoped lint passes with Pyrefly
skipped.
- Full H100 training/numerics still needs CI; keep this draft until
verified. Earlier H100 runs also had separate bitwise-determinism
failures after the integration stage, so fixing these configurations
alone does not establish that the entire workflow is green.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/b200 Trigger B200 CI ciflow/docker ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants