Repository navigation
[MoE][8/n] Use shape suffix for MoE - #3425
Conversation
[ghstack-poisoned]
|
@claude review |
|
Claude finished @acisseJZhong's task in 1m 26s —— View job Code Review: refactor moe to shape suffix
Overall this is a clean readability refactor adopting the Shazeer shape-suffix convention. The rename is consistent and mechanical across the five files. A few observations: Positives
Issues / Suggestions1. Inconsistency: The legend says:
In token_indices_experts_sorted: torch.Tensor # (N*top_k,)
topk_scores_experts_sorted: torch.Tensor # (N*top_k,) scores in expert-sorted orderThese should be 2.
3. At 4. At 5. At 6. Minor: The dataclass field itself is 7. The keys in SummaryClean, mechanical rename. The PR improves readability significantly for anyone working with the MoE code. The main actionable item is issue #1 (stale |
[ghstack-poisoned]
|
@claude review this PR, especially if there are any typos, try to be concise. |
|
Claude finished @acisseJZhong's task in 1m 10s —— View job Code Review: Shape Suffix Rename
Clean, consistent rename. The legend is helpful, and the suffix convention is applied uniformly across all 12 files. No typos found. One shape suffix inaccuracy
Suggestion: name it Minor naming note
Everything else looks good
LGTM with the above as optional nits. |
[ghstack-poisoned]
…#3423) Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0) (oldest at bottom): * #3425 * __->__ #3423 ## Summary Address #3386 (comment) Move `.view(-1, dim)` from `MoE.forward()` into `GroupedExperts.forward()` / `GptOssGroupedExperts.forward()`, so the router and shared experts see 3D `(bs, slen, dim)` tensors. This avoids `StridedShard` when `.view(-1, dim)` is called on a `Shard(1)` 3D DTensor at the MoE boundary. - `GroupedExperts.forward` / `GptOssGroupedExperts.forward`: flatten to 2D at entry - `TokenChoiceTopKRouter`: use `dim=-1` and relative dim ops to handle any number of leading dims - `moe_sharding.py`: update placements for 3D shapes (`Shard(1)` for slen, `Shard(2)` for feature dim) ## Test ``` NCCL_NVLS_ENABLE=0 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 --training.local_batch_size=1" --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 --training.local_batch_size=1" --test-ngpus=4 --assert-equal --no-seed-checkpoint ```
[ghstack-poisoned]
| with torch.no_grad(): | ||
| num_tokens_per_expert_group = all_to_all_single( | ||
| num_tokens_per_expert, | ||
| num_global_tokens_per_local_expert_eEP = all_to_all_single( |
There was a problem hiding this comment.
change back to E as discussed offline -- one letter one dim
| # (https://medium.com/@NoamShazeer/shape-suffixes-good-coding-style-f836e72e24fd): | ||
| # B = batch, L = sequence length, D = model dimension, | ||
| # F = hidden (FFN intermediate) dimension, E = num experts, | ||
| # e = num local experts (E / EP), EP = expert-parallel ranks, |
There was a problem hiding this comment.
update accordingly -- remove EP
also it might be worth adding a note why we special case e in tokens_per_expert, and it's not used in EP-sharded grouped experts
|
|
||
| h = torch._grouped_mm( | ||
| x.bfloat16(), mlp1_weight.transpose(-2, -1).bfloat16(), offs=offsets | ||
| h_R2F = torch._grouped_mm( |
There was a problem hiding this comment.
Note that this is also violating 1 ascii 1 dim principle. E.g. how I can differentiate a 2 dim tensor from a 3 dim tensor where 2nd dim is of size "2"?
Maybe the obvious way is to introduce another letter which mathematically == 2F.
I'm also OK to live with this, but please add comment here.
Stack from [ghstack](https://github.com/ezyang/ghstack/tree/0.15.0) (oldest at bottom): * __->__ pytorch#3425 Change MoE shape notation to https://medium.com/@NoamShazeer/shape-suffixes-good-coding-style-f836e72e24fd ``` NCCL_NVLS_ENABLE=0 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 --assert-equal --no-seed-checkpoint ```
Merged 1 upstream commit (200100e, PR pytorch#3425). Pure rename refactor applying the Shazeer shape-suffix convention across MoE tensors (x -> x_BLD, routed_output -> routed_output_RD, etc.). Touches common/moe.py, token_dispatcher.py, deepseek_v3/, llama4/, qwen3/, gpt_oss/, optimizer, and EP unit tests. Loss-comparator verified --assert-equal upstream. Several method signatures change (dispatch, _unpermute, _make_dispatcher) but none are called from experiments/ezpz/, so no replay needed. Imports smoke green.
…upedExperts The 41st sync (pytorch#3425, MoE [8/n] shape-suffix rename) renamed GroupedExperts parameters from w1/w2/w3 to w1_EFD/w2_EDF/w3_EFD (Shazeer shape-suffix style). Our EzpzGroupedExperts subclass inherits the params, but three ezpz-side references to the old names were missed at sync time because we didn't smoke moe_2b_ep after the 41st sync landed: - experiments/ezpz/moe/sharding.py: _GROUPED_EXPERTS_PARAM_LAYOUT keys were "w1"/"w2"/"w3" — set_moe_sharding_config blew up with "EzpzGroupedExperts.w1_EFD has no placement declared in sharding_config.state_shardings". - experiments/ezpz/moe/__init__.py: _depth_experts_init returned initializer dict keyed by w1/w2/w3 — model init blew up with "No initializer for parameter 'w1_EFD'". - experiments/ezpz/moe/experts.py: _experts_forward read self.w1 /self.w2/self.w3 — would have AttributeError'd had the prior two bugs not preempted it. All three now use the new w{1,2,3}_E{F,D}D names. Caught by the 42nd-sync 2N smoke (job 12467655). moe_2b_ep at LBS=2 now matches the 2026-05-27 baseline: 50 clean steps in 323 s, peak 26.99 GiB (42.18%), 3,135 TPS, 9.09% MFU, loss step 50 = 6.13.
Summary: Llama4StateDictAdapter has three round-trip bugs that the new HF round-trip test catches. This diff fixes all three and adds llama4 to the test parametrization. 1. MoE expert weight names are out of sync with the model. `common/moe.py` declares MoE expert weights as `w1_EFD`, `w2_EDF`, `w3_EFD` (the shape-suffix convention added in PR pytorch#3425), but the adapter still references `w1`, `w2`, `w3` everywhere. The rename PR updated the model code but did not touch the adapters. This diff updates the adapter to use the suffixed names throughout — in `from_hf_map`, in the `to_hf` branch that transposes `w2` for storage, in the `to_combine` collection logic, and in the `from_hf` chunk-and-split that materializes `w1` / `w3` from HF's `gate_up_proj`. 2. Dense FF layers have no mappings. Llama4's interleaved MoE pattern (debugmodel uses `interleave_moe_layer_step=2`) means layers 0, 2, 4 are dense FF with `feed_forward.w1` / `w2` / `w3.weight` keys, while layers 1, 3, 5 are MoE. The adapter only had MoE mappings — dense FF layers had nowhere to go. Add the dense mappings analogous to llama3, with the HF `gate_proj` / `up_proj` / `down_proj` names under the `feed_forward` prefix per HF's `Llama4TextMLP` and `Llama4TextDecoderLayer`. 3. `expert_bias_E` cannot survive HF round-trip. This is auxiliary-loss-free load-balancing bias (DeepSeek paper, adapted for Qwen/Mixtral-style routers including llama4). HF transformers' Llama4 router has no equivalent — `Llama4Router` is plain `nn.Linear(bias=False)` and the MoE forward never adds any bias. So a real HF llama4 safetensors file cannot have any key for it. We keep the existing `None` mapping in `from_hf_map` (drop on `to_hf`, matches HF format) and add an explicit zeros-reinitialization in `from_hf` so the native key set stays complete. The bias resets across an HF round-trip by design. Adapter audit notes: - No `from_hf` input-mutation antipattern (the function constructs a fresh `state_dict = {}` at the top, never mutates the input). - The transpose on `w2_EDF` (and on `w1_EFD` / `w3_EFD` during the `to_combine` step) produces non-contiguous views. safetensors refuses to serialize non-contiguous tensors, so we now `.contiguous()` after the transpose where the view escapes into `hf_state_dict` directly. The `to_combine` path is OK because `torch.cat` produces a fresh contiguous tensor. Test changes: - Add `("llama4", "debugmodel")` to `_MODEL_FLAVORS`. - Introduce `_NATIVE_EXCLUSIONS: dict[tuple[str, str], list[str]]` for keys whose tensor values cannot round-trip bit-exactly (the key set itself must still match — exclusions only suppress the per-tensor `torch.equal` check). Every exclusion is explicitly listed with a comment explaining why; this is the only entry so far. - Add the llama4 exclusion for `.*\.moe\.expert_bias_E$` with a comment citing HF's missing equivalent and the load-balancing semantics. Test Plan: - python -m unittest tests.unit_tests.test_hf_checkpoint_roundtrip -v - All three subTests pass: llama3/debugmodel, llama3/debugmodel_fused_qkv, llama4/debugmodel. - Test runtime: ~3.6 seconds.
Summary: GptOssStateDictAdapter has the same class of round-trip bugs llama4 had — out-of-sync MoE expert weight names and missing expert_bias_E handling. This diff fixes both and adds gpt_oss to the test parametrization. 1. MoE expert weight names are out of sync with the model. `gpt_oss/moe.py` declares MoE expert weights as `mlp1_weight_EGD`, `mlp1_bias_EG`, `mlp2_weight_EDF`, `mlp2_bias_ED` (the shape-suffix convention added in PR pytorch#3425), but the adapter still references `mlp1_weight`, `mlp1_bias`, `mlp2_weight`, `mlp2_bias`. Update `from_hf_map` to use the suffixed names. 2. `expert_bias_E` is missing from `from_hf_map` entirely. gpt_oss uses the same auxiliary-loss-free load-balancing scheme as llama4. HF transformers' gpt_oss router has no equivalent buffer, so add the `None: "layers.{}.moe.expert_bias_E"` mapping (drop on `to_hf`, matches HF format) and reinitialize it to zeros in `from_hf` so the native key set stays complete. Same design as llama4 — the bias resets across an HF round-trip by design. Adapter audit notes: - No `from_hf` input-mutation antipattern (the function constructs a fresh `state_dict = {}` at the top, never mutates the input). - The `to_hf` function did not guard against `None` hf-key values from the inverted `to_hf_map` (would crash with `AttributeError` on `hf_key.format(layer_num)` once the `None: ...` entry was added). Fix by adding `if hf_key is None: continue` checks in both the layered and non-layered branches — same pattern llama4 already had. - gpt_oss does not transpose expert weights, so no contiguous-view issue. Test changes: - Add `("gpt_oss", "debugmodel")` to `_MODEL_FLAVORS`. - Add gpt_oss exclusion entry to `_NATIVE_EXCLUSIONS` for `.*\.moe\.expert_bias_E$`, citing the same HF-has-no-equivalent reasoning as llama4. Test Plan: - python -m unittest tests.unit_tests.test_hf_checkpoint_roundtrip -v - All four subTests pass: llama3/debugmodel, llama3/debugmodel_fused_qkv, llama4/debugmodel, gpt_oss/debugmodel. - Test runtime: ~4.6 seconds.
Summary: DeepSeekV3StateDictAdapter had the same MoE expert weight name mismatch as llama4 and gpt_oss — `from_hf_map` references `w1` / `w2` / `w3` while `common/moe.py` declares `w1_EFD` / `w2_EDF` / `w3_EFD` (the shape-suffix convention from PR pytorch#3425). This manifested as a hard crash, not a silent miss: `to_hf` invokes `to_hf_map[abstract_key]` directly with no guard, so the missing entry raises `KeyError: 'layers.{}.moe.experts.w1_EFD'`. Rename the three MoE expert weight entries in `from_hf_map` to use the suffixed names. deepseek_v3 is the only MoE adapter in this stack where `expert_bias_E` actually round-trips: HF transformers' DeepSeek router has `e_score_correction_bias` as a real persisted buffer (originally introduced by the DeepSeek paper as part of the model definition), and the adapter already maps to it on line 56: "model.layers.{}.mlp.gate.e_score_correction_bias": "layers.{}.moe.expert_bias_E" So no `_NATIVE_EXCLUSIONS` entry is needed for deepseek_v3, unlike llama4 / gpt_oss where HF's router has no equivalent buffer and the bias is dropped + reset to zeros across the round-trip. Adapter audit notes: - No `from_hf` input-mutation antipattern (the function constructs a fresh `state_dict = {}` at the top, never mutates the input). - to_hf invokes `to_hf_map[abstract_key]` and `to_hf_map[key]` without a presence check or None guard. Today this works for all non-MoE-expert keys because every `from_hf_map` value is a real titan key (no `None` values like the llama4 / gpt_oss `expert_bias_E` drop pattern). If a future change adds a `None: ...` entry, the same guard work as in llama4 / gpt_oss will be needed. Not adding it preemptively to keep this diff focused. - No expert-weight transposes, so no contiguous-view issue. Test changes: - Add `("deepseek_v3", "debugmodel")` to `_MODEL_FLAVORS`. - No `_NATIVE_EXCLUSIONS` entry (expert_bias_E round-trips via HF's e_score_correction_bias). Test Plan: - python -m unittest tests.unit_tests.test_hf_checkpoint_roundtrip -v - All five subTests pass: llama3/debugmodel, llama3/debugmodel_fused_qkv, llama4/debugmodel, gpt_oss/debugmodel, deepseek_v3/debugmodel. - Test runtime: ~5.3 seconds.
PR pytorch#3626 ([MoE] fix MoE state dict convert fqn names) updated deepseek_v3/state_dict_adapter.py's HF→torchtitan mapping for routed expert weights to use the Shazeer shape-suffix names that the GroupedExperts params have used since PR pytorch#3425 (41st sync): w1 → w1_EFD, w2 → w2_EDF, w3 → w3_EFD ezpz/moe's state_dict_adapter mirrored the old un-suffixed surface; replay the same 3-key rename here so HF↔torchtitan conversions match the actual on-disk param names.
## Summary Add shape suffix annotations to `attention.py` following the [Noam Shazeer shape suffix convention](https://medium.com/@NoamShazeer/shape-suffixes-good-coding-style-f836e72e24fd), matching the style introduced for MoE in #3425. Each attention backend's layout transformation is now explicit in variable names: - `_BLNH`: shared input/output layout (batch, seq, heads, head_dim) - `_TNH`: VarlenAttention packed layout (T = B*L) - `_BNLH`: FlexAttention / SDPA heads-first layout No functional changes — rename only. ## Test plan - `pre-commit run --all-files` - Existing attention unit and integration tests (no behavioral change) ``` NCCL_NVLS_ENABLE=0 python scripts/loss_compare.py . main --baseline-module='llama3' --baseline-config='llama3_debugmodel' --baseline-options=" --parallelism.data_parallel_shard_degree 2 --parallelism.t ensor_parallel_degree 2" --baseline-ngpus=4 --test-module= 'llama3' --test-config='llama3_debugmodel' --test-options= "--parallelism.data_parallel_shard_degree 2 --parallelism. tensor_parallel_degree 2" --test-ngpus=4 --assert-equal -- no-seed-checkpoint ```
Takes `_run_experts_batched_mm_padded` from samuelwheeler/torchtitan feature/aurora-moe-training into our ezpz-local experts module, where `EzpzGroupedExperts` and its ExpertComputeBackend selector already live. Core torchtitan is untouched; upstream puts this in torchtitan/models/common/moe.py, we do not need to. Renamed to `_run_experts_bmm_nodrop`. It is NOT a duplicate of our existing `bmm` backend, and the names should say why: ours pads to a capacity derived from `capacity_factor` and DROPS overflow tokens, this one pads to the largest actual per-expert count and drops nothing. That makes it the numerically exact choice, at the cost of a leading dimension that moves with the routing each step (so it is less compile-friendly than the fixed-capacity path). Measured on imbalanced routing: `bmm` zeroes 86/300 rows, `bmm_nodrop` zeroes none. Adapted to our post-pytorch#3425 parameter names -- upstream's copy predates the w1_EFD/w2_EDF/w3_EFD shape-suffix rename, so it could not be taken verbatim. Two fixes to the test that came across in step 1 and could never have passed here: 1. It imported `_run_experts_batched_mm_padded` from torchtitan.models.common.moe, which is where UPSTREAM put it. On our branch that symbol does not exist in core (0 occurrences). Repointed to the ezpz module, aliased so the test body is unchanged. 2. It built fp32 inputs and asserted rtol=1e-5, but `_run_experts_for_loop` casts to bf16 internally -- so it compared a bf16 computation against a full-precision one and saw ~3.5e-3 relative error. That is bf16 rounding, not a backend defect. Switched to bf16, the dtype production runs. Verified on Aurora (macOS cannot collect this file -- no triton): in bf16 the forward and all four gradients (w1, w2, w3, x) are bit-exact against the for_loop reference, including an expert with zero tokens. The remaining tests in that file exercise aurora_sycl / aurora_full_* backends and 50K config flavors that are not ported yet; they still fail and are left for the next step rather than silently deleted.
The ported backend did the GEMMs in whatever dtype it was handed, so it
raised "RuntimeError: expected scalar type Float but found BFloat16" the
moment parameters and activations disagreed -- which is the normal case
under mixed precision, where params stay fp32 and x arrives bf16.
Both existing backends already handle this: _run_experts_for_loop does
x_expert.bfloat16() plus w{1,2,3}[i].bfloat16() and returns
h.type_as(x); _run_experts_bmm does the same in batched form. The sww
original omitted the casts because on that branch the caller had already
aligned dtypes. Ported code inherited the omission.
Now computes in bf16 and returns type_as(x), matching the convention.
Verified both ways round:
fp32 params + bf16 x -> ok, out bf16, matches for_loop
all bf16 -> ok, out bf16, matches for_loop
Also finishes adapting tests/unit_tests/test_moe_expert_backends.py,
which came from the sww branch and disagreed with our tree in six
separate places -- that branch forked before several upstream refactors,
so nothing in it can be lifted verbatim:
1. compute_backend is on our EzpzGroupedExperts.Config, not on core
GroupedExperts.Config (0 hits in core)
2. w1/w2/w3 -> w1_EFD/w2_EDF/w3_EFD (upstream PR pytorch#3425)
3. _experts_forward -> forward
4. score_before_experts: removed from LocalTokenDispatcher.Config
5. use_grouped_mm / token_dispatcher: not fields on our config
6. the _init_grouped_experts_weights helper, same rename as (2)
Three tests are skipped rather than deleted, each naming its reason: two
exercise aurora_full_* (deliberately not ported -- they need routing
scores our forward never receives, plus an EP mesh), and one needs four
config flavors we do not define AND a count_params() that assumes
cfg.experts, which our Config does not expose.
Stack from ghstack (oldest at bottom):
Change MoE shape notation to https://medium.com/@NoamShazeer/shape-suffixes-good-coding-style-f836e72e24fd