Repository navigation
Reorganize repo structure, dependencies, docs, and tests - #5277
Merged
Merged
Conversation
Repo-wide cleanup for discoverability and correctness. No intended change to
training numerics; pure moves/renames plus a few bug fixes found on the way.
Dependencies and environment
- pyproject reads dependencies/extras ([dev], [rl], [vlm], [flux]) from the
requirement files; per-folder requirements are symlinks (fixes broken
kimi_k3/qwen3_5 requirements.txt).
- Pin torch_checkpointing to a git commit (PyPI 0.1.0 predates
default_resharder).
- Add scripts/install_rl_env.sh and use it in the RL README and workflows.
RL
- torchtitan.rl no longer imports vLLM or mutates env vars on import
(12.7s -> 29ms); entry points apply env defaults before importing torch.
- generate.py selects recipes with --module/--config, resolves relative
hf_assets_path, and tears down vLLM's process groups on exit.
- Remove rl/types.py: types live in the modules that create them.
- rubric/env modules move under rollout/; distributed/actors ->
distributed/monarch_actors; vLLM linear attention backend renamed to
family-neutral names with shared hybrid-state helpers.
- RL checkpoints download to ./assets/hf like pretraining.
Core
- protocols/ -> models/base/; models/utils.py split into
models/common/{moe_state_dict_adapter,flops}.py.
- hf_datasets/ merged into components/data/; validate.py -> validator.py.
- Shared GDN/KDA pieces move to attention/{,cp_}linear_attention.py.
- Muse Glimmer renderer moves to models/muse_glimmer/.
- Flux: flatten model/, fold configs.py, data.py, run_train.sh ENTRYPOINT
replaces run_infer.sh; fix stale experiments/flux default paths.
- Structured logger rejects an empty output_dir instead of writing to cwd.
- ConfigLoader no longer imports the RL Controller.
Tests
- Unit tests mirror the source tree; RL/TorchFT tests move to their suites.
- Integration suites keep configs next to their definitions in
tests/integration_tests/; one runner covers features, models, flux, h100,
b200, rl, rl_kda, rl_b200 (per-config entrypoints).
- test_override restores the global override registry (fixes order-dependent
failures) and drops the workarounds other tests had for it.
Docs and repo layout
- README revamp; package READMEs plus co-located UPPERCASE design notes;
new distributed/README.md and PIPELINE_PARALLEL.md; converging/extension/
composability docs folded into debugging.md, model READMEs, and code.
- RELEASE.md at root, benchmarks under docs/, Slurm script under scripts/,
RL images under assets/images/.
- CODEOWNERS aligned for recipes/tests/scripts; agent rules updated.
tianyu-l
requested review from
IvanKobzarev,
SherlockNoMad,
aditvenk,
fegin,
felipemello1,
pzhan9,
sanketpurandare,
wconstab and
wwwjn
as code owners
October 11, 2026 05:54
…M wrapper - run_tests.py imported every suite module at load time, so jobs without the flux (transformers) or RL (vLLM, Monarch) dependencies failed on import, including GraphTrainer B200 and B200 Integration. - The vLLM generator validates the trainer's model-config local_compile_regions, which may name the 'loss' region registered by torchtitan.components.loss. It used to be imported only incidentally via rl/types.py -> components.data; import it explicitly.
After a successful run the RL controller sometimes aborted with exit 134
("FATAL: exception not rethrown"): before CPython 3.14, finalization ends
Monarch's daemon sync-actor threads with pthread_exit while they are inside
PyO3 calls, and PyO3 swallowing the forced unwind aborts the process. The
controller now shuts down the Monarch client explicitly (normally an atexit
hook), flushes logging and stdio, and exits with os._exit(0). Errors still
take the normal exit path.
#5250 (in-place WGRAD accumulation for the bf16 Linear) changes gradient accumulation order, which moves SFT grad_norm from the 5th significant digit (step-1 loss is unchanged). Its fake-PG run failed on this golden and the job does not run on main pushes, so every PR since fails it with identical values. Values are the A10G baseline from CI.
tianyu-l
commented
Oct 11, 2026
Contributor
Author
#5250 changed numerics and regenerated the real-PG goldens but not the fake-PG ones. The fake-PG models suite never ran afterwards because the SFT golden failed first; with that fixed, the stale model goldens surface. Values are the baselines printed by the a10g fake-PG CI run.
wwwjn
approved these changes
Oct 11, 2026
| case "$version" in | ||
| 4) uv pip install "flash-attn-4[cu13]>=4.0.0b34" ;; | ||
| 3) uv pip install flash-attn-3 \ | ||
| --extra-index-url https://download.pytorch.org/whl/test/cu130 \ |
Contributor
Author
There was a problem hiding this comment.
will fix in next PR
SherlockNoMad
approved these changes
Oct 11, 2026
aditvenk
approved these changes
Oct 11, 2026
tianyu-l
added a commit
that referenced
this pull request
Oct 11, 2026
…#5280) ## 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. #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 #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 #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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Why
The repo had grown organically: dependency lists had drifted (and two
requirements.txtfiles could not be installed),import torchtitan.rl.<anything>pulled in vLLM (12.7 s), tests and docs were hard to navigate, and several
modules lived far from what they belong to. This PR reorganizes the tree so
each piece lives with its owner, without intended changes to training numerics.
It is a single bottom-of-stack PR against
mainso follow-ups (e.g. thegenerator.py/controller.pyrefactor) can be stacked on top withgh stack.What changed
Dependencies and environment
pyproject.tomlreads dependencies and extras ([dev],[rl],[vlm],[flux]) from the requirement files; per-folderrequirements.txtfiles are symlinks (fixes brokenkimi_k3/andqwen3_5/requirements.txt).torch_checkpointingis pinned to a git commit; PyPI 0.1.0 predatesdefault_resharder.scripts/install_rl_env.sh(nightlies, git-main deps, FlashAttention per GPU); the RL README and all RL workflows use it.RL
torchtitan/rl/__init__.pyhas no side effects: no vLLM import, no env mutation (import 12.7 s -> 29 ms). Entry points apply env defaults before importing torch.generate.pyselects recipes with--module/--config, resolves relativehf_assets_path(it failed on every RL recipe before), and tears down vLLM's process groups on exit.rl/types.pyremoved; each type lives in the module that creates it.rubric.pyand the envs move underrollout/(message_env.py,token_env.py);distributed/actors/->distributed/monarch_actors/.TorchTitanLinearAttention*, with shared hybrid-state helpers for GDN/KDA../assets/hf/like pretraining.Core
protocols/->models/base/(abstract contracts);models/common/keeps concrete components.models/utils.pysplit intomodels/common/{moe_state_dict_adapter,flops}.py.hf_datasets/merged intocomponents/data/;validate.py->validator.py(core and Flux).attention/linear_attention.pyandattention/cp_linear_attention.py; GDN and KDA no longer import each other.models/muse_glimmer/.model/, foldedconfigs.py,flux_datasets.py->data.py;run_train.shgainsENTRYPOINT=and replacesrun_infer.sh; fixed default paths that pointed at the removedexperiments/flux/.output_dirinstead of writing into the launch directory;ConfigLoaderno longer imports the RL controller.Tests
tests/integration_tests/; one runner coversfeatures,models,flux,h100,b200,rl,rl_kda,rl_b200via per-config entrypoints. CI call sites updated.test_override.pyrestores the global override registry (fixed order-dependent failures) and the workarounds other tests had for it are removed.Docs and layout
README.mdper package for usage, UPPERCASE design notes next to the code. Newdistributed/README.mdandPIPELINE_PARALLEL.md;converging.md,extension.md,composability.mdfolded intodebugging.md, model READMEs, the config README, and code docstrings.RELEASE.mdat root,docs/benchmarks/,scripts/multinode_trainer.slurm, RL images underassets/images/..clauderules updated to the current layout.Numerics
Bitwise comparison of
mainvs this branch withscripts/loss_compare.py(seed 42, deterministic, full-precision TensorBoard loss and grad_norm, 20 steps, GB300):llama3_debugmodelkimi_k3_debugmodel_mm_muon(KDA), seeded fromkimi_k3_debugmodel_mmqwen35_debugmodel_varlen_attn_fsdp2_tp2_sac(GDN)RL
rl_kdasuite:bit_wise/logprob_diff/max: 0at every step.Testing
pre-commit run --all-filesclean; pyrefly 0 errors.main.rl_kdasuite through the unified runner, standalone vLLM generation with real Qwen3-0.6B weights, all suites build with unchanged test counts.Known issues (all reproduce on
main)torchmonarch0.7.0 PyO3 daemon thread + CPython 3.12 finalization).flex_attentionlowering is unsupported there.test_rope_compile, two MXFP8 compile tests, andtest_fsdp_moe_shardingfail onmaintoo.