Skip to content

[MoE] Using routing map instead of histc to count number_tokens_per_expert - #3450

Merged
wwwjn merged 15 commits into
mainfrom
moe_routing_map
Jun 2, 2026
Merged

wwwjn merged 15 commits into
mainfrom
moe_routing_map

Conversation

@acisseJZhong

@acisseJZhong acisseJZhong commented May 28, 2026 •

Copy link
Copy Markdown
Contributor

What changed

  1. Router.forward() now builds and returns an explicit boolean routing_map_BLE with shape (B, L, E), using scatter_() (using a local map to wrap around scatter_ becuase scatter_ doesn't support DTensor yet) from topk_expert_ids_BLK.
  2. Per-expert token counts are computed from routing_map.sum(...) instead of torch.histc(...).

Test plan

Loss comparison: The loss is bit-wise identical across 100 stesps

  NCCL_NVLS_ENABLE=0 \
  CUDA_VISIBLE_DEVICES=4,5,6,7 \
  python scripts/loss_compare.py . main \
    --baseline-module='llama4' \
    --baseline-config='llama4_debugmodel' \
    --baseline-options='--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 2
  --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 2' \
    --baseline-ngpus=4 \
    --test-module='llama4' \
    --test-config='llama4_debugmodel' \
    --test-options='--parallelism.pipeline_parallel_degree 1 --parallelism.data_parallel_shard_degree 2
  --parallelism.tensor_parallel_degree 2 --parallelism.expert_parallel_degree 2' \
    --test-ngpus=4 \
    --no-seed-checkpoint \
    --output-folder=agent_space/loss_compare_current_vs_main_dp2tp2ep2

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label May 28, 2026
@acisseJZhong
acisseJZhong marked this pull request as draft May 28, 2026 18:41
@wwwjn wwwjn changed the title [Do not review] MoE routing map [MoE] Using routing map instead of histc to count number_tokens_per_expert May 29, 2026
@wwwjn
wwwjn marked this pull request as ready for review May 29, 2026 19:59
saforem2 added a commit to saforem2/torchtitan that referenced this pull request May 29, 2026
~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.
Comment thread torchtitan/models/common/moe.py Resolved
Comment thread torchtitan/models/common/moe.py Resolved
Comment thread torchtitan/models/common/moe.py Resolved
Comment thread torchtitan/models/common/moe.py Resolved
Comment thread torchtitan/models/common/moe.py Resolved
Comment thread torchtitan/models/common/moe.py Resolved
@wwwjn
wwwjn requested a review from tianyu-l June 1, 2026 00:40
Comment on lines +91 to +96
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)

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.

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?

@wwwjn wwwjn Jun 1, 2026 •

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.

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:

  1. For AllToAllTokenDispatcher we pass num_tokens_per_expert_E into dispatch() call and return it as is.
  2. 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?

Comment thread torchtitan/models/common/moe.py Resolved

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.

change tokens_per_expert_E variable name
same for DeepEP

input_shape,
routed_input_RD,
permuted_indices,
num_global_tokens_per_local_expert_e,

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.

add a TODO that we might want to use this as buffer to compute expert_bias_E, but HybridEP token dropping is not clear.

Comment thread torchtitan/models/common/moe.py Outdated
self,
x_RD: torch.Tensor,
num_tokens_per_expert_E: torch.Tensor,
num_global_tokens_per_local_expert_e: torch.Tensor,

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.

@tianyu-l Can I get a final review of the rename in _experts_forward function? Basically I renamed E -> e

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.

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_EfD instead 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.

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.

good to add a NOTE on notation

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.

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
)

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.

that sounds good

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),

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.

I have to put a placement here, because local_map doesn't take None as a input, cc @tianyu-l

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.

@wwwjn
wwwjn merged commit 4c6f72d into main Jun 2, 2026
19 of 21 checks passed
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Jun 2, 2026
…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).
SherlockNoMad added a commit that referenced this pull request Jun 2, 2026
## 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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Jun 7, 2026
… 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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

3 participants