Repository navigation
[MoE][6/n] Extract local_reorder, split DeepEP/HybridEP dispatchers - #3389
Conversation
[ghstack-poisoned]
[ghstack-poisoned]
| "comm_backend", | ||
| "standard", | ||
| ) | ||
| td_cfg = layer_cfg.moe.experts.token_dispatcher |
There was a problem hiding this comment.
| td_cfg = layer_cfg.moe.experts.token_dispatcher | |
| token_dispatcher_cfg = layer_cfg.moe.experts.token_dispatcher |
| "comm_backend", | ||
| "standard", | ||
| ) | ||
| td_cfg = layer_cfg.moe.experts.token_dispatcher |
| from torchtitan.distributed.deepep import deepep # noqa: F401 | ||
| from torchtitan.distributed.deepep import hybridep # noqa: F401 | ||
|
|
||
| def wire_meshes( |
There was a problem hiding this comment.
did you mean to put this into DeepEP dispatcher?
| del ep_mesh, tp_mesh | ||
|
|
||
| def dispatch( | ||
| def local_reorder( |
There was a problem hiding this comment.
| def local_reorder( | |
| def _local_reorder( |
| # 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 | ||
| ) |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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]
[ghstack-poisoned]
| 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 |
There was a problem hiding this comment.
can we remove
torchtitan/torchtitan/experiments/transformers_modeling_backend/model.py
Lines 289 to 292 in 963c20c
| 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. |
There was a problem hiding this comment.
separate the comments: this is only for HF models; the line above is only for DeepEP
…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 ```
…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.
…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.
…, 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).
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.
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.
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).
Stack from ghstack (oldest at bottom):
Summary
MoE cleanup from #2956:
local_reorderhelper onLocalTokenDispatcher: deduplicates the histc/argsort/score-weighting block betweenLocalTokenDispatcher.dispatch()andAllToAllTokenDispatcher.dispatch()DeepEPTokenDispatcherintoDeepEPTokenDispatcher+HybridEPTokenDispatcher: eliminatescomm_backendstring branching; config fields (non_blocking_capacity_factor,pad_multiple) are now class-specific. Callsites useisinstanceinstead ofgetattr(..., "comm_backend", ...)torch.cuda.synchronize()beforeget_dispatch_layoutindispatch_tokens()to ensuremasked_fillresults are visible on DeepEP's comm stream. Without this,get_dispatch_layoutreads stale (pre-masked) expert indices, causingnum_tokens_per_expertto overcount and_grouped_mmto assert.Test plan
Test loss comparions