Repository navigation
Build sharded model configs; separate RL trainer and generator models - #5280
Conversation
| from torchtitan.rl.distributed.parallelism import InferenceParallelismConfig | ||
|
|
||
|
|
||
| def build_rl_model_configs( |
There was a problem hiding this comment.
@felipemello1 this could be the central entry for RL models, where we can apply lm_head fp32 transform, router freezing, etc. Wdyt?
There was a problem hiding this comment.
But the transform is not applied here today, it's in each config recipe: https://github.com/pytorch/torchtitan/blob/c4ed6e15c71a8e4acdf3d521f934a3087d1a6ab9/torchtitan_recipes/rl/search_r1.py#L320C5-L320C11
Should we remove apply_transforms into this function?
There was a problem hiding this comment.
This function is about transforms that every rl model need. So yeah fp32 lm head, router freezing goes here.
ee7c954 to
2ee95ab
Compare
…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.
2ee95ab to
c4ed6e1
Compare
wwwjn
left a comment
There was a problem hiding this comment.
The idea looks good, approve to unblock
… 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.
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:SharedExpertRowParallelLinearexisted only because the shared-expert output layout (TP-Partial vs. reduced) could not be fixed at build time.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;parallelismis required so a model config cannot be built without choosing its layout. Each component gets itssharding_configwhere it is constructed; the sharedmake_*factories takeenable_sp/enable_ep. Sequence and expert parallelism are the only settings that change declared layouts; mesh degrees are still resolved at runtime.BaseModel.Config.set_sharding_(), the per-modelset_*_sharding_configwalkers,decoder_sharding.set_*/moe_sharding.set_*/set_vision_transformer_block_sharding_config, and the runtime re-shard in the trainers and the vLLM wrapper. Modelsharding.pyfiles now hold pure constructors returningShardingConfig/SpmdType(deleted for llama3 and qwen3, which need none beyondcommon/).SharedExpertRowParallelLinearis removed: the shared-expertw2is chosen at construction -- aRowParallelLinear(reduce-scatter) with SP, and a plainLinearthat keeps its TP-Partial output without SP, so the MoE reduces routed + shared once.RowParallelLinearis unchanged and transforms such as async TP apply as-is.apply_transformsnever re-derives sharding.RL: one model config per role
Controller.Config.modelis removed;Trainer.Config.modelandVLLMGenerator.Config.modelreplace it, each built for that role's parallelism (build_rl_model_configsbuilds both from one call). The controller requires the same model class; keeping them otherwise aligned is the recipe's job.apply_transforms(config.generator, [TokenDispatcherTransform(DeepEPTokenDispatcher, num_max_tokens_per_rank=..., kwargs={"cuda_graph_compatible": True})]).ModelConfigTransformContextis removed) andapply_transformsworks on any config that owns amodel.TokenDispatcherTransformtakes the EP buffer capacity explicitly: a trainer passes its microbatch / (CP x TP), the generator its per-step token budget / TP.overridemoves fromTrainingEngine.Configto the top-level configs: coreTrainer.Config.overrideand a newController.Config.override, applied to the whole RL tree (both models) before actors spawn.VLLMGenerator.Config.overrideandmoe_token_dispatcher.pyare removed. The CLI--overrideextends the top-level config'soverride.Recipes
parallelism=keyword; derived recipes that only change degrees are unchanged.Cleanups
*_sharding_config(e.g.sharding_config=router_gate_sharding_config()), so call sites do not read like module configs._restore_sharded_params/_unshard_and_free_sharded_params(matching the upstream APIs they stand in for).scripts/install_rl_env.shinstalls FA3 from the samenightly/${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_7andmuse_glimmerbuild_model_configdropped a converter's returned root config (now covered for every model bytest_build_model_config.py).Behavior changes
fused_swigluperf override now set it onController.Config.override, so it applies to both RL models (previously the DeepEP perf recipes applied it to the generator only).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_configand parameter initializer.Bitwise comparison against #5277 with
scripts/loss_compare.py(seed 42, deterministic,--metrics loss,grad_norm --assert-equal, 20 steps, 4x GB300):Linearshared-expertw2)kimi_k3_mm_muon)kimi_k3_debugmodel_mmBeyond loss runs, every recipe in
torchtitan_recipesand 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 afterset_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-filesclean (pyrefly 0 errors).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).torchtitan_recipesand 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.