Repository navigation
[dist_moe] Add DistMoE for the vLLM generator inference path - #5046
Conversation
b334763 to
b2d0ba9
Compare
| disables VMM. | ||
| """ | ||
|
|
||
| scratch_capacity_factor: float = 1.0 |
There was a problem hiding this comment.
Tried my best but need to double check the understanding of the scratch and whether this 1.0 is a good default.
There was a problem hiding this comment.
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
3ce0c45 to
a1d71c4
Compare
a1d71c4 to
9a3438a
Compare
| # 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()) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
double check that num_tokens doesn't include TP/SP/ESP padding from _pad_for_sequence_parallelism
There was a problem hiding this comment.
_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
| # 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) |
There was a problem hiding this comment.
nit: I feel checking num_padded_tokens > 0 should be enough here?>
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
where would this gets called?
There was a problem hiding this comment.
This is patching vllm's code, so it will be called by vllm
…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.
9a3438a to
54a6f81
Compare
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.
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-1in both the trainer and the generator. Builds on the bounded per-call token counts from #5085 and needs adist_moethat ignores-1routes.Why
VLLMModelWrapperitself, so nothing builds one for a generator.DistMoeRuntimeplans for training (PP activation slots, weight gradients); a generator runs no backward and no pipeline.What
DistMoeRuntime.Configgainsinference: bool = False, passed todist_moe, which then plans scratch only (no activation slots). The wrapper builds it after parallelize and before CUDA-graph capture, withpp_schedule=None, sized from vLLM'smax_num_batched_tokens, and rejects a config withoutinference=True. Plumbed throughregister_to_vllmand the generator config asdist_moe_runtime.DistMoeRoutedExpertssets expert ID-1and score0on rows marked inpadding_mask, in training and inference. Dist-MoE never dispatches a-1route, so padding costs no communication or expert GEMM work and its output rows are zero.MoE.forward, andKimiLatentMoE.forward(which overrides it to wrap the experts in latent projections), hand their TP-sharded mask to experts that setuses_padding_mask._determine_batch_execution_and_padding); the wrapper buildspadding_maskfrom it insideforward, so CUDA-graph replay sees the current count.padding_maskfrom 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).zero_out_padded_callback_inputsis set so the callback never reads stale rows of-1routes.dp_metadata.num_tokens_across_dp_cpu), padded with-1rows. Graph steps already share the capture size; eager steps do not. Without DP metadata and with DP > 1, calls pad to the planned maximum.[dist_moe] Use a module's fused postprocess in the generator, lets an inference context take the postprocess module'sto_dist_moe_inference_postprocess(input_dtype)when it defines one, and otherwise keepsto_dist_moe_postprocess(). A route-wise callable makes Dist-MoE execute eagerly, so a generator that captures CUDA graphs needs a fusedRMSNormPostprocess; 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.debug.batch_invariant). Twodist_moechoices 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 uses2cta2mma_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, generatorFULL_DECODE_ONLYgraphs, 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 appliesDistMoeTransformthroughapply_transforms.build_b200_rl_test_list()intests/rl/integration_tests/rl.pyis the B200 suite (--test_suite b200): the existing Kimi K3 KDA test (thekdasuite stays for the H100 workflow) plus this test..github/workflows/integration_test_rl_b200.yamlis one job: one environment that also installsdist_moe; one unit-test step (Kimi K3 bitwise parity plus the Dist-MoE unit tests, which the CPU workflow skips because it does not installdist_moe); one integration step running theb200suite, 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 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
-1routing 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.forwardandKimiLatentMoE.forwardhanding the mask only to opt-in experts, the fused inference postprocess, and the recipe and suite. Rebased onmainwith [dist_moe] Use bounded token capacity API #5085:test_dist_moe.py,test_vllm_dist_moe_padding_mask.py,test_rl_dist_moe_recipe.pyandtest_moe.pygive 82 passed, 3 skipped;test_dist_moe_671b_recipe_topology[deepseek_v3_671b_dist_moe_mxfp8-64-240]fails identically onmainin my environment (needs atorchaonightly). Generator tests also pass withoutdist_moeinstalled.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):