Skip to content

[MoE][7/n] Keep 3D tensors through MoE, flatten inside GroupedExperts - #3423

Merged
acisseJZhong merged 11 commits into
mainfrom
gh/acisseJZhong/18/head
May 27, 2026
Merged

acisseJZhong merged 11 commits into
mainfrom
gh/acisseJZhong/18/head

Conversation

@acisseJZhong

@acisseJZhong acisseJZhong commented May 23, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

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]
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label May 23, 2026
@acisseJZhong
acisseJZhong marked this pull request as draft May 23, 2026 07:37
[ghstack-poisoned]
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request May 23, 2026
Move the `.view(-1, dim)` flatten from `MoE.forward()` into
`GroupedExperts.forward()` and `GptOssGroupedExperts.forward()`, so that
the router and shared experts operate on 3D `(bs, slen, dim)` tensors
throughout.

This fixes the `_router_gate_config` for full_dtensor mode: previously,
`MoE.forward()` called `.view(-1, dim)` on a 3D DTensor with `Shard(1)`,
creating a `StridedShard` that the gate config could not express.  With
this change the gate sees 3D input and can use `Shard(1)` (slen dim)
directly.

Changes:
- `GroupedExperts.forward`: flatten x, top_scores,
  selected_experts_indices to 2D at entry; return 2D output from combine
  (no `.view(input_shape)` — would break when sp_size > 1 since combine
  expands the token count).
- `GptOssGroupedExperts.forward`: same flatten-at-entry pattern, remove
  `.view(input_shape)`.
- `TokenChoiceTopKRouter`: use `dim=-1` everywhere instead of hardcoded
  dim indices; `unflatten(-1, ...)` and `flatten(-2)` for node-limited
  routing; works with any number of leading dims.
- `MoE.forward`: keep 3D x, pass to router/experts/shared_experts,
  `return out.reshape(bs, slen, dim)` at the end.
- `moe_sharding.py`: update shared expert configs from `Shard(1)` to
  `Shard(2)` (feature dim of 3D); router gate EP config from `Shard(0)`
  to `Shard(1)` (slen dim of 3D).


ghstack-source-id: b179269
Pull-Request: #3423
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request May 23, 2026
Move the `.view(-1, dim)` flatten from `MoE.forward()` into
`GroupedExperts.forward()` and `GptOssGroupedExperts.forward()`, so that
the router and shared experts operate on 3D `(bs, slen, dim)` tensors
throughout.

This fixes the `_router_gate_config` for full_dtensor mode: previously,
`MoE.forward()` called `.view(-1, dim)` on a 3D DTensor with `Shard(1)`,
creating a `StridedShard` that the gate config could not express.  With
this change the gate sees 3D input and can use `Shard(1)` (slen dim)
directly.

Changes:
- `GroupedExperts.forward`: flatten x, top_scores,
  selected_experts_indices to 2D at entry; return 2D output from combine
  (no `.view(input_shape)` — would break when sp_size > 1 since combine
  expands the token count).
- `GptOssGroupedExperts.forward`: same flatten-at-entry pattern, remove
  `.view(input_shape)`.
- `TokenChoiceTopKRouter`: use `dim=-1` everywhere instead of hardcoded
  dim indices; `unflatten(-1, ...)` and `flatten(-2)` for node-limited
  routing; works with any number of leading dims.
- `MoE.forward`: keep 3D x, pass to router/experts/shared_experts,
  `return out.reshape(bs, slen, dim)` at the end.
- `moe_sharding.py`: update shared expert configs from `Shard(1)` to
  `Shard(2)` (feature dim of 3D); router gate EP config from `Shard(0)`
  to `Shard(1)` (slen dim of 3D).

ghstack-source-id: 196aad1
Pull-Request: #3423
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request May 23, 2026
Move the `.view(-1, dim)` flatten from `MoE.forward()` into
`GroupedExperts.forward()` and `GptOssGroupedExperts.forward()`, so that
the router and shared experts operate on 3D `(bs, slen, dim)` tensors
throughout.

This fixes the `_router_gate_config` for full_dtensor mode: previously,
`MoE.forward()` called `.view(-1, dim)` on a 3D DTensor with `Shard(1)`,
creating a `StridedShard` that the gate config could not express.  With
this change the gate sees 3D input and can use `Shard(1)` (slen dim)
directly.

Changes:
- `GroupedExperts.forward`: flatten x, top_scores,
  selected_experts_indices to 2D at entry; return 2D output from combine
  (no `.view(input_shape)` — would break when sp_size > 1 since combine
  expands the token count).
- `GptOssGroupedExperts.forward`: same flatten-at-entry pattern, remove
  `.view(input_shape)`.
- `TokenChoiceTopKRouter`: use `dim=-1` everywhere instead of hardcoded
  dim indices; `unflatten(-1, ...)` and `flatten(-2)` for node-limited
  routing; works with any number of leading dims.
- `MoE.forward`: keep 3D x, pass to router/experts/shared_experts,
  `return out.reshape(bs, slen, dim)` at the end.
- `moe_sharding.py`: update shared expert configs from `Shard(1)` to
  `Shard(2)` (feature dim of 3D); router gate EP config from `Shard(0)`
  to `Shard(1)` (slen dim of 3D).

ghstack-source-id: 4d20406
Pull-Request: #3423
[ghstack-poisoned]
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request May 23, 2026
Move the `.view(-1, dim)` flatten from `MoE.forward()` into
`GroupedExperts.forward()` and `GptOssGroupedExperts.forward()`, so that
the router and shared experts operate on 3D `(bs, slen, dim)` tensors
throughout.

This fixes the `_router_gate_config` for full_dtensor mode: previously,
`MoE.forward()` called `.view(-1, dim)` on a 3D DTensor with `Shard(1)`,
creating a `StridedShard` that the gate config could not express.  With
this change the gate sees 3D input and can use `Shard(1)` (slen dim)
directly.

Changes:
- `GroupedExperts.forward`: flatten x, top_scores,
  selected_experts_indices to 2D at entry; return 2D output from combine
  (no `.view(input_shape)` — would break when sp_size > 1 since combine
  expands the token count).
- `GptOssGroupedExperts.forward`: same flatten-at-entry pattern, remove
  `.view(input_shape)`.
- `TokenChoiceTopKRouter`: use `dim=-1` everywhere instead of hardcoded
  dim indices; `unflatten(-1, ...)` and `flatten(-2)` for node-limited
  routing; works with any number of leading dims.
- `MoE.forward`: keep 3D x, pass to router/experts/shared_experts,
  `return out.reshape(bs, slen, dim)` at the end.
- `moe_sharding.py`: update shared expert configs from `Shard(1)` to
  `Shard(2)` (feature dim of 3D); router gate EP config from `Shard(0)`
  to `Shard(1)` (slen dim of 3D).

ghstack-source-id: c3d90f5
Pull-Request: #3423
[ghstack-poisoned]
acisseJZhong added a commit that referenced this pull request May 23, 2026
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)

ghstack-source-id: 9154b16
Pull-Request: #3423
@acisseJZhong

Copy link
Copy Markdown
Contributor Author

@claude review

@acisseJZhong
acisseJZhong marked this pull request as ready for review May 23, 2026 23:13
@claude

claude Bot commented May 23, 2026 •

Copy link
Copy Markdown
Contributor

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


Code Review: [MoE] Keep 3D tensors through MoE, flatten inside GroupedExperts

  • Gather context and read changed files
  • Review torchtitan/models/common/moe.py changes
  • Review torchtitan/models/common/moe_sharding.py changes
  • Review torchtitan/models/gpt_oss/moe.py changes
  • Post review feedback

Overall: Clean PR that correctly moves the flatten from the MoE boundary into GroupedExperts, avoiding StridedShard for DTensors. The approach is sound — the router now uses relative dims (dim=-1, unflatten(-1, ...), flatten(-2)) making it shape-agnostic, and the sharding placements are updated consistently for the 2D→3D shift.

Minor Issues

  1. Stale docstring in _get_node_limited_routing_scores (torchtitan/models/common/moe.py:172-175):

    The Args/Returns still say (bs*slen, num_experts) but inputs are now 3D (bs, slen, num_experts). Should be updated to match:

    Args:
        scores_for_choice: Router scores with expert_bias (if any), shape (*, num_experts)
    Returns:
        scores_for_choice: shape (*, num_experts)

    Fix this →

  2. Typo in docstring (torchtitan/models/common/moe_sharding.py:69):

    "feature dim of for 3-D activations from MoE"

    Should be "feature dim for 3-D activations from MoE" (extra "of").

    Fix this →

What looks good

  • Reshape placement in MoE.forward (line 383): Moving out.reshape(bs, slen, dim) before the shared_out addition is correct since shared_out is now 3D from FeedForward operating on 3D input. The Partial() placement on the experts output DTensor handles reshape cleanly.
  • Router dim changes: All dim=1 → dim=-1, scatter_(1, ...) → scatter_(-1, ...), view(-1, N) → unflatten(-1, ...) / flatten(-2) are correct and make the code more robust.
  • Sharding updates: Shard(0) → Shard(1) for EP token sharding (slen is now dim 1 in 3D), Shard(1) → Shard(2) for TP feature dim — all consistent.
  • Symmetry between GroupedExperts and GptOssGroupedExperts: Both get the same flatten-at-entry pattern.
  • Adding explicit in_dst_shardings for EP-off router gate (moe_sharding.py:123): Good to be explicit rather than relying on implicit behavior.

@acisseJZhong acisseJZhong changed the title [MoE] Keep 3D tensors through MoE, flatten inside GroupedExperts [MoE][7/n] Keep 3D tensors through MoE, flatten inside GroupedExperts May 23, 2026

@tianyu-l tianyu-l left a comment

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.

please address comments

Comment thread torchtitan/models/common/moe.py Outdated
Comment on lines +89 to +93
x = x.reshape(-1, x.size(-1))
top_scores = top_scores.reshape(-1, top_scores.size(-1))
selected_experts_indices = selected_experts_indices.reshape(
-1, selected_experts_indices.size(-1)
)

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.

can we use view instead of reshape, if things are already contiguous

Comment thread torchtitan/models/common/moe.py Outdated
)

# top scores shape (bs*slen, top_k)
# top scores shape (*, top_k)

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.

can we be explicit and use (bs, slen, top_k)

Comment thread torchtitan/models/gpt_oss/moe.py Outdated
Comment on lines +148 to +152
x = x.reshape(-1, x.size(-1))
top_scores = top_scores.reshape(-1, top_scores.size(-1))
selected_experts_indices = selected_experts_indices.reshape(
-1, selected_experts_indices.size(-1)
)

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.

same

Comment thread torchtitan/models/common/moe.py Outdated
"""
n_tokens = scores.size(0)
leading_shape = scores.shape[:-1]
n_tokens = scores[..., 0].numel()

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.

Let's assume the dimension is (bs, slen, _) and use them explicitly.

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

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.

to update

[ghstack-poisoned]
@acisseJZhong

Copy link
Copy Markdown
Contributor Author

@claude review this PR, be concise.

@claude

claude Bot commented May 26, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @acisseJZhong's task in 48s —— View job


Code Review

  • Read PR diff and changed files
  • Post review feedback

Overall: Clean, correct change. Moving the flatten into GroupedExperts/GptOssGroupedExperts keeps the MoE boundary shape-agnostic and avoids StridedShard. The router's dim changes (dim=-1, unflatten, flatten(-2)) are all correct.

Issues to address (from reviewer comments)

  1. Use view instead of reshape (moe.py:382): out.view(bs, slen, dim) — since the experts produce a contiguous 2D output, view is safe and more explicit. Already done in this version. ✅

  2. Use explicit (bs, slen, top_k) in _debug_force_load_balance_routing (moe.py:245): The comment says (*, top_k) but reviewer asked for explicit dims. Should be (bs, slen, top_k).

  3. Stale docstring (moe.py:172-175): Already updated to (bs, slen, num_experts) in this version. ✅

  4. Typo (moe_sharding.py:88): "feature dim of 3-D activation" — extra "of" removed from line 69 but remains on line 88. Should be "feature dim of 3-D activation" → actually line 88 reads correctly as "input Shard(2) (feature dim of 3-D activation) from upstream colwise" — that's fine grammatically.

Remaining reviewer request

The reviewer asked to "assume the dimension is (bs, slen, _) and use them explicitly" in the GroupedExperts.forward docstring/comments and _debug_force_load_balance_routing. The _debug_force_load_balance_routing return comment at line 245 still uses (*, top_k) — consider making it (bs, slen, top_k) as requested.

Looks good

  • Symmetry between GroupedExperts and GptOssGroupedExperts flatten patterns
  • Sharding placement updates (Shard(0)→Shard(1), Shard(1)→Shard(2)) are consistent for the 2D→3D shift
  • Adding explicit in_dst_shardings for the EP-off router gate config
  • out.view(bs, slen, dim) placed before shared_out addition (correct since shared_out is 3D from shared experts operating on 3D input)

[ghstack-poisoned]
@acisseJZhong acisseJZhong added the ciflow/h100.8 Trigger H100.8 CI label May 27, 2026
@acisseJZhong
acisseJZhong changed the base branch from gh/acisseJZhong/18/base to main May 27, 2026 08:24
@acisseJZhong
acisseJZhong merged commit 7fcd9be into main May 27, 2026
12 of 15 checks passed
saforem2 added a commit to saforem2/torchtitan that referenced this pull request May 27, 2026
… routing

Merged 7 upstream commits (19c567f..af33f76). Documents which
ones needed ezpz replays:

- PR pytorch#3398 (Module subclass refactor): 3 import paths replayed in
  b052f29 — pure import-path swap, class API unchanged.
- PR pytorch#3146 (deterministic MoE routing): inherits transitively; this
  is the upstream fix for the _histc_xpu non-determinism blocker
  we hit on 2026-05-21. --debug.deterministic on MoE+XPU should now
  work.
- PR pytorch#3423 (MoE [7/n] 3D tensors): inherits transitively; doesn't
  touch deepseek_v3 callsites.
- PR pytorch#3105 (FSDP symm_mem): skipped — ezpz has its own apply_fsdp
  and symm_mem is an optional optimization XPU CCL likely doesn't
  support.
- PRs pytorch#3331/pytorch#3369/pytorch#3361: graph_trainer-only no-ops.

Captures two action items: smoke-test before next production push,
and re-try --debug.deterministic on MoE+XPU.
saforem2 added a commit to saforem2/torchtitan that referenced this pull request May 27, 2026
… fix is incomplete

Three smokes on my own 2N alloc (12467455):

- agpt_2b clean (24.34 GiB, ~5,900 TPS, ~22% MFU) — matches the
  2026-05-22 baseline exactly. PR pytorch#3398 nn_modules import-path
  replay (b052f29) didn't perturb agpt.
- moe_2b_ep at the new LBS=2 default clean (27.09 GiB, ~3,200 TPS,
  9.4% MFU, loss 12.93→6.12) — numerically identical to the
  2026-05-22 baseline (27.08 GiB, ~3,200 TPS, 9.4% MFU, loss 6.15).
  PR pytorch#3423 (MoE [7/n] 3D tensors) inherits cleanly via the
  dispatcher path.
- moe_2b_ep with --debug.deterministic STILL FAILS with the same
  _histc_xpu error from 2026-05-21. PR pytorch#3146 was advertised to fix
  this but the merged diff only contains the aten.topk.default save
  -list addition — the promised histc → bincount swap in
  common/moe.py:262 is missing from the commit. Verified via GitHub
  API.

Adds smoke report at
docs/experiments/moe/sunspot/20260527-smoke-n2-40th-sync.md, links
from the moe experiments README, updates the 40th-sync entry in
upstream-sync.md, and the journal.

Open action item: file upstream issue on pytorch/torchtitan for
the incomplete PR pytorch#3146.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/h100.8 Trigger H100.8 CI 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