Skip to content

[MoE] Opt-in shared-expert overlap with deferred DeepEP dispatch - #5263

Open
yuweih205 wants to merge 3 commits into
pytorch:mainfrom
yuweih205:feat/deepep-shared-expert-overlap
Open

yuweih205 wants to merge 3 commits into
pytorch:mainfrom
yuweih205:feat/deepep-shared-expert-overlap

Conversation

@yuweih205

@yuweih205 yuweih205 commented Oct 10, 2026 •

Copy link
Copy Markdown

Summary

Add opt-in overlap of shared-expert computation with DeepEP training dispatch.
MoE.Config.overlap_shared_experts defaults to False; no recipe enables it
automatically.

The existing compact training path waits for CPU counts inside dispatch,
before independent shared-expert work is submitted. Reuse DeepEP v2.5's
defer_epilogue API to allow:

launch dispatch -> shared experts -> wait/materialize counts -> routed experts -> combine

This is a scheduling feature, not a new communication kernel or count-prefetch
algorithm. It contains no private-model or two-batch logic.

Implementation and compatibility

  • Split dispatch into ordered launch/wait custom ops. Wait retains the dispatch
    autograd rule and explicit input edges; pending events use the handle-lifetime
    cleanup pattern.
  • Add a callback seam to common token dispatch and routed experts. Other
    dispatchers run the callback synchronously; only DeepEP gets overlap.
    The no-callback path remains the default.
  • Preserve the saved shared-expert add, TP transitions, remat policy and
    checkpoint parameter names.
  • The deferred path requires DeepEP v2.5 EPBuffer. The default path retains
    the older ElasticBuffer import fallback. Custom MoE forward implementations
    (such as Kimi latent MoE) and Dist-MoE routed-expert replacements reject
    opt-in overlap instead of silently ignoring it.

Existing GPU fixtures only gain buffer-class selection for the two DeepEP APIs;
no new test cases are included. A separate small cleanup removes an unused
GraphPP test import that prevented all-files lint on the tested upstream base.

Effective workloads and limitations

Intended for training with standard common MoE / RoutedExperts, independent
shared experts and DeepEP's compact layout. It can help when the shared branch
covers exposed dispatch/count-wait latency without excessive GPU contention.
It does not eliminate the CPU count wait or make compact training CUDA-graph
compatible.

There is no universal speedup: shared-FFN size, CPU launch cost, TP/AC policy and
GPU contention matter. Earlier shared outputs can also live longer.
Debug-model allocator measurements do not establish production memory usage.

Validation covers single-node BF16 EP8 training with SP and the TP/AC matrix
below. Whole-model compile, inference speedups, FP8, Dist-MoE, PP/CP and
multi-node overlap are not validated. Local model compile regions were
disabled; the official Flex kernel still compiled. Synthetic packed inputs
preserve document-causal attention, but do not establish dataset convergence
or full-size model performance.

Completed validation

Tested upstream base: 448b9c8be41abc7fcbd5ccc768242b8865d4347b, after FullAC
migrated to torch_remat and began replaying communication.

Current head: d5e59c25e0900889fe19c2c3c7120273719c4373.
The executable AST of all three production files matches the model-validated
head 53e9beb5b0d73433e5582dfab661150a1b621415, excluding docstrings.
Follow-up changes only trim tests/comments, select the existing GPU fixture's
buffer class, and remove the unused import.

  • pre-commit run --all-files: passed, with no hook edits, including flake8,
    formatting and Pyrefly. The former upstream F401 is fixed.
  • Existing CPU suites for common MoE, DeepSeek-V3/V4, GPT-OSS, Qwen3.5,
    inference MoE and compile config: 43 passed, 1 skipped.
    The skip is the optional Dist-MoE package, not deferred dispatch.
  • Manual CPU MoE regression fixture: 21 passed, including exact shared
    outputs/gradients and rejection by the actual Kimi latent-MoE class.
    The fixture uses Kimi's model-config builder directly, avoiding an unrelated
    multimodal recipe's torchvision import. No runtime packages were changed.
  • Existing DeepEP GPU AC suite on current head: 2 passed (two-rank tests,
    45.42 s). The earlier manual feature-specific GPU fixture had 3 passed,
    including deferred shared experts and FullAC/RegionAC replay.
    Feature-specific fixtures are not included in the PR diff.
  • Public deepseek_v3_debugmodel: all 8 runs completed 20 steps. Four
    OFF/ON pairs are bitwise equal on all 8 ranks for raw loss and grad_norm,
    semantic inputs, shared BF16 initial state and final weights.
    Independent verification checked raw TensorBoard events, all 32 serialized
    checkpoints and inventories, finite metrics and actual runtime paths:
    640 paired rank-steps, zero numerical differences.

Isolated validation runtime: Torch 2.16.0.dev20261009+cu132, CUDA 13.2,
cuDNN 9.26.0.51, NCCL 2.32.3, public DeepEP 2.5.0; H200 141GB, one node.
Native debug logging was disabled in both arms; NCCL checks remained enabled.
Single-node networking used NCCL_NET_PLUGIN=none.
Seed 42, deterministic execution (warn-only disabled), AdamW, SP and the
official Flex document-causal mask were fixed. Each microbatch contains two
packed 128-token documents.

Exploratory performance on the new base

AC / TP (EP8) OFF median step ms ON median step ms OFF/ON - 1
FullAC / TP1 126.835 127.361 -0.41%
SelectiveAC / TP1 131.077 126.011 +4.02%
RegionAC, saved EP / TP1 126.391 125.893 +0.40%
FullAC / TP2 180.224 178.501 +0.97%

One OFF/ON debug-model pair per configuration, not stable performance claims.
Statistic: median over steps 6-20 of each step's maximum wall time across
eight ranks. Full forward/backward and optimizer step are timed after a rank
barrier, with CUDA synchronization at each boundary. Repeated representative
workloads and traces are still needed for production-throughput claims.

CI status and review boundary

The current GitHub Actions runs have action_required and no executed jobs;
they are not passed CI. Maintainer approval is still needed for upstream CI.

Existing native CI pins older DeepEP
01dc3aaac82068020353dce2c302e38153c0bfaa and does not cover this new deferred
path. This PR does not change CI CUDA/NCCL/DeepEP dependencies.
Manual native validation is reported separately; long-term v2.5 regression
coverage remains a review/merge consideration.

This PR was prepared with an AI coding assistant.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 10, 2026
@pytorch-bot

pytorch-bot Bot commented Oct 10, 2026 •

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/rl
  • ciflow/fake-pg

Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows.

@yuweih205
yuweih205 marked this pull request as ready for review October 10, 2026 09:04
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 10, 2026
@tianyu-l

Copy link
Copy Markdown
Contributor

thanks, we used to have this overlap in eager trainer, but deleted due to limited benefit and difficulty of code maintenance

  • we recently added DistMoE backend which does overlapping among routed experts computation and communication, although it only works on Nvidia GB hardware
  • for DeepEP overlapping, maybe checkout the GraphTrainer experiments/graph_trainer/, which manipulates computation order via graph passes

cc @sanketpurandare

@yuweih205

Copy link
Copy Markdown
Author

Thanks, I’ll take a look at DistMoE and GraphTrainer and give those approaches a try.

@yuweih205

Copy link
Copy Markdown
Author

@tianyu-l @sanketpurandare I’ve implemented the GraphTrainer version in #5315 as a follow-up to this PR.

sanketpurandare added a commit that referenced this pull request Oct 20, 2026
## Agent details (AI-generated)

Enqueue independent shared experts before router/dispatch/routed compute on
a separate lower-priority CUDA stream and join both branches before combination.
Reuse the common MoE boundary, including Kimi's latent routed projection,
without duplicating router/sharding/TP-add logic. Dist-MoE's BF16 and MXFP8
transforms opt in automatically; no-shared-expert modules are unaffected.

The caller may already have lowest priority, so cache one routed priority-1
and shared priority0 stream per indexed device rather than changing global
stream policy. Initialize them before graph capture. Explicit waits and
record_stream retain input/output allocator ownership in train and no-grad eval.
Autograd uses each branch's forward stream during backward.

Moving branch readiness can change BF16 input-gradient rounding. A storage-free
input fork combines shared+routed+router contributions in the original order,
including separate TP-sharded input edges and unused gradients. No parameter
gradient cache, extra tensor copy, precision change or owned output is added.
GraphTrainer's own parallel-branch lowering remains downstream work.

Related DeepEP-specific #5263 by @yuweih205 uses a different dispatch callback;
this is generic MoE/Dist-MoE integration and does not copy that implementation.

## Test Plan (AI-generated)

```bash
python -m pytest tests/unit_tests/cpu/models/common/test_moe.py tests/unit_tests/cpu/models/common/test_dist_moe.py tests/unit_tests/gpu/models/common/test_dist_moe.py -q
pre-commit run --all-files
```

93 current CPU/GPU checks passed, including exact BF16 gradients, nonassociative
fan-in, alias/distinct/unused edges, forward/backward stream identity, cache
priming and capture/replay. Four real-NCCL PP2/DP2/EP2 and PP4/DP1/EP1 OFF/ON
runs passed ten train/validation updates each: full model/optimizer state was
bitwise equal on every rank, with MXFP8/FSDP, all three fusions, dense/fused MLA,
optimizer/training/validation graphs and clean teardown. Profiling was disabled;
these correctness runs are not 671B throughput evidence. Strict README/config
Sphinx and staged-aware non-type lint passed. Existing unrelated video type
error remains excluded; no full-cluster convergence/performance claim.
sanketpurandare added a commit that referenced this pull request Oct 23, 2026
Enqueue independent shared experts before router/dispatch/routed compute on
a separate lower-priority CUDA stream and join both branches before combination.
Reuse the common MoE boundary, including Kimi's latent routed projection,
without duplicating router/sharding/TP-add logic. Dist-MoE's BF16 and MXFP8
transforms opt in automatically; no-shared-expert modules are unaffected.

The caller may already have lowest priority, so cache one routed priority-1
and shared priority0 stream per indexed device rather than changing global
stream policy. Initialize them before graph capture. Explicit waits and
record_stream retain input/output allocator ownership in train and no-grad eval.
Autograd uses each branch's forward stream during backward.

Moving branch readiness can change BF16 input-gradient rounding. A storage-free
input fork combines shared+routed+router contributions in the original order,
including separate TP-sharded input edges and unused gradients. No parameter
gradient cache, extra tensor copy, precision change or owned output is added.
GraphTrainer's own parallel-branch lowering remains downstream work.

Related DeepEP-specific #5263 by @yuweih205 uses a different dispatch callback;
this is generic MoE/Dist-MoE integration and does not copy that implementation.

```bash
python -m pytest tests/unit_tests/cpu/models/common/test_moe.py tests/unit_tests/cpu/models/common/test_dist_moe.py tests/unit_tests/gpu/models/common/test_dist_moe.py -q
pre-commit run --all-files
```

93 current CPU/GPU checks passed, including exact BF16 gradients, nonassociative
fan-in, alias/distinct/unused edges, forward/backward stream identity, cache
priming and capture/replay. Four real-NCCL PP2/DP2/EP2 and PP4/DP1/EP1 OFF/ON
runs passed ten train/validation updates each: full model/optimizer state was
bitwise equal on every rank, with MXFP8/FSDP, all three fusions, dense/fused MLA,
optimizer/training/validation graphs and clean teardown. Profiling was disabled;
these correctness runs are not 671B throughput evidence. Strict README/config
Sphinx and staged-aware non-type lint passed. Existing unrelated video type
error remains excluded; no full-cluster convergence/performance claim.
@yuweih205
yuweih205 force-pushed the feat/deepep-shared-expert-overlap branch from d5e59c2 to fb20a71 Compare November 6, 2026 09:46
@tianyu-l

tianyu-l commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

@sanketpurandare is on vacation, will come back soon

Resolve dispatch API conflicts by retaining per-row router scores in metadata. Preserve the main combine SAVE region and the PR-specific overlap/tracing behavior.
Check and patch EPBuffer on current DeepEP while retaining the existing ElasticBuffer selection for older supported builds. This prevents the AC suite being skipped solely because the buffer was renamed. CPU dispatcher regression and non-type lint hooks passed; GPU AC validation remains pending. Assisted-by: Codex

Signed-off-by: HuangYuwei <[email protected]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

3 participants