Skip to content

Reorganize repo structure, dependencies, docs, and tests - #5277

Merged
tianyu-l merged 5 commits into
mainfrom
repo-structure-cleanup
Oct 11, 2026
Merged

tianyu-l merged 5 commits into
mainfrom
repo-structure-cleanup

Conversation

@tianyu-l

Copy link
Copy Markdown
Contributor

Why

The repo had grown organically: dependency lists had drifted (and two
requirements.txt files 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 main so follow-ups (e.g. the
generator.py / controller.py refactor) can be stacked on top with gh stack.

What changed

Dependencies and environment

  • pyproject.toml reads dependencies and extras ([dev], [rl], [vlm], [flux]) from the requirement files; per-folder requirements.txt files are symlinks (fixes broken kimi_k3/ and qwen3_5/requirements.txt).
  • torch_checkpointing is pinned to a git commit; PyPI 0.1.0 predates default_resharder.
  • New 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__.py has no side effects: no vLLM import, no env mutation (import 12.7 s -> 29 ms). Entry points apply env defaults before importing torch.
  • generate.py selects recipes with --module/--config, resolves relative hf_assets_path (it failed on every RL recipe before), and tears down vLLM's process groups on exit.
  • rl/types.py removed; each type lives in the module that creates it.
  • rubric.py and the envs move under rollout/ (message_env.py, token_env.py); distributed/actors/ -> distributed/monarch_actors/.
  • vLLM linear-attention backend renamed to family-neutral TorchTitanLinearAttention*, with shared hybrid-state helpers for GDN/KDA.
  • RL checkpoints download to ./assets/hf/ like pretraining.

Core

  • protocols/ -> models/base/ (abstract contracts); models/common/ keeps concrete components. models/utils.py split into models/common/{moe_state_dict_adapter,flops}.py.
  • hf_datasets/ merged into components/data/; validate.py -> validator.py (core and Flux).
  • Shared GDN/KDA code moves to attention/linear_attention.py and attention/cp_linear_attention.py; GDN and KDA no longer import each other.
  • Muse Glimmer renderer moves to models/muse_glimmer/.
  • Flux: flattened model/, folded configs.py, flux_datasets.py -> data.py; run_train.sh gains ENTRYPOINT= and replaces run_infer.sh; fixed default paths that pointed at the removed experiments/flux/.
  • The structured logger rejects an empty output_dir instead of writing into the launch directory; ConfigLoader no longer imports the RL controller.

Tests

  • Unit tests mirror the source tree; RL and TorchFT tests that lived in the core suite move to their own suites.
  • Integration suites keep their configurations next to their test definitions in tests/integration_tests/; one runner covers features, models, flux, h100, b200, rl, rl_kda, rl_b200 via per-config entrypoints. CI call sites updated.
  • test_override.py restores the global override registry (fixed order-dependent failures) and the workarounds other tests had for it are removed.

Docs and layout

  • README revamp. Convention: README.md per package for usage, UPPERCASE design notes next to the code. New distributed/README.md and PIPELINE_PARALLEL.md; converging.md, extension.md, composability.md folded into debugging.md, model READMEs, the config README, and code docstrings.
  • RELEASE.md at root, docs/benchmarks/, scripts/multinode_trainer.slurm, RL images under assets/images/.
  • CODEOWNERS aligned for recipes/tests/scripts; .claude rules updated to the current layout.

Numerics

Bitwise comparison of main vs this branch with scripts/loss_compare.py (seed 42, deterministic, full-precision TensorBoard loss and grad_norm, 20 steps, GB300):

Config GPUs Result
llama3_debugmodel 4 identical
kimi_k3_debugmodel_mm_muon (KDA), seeded from kimi_k3_debugmodel_mm 2 identical
qwen35_debugmodel_varlen_attn_fsdp2_tp2_sac (GDN) 4 identical in 4 of 5 runs; one run differed in the 7th digit with no code difference (run-to-run nondeterminism of this config on this hardware)

RL rl_kda suite: bit_wise/logprob_diff/max: 0 at every step.

Testing

  • pre-commit run --all-files clean; pyrefly 0 errors.
  • CPU unit tests (core + RL + TorchFT): all pass except pre-existing, platform-specific failures (see below).
  • GPU unit tests (1 and multi-GPU) and the GDN/KDA GPU tests pass except failures that reproduce on main.
  • E2E: Llama 3 debug pretraining (1 and 4 GPUs), RL rl_kda suite 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)

  • RL runs exit with code 134 at shutdown after all work completes (torchmonarch 0.7.0 PyO3 daemon thread + CPython 3.12 finalization).
  • aarch64 only: 4 CPU tests fail because Inductor's CPU flex_attention lowering is unsupported there.
  • GPU: test_rope_compile, two MXFP8 compile tests, and test_fsdp_moe_sharding fail on main too.

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.
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 11, 2026
@pytorch-bot pytorch-bot Bot added ciflow/b200 Trigger B200 CI ciflow/docker ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl labels Oct 11, 2026
…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 tianyu-l Oct 11, 2026 •

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 should be from leftover of #5250

agent: the fake-PG golden mismatch to #5250's intentional WGRAD accumulation change on main, which never surfaced because a stale SFT golden was blocking the models suite until this PR fixed it

#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.
Comment thread scripts/install_rl_env.sh
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 \

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.

Why cu130 here for FA3?

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.

will fix in next PR

@tianyu-l
tianyu-l merged commit 6f22255 into main Oct 11, 2026
@tianyu-l
tianyu-l deleted the repo-structure-cleanup branch October 11, 2026 18:23
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.
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