Skip to content

[MoE][6/n] Extract local_reorder, split DeepEP/HybridEP dispatchers - #3389

Merged
acisseJZhong merged 39 commits into
mainfrom
gh/acisseJZhong/17/head
May 21, 2026
Merged

acisseJZhong merged 39 commits into
mainfrom
gh/acisseJZhong/17/head

Conversation

@acisseJZhong

@acisseJZhong acisseJZhong commented May 17, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Summary

MoE cleanup from #2956:

  • Extract local_reorder helper on LocalTokenDispatcher: deduplicates the histc/argsort/score-weighting block between LocalTokenDispatcher.dispatch() and AllToAllTokenDispatcher.dispatch()
  • Split DeepEPTokenDispatcher into DeepEPTokenDispatcher + HybridEPTokenDispatcher: eliminates comm_backend string branching; config fields (non_blocking_capacity_factor, pad_multiple) are now class-specific. Callsites use isinstance instead of getattr(..., "comm_backend", ...)
  • Fix DeepEP CUDA stream race (DeepEP: CUDA stream race between masked_fill and get_dispatch_layout causes grouped_mm assertion failure #3413): added torch.cuda.synchronize() before get_dispatch_layout in dispatch_tokens() to ensure masked_fill results are visible on DeepEP's comm stream. Without this, get_dispatch_layout reads stale (pre-masked) expert indices, causing num_tokens_per_expert to overcount and _grouped_mm to assert.

Test plan

Test loss comparions

NCCL_NVLS_ENABLE=0 python scripts/loss_compare.py . main --baseline-module='llama4' --baseline-config='llama4_debugmodel_ep' --baseline-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 2 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 2 --parallelism.no-enable_sequence_parallel" --baseline-ngpus=4 --test-module='llama4' --test-config='llama4_debugmodel_ep' --test-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 2 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 2 --parallelism.no-enable_sequence_parallel" --test-ngpus=4 --assert-equal --no-seed-checkpoint

[ghstack-poisoned]
[ghstack-poisoned]
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label May 17, 2026
[ghstack-poisoned]
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request May 17, 2026
ghstack-source-id: a6cc5c3
Pull-Request: #3389
@acisseJZhong acisseJZhong changed the title cleanup moe [MoE] Cleanup: extract local_reorder, split DeepEP/HybridEP dispatchers, migrate MoE sharding May 17, 2026
@acisseJZhong acisseJZhong changed the title [MoE] Cleanup: extract local_reorder, split DeepEP/HybridEP dispatchers, migrate MoE sharding [MoE] Cleanup: extract local_reorder, split DeepEP/HybridEP dispatchers May 17, 2026
@acisseJZhong acisseJZhong changed the title [MoE] Cleanup: extract local_reorder, split DeepEP/HybridEP dispatchers [MoE] Cleanup: extract local_reorder, split DeepEP/HybridEP dispatchers, migrate MoE sharding May 17, 2026
@acisseJZhong acisseJZhong changed the title [MoE] Cleanup: extract local_reorder, split DeepEP/HybridEP dispatchers, migrate MoE sharding [MoE] Extract local_reorder, split DeepEP/HybridEP dispatchers May 17, 2026
@acisseJZhong acisseJZhong changed the title [MoE] Extract local_reorder, split DeepEP/HybridEP dispatchers [MoE][6/n] Extract local_reorder, split DeepEP/HybridEP dispatchers May 17, 2026
Comment thread torchtitan/models/deepseek_v3/model.py Outdated
"comm_backend",
"standard",
)
td_cfg = layer_cfg.moe.experts.token_dispatcher

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.

Suggested change
td_cfg = layer_cfg.moe.experts.token_dispatcher
token_dispatcher_cfg = layer_cfg.moe.experts.token_dispatcher

Comment thread torchtitan/models/llama4/model.py Outdated
"comm_backend",
"standard",
)
td_cfg = layer_cfg.moe.experts.token_dispatcher

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.

similar

from torchtitan.distributed.deepep import deepep # noqa: F401
from torchtitan.distributed.deepep import hybridep # noqa: F401

def wire_meshes(

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.

did you mean to put this into DeepEP dispatcher?

del ep_mesh, tp_mesh

def dispatch(
def local_reorder(

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.

Suggested change
def local_reorder(
def _local_reorder(

Comment on lines 427 to 432
# With SP, token indices are 0-based within the local shard.
# Offset to global positions for the full-size scatter buffer.
if self.sp_size > 1:
token_indices_experts_sorted = (
metadata.token_indices_experts_sorted + x.shape[0] * self.sp_rank
)

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.

To double check

  • The Expert SP initial sharding is handled uniformly by config now, in the last PR.
  • Do we not need this in DeepEP / HybridEP token combine, because it's handled correctly internally?

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.

The Expert SP initial sharding is handled uniformly by config now, in the last PR.

Yes this correct. I removed the manual SP split, sharding should be handled by config now.

    moe_desired_input_layouts = Replicate() if not enable_ep else sp_layout

Do we not need this in DeepEP / HybridEP token combine, because it's handled correctly internally?

I assume it's handled internally by deepep/hybridep? But now that you brining up this I am not sure if it could handle SP? I need to look deeper.

Previously we were not manually splitting for deepep / hybridep, but now config will shard input so I am not sure how deepep / hybrid handles it.

[ghstack-poisoned]
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request May 17, 2026
ghstack-source-id: 5ceffa8
Pull-Request: #3389
[ghstack-poisoned]
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request May 18, 2026
ghstack-source-id: 8769f89
Pull-Request: #3389
[ghstack-poisoned]
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request May 20, 2026
ghstack-source-id: 4aea9eb
Pull-Request: #3389
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request May 21, 2026
ghstack-source-id: e460445
Pull-Request: #3389
@acisseJZhong acisseJZhong added the ciflow/h100.8 Trigger H100.8 CI label May 21, 2026
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request May 21, 2026
ghstack-source-id: 251da64
Pull-Request: #3389
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request May 21, 2026
ghstack-source-id: 574d20f
Pull-Request: #3389
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request May 21, 2026
ghstack-source-id: 4aea9eb
Pull-Request: #3389
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
# DeepEP's comm streams conflict with torch.empty() init kernels
torch.utils.deterministic.fill_uninitialized_memory = False

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.

can we remove

# NOTE(3outeille): This prevents Hugging Face modeling from initializing ROPE (inv_freq) buffers to NaN.
# Needed when loading from seed checkpoint.
if hasattr(config, "deterministic") and config.deterministic:
torch.utils.deterministic.fill_uninitialized_memory = False

[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request May 21, 2026
ghstack-source-id: 1ca7cbb
Pull-Request: #3389
Comment thread torchtitan/distributed/utils.py Outdated
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
# torch.empty() init kernels overlap with DeepEP comm streams and
# initialize HF ROPE (inv_freq) buffers to NaN when this is True.

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.

separate the comments: this is only for HF models; the line above is only for DeepEP

[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request May 21, 2026
ghstack-source-id: 4e79c6b
Pull-Request: #3389
@acisseJZhong
acisseJZhong changed the base branch from gh/acisseJZhong/17/base to main May 21, 2026 17:47
@acisseJZhong
acisseJZhong merged commit da38566 into main May 21, 2026
9 of 15 checks passed
felipemello1 pushed a commit to felipemello1/torchtitan that referenced this pull request May 22, 2026
…ytorch#3389)

Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0)
(oldest at bottom):
* __->__ pytorch#3389
* pytorch#3385

## Summary
MoE cleanup from pytorch#2956:

- **Extract `local_reorder` helper** on `LocalTokenDispatcher`:
deduplicates the histc/argsort/score-weighting block between
`LocalTokenDispatcher.dispatch()` and
`AllToAllTokenDispatcher.dispatch()`
- **Split `DeepEPTokenDispatcher` into `DeepEPTokenDispatcher` +
`HybridEPTokenDispatcher`**: eliminates `comm_backend` string branching;
config fields (`non_blocking_capacity_factor`, `pad_multiple`) are now
class-specific. Callsites use `isinstance` instead of `getattr(...,
"comm_backend", ...)`
- **Fix DeepEP CUDA stream race** (pytorch#3413): added
`torch.cuda.synchronize()` before `get_dispatch_layout` in
`dispatch_tokens()` to ensure `masked_fill` results are visible on
DeepEP's comm stream. Without this, `get_dispatch_layout` reads stale
(pre-masked) expert indices, causing `num_tokens_per_expert` to
overcount and `_grouped_mm` to assert.

## Test plan
Test loss comparions 
```
NCCL_NVLS_ENABLE=0 python scripts/loss_compare.py . main --baseline-module='llama4' --baseline-config='llama4_debugmodel_ep' --baseline-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 2 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 2 --parallelism.no-enable_sequence_parallel" --baseline-ngpus=4 --test-module='llama4' --test-config='llama4_debugmodel_ep' --test-options="--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 2 --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 2 --parallelism.no-enable_sequence_parallel" --test-ngpus=4 --assert-equal --no-seed-checkpoint
```
saforem2 added a commit to saforem2/torchtitan that referenced this pull request May 22, 2026
…dispatcher Config

Upstream PR pytorch#3389 (MoE [6/n], 38th sync) split DeepEPTokenDispatcher into
DeepEPTokenDispatcher + HybridEPTokenDispatcher and replaced the
comm_backend string branching with isinstance checks on the dispatcher
Config classes. The DeepEPMoE class was removed entirely; the work
moved into the dispatcher classes themselves.

Apply the same pattern to ezpz/moe/model.py:

- Import DeepEPTokenDispatcher / HybridEPTokenDispatcher.
- Replace `getattr(..., "comm_backend", "standard") in ("deepep",
  "hybridep")` with isinstance(token_dispatcher_cfg, (...Config, ...)).
- Drop the dead `MoE → DeepEPMoE.Config` swap (DeepEPMoE no longer
  exists; the dispatcher classes now own the deepep/hybridep logic).

ezpz does not exercise the deepep/hybridep paths on XPU (no DeepEP
kernels), but we keep the EP=1 guard so any CUDA-side ezpz user who
flips the dispatcher config to deepep gets the same error semantics as
upstream deepseek_v3.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request May 22, 2026
…eport

Documents the 38th upstream sync (4 commits, cfe97c6..c2a3771):

- PR pytorch#3389 (MoE [6/n] dispatcher split) — replayed in d87729a;
  smoke report at docs/experiments/moe/sunspot/20260522-smoke-n2-pr3389-replay.md
- PR pytorch#3412 (ChunkedCELoss + TP gradient fix) — internal to upstream
  loss.py, no ezpz replay; flagged interaction with ezpz's separate
  TP-loss-reporting workaround
- PR pytorch#3414 (DeepEP imports) — XPU-irrelevant no-op
- PR pytorch#3416 (graph_trainer fsdp_passes) — Meta-internal experiment, no-op

Smoke results (2N Sunspot, jobs 12467277 + 12467288):

- agpt_2b clean, byte-comparable baseline (140s, peak 24.34 GiB).
- moe_2b_ep REGRESSED at LBS=16: 62.53 GiB OOM vs yesterday's
  15.03 GiB peak with identical config. Almost certainly PR pytorch#3389's
  token-dispatcher restructure responsibility.
- moe_2b_ep at LBS=2 workaround clean (427s, peak 27.08 GiB, 9.4%
  MFU, loss 12.93 → 6.15).

Adds the 38th-sync entry to docs/upstream-sync.md, the smoke report
to docs/experiments/moe/sunspot/, links it from the moe experiments
README, and updates today's journal entry with the sync details.

Action items captured in upstream-sync.md: file upstream issue for
the LBS=16 OOM regression, pin moe_2b_ep LBS=2 in registry.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request May 22, 2026
…, not PR pytorch#3389

LBS=1 parity re-run on alloc 12467323 (vs yesterday's 1d4115d at
the same config):

- Today: 14.95 GiB peak, ~2,820 TPS
- Yesterday: 15.03 GiB peak, ~2,860 TPS

Delta within run-to-run noise on both memory (0.08 GiB) and
throughput (1.4%). PR pytorch#3389's token_dispatcher.py restructure is
numerically equivalent on the LocalTokenDispatcher + for_loop
backend that ezpz uses on XPU.

The earlier "OOM regression at LBS=16" reading was a misattribution:
yesterday's "clean 15 GiB" datapoint was at LBS=1 OVERRIDE, not
LBS=16. The LBS=16 default would have OOMed yesterday too — the
allocation request (62.53 GiB) is the bf16 vocab projection
[LBS x 8192, 256128] = 62.5 GiB exactly, which is the same pre-existing
_ep registry bug the 37th-sync follow-up already flagged as
"_ep configs should override LBS in the registry."

Updates the smoke report, upstream-sync entry, moe experiments
README, and today's journal entry to reflect the corrected
diagnosis. No upstream issue to file. Action item is now just
the registry LBS pin (mirroring f2cbc03 for moe_debugmodel_ep).
saforem2 added a commit to saforem2/torchtitan that referenced this pull request May 22, 2026
PR pytorch#3389 was implicated in the moe_2b_ep OOM I initially saw, but a
LBS=1 parity re-run showed no regression — the OOM was the
pre-existing _ep vocab-projection bug. The PR cross-reference and
"earlier docstring was wrong" history in moe_2b_ep's docstring are
just rot; trim to the measured numbers and the formula.

Also drop the historical "ETP was deprecated upstream / PR pytorch#3389
replaced the dispatch" block in moe/model.py: the code now reads
self-evidently as an isinstance check on the dispatcher Config
classes.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request May 22, 2026
Rewrites the 38th-sync smoke report, upstream-sync entry, journal
entry, and moe experiments README to record what the smoke actually
established (LBS=1 numerical parity vs the 37th-sync baseline,
pre-existing _ep registry vocab-projection OOM at LBS=16) without
the "first thought it was a PR pytorch#3389 regression / then re-verified"
arc. That arc was process detail; persisting it on every reader's
desk implicates an upstream PR for a bug it didn't introduce.

Renames the smoke report 20260522-smoke-n2-pr3389-replay.md →
20260522-smoke-n2-38th-sync.md so the filename describes what it is
(a routine post-sync smoke) rather than implying PR pytorch#3389 was
specifically being scrutinized.

The remaining pytorch#3389 references are now only the legitimate ones:
the upstream commit being attributed, and the subject line of the
ezpz replay commit. No invented-issue framing remains.
saforem2 added a commit to nscottnichols/torchtitan that referenced this pull request Jun 11, 2026
Replays the documented fix from upstream-sync.md (replay of upstream
PR pytorch#3389): replace `getattr(token_dispatcher, "comm_backend", "standard")`
with `isinstance(token_dispatcher, (DeepEPTokenDispatcher.Config,
HybridEPTokenDispatcher.Config))`.

Two bugs fixed together:

(1) The getattr lookup ALWAYS returned "standard" because
`make_ezpz_token_dispatcher_config` uses `comm_backend` as a function
arg that selects which Config TYPE to instantiate — it's never stored
as a field on the resulting Config. The downstream check
`if comm_backend in ("deepep", "hybridep")` therefore never fired.

(2) The branch's import `from torchtitan.models.common.moe_deepep import
DeepEPMoE` references a module that doesn't exist (only `moe.py`,
`moe_sharding.py`, `token_dispatcher.py` live in `models/common/`).
`DeepEPMoE` was removed from upstream when the dispatcher classes
took over the comm-backend-specific logic; the `MoE → DeepEPMoE.Config`
swap that used to live here is now dead and can be deleted entirely.

After this change:
- isinstance check on the dispatcher Config correctly detects
  deepep/hybridep configs
- the EP=1 guard fires correctly with a clear error message
  (`f"{dispatcher_name} requires expert parallelism..."`)
- no more dead import; no more no-op `MoE → DeepEPMoE.Config` swap

ezpz doesn't exercise deepep/hybridep on XPU (no DeepEP kernels),
but we keep the EP=1 guard so any CUDA-side ezpz user who flips the
dispatcher config to deepep gets the same error semantics as
upstream `deepseek_v3`.

Addresses review findings saforem2#6 + saforem2#7 on saforem2#14
(they were the same dead branch).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/h100.8 Trigger H100.8 CI ciflow/8gpu 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.

2 participants