Repository navigation
[MoE][perf] Avoid repeated EP submesh construction - #5323
Conversation
|
Hi @oonyshch! Thank you for your pull request and welcome to our community. Action RequiredIn 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. ProcessIn 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 If you have received this in error or have any questions, please contact us at [email protected]. Thanks! |
|
|
| @@ -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 | |||
There was a problem hiding this comment.
Can we use functools.cached_property here? What are the performance and correctness implications?
There was a problem hiding this comment.
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.
|
Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks! |
|
@claude review this PR |
|
Claude finished @tianyu-l's task in 1m 47s —— View job Review: [MoE][perf] Cache the EP submesh in
|
fcfef3c to
0f90fcf
Compare
| # weirdly, accessing ep PG hits DeviceMesh internals that expects type annotations | ||
| cache = (mesh, mesh["ep"]) | ||
| self._ep_mesh_cache = cache | ||
| return cache[1] |
There was a problem hiding this comment.
instead of cache the ep mesh, can we use process group API like https://github.com/pytorch/torchtitan/blob/main/torchtitan/models/common/linear/linear.py#L255
and maybe delete this function
There was a problem hiding this comment.
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?
a774df5 to
452f3fb
Compare
|
@claude review again |
|
Claude finished @tianyu-l's task in 1m 52s —— View job Re-review: [MoE][perf] Avoid repeated EP submesh construction
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
Items
Validation
|
…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
#4810 made
BaseEPTokenDispatcher.ep_meshslicespmd_sparse_mesh()["ep"]on every read, andDeviceMesh.__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_meshand resolves the existing EP process group throughspmd_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.main.Performance measurements
DeepSeek-V3 16B, bf16, EP=8, local batch 4, sequence length 4096, forced expert load balance, eager, 2 nodes x 4 GB200.
mainRank-0 instrumentation records 12,999
DeviceMesh.__getitem__calls fromep_meshover 50 steps on uncachedmain, totaling 2.99 seconds. The process-group implementation makes noDeviceMeshslices 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.