Skip to content

[MoE][perf] Avoid repeated EP submesh construction - #5323

Merged
tianyu-l merged 1 commit into
pytorch:mainfrom
oonyshch:lonyshchenko/ep-mesh-cache
Oct 29, 2026
Merged

tianyu-l merged 1 commit into
pytorch:mainfrom
oonyshch:lonyshchenko/ep-mesh-cache

Conversation

@oonyshch

@oonyshch oonyshch commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

#4810 made BaseEPTokenDispatcher.ep_mesh slice spmd_sparse_mesh()["ep"] on every read, and DeviceMesh.__getitem__ builds a new submesh each time. DeepSeek-V3 16B with EP=8 reads it hundreds of times per step, spending tens to hundreds of milliseconds of CPU per step on mesh slicing while GPU compute stays unchanged.

This removes ep_mesh and resolves the existing EP process group through spmd_mesh_group(MeshAxisName.EP), avoiding submesh construction and mutable cache state on every dispatcher module.

Test plan

  • python -m pytest -q tests/unit_tests/cpu/distributed/test_expert_parallel.py tests/unit_tests/cpu/models/common/test_moe.py: 36 passed.
  • On 2x4 GB200 with DeepSeek-V3 16B and EP=8, the process-group version is within 0.15% of the cached version and 6.2% faster than uncached main.
  • A deterministic 50-step cache/process-group A/B finished with final loss 5.861 / 5.864. The trajectories were close but not bit-identical.
Performance measurements

DeepSeek-V3 16B, bf16, EP=8, local batch 4, sequence length 4096, forced expert load balance, eager, 2 nodes x 4 GB200.

implementation tokens/s, run 1 tokens/s, run 2 mean
uncached main 19,388 19,389 19,388
cached submesh 20,617 20,619 20,618
EP process group 20,579 20,596 20,588

Rank-0 instrumentation records 12,999 DeviceMesh.__getitem__ calls from ep_mesh over 50 steps on uncached main, totaling 2.99 seconds. The process-group implementation makes no DeviceMesh slices from the token dispatcher. All three arms used the same image, recipe, node pair, and source base.

An independent 2x4 GB200 validation, pinned to the same software base for both arms, measured 19,578 tokens/s without the change and 21,397 with the process-group implementation (+9.3%). The scheduler placed the arms on different node pairs.

@meta-cla

meta-cla Bot commented Oct 12, 2026

Copy link
Copy Markdown

Hi @oonyshch!

Thank you for your pull request and welcome to our community.

Action Required

In order to merge any pull request (code, docs, etc.), we require contributors to sign our Contributor License Agreement, and we don't seem to have one on file for you.

Process

In order for us to review and merge your suggested changes, please sign at https://code.facebook.com/cla. If you are contributing on behalf of someone else (eg your employer), the individual CLA may not be sufficient and your employer may need to sign the corporate CLA.

Once the CLA is signed, our tooling will perform checks and validations. Afterwards, the pull request will be tagged with CLA signed. The tagging process may take up to 1 hour after signing. Please give it that time before contacting us about it.

If you have received this in error or have any questions, please contact us at [email protected]. Thanks!

@pytorch-bot

pytorch-bot Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

@@ -192,14 +192,22 @@ class Config(LocalTokenDispatcher.Config):

def __init__(self, config: Config):
super().__init__(config)
self._ep_mesh: DeviceMesh | None = None
self._ep_mesh_parent: DeviceMesh | None = None

@property

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Can we use functools.cached_property here? What are the performance and correctness implications?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I'd keep the current version rather than switch to cached_property. both are equally fast, but with cached_property the first read decides the value for good. if anything ever reads ep_mesh before activate_spmd() sets up the EP mesh, it would cache None, and the MoE layers would quietly run without expert parallelism. nothing reads it that early today, but caching per parent mesh rules this out at no extra cost.

measurements
main this PR cached_property
time per ep_mesh read (CPU, fake PG) 72.8 us 0.084 us 0.020 us
tokens/s (1x4 GB200, EP=4) 13.1k 15.4-15.6k 15.4-15.5k
loss and grad_norm (seed 42, deterministic) reference identical identical

an instrumented 50-step run on main read ep_mesh 20,800 times, always on the main thread, after the sparse mesh was set, and always from the same parent mesh.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 12, 2026
@meta-cla

meta-cla Bot commented Oct 12, 2026

Copy link
Copy Markdown

Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks!

@oonyshch
oonyshch marked this pull request as ready for review October 14, 2026 13:16
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Oct 14, 2026
@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review this PR

@claude

claude Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 47s —— View job


Review: [MoE][perf] Cache the EP submesh in BaseEPTokenDispatcher.ep_mesh

  • Gather context (diff, callsites)
  • Review the caching logic and the test
  • Post review

Verdict: I found no correctness problems. The change is small, keeps the old behavior, and fixes a real regression from #4810. The notes below are suggestions; none of them blocks merging.

Correctness

  • The cache key holds up. spmd_sparse_mesh() returns ParallelismContext._global_meshes["spmd_sparse_for_fwdbwd"] (torchtitan/distributed/parallelism_context.py:345). That object is built once in build_mesh() and then handed to set_spmd_meshes on every activate_spmd(). Since the same object comes back each time, checking is on it hits the cache every time. If a different mesh is registered, the slice is rebuilt, which the new test covers.
  • EP=1 behaves as before. When the sparse mesh is None, the property still returns None and never reads or writes the cache, so a stale submesh can't leak into a non-EP run.
  • Moving spmd_sparse_mesh() outside spmd.no_typecheck() is fine. It's just a getattr on thread-local storage (spmd_types.py:86-88). Only the mesh["ep"] slice needs the no-typecheck context, and it still has it.
  • On the cached_property thread: I agree with keeping the current version. With cached_property, an early read that returns None would turn off EP for good with no error. The current version can't fail that way, and the cost is about 60 ns per read.
  • PP split_module deepcopy (pipeline_parallel.py:613): this runs before any forward pass, so the cache is still None when the model is copied. Even if a copy did carry a cached submesh, its _ep_mesh_parent wouldn't be the live TLS mesh, so it would just slice again. I don't see a problem here.

Suggestions

  1. Optional: cache at the source instead. ParallelismContext already builds a one-axis EP mesh once: _single_axis_meshes["ep"] = full_sparse_mesh["ep"] (parallelism_context.py:368). If set_spmd_meshes also stored the EP mesh in _MESH_TLS (for example behind a spmd_ep_mesh() getter in torchtitan/distributed/spmd_types.py), the property would become a plain TLS lookup:

    • no mutable cache on each module;
    • other places that slice every time would also benefit, e.g. decoder.py:199 (sparse_mesh["ep"].size());
    • this matches the "model-agnostic parallelism helpers live in torchtitan/distributed/" guidance.

    The cost is changing every set_spmd_meshes callsite (tests, graph_trainer/precompile.py). It's also worth checking that full_sparse_mesh["ep"] and spmd_sparse_for_fwdbwd["ep"] give the same group (they should, since both slice the same ep axis). Since this PR fixes a regression, landing it as is and doing this as a follow-up seems fine.

  2. Nit: update the cache in one assignment. _ep_mesh and _ep_mesh_parent are set separately and the property returns self._ep_mesh. If two threads ever saw different sparse meshes, one could get the other's submesh. That doesn't happen today (all reads are on the main thread, as your instrumentation shows), but one tuple removes the window and saves an attribute:

    self._ep_mesh_cache: tuple[DeviceMesh, DeviceMesh] | None = None
    ...
    cache = self._ep_mesh_cache
    if cache is None or cache[0] is not mesh:
        with spmd.no_typecheck():
            # weirdly, accessing ep PG hits DeviceMesh internals that expects type annotations
            cache = (mesh, mesh["ep"])
        self._ep_mesh_cache = cache
    return cache[1]

    Fix this →

  3. Nit: the comment. # mesh["ep"] builds a new DeviceMesh on every call, about 0.4 ms of CPU each. The exact timing will go stale as DeviceMesh changes. Something like # DeviceMesh.__getitem__ builds a new submesh on every call, and ep_mesh is read hundreds of times per step. explains the reason and will stay accurate.

  4. Test. The test checks both identity on repeated reads and a fresh slice after a new mesh is registered, and its cleanup is correct. Two small things:

    • The name says "sliced once", but the test checks object identity. Patching DeviceMesh.__getitem__ with wraps= and asserting call_count == 1 would test exactly what the name claims and catch a cache that rebuilds and happens to return an equal object.
    • Adding self.assertIsNone(dispatcher.ep_mesh) before the first set_spmd_meshes would also cover the "read before EP is set up" case you described in the cached_property reply.

Validation

  • The throughput numbers and the bit-identical loss/grad_norm at seed 42 with deterministic=True (EP=4) cover what CLAUDE.md asks for on a non-computation change.
  • The runs were eager only. The ciflow/rl and ciflow/fake-pg jobs (once approved) should show whether a compiled / graph_trainer path that reads ep_mesh inside traced code handles the attribute write in the property. I expect it to, since core compiles only local_compile functions and not the dispatcher module.
  • I couldn't run the unit tests here: running pytest needs a permission this job doesn't have. If you want CI-independent checks from me, add Bash(python -m pytest:*) to --allowedTools.

@oonyshch
oonyshch force-pushed the lonyshchenko/ep-mesh-cache branch from fcfef3c to 0f90fcf Compare October 15, 2026 12:42
# weirdly, accessing ep PG hits DeviceMesh internals that expects type annotations
cache = (mesh, mesh["ep"])
self._ep_mesh_cache = cache
return cache[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.

@oonyshch oonyshch Oct 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

thanks for this suggestion – entirely agree, much cleaner with similar perf.
i switched the dispatcher to spmd_mesh_group(MeshAxisName.EP) and removed ep_mesh and its cache. the process group is now passed directly to the functional and SPMD all-to-all paths, DeepEP, and HybridEP.

validation
implementation tokens/s run 1 tokens/s run 2 mean
uncached main 19,388 19,389 19,388
cached submesh 20,617 20,619 20,618
EP process group 20,579 20,596 20,588

2x4 GB200, EP=8, same image, recipe, source base, and node pair. the process-group version is within 0.15% of the cache and 6.2% faster than uncached main.

an independent 2x4 GB200 validation pinned to the same software base measured 19,578 tokens/s without the change and 21,397 with the process-group implementation (+9.3%). those arms ran on different node pairs.

rank-0 instrumentation records 12,999 DeviceMesh.__getitem__ calls from ep_mesh over 50 steps on uncached main; the process-group version makes none from the token dispatcher.

35 affected CPU tests pass. a deterministic 50-step cache/process-group A/B finished with final loss 5.861 / 5.864; the trajectories were close but not bit-identical.

could you take another look?

@oonyshch oonyshch Oct 28, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

rebased the process-group implementation onto current main and integrated the token-dispatch API changes from #5516. no behavior changed. @tianyu-l could you take another look when you get a chance?

@oonyshch oonyshch changed the title [MoE][perf] Cache the EP submesh in BaseEPTokenDispatcher.ep_mesh [MoE][perf] Avoid repeated EP submesh construction Oct 20, 2026
@oonyshch
oonyshch requested a review from tianyu-l October 20, 2026 22:50
@oonyshch
oonyshch force-pushed the lonyshchenko/ep-mesh-cache branch from a774df5 to 452f3fb Compare October 28, 2026 18:57
@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 52s —— View job


Re-review: [MoE][perf] Avoid repeated EP submesh construction

  • Read the diff (git diff origin/main...HEAD)
  • Check spmd_mesh_group / maybe_set_sparse_mesh semantics
  • Audit remaining ep_mesh / _permute / exchange-helper callsites
  • Post review

Verdict: The change looks correct, and it's a clear improvement over the cached-submesh version. I found no blocking correctness problems. The one thing I'd still like settled before merge is why the A/B loss is not bit-identical (item 1).

Correctness

  • The process group is the same one as before. _ep_process_group() enters the registered sparse mesh and calls spmd_mesh_group("ep"), which returns mesh.get_group("ep") (torchtitan/distributed/spmd_types.py:118-127). That is the same PG that mesh["ep"].get_group() returned, but without building a submesh. Passing a PG into spmd.all_to_all and into the functional all_to_all_single matches how linear.py:272-281 already works with tp_group.
  • The EP=1 fallback still behaves the same. spmd_mesh_group also returns None when the group size is 1, which the old ep_mesh did not. That case can't happen here, because spmd_sparse_for_fwdbwd is only registered when self.ep > 1 (parallelism_context.py:344). So "sparse mesh present" and "EP group exists" mean the same thing.
  • _permute gets ep_size passed in explicitly. Both overrides (token_dispatcher.py:517, :751) and both callers were updated, as was the CPU test. The TorchAO EP=1 path now passes ep_size=1 instead of computing it from self.ep_mesh, which is simpler. No other subclass overrides _permute (I checked experiments/ too).
  • Nothing else used ep_mesh. No references to .ep_mesh remain in the repo. The graph_trainer annotations (common_utils.py:412-423) wrap the exchange helpers by name and never relied on the parameter name, so the pg -> ep_group rename is safe.

Items

  1. The loss isn't bit-identical, and the cause isn't explained yet. CLAUDE.md asks that a non-computation change give identical loss with seed=42, deterministic=True. The earlier cache-vs-main A/B at EP=4 was bit-identical. The PG-vs-cache A/B at EP=8 on 2x4 ended at 5.861 / 5.864. Nothing in this diff should change numerics: same PG, same splits, same ops. My guess is the 2-node EP=8 setup itself isn't run-to-run deterministic (inter-node a2a or the scheduler's node placement), not this change. Either of these would settle it:

    • run the same arm twice at 2x4 EP=8 to measure the noise floor, or
    • repeat the PG-vs-cache (or PG-vs-main) A/B on 1x4 EP=4, where you already showed bit-identical results.
  2. Nit: the assert message is stale. token_dispatcher.py:895 and :1029 say "ExpertParallel._partition_fn() should set it." _partition_fn doesn't exist anymore. The sparse mesh is registered by ParallelismContext.activate_spmd() -> set_spmd_meshes. This PR rewrites those lines, so it's a good time to fix them, e.g. "EP process group is not set; ParallelismContext.activate_spmd() registers the sparse mesh."
    Fix this ->

  3. Nit: Unicode in a rewritten docstring. token_dispatcher.py:366, "When the EP process group is absent (EP=1), falls back to local dispatch — no", is a rewritten line that still has the em dash. CLAUDE.md asks for ASCII (--) in rewritten docstrings.

  4. Optional: ep_size is redundant in _token_count_exchange. It now receives ep_group, so it could use ep_group.size() itself. _sync_token_count_exchange and _permute still need ep_size as a parameter, so leaving it as is for consistency is also fine.

  5. Optional: where _ep_process_group() lives. It's a model-agnostic "PG for an axis of the sparse mesh" helper. If another module needs it later, it belongs in torchtitan/distributed/spmd_types.py (e.g. spmd_sparse_mesh_group(axis_name)). For a single user, keeping it private here is fine.

Validation

  • The throughput numbers (+6.2% same node pair, +9.3% independent run) and the zero DeviceMesh.__getitem__ calls from the dispatcher support the change well.
  • I didn't run the unit tests in this job: chained Bash commands need approval here. The PR reports 36 passing CPU tests. ciflow/fake-pg and ciflow/rl should cover the compile/graph_trainer path that now passes a PG into all_to_all_single.

@tianyu-l
tianyu-l merged commit 6a06c7a into pytorch:main Oct 29, 2026
24 of 25 checks passed
submartingales pushed a commit to botcanlearn/torchtitan-npu-upstream that referenced this pull request Nov 28, 2026
…sh slicing

Co-authored-by: xuyujun<[email protected]>



# message auto-generated for no-merge-commit merge:
!1397 merge fix/cache-ep-submesh-backport-5323 into dev_0.4.0

[perf] Cache BaseEPTokenDispatcher.ep_mesh to avoid repeated EP submesh slicing

Created-by: xuyujun
Commit-by: xuyujun
Merged-by: cann-robot
Description: ## 描述

在当前固定的 `torchtitan==0.4.0` 基线中,`BaseEPTokenDispatcher.ep_mesh` 每次访问都会执行 `spmd_sparse_mesh()["ep"]`,在前向、重计算与反向期间为每个 MoE 层重复创建一维 `DeviceMesh` 子网并引入显著的宿主侧对象构造开销。

参考上游 [`pytorch/torchtitan#5323`](pytorch/torchtitan#5323) 的优化目标,在 [`torchtitan_npu/patches/torchtitan/models/common/token_dispatcher.py`](torchtitan_npu/patches/torchtitan/models/common/token_dispatcher.py) 为 `BaseEPTokenDispatcher.ep_mesh` 补充临时只读缓存补丁(依赖升级合入 `#5323` 后可随补丁文件一并移除):

1. **按实例就地缓存(零全局引用泄漏)**:将切片结果 `_torchtitan_npu_cached_ep_submesh` 直接缓存在活跃 `sparse_mesh` 实例上,保持 `submesh._root_mesh` 仅形成实例内局部引用闭环,可被 Python 周期 GC 正常回收;对禁止属性赋值的只读对象自动回退至原 `mesh["ep"]`。
2. **绑定 `_dim_group_names` 缓存键**:缓存键取 `tuple(mesh._dim_group_names)`,确保 `ep_process_group._replace_sparse_ep_mesh` 在浅拷贝 `sparse_mesh` 并替换专用 HCCL EP 通信组名称后不会误命中旧子网。
3. **保持调用契约不变**:`BaseEPTokenDispatcher.ep_mesh` 保留属性签名,全面兼容现有所有 dispatcher 与 NPU override(`AllToAllTokenDispatcher`、`DeepEPTokenDispatcher`、`HybridEPTokenDispatcher`、`AscAllToAllTokenDispatcher`)及现有单测。
4. 同步登记 `#5323` 至 [`torchtitan_npu/patches/torchtitan/README.md`](torchtitan_npu/patches/torchtitan/README.md) 并补充 CPU 单元测试。

## 类型
- [x] Bug 修复
- [ ] 新功能
- [ ] 重构(即不是新增功能,也不是修改bug的代码变动)
- [ ] 构建过程或辅助工具的变动
- [ ] 文档内容更新

## Checklist:
- [x] 我的代码遵循这个项目的代码风格
- [x] 我已经自己测试过我的代码
- [x] 我已经更新了相应的文档
- [x] 我已经在标题中正确使用了类型标签(例如:`feat`, `fix`, `refactor`, `docs`, `test`)

## 如何测试

1. 架构边界与代码规范校验:
```bash
ruff check torchtitan_npu/patches/torchtitan/models/common/token_dispatcher.py tests/unit_tests/patches/torchtitan/models/common/test_token_dispatcher_ep_mesh.py
ruff format --check torchtitan_npu/patches/torchtitan/models/common/token_dispatcher.py tests/unit_tests/patches/torchtitan/models/common/test_token_dispatcher_ep_mesh.py
python3 scripts/check_architecture_boundaries.py
```
均已通过。

2. CPU 单元测试:
```bash
TORCH_DEVICE_BACKEND_AUTOLOAD=0 python -m pytest -v --tb=short   tests/unit_tests/patches/torchtitan/models/common/   tests/unit_tests/override/common/test_moe_score_absorption.py   tests/unit_tests/extensions/torchtitan/components/test_checkpoint_v04.py
```
结果:`35 passed, 1 skipped, 1 xfailed`(其中新增 `test_token_dispatcher_ep_mesh.py` 4/4 通过,覆盖同实例复用、浅拷贝替换通信组后刷新、含 `_root_mesh` 反向引用的 GC 回收及 `__slots__` 回退;2-rank Gloo 分布式 MoE 契约测试全部通过)。

### 精度和性能验证结果

- **数值等价性(按 `docs/developer_guides/numerical_alignment.md` 第 3 节非数值变动跳过精度对齐)**:本改动仅在 `sparse_mesh` 实例上缓存 `mesh["ep"]` 返回的 `DeviceMesh` 子网对象引用(并以 `tuple(mesh._dim_group_names)` 为缓存键防止通信组替换后误命中),不涉及任何算子、张量数值、通信组映射或计算图语义改动,前反向数学行为与未缓存路径严格等价。
- **性能验证(16-rank `(2, 8)` `DeviceMesh` `("dp", "ep")` 访问基准,1032 次连续调用)**:

| 方式 | 1032 次 `ep_mesh` 访问耗时 | 相对提速 |
| --- | ---: | ---: |
| 修改前(每次重切片 `mesh["ep"]`) | 309.70 ms | 1.0× |
| **修改后(`_cached_ep_mesh`)** | **4.20 ms** | **73.7×**(节省 305.50 ms) |

## 其他信息

- 上游关联 PR:pytorch/torchtitan#5323 (已合入上游主线,当前仓固定 `torchtitan==0.4.0` 尚未包含,待版本升级后可清理)。

See merge request: cann/torchtitan-npu!1397
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl 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