Repository navigation
[MoE] Using routing map instead of histc to count number_tokens_per_expert - #3450
Conversation
~80 commits across 8 days. Organized by 7 themes: - 2 upstream PRs filed: pytorch/pytorch#184767 (xccl _set_pg_timeout dispatch, closed in deference to #183625) and pytorch#3436 (histc -> bincount/scatter, open and likely superseded by draft pytorch#3450). - 5 upstream syncs absorbed (39th-42nd plus a 41st-sync catch-up the 42nd-sync smoke surfaced). Lesson logged: always smoke moe_2b_ep after a sync that touches GroupedExperts. - Production v2 training: 20B 512N HSn 0.579 -> 0.635 in 1100 steps; 2B 256N + 512N stepping through 28K-54K with the keep_latest_k=10 ckpt-purge root cause closed. - Failover wrapper hardening: ANSI exit-code parsing fix, silent-hang watchdog via --timeout, preflight smoke + env overrides, fixture- based test harness. - Scaling sweep infrastructure: 2B {4..4096}N sweep, walltime right- sized, venv pinned to project .venv. - Chart/plotting hardening across 6+ scripts (palette consistency, ambivalent style fixes, dual SVG+PNG output). - Docs hygiene: production READMEs refreshed across 4 stale pages, TREE.md unstaled. Includes the corresponding row in docs/summaries/README.md.
| num_tokens_per_expert_E = torch.histc( | ||
| topk_expert_ids_TK.view(-1), | ||
| topk_expert_ids_TK.float(), | ||
| bins=self.num_experts, | ||
| min=0, | ||
| max=self.num_experts, | ||
| ) | ||
| ).to(torch.int64) |
There was a problem hiding this comment.
maybe I'm missing something -- could you explain why we need to compute num_tokens_per_expert_E in dispatcher and return it AT ALL?
There was a problem hiding this comment.
mb, I've already moved the calculation in MoE level and we don't need to calculate in dispatcher level. I should clean up this part cleanly
But we still need to pass num_tokens_per_expert_E into dispatch() API and return from it. This is because for num_tokens_per_expert_E in DeepEPDispatcher path actually comes from DeepEP kernel's return value. If DeepEP is applied, we still need to return. To be more clear, the current implementation is:
- For AllToAllTokenDispatcher we pass
num_tokens_per_expert_Einto dispatch() call and return it as is. - For DeepEPTokenDispatcher, we use the DeepEP returned
num_tokens_per_expert_E, instead of what we passed into dispatch().
An alternative is don't pass num_tokens_per_expert_E into dispatch() at all, just drop thenum_tokens_per_expert_E from DeepEP and use the value calculated in MoE. Can we take the alternative way? Is it possible that DeepEP returns a different value than what we calculated from routing_map?
There was a problem hiding this comment.
change tokens_per_expert_E variable name
same for DeepEP
| input_shape, | ||
| routed_input_RD, | ||
| permuted_indices, | ||
| num_global_tokens_per_local_expert_e, |
There was a problem hiding this comment.
add a TODO that we might want to use this as buffer to compute expert_bias_E, but HybridEP token dropping is not clear.
| self, | ||
| x_RD: torch.Tensor, | ||
| num_tokens_per_expert_E: torch.Tensor, | ||
| num_global_tokens_per_local_expert_e: torch.Tensor, |
There was a problem hiding this comment.
@tianyu-l Can I get a final review of the rename in _experts_forward function? Basically I renamed E -> e
There was a problem hiding this comment.
Good point. I discussed with @acisseJZhong before.
In grouped experts:
- if EP is used, then this notation is correct (e is sharded version of E)
- if TP is used, then we should do
w1_EfDinstead because TP shards on different things - maybe we should use x_rD instead of x_RD depending on batch/seq dim sharding
Given all these complications, let's just use capital letters (such as E) and num_tokens_per_expert_E.
There was a problem hiding this comment.
good to add a NOTE on notation
There was a problem hiding this comment.
Sounds good,
let's just use capital letters (such as E) and
num_tokens_per_expert_E.
I updated num_tokens_per_expert_E to be the parameter name of _expert_forwarrd(), but in the callsite, I still pass num_tokens_per_expert_E=num_global_tokens_per_local_expert_e to distinguish:
(
routed_input_RD,
num_global_tokens_per_local_expert_e,
metadata,
) = self.token_dispatcher.dispatch(
x_TD, topk_scores_TK, topk_expert_ids_TK, num_local_tokens_per_expert_E
)
routed_output_RD = self._experts_forward(
routed_input_RD, num_global_tokens_per_local_expert_e
)
| experts_in_grad_layout, | ||
| # num_local_tokens_per_expert_E is routing metadata, but it is | ||
| # still a DTensor input to local_map and must have placements. | ||
| _tokens_per_expert_placement(enable_ep=enable_ep), |
There was a problem hiding this comment.
I have to put a placement here, because local_map doesn't take None as a input, cc @tianyu-l
There was a problem hiding this comment.
…orch#3436 thread Merged 7 upstream commits (b72d986..04a3098). Headline is PR pytorch#3450 — the upstream-canonical fix for the histc->scatter swap that our PR pytorch#3436 was tracking. Approach: build boolean routing_map_BLE via scatter_ in router, compute num_tokens_per_expert via routing_map.sum, thread the map through to dispatcher. Same scatter direction we recommended, done better (computed once, reused). API change at the boundary: router returns 4-tuple; dispatch() takes new num_local_tokens_per_expert_E positional arg. ezpz doesn't override these methods or unpack router output directly, inherits cleanly. set_moe_sharding_config call into upstream's helper picks up the new shard declaration automatically. No ezpz replay needed. Other 6 commits: HybridEP compile (pytorch#3360), MXFP8 consolidation (pytorch#3473), graph_trainer DTensor fix (pytorch#3480), graph_trainer test skips (pytorch#3432), two CI migrations (pytorch#3464, pytorch#3479). None touch ezpz. Live 2N smoke deferred to Aurora: the project .venv/bin/python symlinks at an Aurora-only Spack hash (python-3.12.12-5zo3wzv) that Sunspot doesn't have (Sunspot equivalent is the nvje3vk hash). Smoke per the journal's "always smoke after GroupedExperts touches" lesson should run on Aurora. Also: updated ~/.ezpz/utils.sh from bit.ly canonical (now exposes unified ezpz_setup; backup at utils.sh-20260602-065437).
## Summary The two DSv3 `test_eager_self_deterministic` tests (sdpa + FlexAttn) in `test_bitwise_deterministic.py` were `@unittest.skip`-ped in #3432 because their hardcoded `model_hash`/`grad_hash` went stale after upstream PyTorch nightly changes (notably the MoE expert-counting switch from `histc` to routing map in #3450). This re-enables them: - Re-baselined the inline hashes on H100 via `EXPECTTEST_ACCEPT=1`. - Replaced the unconditional `@unittest.skip` with the `@unittest.skipUnless(has_cuda_capability(9, 0), ...)` gate that the Llama3 / Qwen3 siblings already use, since these numerics only match on sm_90+. ## Why These are the `eager` self-determinism guardrails (run via `Trainer`, no `make_fx`), so the histc/tracing regressions never applied to them — only the baked-in expected hashes were stale. The loss is **unchanged** (`7.4749956130981445` for both); only the full-precision `model_hash` / `grad_hash` moved. ## Test On 8×H100 (sm_90): ``` pytest torchtitan/experiments/graph_trainer/tests/test_bitwise_deterministic.py \ -k "TestDSv3BitwiseDeterministic and test_eager_self_deterministic or \ TestDSv3FlexAttnBitwiseDeterministic and test_eager_self_deterministic" -v ``` Both pass reproducibly against the new baselines (verified without `EXPECTTEST_ACCEPT`, i.e. a true guardrail check). `pre-commit` clean. Note: the FlexAttention `test_precompile_vs_trace` skips ("unpicklable code objects") are intentionally left in place — that is a separate, structural limitation tracked elsewhere.
… working combo) Prior default ``local_batch_size=2, activation_checkpoint_mode="none"`` OOMs at first forward on Sunspot 2N (level_zero / UR_RESULT_ERROR_OUT_OF_RESOURCES). Production scripts already overrode LBS=1 on the CLI, so this brings the registry default in line. AC=none also leaves no headroom for optimizer-step transient memory. AC="full" doesn't help — it hits PyTorch's ``CheckpointError: Recomputed values have different metadata`` mid-step because MoE token routing isn't bit-exact across forward + recompute passes (router picks ±1 token per expert → saved shape (N, hidden) vs recomputed (N±1, hidden)). This is a long-standing failure (May 12 log shows the same error); PR pytorch#3146 / PR pytorch#3450's deterministic ``histc → bincount`` swap fixed it only in the *forward* path — AC=full still re-routes on recompute. AC="selective" only checkpoints ops in the SAC save list (which excludes the router), so the non-deterministic routing decision is NOT recomputed and the shape stays stable. Smoke verified on Sunspot 2N (job 12468186, moe_10b_2b_sdpa_ep at new defaults): step 1 loss 12.96, grad_norm 2.28, peak memory 51.05 GiB / 79.79% — fits with ~13 GiB headroom. Step 5 stable at loss 12.23. ``moe_10b_2b_sdpa_ep`` inherits from ``moe_10b_2b_sdpa`` so both pick up the new default.
What changed
routing_map.sum(...)instead oftorch.histc(...).Test plan
Loss comparison: The loss is bit-wise identical across 100 stesps