Skip to content

[MoE][8/n] Use shape suffix for MoE - #3425

Merged
acisseJZhong merged 20 commits into
mainfrom
gh/acisseJZhong/19/head
May 28, 2026
Merged

acisseJZhong merged 20 commits into
mainfrom
gh/acisseJZhong/19/head

Conversation

@acisseJZhong

@acisseJZhong acisseJZhong commented May 24, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

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

[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 24, 2026
@acisseJZhong
acisseJZhong marked this pull request as draft May 24, 2026 05:37
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request May 24, 2026
ghstack-source-id: d8f92f4
Pull-Request: #3425
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request May 24, 2026
ghstack-source-id: ef150fe
Pull-Request: #3425
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request May 24, 2026
ghstack-source-id: cad12d6
Pull-Request: #3425
@acisseJZhong

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented May 24, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @acisseJZhong's task in 1m 26s —— View job


Code Review: refactor moe to shape suffix

  • Gather context and review diff
  • Review torchtitan/models/common/moe.py
  • Review torchtitan/models/common/token_dispatcher.py
  • Review torchtitan/models/common/moe_sharding.py
  • Review torchtitan/components/optimizer.py
  • Review torchtitan/models/gpt_oss/moe.py
  • Post review summary

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

  • The legend comment at the top of moe.py is helpful and concise.
  • The suffix convention is applied consistently (E, D, F, K, T, N, R).
  • Docstrings are updated to match the new naming, which is good.

Issues / Suggestions

1. Inconsistency: N vs R in token_dispatcher.py comments

The legend says:

  • N = routed tokens (T*K) — all token–expert assignments
  • R = routed tokens assigned to local experts — subset after dispatch

In LocalDispatchMetadata (line 24-25), the comment still says # (N*top_k,) which should just be # (N,) since N is already T*K:

token_indices_experts_sorted: torch.Tensor  # (N*top_k,)
topk_scores_experts_sorted: torch.Tensor  # (N*top_k,) scores in expert-sorted order

These should be # (N,) per the legend definition. Fix this →

2. _permute and _unpermute not renamed

AllToAllTokenDispatcher._permute (line 344) and _unpermute (line 387) still use unsuffixed parameter names (routed_input, num_tokens_per_expert_group, routed_output, input_shape, permuted_indices). Since these are internal methods of a file that's otherwise fully converted, it would be more consistent to suffix them too. Not blocking, but worth a follow-up.

3. num_tokens_per_expert_E return from _permute is semantically "local experts"

At token_dispatcher.py:326, _permute returns its last value as num_tokens_per_expert_E, but the actual computation (t_mat.sum(0) at line 379) sums across EP ranks for each local expert. The suffix _E implies all experts, but this is only num_local_experts in size. This could be confusing — maybe num_tokens_per_local_expert_E or a comment clarifying the shape is (num_local_experts,) not (num_experts,) would help.

4. out_TD naming in MoE.forward before reshape

At moe.py:375, out_TD = self.experts(...) — but GroupedExperts.forward returns a (T, D) tensor (after combine scatter_adds), so this is correct. However two lines later at line 393, out_BLD = out_TD.reshape(bs, slen, dim) reshapes to BLD. The naming accurately tracks the shape transformation — looks good.

5. DeepEPTokenDispatcher.combine introduces combined_TD

At token_dispatcher.py:621, the result of combine_tokens is named combined_TD. This diverges from the pattern in other dispatchers which use routed_output_RD through the combine path. The new name is actually more accurate here since after combine_tokens the tensor is back in token-space (T, D), not routed-expert space. Good naming choice.

6. Minor: LocalDispatchMetadata field name not suffixed

The dataclass field itself is token_indices_experts_sorted (no suffix), but the local variables that fill it are token_indices_experts_sorted_N. This is fine for struct fields (suffixing struct field names can be noisy), just noting the convention choice is intentional.

7. moe_sharding.py — the in_src_shardings / in_dst_shardings keys must match forward() parameter names

The keys in _moe_sharding_config were updated from "x" to "x_BLD" (line 159-162). These presumably need to match the actual parameter name of MoE.forward. Verified this is correct — MoE.forward(self, x_BLD) at moe.py. Same for GroupedExperts.forward args ("x_BLD", "topk_scores_BLK", "topk_ids_BLK") at moe_sharding.py:249-251. This is correct and critical — good that it's consistent.

Summary

Clean, mechanical rename. The PR improves readability significantly for anyone working with the MoE code. The main actionable item is issue #1 (stale N*top_k comments in LocalDispatchMetadata). Issue #2-3 are optional follow-ups.


[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request May 26, 2026
ghstack-source-id: 91ab7e3
Pull-Request: #3425
[ghstack-poisoned]
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request May 26, 2026
ghstack-source-id: b68eea6
Pull-Request: #3425
@acisseJZhong acisseJZhong changed the title refactor moe to shape suffix [MoE][8/n] Use shape suffix for MoE May 26, 2026
@acisseJZhong
acisseJZhong marked this pull request as ready for review May 26, 2026 17:34
@acisseJZhong

Copy link
Copy Markdown
Contributor Author

@claude review this PR, especially if there are any typos, try to be concise.

@claude

claude Bot commented May 26, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @acisseJZhong's task in 1m 10s —— View job


Code Review: Shape Suffix Rename

  • Gather context and review diff
  • Review moe.py for typos
  • Review token_dispatcher.py for typos
  • Review other changed files
  • Post review summary

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

gpt_oss/moe.py:122 — h_RF after the first grouped_mm actually has shape (R, 2*F) since mlp1_weight is (E, hidden_dim*2, dim). It only becomes (R, F) after swiglu on line 134. The suffix is correct after swiglu but not between lines 122–133.

Suggestion: name it h_R2F or just leave it as h_RF with the understanding that F encompasses the gated dimension. Not blocking — just noting the imprecision.

Minor naming note

token_dispatcher.py:383 — num_tokens_per_local_expert_E uses suffix _E but represents only local experts (size num_local_experts, not num_experts). The added comment on line 382 clarifies this, which is good. An alternative suffix like _El (local E) could be more precise, but the comment is sufficient.

Everything else looks good

  • Legend comment at top of moe.py ✓
  • moe_sharding.py keys match forward() parameter names ✓
  • All model variants (deepseek_v3, llama4, qwen3, qwen3_vl) updated consistently for w1_EFD/w2_EDF/w3_EFD init and sharding dicts ✓
  • optimizer.py buffer/variable renames are consistent ✓
  • LocalDispatchMetadata field suffixes with # noqa: N815 for pep8-naming ✓

LGTM with the above as optional nits.


[ghstack-poisoned]
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request May 26, 2026
ghstack-source-id: d4c7b60
Pull-Request: #3425
acisseJZhong added a commit that referenced this pull request May 27, 2026
…#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]
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request May 27, 2026
ghstack-source-id: 91bde58
Pull-Request: #3425
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(

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 back to E as discussed offline -- one letter one dim

Comment thread torchtitan/models/common/moe.py Outdated
# (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,

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.

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

Comment thread torchtitan/models/gpt_oss/moe.py Outdated

h = torch._grouped_mm(
x.bfloat16(), mlp1_weight.transpose(-2, -1).bfloat16(), offs=offsets
h_R2F = torch._grouped_mm(

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.

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.

[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request May 27, 2026
ghstack-source-id: 1a3b37c
Pull-Request: #3425
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request May 27, 2026
ghstack-source-id: 7d7730e
Pull-Request: #3425
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request May 27, 2026
ghstack-source-id: 0e79ca7
Pull-Request: #3425
@acisseJZhong
acisseJZhong changed the base branch from gh/acisseJZhong/19/base to main May 28, 2026 00:22
@acisseJZhong
acisseJZhong merged commit 200100e into main May 28, 2026
11 checks passed
saforem2 pushed a commit to saforem2/torchtitan that referenced this pull request May 28, 2026
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
```
saforem2 added a commit to saforem2/torchtitan that referenced this pull request May 28, 2026
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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request May 29, 2026
…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.
ivy-zhou added a commit to ivy-zhou/torchtitan that referenced this pull request Jun 5, 2026
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.
ivy-zhou added a commit to ivy-zhou/torchtitan that referenced this pull request Jun 5, 2026
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.
ivy-zhou added a commit to ivy-zhou/torchtitan that referenced this pull request Jun 5, 2026
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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Jun 12, 2026
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.
acisseJZhong added a commit that referenced this pull request Jun 17, 2026
## 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
```
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Sep 15, 2026
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.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Sep 15, 2026
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.
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.

2 participants