Skip to content

[dist_moe] Add DistMoE for the vLLM generator inference path - #5046

Merged
wwwjn merged 8 commits into
pytorch:mainfrom
wwwjn:jianiw/distmoe-inference-main
Oct 10, 2026
Merged

wwwjn merged 8 commits into
pytorch:mainfrom
wwwjn:jianiw/distmoe-inference-main

Conversation

@wwwjn

@wwwjn wwwjn commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

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 [dist_moe] Use bounded token capacity API #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.

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Oct 3, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 3, 2026
@wwwjn
wwwjn force-pushed the jianiw/distmoe-inference-main branch from b334763 to b2d0ba9 Compare October 3, 2026 19:41
disables VMM.
"""

scratch_capacity_factor: float = 1.0

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.

Tried my best but need to double check the understanding of the scratch and whether this 1.0 is a good default.

@sanketpurandare sanketpurandare Oct 4, 2026 •

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.

1.0 is a good default only for forced balanced routing or if you are backing your scratch by VMM. scratch_capacity_factor tells you what is the imbalance upper bound you want to support. Its range is from 1.0 -> ep_size * min(num_local_experts, k)/ k where k is your top-k. I would set 4.0 as deafult but IMO one should always set their own default since its dataset and model dependent factor

Comment thread torchtitan_recipes/tests/rl.py Resolved
Comment thread torchtitan/rl/generator.py Resolved
Comment thread torchtitan/rl/model/vllm_wrapper.py Resolved
Comment thread tests/rl/integration_tests/rl.py Resolved
Comment thread torchtitan/rl/model/vllm_worker.py Resolved
@wwwjn wwwjn changed the title [WIP][dist_moe] Add DistMoeInferenceRuntime for the vLLM generator [dist_moe] Add DistMoE for the vLLM generator inference path Oct 5, 2026
@wwwjn
wwwjn force-pushed the jianiw/distmoe-inference-main branch 4 times, most recently from 3ce0c45 to a1d71c4 Compare October 8, 2026 18:30
@wwwjn
wwwjn marked this pull request as ready for review October 8, 2026 20:22
@pytorch-bot pytorch-bot Bot added ciflow/b200 Trigger B200 CI ciflow/fake-pg Run 1-GPU Fake PG integration tests labels Oct 8, 2026
Comment thread torchtitan/models/common/moe.py Resolved
Comment thread torchtitan/rl/model/vllm_worker.py Resolved
Comment thread torchtitan/rl/model/vllm_wrapper.py Resolved
Comment thread torchtitan_recipes/tests/rl.py Resolved
Comment thread torchtitan_recipes/tests/rl.py Resolved
Comment thread torchtitan/rl/generator.py Resolved
Comment thread torchtitan/rl/model/vllm_wrapper.py Resolved
@wwwjn
wwwjn force-pushed the jianiw/distmoe-inference-main branch from a1d71c4 to 9a3438a Compare October 9, 2026 04:30
Comment thread torchtitan/rl/model/vllm_wrapper.py Resolved
Comment thread torchtitan/rl/model/vllm_wrapper.py Resolved
# steps and capture runs alike. The EP group spans the DP replicas,
# which run equal sizes in graph steps but their own sizes in eager
# steps, so every replica uses the largest count.
num_tokens = int(dp_metadata.num_tokens_across_dp_cpu.max())

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.

comment that:

  • without cudagraph, different DP ranks may have different value
  • with cudagraph, padding is already done outside model forward, so this max == original value

come through here too with their own token count, so their rows count as
real; graph replay reads the value published for the real step.
"""
self.get_model().set_num_valid_tokens(num_tokens)

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.

double check that num_tokens doesn't include TP/SP/ESP padding from _pad_for_sequence_parallelism

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.

_pad_for_sequence_parallelism() is called by vllm's original _determine_batch_execution_and_padding(), so it will be called at line 105 here.

num_tokens is unpadded

Comment thread torchtitan_recipes/tests/rl.py Resolved
# of -1 routes, and their stale values can reach its gradients.
zero_out_padded_callback_inputs=(
callable(postprocess)
and (padding_mask_T is not None or num_padded_tokens > 0)

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.

nit: I feel checking num_padded_tokens > 0 should be enough here?>

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.

padding_mask_T represents padding come from other source, instead of the ad-hoc padding we added here.

assert not self.cudagraph_dispatcher.keys_initialized
self.cudagraph_dispatcher = TorchTitanCudagraphDispatcher(self.vllm_config)

def _determine_batch_execution_and_padding(self, num_tokens: int, *args, **kwargs):

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.

where would this gets called?

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 is patching vllm's code, so it will be called by vllm

wwwjn added 6 commits October 9, 2026 21:05
…r step

Rework Dist-MoE padding for the bounded per-call Dist-MoE API (bounded
per-call token count and inactive -1 routes in dist_moe; TorchTitan pytorch#5085).

- DistMoeRoutedExperts: rows marked in padding_mask get expert ID -1 and score
  0, in training and inference. Dist-MoE never dispatches a -1 route, so padding
  costs no communication or expert GEMM work and returns zero rows. Replaces
  padding.py, which kept padding rows on local experts (they still used GEMM
  rows and received capacity). MoE.forward and KimiLatentMoE.forward (which
  wraps the experts in latent projections) pass their TP-local mask to the
  routed experts, so the trainer also skips padding from the RL batcher and the
  pretraining packer; training passes its row count unchanged.
  RoutedExperts.forward takes padding_mask_T too and ignores it: the standard
  path computes padding rows, and the router already leaves them out of the
  load-balancing statistics.
- Inference calls carry only the rows the step needs: the largest TP-local
  token count across vLLM DP replicas, from dp_metadata.num_tokens_across_dp_cpu
  (every EP rank must pass the same count; graph steps already share one size,
  eager steps do not). Rows up to that count are -1 routes.
- With a Python callback postprocess and -1 routes present, set
  zero_out_padded_callback_inputs so the callback never reads stale rows.
- Batch-invariant mode: 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.
- The RL Dist-MoE test recipe applies DistMoeTransform through
  apply_transforms, like the other RL recipes, so the transform is validated.

Validation on GB300 with real weights of a large MoE model (greedy AIME 2025,
FULL CUDA graphs): rollouts are coherent and correct; reruns are bitwise
identical; with the expert-GEMM schedule fixed, outputs are bitwise identical
(tokens and logprobs, up to 1823 tokens) to the previous pad-to-maximum path.
Keep DistMoeRuntime's scratch_capacity_factor default at 1.0 and set 4.0
explicitly in the recipe, for both the trainer and the generator. At EP=4
this is the same value as before.
… the generator call size

- Rename TrainingEngine.Config.dist_moe to dist_moe_runtime, matching
  VLLMGenerator.Config.dist_moe_runtime (engine, GraphTrainer, recipes, tests,
  README).
- The generator's Dist-MoE call size reads vLLM's DP metadata whenever it is
  there: vLLM builds it for every MoE forward when DP > 1, so the "DP > 1
  without metadata" path (pad to the context maximum) could not happen and is
  removed. set_num_local_input_tokens_per_call now takes an int. Comments on
  when each branch applies.
- TorchTitanGPUModelRunner always runs a VLLMModelWrapper, so it calls
  set_num_valid_tokens directly instead of probing for it.
- The RL Dist-MoE test recipe captures prefill steps too (FULL CUDA graphs).
- TODO on RoutedExperts for skipping padding rows in the stock dispatchers.
- Drop the duplicate Dist-MoE import in VLLMModelWrapper (flake8 F401/F811).
…sert the call size divides TP

- The vLLM runner/wrapper padding-mask tests move to tests/rl/unit_tests/cpu
  (the RL CPU job installs vLLM; they need no dist_moe package), and the
  MoE/KimiLatentMoE mask hand-off test moves into tests/unit_tests/cpu/test_moe.py
  (core CPU job, no vLLM). Previously the file was skipped on CPU and only ran in
  the B200 job, which no longer lists it.
- The generator's Dist-MoE call size asserts that TP divides this replica's
  token count and the DP maximum, and divides exactly. Comments on the eager vs
  CUDA-graph DP cases.
- Comments: only the MoE reads the generator's padding mask (attention uses
  vLLM's metadata); where vLLM calls the runner hook and that it receives the
  unpadded count; the two sources of -1 routes behind
  zero_out_padded_callback_inputs.
…l/alphabet_sort.py

The rebase onto main moved rl_grpo_moe_debug_dist_moe_tp2_ep4 with the other
RL test recipes into torchtitan_recipes/tests/rl/alphabet_sort.py, which
already imports apply_transforms and ModelConfigTransformContext; drop the
recipe's local copies. Format the updated module paths in its test.
@wwwjn
wwwjn force-pushed the jianiw/distmoe-inference-main branch from 9a3438a to 54a6f81 Compare October 10, 2026 04:09
wwwjn added 2 commits October 9, 2026 22:42
TorchStore stages same-host weight syncs in /dev/shm. The B200 RL job runs in
a GitHub container with Docker's 64 MiB default, which cannot hold the
Dist-MoE test model's weights (debugmodel_moe, ~300M parameters, ~600 MB in
bf16): the trainer's first push failed with "unable to allocate shared memory
... No space left on device".
The RL B200 job ran tests/unit_tests/cpu/test_dist_moe.py after the Kimi K3
bitwise-parity test in one pytest process, and in an environment without
torchao:
- the parity test leaves batch-invariant mode on, so the call-size test's
  default-mode check saw the batch-invariant 129-row minimum (129 != 1). The
  test now pins both modes explicitly instead of reading the global mode.
- the MXFP8 671B recipe test needs a torchao nightly, which only the B200
  Integration job installs.

The file has no RL or vLLM dependency, so it moves to the B200 Integration job
(dist_moe and torchao nightly installed, same ciflow/b200 trigger). The RL B200
job keeps the RL Dist-MoE recipe test.
@wwwjn
wwwjn merged commit 826d018 into pytorch:main Oct 10, 2026
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/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