Skip to content

[dist_moe] Add the TorchTitan backend adapter - #4541

Merged
sanketpurandare merged 107 commits into
mainfrom
gh/sanketpurandare/17/head
Oct 3, 2026
Merged

sanketpurandare merged 107 commits into
mainfrom
gh/sanketpurandare/17/head

Conversation

@sanketpurandare

@sanketpurandare sanketpurandare commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

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.

The following technical description was prepared with Codex assistance and reviewed before posting.

Summary

Integrate the standalone dist-moe
package as an optional routed-expert backend for BF16 and asynchronous MXFP8
training on NVIDIA SM100-or-newer GPUs.

TorchTitan owns routing, structured W13/W2 parameters, optimizer and
checkpoint state, FSDP, model transforms, pipeline policy, and the training
lifecycle. Dist-MoE owns dispatch through combine, grouped expert kernels,
communication buffers, saved activations, device scratch, optional VMM
overflow scratch, and its device-side save/recompute policy. PyTorch
pipelining owns stage/microbatch metadata and schedule-derived liveness.

Optional dependency boundary

Ordinary TorchTitan and GraphTrainer imports do not import or install
Dist-MoE. TrainingEngine.Config.dist_moe is a
Configurable.Config | None; None is the only disabled state, so there is
no duplicate enable flag. A selected recipe performs a guarded import and
supplies DistMoeRuntime.Config. Base requirements intentionally do not
install this Blackwell-only package.

The built object is retained as an exactly typed optional runtime through a
TYPE_CHECKING-only import. Dist-MoE operator handles used by GraphPP are
loaded lazily only when a Dist-MoE graph is traced.

Routed-expert transform

One DistMoeTransform(expert_precision="bf16" | "mxfp8") replaces each stock
RoutedExperts.Config directly. The source uses stock GroupedLinear W13/W2,
SwiGLU, and all-to-all dispatcher configs. The replacement retains:

  • w13.weight: [E, 2, F, D]
  • w2.weight: [E, D, F]

Dist-MoE owns dispatch, activation, expert compute, and combine, so the
transform conflicts with LoRA and TokenDispatcherTransform. Dense MXFP8
Linear conversion remains an independent recipe choice.

Optional expert output postprocessing remains a normal TorchTitan module with
optimizer, checkpoint, FSDP, autograd, and tracing ownership. The adapter
binds its live parameter into the Annex descriptor executed after W2 and
before score-weighted combine.

Runtime lifecycle and memory

Runtime construction is the first forward/backward-initialization phase,
after model materialization and before tracing or CUDA-graph capture. The
standard or graph engine supplies final model parts, topology, the liveness
schedule, and a narrow context-registration capability. DistMoeRuntime
owns expert discovery, EP group resolution, token capacity, slot coloring,
Annex context creation, eager/GraphPP registration, handles, partial-failure
unwind, module attachment, and idempotent close.

TrainingEngine does not own Dist-MoE hook handles or inspect Annex memory.
Runtime configuration separates device scratch, per-live-slot saved
activations, optional host-backed VMM scratch, and PP slot granularity.

Eager PP and GraphPP

Eager PP uses PyTorch's registered stage-forward context and a deterministic
(stage, microbatch) -> activation slot mapping. GraphPP uses the same
resolver but supplies an immutable activation_slot_id_1 graph input. The
graph builder lazily imports exact registered operators, resolves the slot
operand from each schema, and performs no string target matching.

FSDP and WGrad

BF16 experts use ordinary FSDP ownership. MXFP8 experts reuse TorchTitan's
prepared-weight post-all-gather lifecycle for 32x32 qdata and FPROP/DGRAD
scales. Prepared storage follows the normal reshard boundary.

The integration currently emits WGrad in the BF16 unsharded compute-parameter
dtype. FSDP independently casts to mixed_precision_reduce before
reduce-scatter. A TODO records future Annex parameter.grad_dtype support.
#4541 defaults to functional WGrad; #4542 enables eager in-place accumulation
and keeps GraphTrainer functional.

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.

Scope

This PR integrates training. Annex supports inference execution, but
TorchTitan does not yet provide an inference runtime owner. The PR does not
copy kernels, expose allocator internals, add optimizer/checkpoint branches,
or enable VMM tests on a personal development host.

Verification

  • 25 focused eager/common and GraphTrainer-owned adapter/GraphPP CPU tests
    pass at the [dist_moe] Add the TorchTitan backend adapter #4541 commit boundary.
  • The final stacked affected CPU suite passes 136 tests.
  • Focused GraphPP runner slot-input and runtime registration tests pass.
  • The stack is semantically rebased onto current TorchTitan main and retains
    [2/2] [graph_trainer] PP=1 GA schedule with FSDP overlap #4927's GraphTrainer gradient-accumulation state and execution modes.
  • Common modules import with dist_moe blocked; selecting a Dist-MoE recipe
    raises the focused optional-package diagnostic.
  • Formatting, Flake8, pydoclint, codespell, AST, merge-conflict, and link
    checks pass.
  • Pyrefly reports no error in the new integration files. Its configured
    project check reproduces only the current-main _set_lru_cache and PyAV
    nullability findings outside this stack.

[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]

@tianyu-l tianyu-l 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.

please address remaining comments

Comment thread torchtitan/training_engine.py Resolved
Comment thread torchtitan/training_engine.py Resolved
[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.
Comment thread torchtitan/training_engine.py Resolved
Comment thread torchtitan/training_engine.py Resolved
Comment thread torchtitan/training_engine.py Resolved
[ghstack-poisoned]
[ghstack-poisoned]
[ghstack-poisoned]
@sanketpurandare sanketpurandare added the ciflow/b200 Trigger B200 CI label Oct 3, 2026
@sanketpurandare
sanketpurandare changed the base branch from gh/sanketpurandare/17/base to main October 3, 2026 13:22
@sanketpurandare
sanketpurandare merged commit a5e1af3 into main Oct 3, 2026
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.
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