Skip to content

[TokenSwitch] Add expert-major dispatch layout - #187784

Closed
kwen2501 wants to merge 4 commits into
gh/kwen2501/350/basefrom
gh/kwen2501/350/head
Closed

kwen2501 wants to merge 4 commits into
gh/kwen2501/350/basefrom
gh/kwen2501/350/head

Conversation

@kwen2501

@kwen2501 kwen2501 commented Jun 21, 2026 •

Copy link
Copy Markdown
Collaborator

Stack from ghstack (oldest at bottom):

Expose the receive-buffer layout through the token-switch API so callers can
select it (the NCCL EP algorithm stays high_throughput).

Expert-major orders the dispatched tokens so that all tokens routed to the same
local expert are contiguous, which is the layout a grouped GEMM over experts
consumes directly -- no regrouping pass between dispatch and the expert matmul.

  • Add a NcclEpLayout enum (Unset / ExpertMajor / RankMajor / Flat) in
    the header, values mirroring ncclEpLayout_t (ep_enums.h); kept standalone so
    the header stays free of <nccl_ep.h> (the .cu maps it via to_nccl_layout).
  • nccl_ep_create_handle takes a NcclEpLayout arg instead of hardcoding
    NCCL_EP_LAYOUT_FLAT; the layout is stashed on the handle.
  • nccl_ep_dispatch's out_topk_idx is now optional, since expert-major
    layouts leave it unpopulated; out_topk_weights also becomes optional for API
    symmetry (it stays populated -- 1-D for expert-major, 2-D for flat).
  • Python: create_routing gains a required keyword-only layout arg, with the
    output-buffer shapes chosen per layout.
  • pybind binds NcclEpLayout as a Layout enum object.

Test Plan:
On a node with 2+ GPUs and a USE_NCCL_EP=1 build:

python -m pytest test/distributed/test_token_switch.py -k expert_major -v
  • ✅ test_dispatch_expert_major
  • ✅ test_dispatch_combine_roundtrip_expert_major

(8xH100)

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Jun 21, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/187784

Note: Links to docs will display an error until the docs builds have been completed.

✅ You can merge normally! (2 Unrelated Failures)

As of commit 4e5d065 with merge base a3af108 (image):

CRCR (non-blocking) - The following CRCR downstream CI jobs failed but are non-blocking:

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@pytorch-bot pytorch-bot Bot added ciflow/h100-symm-mem ciflow/torchtitan Run TorchTitan integration tests release notes: distributed (c10d) release notes category labels Jun 21, 2026
@kwen2501
kwen2501 marked this pull request as ready for review June 21, 2026 08:49
const at::Tensor& topk_idx,
const std::optional<at::Tensor>& recv_expert_counter);
const std::optional<at::Tensor>& recv_expert_counter,
int64_t layout); // ncclEpLayout_t: expert_major=1, rank_major=2, flat=3

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be properly typed as an enum!

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done — now `NcclEpLayout`.

NcclEpHandle(void* handle, at::Tensor topk_idx, at::Tensor recv_total_counter)
NcclEpHandle(
void* handle,
int64_t layout,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same here, type is as an enum!

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done — now `NcclEpLayout`.


struct NcclEpHandle : c10::intrusive_ptr_target {
void* handle{nullptr}; // ncclEpHandle_t, opaque
int64_t layout{0}; // ncclEpLayout_t, for callers to query dispatch output shapes

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why don't we use ncclEpLayout_t enum?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a standalone `NcclEpLayout` enum mirroring `ncclEpLayout_t` — kept separate so this header stays free of `<nccl_ep.h>`; the `.cu` maps it via `to_nccl_layout()`. Done.

#endif

// Layout constants matching ncclEpLayout_t.
m.attr("LAYOUT_EXPERT_MAJOR") = static_cast<int64_t>(NCCL_EP_LAYOUT_EXPERT_MAJOR);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, just bind this to a real enum object!

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done — now bound as a real enum: `py::enum_(m, "Layout")`.

kwen2501 added 2 commits June 21, 2026 22:33
[ghstack-poisoned]
[ghstack-poisoned]
num_local_experts, dtype=torch.int32, device=self.device
)
ts.create_routing(topk_idx, per_expert_counts)
ts.create_routing(topk_idx, per_expert_counts, layout="flat")

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.

could we just expand existing tests with parameterization on layout?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's possible for create_routing. For dispatch, the output may be different for the two modes (tensor shapes, etc). But let me try to consolidate as much as possible.

Comment on lines +45 to +58
static ncclEpLayout_t to_nccl_layout(NcclEpLayout layout) {
switch (layout) {
case NcclEpLayout::ExpertMajor:
return NCCL_EP_LAYOUT_EXPERT_MAJOR;
case NcclEpLayout::RankMajor:
return NCCL_EP_LAYOUT_RANK_MAJOR;
case NcclEpLayout::Flat:
return NCCL_EP_LAYOUT_FLAT;
case NcclEpLayout::Unset:
break; // not a valid dispatch layout
}
TORCH_CHECK(
false, "nccl_ep: layout must be set; got ", static_cast<int64_t>(layout));
}

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 just default to flat? and not have Unset at all?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought about that. But I felt that user may want either one of them 50:50. Thus giving the ball back to the user.

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 feel it is reasonable to have a default as a good user experience - ideally pre-dominant use case as default.

@kapilsh

kapilsh commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

sorry - dropped of the queue. LGTM! only lingering comment was default layout - let's just set it to FLAT? I feel passing the responsibility to user doesnt make sense to me - i lean towards having a default layout as a good user experience.

@kwen2501

Copy link
Copy Markdown
Collaborator Author

@pytorchbot rebase

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot started a rebase job onto refs/remotes/origin/viable/strict. Check the current status here

[ghstack-poisoned]
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Successfully rebased gh/kwen2501/350/orig onto refs/remotes/origin/viable/strict, please pull locally before adding more changes (for example, via ghstack checkout https://github.com/pytorch/pytorch/pull/187784)

@kwen2501

Copy link
Copy Markdown
Collaborator Author

@kapilsh Thank you!
Re your question:
It needs to be an explicit choice by the user, and the user would need to size the receive buffer accordingly. (Expert major layout would require bigger receive buffer)

pytorchmergebot pushed a commit that referenced this pull request Aug 11, 2026
Expose the receive-buffer layout through the token-switch API so callers can
select it (the NCCL EP algorithm stays high_throughput).

Expert-major orders the dispatched tokens so that all tokens routed to the same
local expert are contiguous, which is the layout a grouped GEMM over experts
consumes directly -- no regrouping pass between dispatch and the expert matmul.

- Add a `NcclEpLayout` enum (`Unset` / `ExpertMajor` / `RankMajor` / `Flat`) in
  the header, values mirroring `ncclEpLayout_t` (ep_enums.h); kept standalone so
  the header stays free of `<nccl_ep.h>` (the `.cu` maps it via `to_nccl_layout`).
- `nccl_ep_create_handle` takes a `NcclEpLayout` arg instead of hardcoding
  `NCCL_EP_LAYOUT_FLAT`; the layout is stashed on the handle.
- `nccl_ep_dispatch`'s `out_topk_idx` is now optional, since expert-major
  layouts leave it unpopulated; `out_topk_weights` also becomes optional for API
  symmetry (it stays populated -- 1-D for expert-major, 2-D for flat).
- Python: `create_routing` gains a required keyword-only `layout` arg, with the
  output-buffer shapes chosen per layout.
- pybind binds `NcclEpLayout` as a `Layout` enum object.

Test Plan:
On a node with 2+ GPUs and a `USE_NCCL_EP=1` build:

```
python -m pytest test/distributed/test_token_switch.py -k expert_major -v
```

- ✅ `test_dispatch_expert_major`
- ✅ `test_dispatch_combine_roundtrip_expert_major`

(8xH100)

ghstack-source-id: 81ceaf0
Pull-Request: #187784
@kwen2501

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Aug 28, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #187785

orrangetabby17 pushed a commit to orrangetabby17/pytorch that referenced this pull request Sep 2, 2026
Expose the receive-buffer layout through the token-switch API so callers can
select it (the NCCL EP algorithm stays high_throughput).

Expert-major orders the dispatched tokens so that all tokens routed to the same
local expert are contiguous, which is the layout a grouped GEMM over experts
consumes directly -- no regrouping pass between dispatch and the expert matmul.

- Add a `NcclEpLayout` enum (`Unset` / `ExpertMajor` / `RankMajor` / `Flat`) in
  the header, values mirroring `ncclEpLayout_t` (ep_enums.h); kept standalone so
  the header stays free of `<nccl_ep.h>` (the `.cu` maps it via `to_nccl_layout`).
- `nccl_ep_create_handle` takes a `NcclEpLayout` arg instead of hardcoding
  `NCCL_EP_LAYOUT_FLAT`; the layout is stashed on the handle.
- `nccl_ep_dispatch`'s `out_topk_idx` is now optional, since expert-major
  layouts leave it unpopulated; `out_topk_weights` also becomes optional for API
  symmetry (it stays populated -- 1-D for expert-major, 2-D for flat).
- Python: `create_routing` gains a required keyword-only `layout` arg, with the
  output-buffer shapes chosen per layout.
- pybind binds `NcclEpLayout` as a `Layout` enum object.

Test Plan:
On a node with 2+ GPUs and a `USE_NCCL_EP=1` build:

```
python -m pytest test/distributed/test_token_switch.py -k expert_major -v
```

- ✅ `test_dispatch_expert_major`
- ✅ `test_dispatch_combine_roundtrip_expert_major`

(8xH100)
Pull Request resolved: pytorch#187784
Approved by: https://github.com/kapilsh
Sanskaaar1 pushed a commit to Sanskaaar1/pytorch that referenced this pull request Sep 8, 2026
Expose the receive-buffer layout through the token-switch API so callers can
select it (the NCCL EP algorithm stays high_throughput).

Expert-major orders the dispatched tokens so that all tokens routed to the same
local expert are contiguous, which is the layout a grouped GEMM over experts
consumes directly -- no regrouping pass between dispatch and the expert matmul.

- Add a `NcclEpLayout` enum (`Unset` / `ExpertMajor` / `RankMajor` / `Flat`) in
  the header, values mirroring `ncclEpLayout_t` (ep_enums.h); kept standalone so
  the header stays free of `<nccl_ep.h>` (the `.cu` maps it via `to_nccl_layout`).
- `nccl_ep_create_handle` takes a `NcclEpLayout` arg instead of hardcoding
  `NCCL_EP_LAYOUT_FLAT`; the layout is stashed on the handle.
- `nccl_ep_dispatch`'s `out_topk_idx` is now optional, since expert-major
  layouts leave it unpopulated; `out_topk_weights` also becomes optional for API
  symmetry (it stays populated -- 1-D for expert-major, 2-D for flat).
- Python: `create_routing` gains a required keyword-only `layout` arg, with the
  output-buffer shapes chosen per layout.
- pybind binds `NcclEpLayout` as a `Layout` enum object.

Test Plan:
On a node with 2+ GPUs and a `USE_NCCL_EP=1` build:

```
python -m pytest test/distributed/test_token_switch.py -k expert_major -v
```

- ✅ `test_dispatch_expert_major`
- ✅ `test_dispatch_combine_roundtrip_expert_major`

(8xH100)
Pull Request resolved: pytorch#187784
Approved by: https://github.com/kapilsh
@github-actions
github-actions Bot deleted the gh/kwen2501/350/head branch November 3, 2026 01:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/h100-symm-mem ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged open source release notes: distributed (c10d) release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants