Repository navigation
[dist_moe] Add the TorchTitan backend adapter - #4541
Merged
Merged
Conversation
[ghstack-poisoned]
[ghstack-poisoned]
This was referenced Sep 9, 2026
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
This was referenced Sep 10, 2026
sanketpurandare
marked this pull request as ready for review
September 10, 2026 20:03
sanketpurandare
requested review from
fegin,
tianyu-l,
wconstab and
wwwjn
as code owners
September 10, 2026 20:03
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
tianyu-l
approved these changes
Oct 2, 2026
tianyu-l
left a comment
Contributor
There was a problem hiding this comment.
please address remaining comments
[ghstack-poisoned]
[ghstack-poisoned]
sanketpurandare
added a commit
that referenced
this pull request
Oct 2, 2026
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.18.0) (oldest at bottom): * #4543 * #4542 * #4541 * __->__ #4934 Summary: SimpleFSDP intentionally materializes a parameter on each property access, so tracing may produce duplicate annotated all-gather and post-gather preparation chains for one parameter. GraphTrainer already canonicalizes those chains before partitioning and FSDP extraction. Prefer an unshard endpoint that still has consumers when choosing the canonical chain. Dead-code elimination removes an unused preparation tail but retains its effectful collective; choosing that dead raw endpoint can otherwise replace a live prepared MXFP8 value with a BF16 gathered tensor. Remove dead duplicate chains without substituting their unused endpoints. This keeps SimpleFSDP functional and compiler-safe. It adds no module hooks, Python cache state, MXFP8 execution-mode branches, or changes to eager FSDP behavior. Test Plan: - The six focused FSDP unshard-deduplication and overlap tests pass on the current base. - The final changed-surface suite passes with 315 tests and 1 skip.
[ghstack-poisoned]
[ghstack-poisoned]
SherlockNoMad
added a commit
that referenced
this pull request
Oct 2, 2026
Rebased directly onto `main`; no longer depends on the `graph_builder.py` split (#5000), so all changes are in `graph_builder.py`. ## Why `_annotate_graph_pp_graph` wrote `graph_pp_stage_index`, `graph_pp_callable`, `graph_pp_action`, and `graph_pp_slot` into `node.meta` of every GraphPP and SPMD gradient-accumulation graph. It was added in #3089 ("GraphPP node metadata is annotated for TLParse and debugging"), but nothing ever consumed it: - **No reader anywhere.** `git log --all -S` for each key finds only the writers and a unit test asserting them; no reader existed at any point. Upstream PyTorch has no references either. - **TLParse never showed them.** TLParse graph dumps use `gm.print_readable()`, which only prints extra `node.meta` keys listed in `additional_meta` (`torch/fx/graph.py`). `trace_graph_pp_graph` passes none, and `debug_utils` only lists `autograd_backward` / `seq_nr`. ## What - Remove `_annotate_graph_pp_graph` and `_annotate_graph_pp_modules`. - Drop the `annotate_graph` parameter from `stage_builder._build_graph_pp_overlap_graphs`. - Rename `_annotate_and_compile_scheduled_fwd_bwd_graphs` -> `_compile_scheduled_fwd_bwd_graphs`. Compiled graph names (visible in TLParse) are unchanged. - Remove `test_graph_pp_node_metadata_is_annotated`, the only consumer of the keys. Net: -84 / +3. No behavior change. ## Tests - Before rebasing onto `main` (same change applied to the unsplit `graph_builder.py`): `test_graph_pp_runner.py`, `test_graph_pp_passes.py`, `test_trace_module.py` -> 161 passed, 3 skipped (one GPU-contention flake in `test_peak_memory_identical_fsdp` passed on rerun). - After rebasing onto `main`: pre-commit and pyflakes clean. Unit tests not re-run locally (current `main` needs a newer PyTorch than the local build for `WAIT_REDUCE_GRAD`); relying on CI. - Merges cleanly with Sanket's Dist-MoE stack (#4541, #4542, #4543), none of which use the removed annotation API.
sanketpurandare
commented
Oct 3, 2026
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
sanketpurandare
changed the base branch from
gh/sanketpurandare/17/base
to
main
October 3, 2026 13:22
submartingales
pushed a commit
to botcanlearn/torchtitan-upstream
that referenced
this pull request
Oct 3, 2026
Summary: Integrate the optional standalone Dist-MoE package as a BF16 or asynchronous MXFP8 routed-expert backend while retaining TorchTitan ownership of routing, W13/W2 parameters, FSDP, optimizer state, checkpoints, and pipeline policy. One precision-selecting model transform replaces stock routed experts and conflicts with LoRA and token-dispatcher transforms whose forward semantics it bypasses. Common TorchTitan and GraphTrainer imports do not require Dist-MoE; the optional Configurable.Config field builds a concrete runtime only when a recipe selects the package. Forward/backward initialization supplies materialized model parts, topology, the PP liveness schedule, and a narrow context setter. DistMoeRuntime owns slot coloring, Annex context creation, eager or GraphPP registration, module attachment, and idempotent close. Trainer closes a partially initialized engine when engine.initialize() fails before config.build() can return it. GraphPP uses an explicit immutable slot input and lazily imports exact registered operator schemas only for Dist-MoE tracing. MXFP8 experts reuse TorchTitan's prepared-weight FSDP lifecycle. Eager Dist-MoE resolves WGrad storage from the live parameter; GraphTrainer supplies BF16 for its functional WGrad graph. Eager/common adapter tests and GraphTrainer adapter tests live in separate owner-specific files. Recipe and B200 coverage belongs to the stacked recipe integration PR. Test Plan: - 23 focused eager/common and GraphTrainer-owned adapter CPU tests pass. - Focused GraphPP runner slot-input and runtime registration tests pass. - Changed-file formatting, lint, docstring, spelling, and link hooks pass. - Pyrefly reports only existing current-main findings outside this stack. ghstack-source-id: ee2a87e Pull Request resolved: pytorch/torchtitan#4541
SherlockNoMad
added a commit
that referenced
this pull request
Oct 5, 2026
Regenerated on current `main` (the earlier version predated #4999, #5001, #5003, #5035, #5038 and the Dist-MoE adapter #4541, which all touched `graph_builder.py`). ## Why `graph_builder.py` had grown to ~2650 lines mixing the stage-graph provider, shared helpers, SPMD graph construction (with and without gradient accumulation), and PP stage graph construction. Splitting it along the execution paths (SPMD / PP) makes each path readable on its own. ## What | File | Contents | |---|---| | `graph_builder.py` (~290 lines) | `GraphExecutionPlan`, placement types, `GraphTrainerStageGraphProvider`, the provider's Dist-MoE slot lookup | | `graph_builder_utils.py` (~310) | `GraphTrainerConfigView`, FSDP bucketing helpers, graph execute/pack/compile helpers shared by both paths | | `spmd_graph_builder.py` (~360) | joint-graph tracing shared by both SPMD paths; SPMD without gradient accumulation executor and builder | | `spmd_gradient_accumulation_graph_builder.py` (~810) | SPMD with gradient accumulation: first / middle / last graphs, their executor, accumulation, edge-graph bucketing | | `graph_pp/pp_graph_builder.py` (~1020) | PP stage graphs, partitioning, overlap graphs, the Dist-MoE activation-slot rewrite used by PP stages | **Pure code move.** All 45 top-level definitions are AST-identical to `main` (checked by script), except: - `spmd_graph_builder.py` imports `GraphExecutionPlan` under `TYPE_CHECKING` and quotes its annotations, to avoid an import cycle with `graph_builder.py`. - Each file has only the imports it uses, its own `logger`, and keeps `graph_builder.py`'s `from __future__ import annotations` (needed for the `TYPE_CHECKING`-only Dist-MoE annotations). Callers (`pipeline.py`, `precompile_main.py`, tests) and `mock.patch` targets are updated to the new modules. **Second commit** moves the SPMD gradient-accumulation code out of `spmd_graph_builder.py` (it was ~70% of that file), so the simple SPMD path reads on its own. The only non-move change is the dispatch: `_build_fwd_bwd_graphs` used to trace and then branch on `plan.has_gradient_accumulation`; its tracing becomes `_trace_spmd_stage_graph` (shared), `_build_fwd_bwd_graphs` builds only SPMD without gradient accumulation, the new `_build_gradient_accumulation_fwd_bwd_graphs` builds the GA path, and `GraphTrainerStageGraphProvider` picks between them as it already does for PP. The new module imports from `spmd_graph_builder.py`, not the reverse. ## Tests - `test_graph_pp_runner.py`, `test_graph_pp_passes.py`, `test_trace_module.py`: 169 passed, 4 skipped, 2 failed. Both failures reproduce on unmodified `main`: - `test_dist_moe_slot_is_an_explicit_stage_graph_input`: `dist_moe` package not installed locally. - `test_initializes_one_stage_pipeline_runtime`: its `SimpleNamespace` config lacks the new `dist_moe` field read at `trainer.py:108`. - Bitwise-identical loss and grad_norm vs. `main`, 10 steps, `seed=42`, `deterministic=True` (`scripts/loss_compare.py --assert-equal`): SPMD GA first/last (FSDP=4), SPMD GA without FSDP (1 GPU), SPMD without GA (FSDP=4). - `precompile_main` / `trainer` import check passes. - pre-commit clean.
wwwjn
added a commit
that referenced
this pull request
Oct 6, 2026
## Why RL CPU Unit Tests is red on `main` and on every PR that runs it. Four test modules fail at collection: ``` ERROR tests/rl/unit_tests/cpu/test_alphabet_sort.py ERROR tests/rl/unit_tests/cpu/test_verifiers_example.py ERROR tests/rl/unit_tests/cpu/test_vllm_registry.py ERROR tests/rl/unit_tests/cpu/test_vllm_wrapper.py E ImportError: cannot import name 'analyze_pipeline_activation_liveness' from 'torch.distributed.pipelining' ``` The cause is the torch the job ends up with. The CPU job resolves `torch 2.15.0.dev20260830` + `vllm 1.0.0.dev20260830`, while the RL GPU jobs in the same run get `20261005` for both. The CPU job installs the Verifiers example requirements first and then passes them as a `--constraint` to the nightly install: - `verifiers==0.3.1` requires `mcp>=1.24.0,<2`. - vLLM nightlies since about 2026-10-01 require `mcp>=2.0.0,<3.0.0`. uv therefore falls back to the newest vLLM that accepts mcp 1.x (`1.0.0.dev20260830`), which pins a torch from the same day. That torch predates `analyze_pipeline_activation_liveness`, which `dist_moe` started importing in #4541. To reproduce, force a current vLLM next to the Verifiers requirements: ``` $ uv pip compile in.txt --prerelease allow ... # vllm>=1.0.0.dev20261001, verifiers==0.3.1 × No solution found when resolving dependencies: ╰─▶ Because vllm>=1.0.0.dev20261001+cu132 depends on mcp>=2.0.0,<3.0.0 [...] And because you require mcp>=1.24.0,<2, we can conclude that your requirements are unsatisfiable. ``` ## What - Install torch/torchvision/vLLM nightlies the same way the RL GPU jobs do (no Verifiers constraint), then run the CPU suite. The plain DAPO example requirements (`torchtitan/rl/examples/dapo_math/requirements.txt`, i.e. `math-verify==0.9.0` for `test_dapo_math.py`) are still installed first and passed as a constraint. They resolve fine with the current nightlies. - After that, install the Verifiers requirements with the installed torch/torchvision/vLLM versions as constraints, and run `test_verifiers.py` and `test_verifiers_example.py`. Verifiers only changes its own dependencies: uv swaps `mcp` 2.x -> 1.30.0 and `websockets` 17.1 -> 16.1.1 and leaves the nightlies alone. - Add `pytest.importorskip("verifiers")` to `test_verifiers.py`, the same guard `test_verifiers_example.py` already has, so the first run skips it instead of failing at collection. - Drop the `mcp>=1.24.0,<2` line from `dapo_math/requirements.txt`. It only existed to constrain the nightly install, and `verifiers==0.3.1` already requires the same bound. ## Tests Run locally with torch `2.15.0.dev20260926` and vLLM `1.0.0.dev20260926` (mcp 2.2.0): - First run, without Verifiers: `pytest tests/rl/unit_tests/cpu` gives 474 passed, 6 skipped. That includes the three non-Verifiers modules above; both Verifiers files skip with "could not import 'verifiers'". - Second run, with `verifiers==0.3.1` installed on top: `test_verifiers.py` and `test_verifiers_example.py` give 11 passed, and vLLM still imports with mcp 1.30.0. - Dry run of the new `uv pip install -r .../requirements.txt --constraint <nightly pins>` against that env: it installs 19 packages, changes only `mcp` and `websockets`, and leaves torch/torchvision/vLLM untouched. - `uv pip compile` of the nightlies plus `math-verify==0.9.0` resolves to torch/vLLM `20261005`. - CI on the first commit picked up torch/vLLM `20261005`, but `test_dapo_math.py` failed to collect because `math_verify` was missing. That's fixed by the DAPO requirements step above. ## Follow-up Outside CI, the Verifiers example still can't share an environment with current vLLM nightlies, since `verifiers==0.3.1` needs `mcp<2`. The `verifiers` 0.3.2 dev releases move to `mcp==2.0.0`, but they also require `renderers>=0.1.12.dev2`, while torchtitan pins `renderers==0.1.11`. Bumping `verifiers` makes sense once a 0.3.2 release is out.
wwwjn
added a commit
that referenced
this pull request
Oct 10, 2026
Follow-up to #4541 (generator side). Lets a vLLM generator run Dist-MoE experts with `DistMoeRuntime.Config(inference=True)`, and routes padding rows to expert `-1` in both the trainer and the generator. Builds on the bounded per-call token counts from #5085 and needs a `dist_moe` that ignores `-1` routes. ## Why - Dist-MoE experts refuse to run without a runtime, and vLLM constructs `VLLMModelWrapper` itself, so nothing builds one for a generator. `DistMoeRuntime` plans for training (PP activation slots, weight gradients); a generator runs no backward and no pipeline. - Both roles feed Dist-MoE padding rows: vLLM pads each step (TP rounding, CUDA-graph capture size, DP equalization), and the RL batcher and pretraining packer pad microbatches. Dist-MoE cannot tell a padding row from a real one, so without a mask every padding row is dispatched, computed and combined like a real token. - Every EP rank must pass Dist-MoE the same row count per call. Padding every inference call to the planned maximum made a decode step run as many rows as the largest step (measured in the previous revision: about 71 ms per decode step, against 20 to 23 ms when padding only to the EP-group maximum). ## What - **Inference runtime.** `DistMoeRuntime.Config` gains `inference: bool = False`, passed to `dist_moe`, which then plans scratch only (no activation slots). The wrapper builds it after parallelize and before CUDA-graph capture, with `pp_schedule=None`, sized from vLLM's `max_num_batched_tokens`, and rejects a config without `inference=True`. Plumbed through `register_to_vllm` and the generator config as `dist_moe_runtime`. - **Padding rows go nowhere.** `DistMoeRoutedExperts` sets expert ID `-1` and score `0` on rows marked in `padding_mask`, in training and inference. Dist-MoE never dispatches a `-1` route, so padding costs no communication or expert GEMM work and its output rows are zero. `MoE.forward`, and `KimiLatentMoE.forward` (which overrides it to wrap the experts in latent projections), hand their TP-sharded mask to experts that set `uses_padding_mask`. - Generator: the runner publishes the unpadded token count into a device scalar before vLLM pads the step (`_determine_batch_execution_and_padding`); the wrapper builds `padding_mask` from it inside `forward`, so CUDA-graph replay sees the current count. - Trainer: the existing `padding_mask` from the RL batcher or the pretraining packer already reaches every MoE block; training passes its microbatch row count unchanged (every EP rank runs the same shape). - With a Python-callback post-expert postprocess, `zero_out_padded_callback_inputs` is set so the callback never reads stale rows of `-1` routes. - **Per-step call size in inference.** Each call carries the largest TP-local token count across vLLM DP replicas (`dp_metadata.num_tokens_across_dp_cpu`), padded with `-1` rows. Graph steps already share the capture size; eager steps do not. Without DP metadata and with DP > 1, calls pad to the planned maximum. - **Fused postprocess in the generator (optional, can be removed).** The last commit, `[dist_moe] Use a module's fused postprocess in the generator`, lets an inference context take the postprocess module's `to_dist_moe_inference_postprocess(input_dtype)` when it defines one, and otherwise keeps `to_dist_moe_postprocess()`. A route-wise callable makes Dist-MoE execute eagerly, so a generator that captures CUDA graphs needs a fused `RMSNormPostprocess`; this lets a trainable post-expert norm keep its callable form in training (its gamma gets gradients) and use the fused form in the generator. No model in this repo defines the hook yet, so the commit can be dropped without affecting anything here. - **Batch-invariant mode** (`debug.batch_invariant`). Two `dist_moe` choices depend on the call size: the post-expert top-k reduction uses another, equally correct, accumulation order at or below 128 rows, and the BF16 expert-GEMM schedule is picked from the call size. In batch-invariant mode, inference calls are raised above 128 rows and an inference context without an explicit preset uses `2cta2mma_bm512_bn256`, so a token's output does not depend on how many tokens share its step. Outside batch-invariant mode both keep the size-tuned defaults. ## RL integration test Recipe `rl_grpo_moe_debug_dist_moe_tp2_ep4` (`torchtitan_recipes/tests/rl.py`): trainer FSDP=2 x TP=2 with EP=4 and one generator with vLLM DP=2 x TP=2 and EP=4 on the Qwen3 debug MoE model, generator `FULL_DECODE_ONLY` graphs, scratch factor equal to the EP size. The two generator replicas hold different token counts, so uneven per-step call sizes and padding run. The recipe applies `DistMoeTransform` through `apply_transforms`. `build_b200_rl_test_list()` in `tests/rl/integration_tests/rl.py` is the B200 suite (`--test_suite b200`): the existing Kimi K3 KDA test (the `kda` suite stays for the H100 workflow) plus this test. `.github/workflows/integration_test_rl_b200.yaml` is one job: one environment that also installs `dist_moe`; one unit-test step (Kimi K3 bitwise parity plus the Dist-MoE unit tests, which the CPU workflow skips because it does not install `dist_moe`); one integration step running the `b200` suite, which still runs if the unit tests fail. Timeout 60 -> 90 minutes. ## Tested - **RL with Dist-MoE in both the trainer and the generator, GB300.** GRPO on DAPO-Math with real weights of a large MoE model and the same padding and call-size logic: trainer FSDP 32 x TP 4 x EP 4 (128 GPUs, fp32 master weights, bf16 forward), generator vLLM DP 4 x TP 4 x EP 16 (16 GPUs, FULL CUDA graphs), on-policy so the logprob diff compares the two roles under the same weights. All 5 steps completed: | Step | 1 | 2 | 3 | 4 | 5 | |---|---|---|---|---|---| | logprob diff mean (trainer - generator) | -0.0013 | -0.0015 | -0.0014 | -0.0012 | -0.0012 | | logprob diff max | 1.02 | 3.07 | 1.92 | 1.73 | 1.23 | | reward mean | 0.875 | 0.609 | 0.828 | 0.969 | 0.859 | | grad norm | 0.0 | 8.06 | 0.35 | 0.63 | 1.71 | | train-batch padding | 60% | 10% | 18% | 30% | 48% | Step 1 had zero reward variance in every group, so its gradient is zero. The two roles run different Dist-MoE kernels, so the diff is small but not zero. No scratch overflow or non-finite values in either role. - CPU: the new tests cover `-1` routing at the call size, training keeping its row count, callback zeroing, per-call size bounds, the batch-invariant floor and GEMM schedule, the wrapper's mask and per-step size from DP metadata, the runner hook, `MoE.forward` and `KimiLatentMoE.forward` handing the mask only to opt-in experts, the fused inference postprocess, and the recipe and suite. Rebased on `main` with #5085: `test_dist_moe.py`, `test_vllm_dist_moe_padding_mask.py`, `test_rl_dist_moe_recipe.py` and `test_moe.py` give 82 passed, 3 skipped; `test_dist_moe_671b_recipe_topology[deepseek_v3_671b_dist_moe_mxfp8-64-240]` fails identically on `main` in my environment (needs a `torchao` nightly). Generator tests also pass without `dist_moe` installed. - pre-commit passes on the changed files. - GB300 inference, real weights of a large MoE model, greedy decoding on AIME 2025, vLLM DP=4 x TP=4 x EP=16 with FULL CUDA graphs, one sequence per DP replica (4 prompts): - Default path (per-step call size, auto GEMM schedule): coherent, 3/4 correct. It first differs from the previous pad-to-maximum path (4/4) by about 1e-5 in logprob at the first decode step; the cause is the small-call reduction order above, not padding. - Batch-invariant settings (calls above 128 rows, fixed GEMM schedule): tokens and logprobs bitwise identical to the previous path under the same schedule on 4/4 prompts (up to 1823 tokens), 4/4 correct. - Reruns of the same code are bitwise identical. The standard all-to-all MoE backend gives the same answers but not identical tokens. - 30 prompts with FULL graphs (capture sizes up to 512, and up to 64), with calls raised above 128 rows: completed without errors.
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.
Stack from ghstack (oldest at bottom):
I reviewed this integration against the standalone Dist-MoE API, TorchTitan's
current model-transform and FSDP contracts, eager pipeline execution, GraphPP
tracing, and the recorded local distributed validation.