Draft
[WIP] feat(npu): add deterministic canonical owner geometry #25
[WIP] feat(npu): add deterministic canonical owner geometry #25
Draft
Jia_AustinAdd on 1 day ago
Total: 120 files changed+45545-18
@@ -0,0 +1,8 @@
1+[submodule "npu_patch/3rdparty/shmem"]
2+ path = npu_patch/3rdparty/shmem
3+ url = https://gitcode.com/cann/shmem.git
4+ branch = master
5+[submodule "npu_patch/3rdparty/catlass"]
6+ path = npu_patch/3rdparty/catlass
7+ url = https://gitcode.com/cann/catlass.git
8+ branch = master
@@ -1,9 +1,34 @@
1-from .api import (1+from . import _backend as _backend
2- Buffer,2+ 
3-)3+if _backend.npu_enabled():
4-from .planning import MoonEPCommPlan4+ # NPU backend: expose the vendored Ascend implementation directly. The
5+ # CUDA/cutlass GPU kernel stack (moonep.api, moonep.planning,
6+ # dispatch/combine/prefetch/...) is deliberately NOT imported here: those
7+ # modules import `cuda.bindings.driver` / `cutlass`, which are not installed
8+ # on an NPU-only host and are never used by the NPU backend.
9+ # `moonep.buffer` re-exports its NPU-only helpers itself.
10+ from npu_patch.api import Buffer as Buffer
11+ from npu_patch.planning import MoonEPCommPlan as MoonEPCommPlan
12+ from npu_patch.shmem_runtime import ShmemRuntime as ShmemRuntime
13+else:
14+ from .api import Buffer, MoonEPCommPlan as MoonEPCommPlan
15+ 
16+ 
17+def init_shmem(group=None, **kwargs):
18+ """Initialize the shmem symmetric heap on NPU (no-op on GPU).
19+ 
20+ Required on Ascend before the first dispatch/combine/prefetch/reduce_grad,
21+ after every ``Buffer`` has been constructed. On GPU this is a no-op so
22+ single-file test/benchmark code can call it unconditionally.
23+ """
24+ if not _backend.npu_enabled():
25+ return
26+ from npu_patch.shmem_runtime import ShmemRuntime
27+ ShmemRuntime.init_with_buffer(group=group, **kwargs)
28+ 
5 29 
6__all__ = [30__all__ = [
7 "Buffer",31 "Buffer",
8 "MoonEPCommPlan",32 "MoonEPCommPlan",
33+ "init_shmem",
9]34]
@@ -0,0 +1,50 @@
1+"""
2+Runtime backend detection for MoonEP.
3+ 
4+Default is GPU (CUDA). The NPU backend is only engaged when an Ascend runtime
5+is actually present (``torch_npu`` importable and either ``ASCEND_HOME_PATH``
6+set or an NPU device reported available). ``MOONEP_BACKEND`` may force a
7+backend explicitly (``gpu``/``cuda``/``npu``/``ascend``).
8+ 
9+GPU hosts never ``import torch_npu`` here.
10+"""
11+ 
12+from __future__ import annotations
13+ 
14+import os
15+ 
16+ 
17+def _env_backend() -> str | None:
18+ val = os.environ.get("MOONEP_BACKEND", "").strip().lower()
19+ if not val:
20+ return None
21+ if val in ("gpu", "cuda"):
22+ return "gpu"
23+ if val in ("npu", "ascend"):
24+ return "npu"
25+ raise ValueError(
26+ f"MOONEP_BACKEND must be one of gpu/cuda/npu/ascend, got {val!r}"
27+ )
28+ 
29+ 
30+def npu_enabled() -> bool:
31+ """True only when the NPU (Ascend) backend should drive moonep imports."""
32+ forced = _env_backend()
33+ if forced == "npu":
34+ return True
35+ if forced == "gpu":
36+ return False
37+ try:
38+ import torch_npu
39+ except Exception:
40+ return False
41+ if not os.environ.get("ASCEND_HOME_PATH"):
42+ return False
43+ try:
44+ return bool(torch_npu.is_available())
45+ except Exception:
46+ return True
47+ 
48+ 
49+def backend_name() -> str:
50+ return "npu" if npu_enabled() else "gpu"
@@ -0,0 +1,325 @@
1+"""
2+Ascend-only part of ``moonep.buffer``'s public surface.
3+ 
4+This module is NPU-only: it is imported exclusively from the ``if _NPU`` binding
5+block at the bottom of ``moonep.buffer`` (which re-exports the NPU-only names
6+defined here), so ``npu_patch`` / ``torch_npu`` are imported once at module
7+level and a pure-GPU process never loads this module at all (``npu_patch``
8+itself never imports ``moonep``, so there is no import cycle).
9+ 
10+Every name here is NPU-only — pool builders, point-visit cross-rank accessors
11+and ``release_owned``; ``moonep.buffer`` publishes them only on the Ascend
12+backend, and a GPU process never sees them (a GPU test builds the equivalent
13+tensors with plain ``torch.empty`` slices). See each docstring for the home/slot
14+VMM layout it builds or reads. The GPU NVLink allocation helpers
15+(``create_nvl_dist_tensor``, ``create_nvl_single_owner_tensor``,
16+``pad_dim0_for_alignment``) are deliberately not adapted: no NPU code path calls
17+them.
18+ 
19+Builders (``create_full_weight`` / ``create_full_grad_and_reduce_buffer``)
20+allocate and register the CANN VMM descriptors *before*
21+``ShmemRuntime.init_with_buffer`` runs — init consumes the frozen descriptor
22+set, so chunks created afterwards never enter the current symmetric heap. The
23+point-visit accessors (``remote_home_rows`` / ``read_reduce_slot`` /
24+``expert_pool_row``) instead require init to have run already.
25+"""
26+ 
27+from __future__ import annotations
28+ 
29+import torch
30+import torch_npu
31+ 
32+from npu_patch import ShmemRuntime, buffer_c
33+ 
34+ 
35+def _require_npu():
36+ if not ShmemRuntime.is_initialized():
37+ raise RuntimeError(
38+ "moonep.buffer (NPU): buffer-backed shmem heap is not initialized. "
39+ "Construct all Buffers first, then call "
40+ "moonep.init_shmem() / ShmemRuntime.init_with_buffer()."
41+ )
42+ return None
43+ 
44+ 
45+def _current_device() -> int:
46+ return int(torch.npu.current_device())
47+ 
48+ 
49+# ---------------------------------------------------------------------------
50+# Public pool / reduce-buffer builders (NPU-only names).
51+#
52+# These are the constructs the framework/test feeds straight into
53+# ``Buffer.prefetch_weight`` / ``Buffer.reduce_grad``. They build the registered
54+# home/slot VMM chunks, form the [E+B] projection view, and attach the source-VA
55+# tags the ascend Buffer consumes — so the framework never needs to touch VMM
56+# home/slot or ``attach_local_source_vas`` itself.
57+# ---------------------------------------------------------------------------
58+ 
59+ 
60+def _tag_layout(tensor, local_rank, num_ep_ranks, num_home, num_slots):
61+ """Record the container layout on ``tensor`` (``_moonep_*`` tags)."""
62+ tensor._moonep_local_rank = int(local_rank)
63+ tensor._moonep_num_ep_ranks = int(num_ep_ranks)
64+ tensor._moonep_num_home = int(num_home)
65+ tensor._moonep_num_slots = int(num_slots)
66+ return tensor
67+ 
68+ 
69+# ---------------------------------------------------------------------------
70+# Owned-resource registry.
71+#
72+# Every VMM chunk / projection the pool & reduce-buffer builders hand out is
73+# tracked here, so ``release_owned(buffers=(...))`` can tear everything down
74+# without the caller collecting projections and chunks by hand. Teardown order
75+# (finalize -> projection -> VMM inverse ops -> reset) stays in ``release_owned``.
76+# ---------------------------------------------------------------------------
77+ 
78+_OWNED_RESOURCES: list = []
79+ 
80+ 
81+def _track_owned(*tensors) -> None:
82+ for t in tensors:
83+ if t is not None:
84+ _OWNED_RESOURCES.append(t)
85+ 
86+ 
87+def _take_owned() -> list:
88+ owned = list(_OWNED_RESOURCES)
89+ _OWNED_RESOURCES.clear()
90+ return owned
91+ 
92+ 
93+def _home_slot_projection(E, B, R, H, Hp, dtype, device, local_rank):
94+ epn = int(E) // int(R)
95+ home, _, _ = buffer_c.create_vmm_physical([epn, H, Hp], dtype, device)
96+ slot, _, _ = buffer_c.create_vmm_physical([B, H, Hp], dtype, device)
97+ full = buffer_c.create_full_projection_tensor(
98+ home, slot, int(E), int(B), int(local_rank), device)
99+ buffer_c.attach_local_source_vas(full, home.data_ptr(), slot.data_ptr())
100+ full._npu_home_chunk = home
101+ full._npu_slot_chunk = slot
102+ _track_owned(full, home, slot)
103+ return full, home, slot
104+ 
105+ 
106+def create_full_weight(
107+ num_experts: int,
108+ slot_rows: int,
109+ hidden: int,
110+ hidden_prime: int,
111+ local_rank: int,
112+ num_ep_ranks: int,
113+ expert_table: torch.Tensor,
114+ source_offset: float = 0.0,
115+ group=None,
116+ dtype: torch.dtype = torch.bfloat16,
117+ device: int | None = None,
118+) -> torch.Tensor:
119+ """Backend-specific high-level constructor for one ``[E+B]`` weight pool.
120+ 
121+ Only this rank's home rows and local prefetch slots have physical backing
122+ in the returned projection. Remote expert rows are observable after shmem
123+ initialization through :func:`remote_home_rows` / :func:`expert_pool_row`
124+ (bind-free point-visit).
125+ """
126+ E, B, R = int(num_experts), int(slot_rows), int(num_ep_ranks)
127+ rank = int(local_rank)
128+ epn = E // R
129+ device = _current_device() if device is None else int(device)
130+ pool, home, slot = _home_slot_projection(
131+ E, B, R, int(hidden), int(hidden_prime), dtype, device, rank)
132+ home.copy_(expert_table[rank * epn:(rank + 1) * epn])
133+ if source_offset:
134+ home.add_(source_offset)
135+ slot.zero_()
136+ pool._npu_expert_reference = expert_table
137+ pool._npu_reference_offset = source_offset
138+ return _tag_layout(pool, rank, R, E, B)
139+ 
140+ 
141+def create_full_grad_and_reduce_buffer(
142+ num_experts: int,
143+ slot_rows: int,
144+ hidden: int,
145+ hidden_prime: int,
146+ local_rank: int,
147+ num_ep_ranks: int,
148+ grad_table: torch.Tensor,
149+ reduce_table: torch.Tensor,
150+ group=None,
151+ dtype: torch.dtype = torch.float32,
152+ device: int | None = None,
153+) -> tuple[torch.Tensor, torch.Tensor]:
154+ """Create one local full-grad projection and its pre-init reduce carrier.
155+ 
156+ ``grad_table`` is the rank-invariant ``[E, H, H']`` reference; this rank
157+ copies only its home slice. ``reduce_table`` is ``[R, B, H, H']``; this
158+ rank copies only its own slot slice. Cross-rank slot reads go through
159+ :func:`read_reduce_slot` (bind-free point-visit).
160+ """
161+ E, B, R = int(num_experts), int(slot_rows), int(num_ep_ranks)
162+ rank = int(local_rank)
163+ epn = E // R
164+ H, Hp = int(hidden), int(hidden_prime)
165+ device = _current_device() if device is None else int(device)
166+ 
167+ full_grad, home, slot = _home_slot_projection(
168+ E, B, R, H, Hp, dtype, device, rank)
169+ home.copy_(grad_table[rank * epn:(rank + 1) * epn])
170+ slot.copy_(reduce_table[rank])
171+ # Logical [R,B,H,H'] over the local slot chunk: every rank slice is a
172+ # stride-0 alias, so this process backs only epn*H*H' floats and slice
173+ # [rank] *is* the local chunk the reduce kernel consumes. No storage exists
174+ # for the other ranks; remote reads go through read_reduce_slot().
175+ reduce_buffer = slot.unsqueeze(0).expand(R, -1, -1, -1)
176+ buffer_c.attach_local_source_vas(
177+ reduce_buffer, home.data_ptr(), slot.data_ptr())
178+ reduce_buffer._npu_slot_chunk = slot
179+ _track_owned(reduce_buffer)
180+ return (_tag_layout(full_grad, rank, R, E, B),
181+ _tag_layout(reduce_buffer, rank, R, E, B))
182+ 
183+ 
184+def projection_home_slice(projection: torch.Tensor) -> torch.Tensor:
185+ """Directly readable local home slice of an ``[E+B]`` projection."""
186+ epn = int(projection._moonep_num_home) // int(projection._moonep_num_ep_ranks)
187+ start = int(projection._projection.home_start)
188+ return projection[start:start + epn]
189+ 
190+ 
191+def projection_slot_slice(projection: torch.Tensor) -> torch.Tensor:
192+ """Directly readable local slot slice of an ``[E+B]`` projection."""
193+ B = int(projection._moonep_num_slots)
194+ start = int(projection._projection.slot_start)
195+ return projection[start:start + B]
196+ 
197+ 
198+# ---------------------------------------------------------------------------
199+# Point-visit cross-rank accessors (no pre-binding required).
200+#
201+# Each call resolves one peer's symmetric address (``buffer_c.remote_view``) and
202+# returns a live zero-copy view. Both require buffer-backed shmem init; callers
203+# synchronize before reading so peer writes are visible.
204+# ---------------------------------------------------------------------------
205+ 
206+ 
207+def remote_home_rows(projection: torch.Tensor, pe: int) -> torch.Tensor:
208+ """Live view of rank ``pe``'s home chunk ``[E/R, H, H']``."""
209+ _require_npu()
210+ return buffer_c.remote_view(projection._npu_home_chunk, int(pe))
211+ 
212+ 
213+def read_reduce_slot(reduce_buffer: torch.Tensor, pe: int) -> torch.Tensor:
214+ """Live view of rank ``pe``'s reduce slot chunk ``[B, H, H']``.
215+ 
216+ Bind-free cross-rank read for the reduce carrier: resolves ``pe``'s
217+ address from the attached slot chunk's source VA on demand. Accepts the
218+ pre-init ``[R,B,...]`` carrier or a bare slot chunk — anything carrying
219+ ``_npu_slot_chunk`` (or being the chunk itself).
220+ """
221+ _require_npu()
222+ chunk = getattr(reduce_buffer, "_npu_slot_chunk", None)
223+ if chunk is None:
224+ chunk = reduce_buffer
225+ return buffer_c.remote_view(chunk, int(pe))
226+ 
227+ 
228+# ---------------------------------------------------------------------------
229+# Pool read-back accessor.
230+#
231+# The Ascend kernels read each rank's *own* home chunk through the symmetric
232+# mapping, so a rank only ever materialises the rows it owns; the [E+B] view is
233+# the projection whose home/slot segments alias the local chunks. Read-back for
234+# remote experts resolves the owner's chunk on demand (point-visit) after shmem
235+# init; pre-init it falls back to the rank-invariant reference table captured
236+# by ``create_full_weight``.
237+# ---------------------------------------------------------------------------
238+ 
239+ 
240+def expert_pool_row(pool, expert):
241+ """Read expert ``expert`` from the owner's home chunk.
242+ 
243+ Resolution order: locally owned row (home chunk) → live point-visit view of
244+ the owner's chunk (requires shmem init, no binding) → rank-invariant
245+ reference table (pre-init fallback captured by :func:`create_full_weight`).
246+ """
247+ rank = int(pool._moonep_local_rank)
248+ R = int(pool._moonep_num_ep_ranks)
249+ epn = int(pool._moonep_num_home) // R
250+ expert = int(expert)
251+ owner, local = expert // epn, expert % epn
252+ if owner == rank:
253+ return pool._npu_home_chunk[local]
254+ if ShmemRuntime.is_initialized():
255+ return buffer_c.remote_view(pool._npu_home_chunk, owner)[local]
256+ row = pool._npu_expert_reference[expert]
257+ offset = getattr(pool, "_npu_reference_offset", 0.0)
258+ return row + offset if offset else row
259+ 
260+ 
261+def release_owned(projections=(), vmm_tensors=(), buffers=()):
262+ """Tear down buffer-backed shmem heap + caller-owned VMM/projection resources.
263+ 
264+ Teardown order (must not be inverted):
265+ 1. ``ShmemRuntime.finalize()`` --- unmap the symmetric heap first. Freeing /
266+ reusing the backing VMM physical memory while shmem still holds mappings
267+ to those addresses would be a use-after-free hazard.
268+ 2. Destroy the VMM ``_vmm_allocation`` objects (reverse VMM op) and destroy
269+ ``_projection`` handles. Physical memory is owned by the caller; it may
270+ only be freed after the symmetric mapping is gone.
271+ 3. ``reset_symmetric_descriptors()`` --- clear the process-wide descriptor
272+ registry so the next case can re-init with fresh Buffers/chunks.
273+ 
274+ ``projections`` are the ``[E+B]`` full/full_grad projection tensors (each may
275+ carry a ``_projection`` handle); ``vmm_tensors`` are the home/slot VMM chunks
276+ (their ``_vmm_allocation``); ``buffers`` are ``Buffer`` objects. Dedup of a
277+ shared ``VmmAllocation`` is idempotent (same allocation destroyed once).
278+ Everything ``create_full_weight`` / ``create_full_grad_and_reduce_buffer``
279+ allocated is merged in automatically (see ``_OWNED_RESOURCES``), so callers
280+ normally only pass ``buffers``; explicit ``projections`` / ``vmm_tensors``
281+ still work.
282+ 
283+ This name only exists on the Ascend backend. A GPU process has no shmem
284+ runtime / VMM heap to unwind, so it destroys each ``Buffer`` directly and
285+ never calls a release helper.
286+ """
287+ if ShmemRuntime.is_initialized():
288+ ShmemRuntime.finalize()
289+ 
290+ owned = _take_owned()
291+ owned_projections = [
292+ t for t in owned if getattr(t, "_projection", None) is not None]
293+ owned_chunks = [
294+ t for t in owned if getattr(t, "_vmm_allocation", None) is not None]
295+ 
296+ destroyed_projections = set()
297+ for t in list(projections) + owned_projections:
298+ proj = getattr(t, "_projection", None)
299+ if proj is None or id(proj) in destroyed_projections:
300+ continue
301+ destroyed_projections.add(id(proj))
302+ try:
303+ proj.destroy()
304+ except Exception: # best-effort teardown
305+ pass
306+ 
307+ destroyed = set()
308+ for t in list(vmm_tensors) + owned_chunks:
309+ alloc = getattr(t, "_vmm_allocation", None)
310+ if alloc is None or id(alloc) in destroyed:
311+ continue
312+ destroyed.add(id(alloc))
313+ try:
314+ alloc.destroy()
315+ except Exception: # best-effort teardown
316+ pass
317+ 
318+ for b in buffers:
319+ if not b.destroyed:
320+ try:
321+ b.destroy()
322+ except Exception: # best-effort teardown
323+ pass
324+ 
325+ buffer_c.reset_symmetric_descriptors()
@@ -7,20 +7,35 @@ import tempfile
7import torch7import torch
8import torch.distributed as dist8import torch.distributed as dist
9 9 
10-from moonep._C import (10+from moonep import _backend as _backend
11- FABRIC_HANDLE_BYTES as _FABRIC_HANDLE_BYTES,11+ 
12- nvl_dist_alloc,12+# Backend switch: default is GPU. Only the NPU path skips importing the CUDA
13- nvl_dist_map,13+# `_C` extension (which cannot load on a non-CUDA device). On GPU this import
14- nvl_fabric_supported,14+# runs untouched, so the NVLink path below is byte-for-byte identical.
15- nvl_release_mem_handle,15+_NPU = _backend.npu_enabled()
16- get_vmm_granularity,16+if not _NPU:
17- get_multicast_granularity,17+ from moonep._C import (
18- nvl_multicast_supported,18+ FABRIC_HANDLE_BYTES as _FABRIC_HANDLE_BYTES,
19- nvl_multicast_create,19+ nvl_dist_alloc,
20- nvl_multicast_import,20+ nvl_dist_map,
21- nvl_multicast_add_device,21+ nvl_fabric_supported,
22- nvl_multicast_bind_map,22+ nvl_release_mem_handle,
23-)23+ get_vmm_granularity,
24+ get_multicast_granularity,
25+ nvl_multicast_supported,
26+ nvl_multicast_create,
27+ nvl_multicast_import,
28+ nvl_multicast_add_device,
29+ nvl_multicast_bind_map,
30+ )
31+else:
32+ _FABRIC_HANDLE_BYTES = None
33+ nvl_dist_alloc = nvl_dist_map = nvl_fabric_supported = None
34+ nvl_release_mem_handle = get_vmm_granularity = \
35+ get_multicast_granularity = None
36+ nvl_multicast_supported = nvl_multicast_create = \
37+ nvl_multicast_import = None
38+ nvl_multicast_add_device = nvl_multicast_bind_map = None
24 39 
25# How VMM allocations are shared between the ranks of an EP group. "auto" (the40# How VMM allocations are shared between the ranks of an EP group. "auto" (the
26# default) picks fabric handles when the group spans more than one node and the41# default) picks fabric handles when the group spans more than one node and the
@@ -386,3 +401,27 @@ def create_nvl_single_owner_tensor(
386 if is_owner:401 if is_owner:
387 tensor._keepalive = keepalive402 tensor._keepalive = keepalive
388 return tensor403 return tensor
404+ 
405+ 
406+# ---------------------------------------------------------------------------
407+# NPU backend binding.
408+#
409+# `moonep._npu_buffer` provides the weight/grad pool builders, the cross-rank
410+# point-visit accessors and the shmem teardown helper — names that have no GPU
411+# counterpart here at all (a GPU test builds those tensors with plain
412+# `torch.empty` slices). This block only re-exports them, so callers reach all of
413+# them through `moonep.buffer`; the import stays behind `_NPU`, so a GPU process
414+# never loads `torch_npu` / `npu_patch`. It sits at the bottom of the module
415+# purely to keep every NPU re-export in one place.
416+# ---------------------------------------------------------------------------
417+if _NPU: # pragma: no cover - exercised only on Ascend hardware
418+ from moonep._npu_buffer import (
419+ create_full_grad_and_reduce_buffer,
420+ create_full_weight,
421+ expert_pool_row,
422+ projection_home_slice,
423+ projection_slot_slice,
424+ read_reduce_slot,
425+ release_owned,
426+ remote_home_rows,
427+ )
@@ -0,0 +1 @@
1+Subproject commit 4fab1d0953b846f4876aa04cf07d1ecbd1110fad
@@ -0,0 +1 @@
1+Subproject commit 431c3c43232917f663b7a7022f321802ff23a5c1
@@ -0,0 +1,447 @@
1+# npu_patch(MoonEP Ascend NPU 后端)
2+ 
3+`npu_patch` 是 MoonEP 仓库内为 **Ascend(NPU)** 提供的后端模块,由
4+[`ascend-moonep`](../../../ascend-moonep) 迁移而来,保持 Python `Buffer` API
5+(shmem 对称内存,`dispatch` / `prefetch_weight` / `combine` / `reduce_grad`)
6+与调用面兼容。C++ runtime 负责 CANN SHMEM 生命周期、对称内存与 runtime
7+workspace 管理;AscendC kernel 经预编译的 `ascend_moonep_kernels`(native
8+CMake)暴露 C ABI launcher,再由 PyTorch C++ extension `npu_patch._C` 调用。
9+ 
10+构建目标覆盖 **Ascend950 / A5**(NPU 3510,SIMT)与
11+**Ascend910_93 / A3**(NPU 2201,非 SIMT)。URMA/UDMA(URMA)通信依赖 A5
12+的对称内存 RMA 能力(SIMT),仅 A5 可用;A3 自动走 MTE(ubmem)路径,
13+不可使用 `--use_urma`。
14+ 
15+## 目录结构
16+ 
17+```text
18+npu_patch/
19+├── 3rdparty/
20+│ ├── shmem/ # CANN SHMEM submodule
21+│ └── catlass/ # CATLASS submodule
22+├── __init__.py # 导出 Buffer / MoonEPCommPlan / ShmemRuntime
23+├── api.py # MoonEP Buffer API(shmem 对称内存)
24+├── buffer_c.py # 对称分配/包装 + 框架侧 VMM 助手(create_vmm_physical 等)
25+├── planning.py # MoonEPCommPlan / 计划输出分配
26+├── shmem_runtime.py # ShmemRuntime(shmem Python API 生命周期)
27+├── kernel_op.py / ops.py # KernelOp 基类与各算子对象(AscendC 迁移接缝)
28+├── launchers.py # moonep launch_* 兼容 shim(launch_planning / launch_dispatch/…)
29+├── _common.py # 2MiB 对齐 / sym put-get / 跨 rank 屏障
30+├── _device.py # 把 ASCEND_RT_VISIBLE_DEVICES 映射成可见索引 0..N-1
31+├── native/ # CMakeLists、AscendC/Bisheng kernel、C++ host csrc
32+│ ├── csrc/ops/ # 每个 Python 侧算子的参数校验、输出分配、tiling 构造
33+│ ├── kernels/ # AscendC kernel launcher 与 kernel(含 *_udma 变体)
34+│ │ ├── planning_common.h # planning 各家族共享的常量 / UB 布局 / arch 无关 helper
35+│ │ ├── planning_simt.cpp # planning A5(SIMT)后端
36+│ │ └── planning_aicore.cpp # planning A3(非 SIMT)后端
37+│ └── include/ascend_moonep/kernels/
38+├── scripts/
39+│ ├── build_base.sh # 唯一构建实现(CANN 发现 / shmem / kernel 库 / pip install)
40+│ ├── build_a5.sh # Ascend950/A5 薄封装
41+│ ├── build_a3.sh # Ascend910_93/A3 薄封装
42+│ └── run_test.sh # 测试驱动(含 BUILD=1 重建)
43+├── benchmarks/ # MoonEP benchmark 集(--engine {ubmem,urma})
44+└── lib/ # 随包分发的 kernel / shmem .so(构建产物)
45+```
46+ 
47+## 获取代码
48+ 
49+```bash
50+git clone --recursive <repository-url>
51+cd MoonEP
52+```
53+ 
54+已有仓库时初始化 submodule:
55+ 
56+```bash
57+git submodule update --init --recursive
58+```
59+ 
60+当前 submodule:
61+ 
62+```text
63+npu_patch/3rdparty/shmem https://gitcode.com/cann/shmem.git
64+npu_patch/3rdparty/catlass https://gitcode.com/cann/catlass.git
65+```
66+ 
67+## 构建
68+ 
69+先加载 CANN 环境(未设置 `ASCEND_HOME_PATH` 时构建脚本会自动发现):
70+ 
71+```bash
72+source /usr/local/Ascend/ascend-toolkit/set_env.sh
73+```
74+ 
75+一键构建(按目标 SoC 选择封装脚本):
76+ 
77+```bash
78+# Ascend950 / A5
79+bash npu_patch/scripts/build_a5.sh [CANN_SET_ENV]
80+# Ascend910_93 / A3
81+bash npu_patch/scripts/build_a3.sh [CANN_SET_ENV]
82+```
83+ 
84+或显式指定 SoC:
85+ 
86+```bash
87+bash npu_patch/scripts/build_base.sh -soc_type Ascend950 [CANN_SET_ENV]
88+bash npu_patch/scripts/build_base.sh -soc_type Ascend910_93 [CANN_SET_ENV]
89+```
90+ 
91+> `-soc_type` 使用 `Ascend910_93` / `Ascend950`。A3 使用
92+> 非 SIMT Bisheng 后端(`planning_aicore.cpp` 等),产品架构由
93+> `ASCEND_MOONEP_ARCH_A3` 宏标识;A5 走 SIMT 后端(`planning_simt.cpp` 与
94+> 各 `*_udma.cpp`)。每个 SoC 有独立 build 目录(`build_ascend_<a3|a5>`),
95+> 切换 SoC 不会复用旧缓存。
96+ 
97+`build_base.sh` 是构建逻辑的**唯一实现**,依次:
98+ 
99+1. (如配置CANN_SET_ENV)`source` CANN `set_env.sh`;
100+2. `git submodule update --init --recursive`(cann/shmem、catlass);
101+3. 为当前 SoC 构建 cann/shmem 到 `npu_patch/3rdparty/shmem/install`;
102+4. `cmake -S npu_patch/native -B <build dir>`,用 Bisheng 编译 kernel,
103+ 生成 `ascend_moonep_kernels`;
104+5. 将 kernel 与 shmem `.so` 拷入 `npu_patch/lib/`;
105+6. `pip install -e .`,编译并安装 `npu_patch._C` PyTorch extension。
106+ 
107+> kernel `.so` 与 host 扩展 `npu_patch._C` 是**链接**关系,必须整套跑完,
108+> 不能只跑其中一步。可用环境变量 `FORCE_SHMEM=1`(重建 shmem)、
109+> `SHMEM_HOME_PATH`(复用已构建 install)、`BUILD_DIR`(指定 cmake 构建目录)
110+> 调整。
111+ 
112+## 运行测试
113+ 
114+统一入口是 `npu_patch/scripts/run_test.sh`(仓库根目录执行即可),按引擎拆分
115+**ubmem(MTE/AscendC,默认)** 与 **urma(URMA/UDMA,仅 A5/Ascend950)**,
116+目标 SoC 用 `--soc_type` 指定(默认 `Ascend950`):
117+ 
118+```bash
119+# ubmem / MTE 引擎(默认,A5)
120+bash npu_patch/scripts/run_test.sh
121+# urma 引擎(仅 A5)
122+bash npu_patch/scripts/run_test.sh --use_urma
123+ 
124+# A3(Ascend910_93):仅 mte 引擎,不要加 --use_urma
125+bash npu_patch/scripts/run_test.sh --soc_type Ascend910_93
126+# 改过 csrc/kernels 后强制重编再测:
127+BUILD=1 bash npu_patch/scripts/run_test.sh --soc_type Ascend910_93
128+```
129+ 
130+> **A3 不可加 `--use_urma`**:URMA/UDMA 算子依赖 SIMT,A3 没有,
131+> `run_test.sh` 检测到非 A5 + `--use_urma` 会直接报错退出。A3 上唯一有效的
132+> 引擎是 mte(默认,不加开关)。卡数可用 `NPROC` / `RANK_N` 覆盖(默认取
133+> `ASCEND_RT_VISIBLE_DEVICES` 的可见卡数,未设置时按 8)。
134+ 
135+`run_test.sh` 覆盖三类测试:
136+ 
137+1. **Buffer 公共 API(`test_npu/buffer_test`)**:`test_buffer_*` pytest 文件按
138+ `--use_urma` 用 `pytest -k` 筛选 parametrize 出的 `urma` / `mte` 变体;脚本式
139+ C / cpython 接口测试(`test_buffer_c_api` / `test_buffer_cpython_api`)引擎
140+ 不可切、原样运行;分组 e2e(`test_buffer_grouped_e2e`)单独一节、不带 `-k`。
141+2. **urma 算子(`test_npu/urma`,仅 `--use_urma` 且仅 A5)**:`test_*_udma` +
142+ 各 UDMA 脚本式算子测试(`test_moonep_combine_udma_with_plan` /
143+ `test_moonep_dispatch_udma_with_plan` / `test_dispatch_combine_udma_joint`)。
144+3. **mte ubmem 算子(`test_npu/mte`,默认)**:`test_*` + `test_planning` /
145+ `test_moonep_combine` / `test_moonep_dispatch_with_plan` /
146+ `test_dispatch_combine_joint`。
147+ 
148+多进程下所有 rank 使用相同的 shmem bootstrap:单机走 UID bootstrap
149+(`ShmemRuntime.init_with_buffer`),多机走 ip_port/DEFAULT bootstrap(见
150+「多机运行(buffer-backed + ip_port bootstrap)」)。
151+ 
152+## Python API
153+ 
154+`moonep` 顶层已按后端替换,统一
155+`from moonep import ...` 即可拿到Ascend实现(当 NPU 后端启用时,`moonep.Buffer` /
156+`moonep.MoonEPCommPlan` / `moonep.ShmemRuntime` 即 `npu_patch` 的同名对象,并保留 `moonep.init_shmem`,见 `MoonEP/moonep/__init__.py`)。
157+ 
158+对外可用API:
159+ 
160+- **MoonEP 风格 Buffer API**(推荐,Python + shmem 对称内存):`Buffer` /
161+ `MoonEPCommPlan` / `ShmemRuntime`,`dispatch` / `prefetch_weight` / `combine` /
162+ `reduce_grad` 用法见下一节。
163+ 
164+```python
165+# Buffer / Plan / shmem / init 一律从 moonep 顶层入口拿(NPU 上已替换为 npu_patch 实现)
166+from moonep import Buffer, MoonEPCommPlan, ShmemRuntime, init_shmem
167+# 框架侧对称张量助手统一走 moonep.buffer,下列都是 NPU 专有名字
168+# (GPU 进程里不存在,也无需使用):
169+from moonep.buffer import (
170+ create_full_weight, # 创建并填充 full weight([E+B,H,H'])
171+ create_full_grad_and_reduce_buffer, # reduce_grad 的 (full_grad, reduce_buffer)
172+ remote_home_rows, # 按 pe 点读 home chunk(免 bind,init 后可用)
173+ read_reduce_slot, # 按 pe 点读 reduce slot chunk(免 bind)
174+ expert_pool_row, # 全局 expert 的 [H, H'] 源行(init 后免 bind)
175+)
176+# 说明:GPU 的 create_nvl_dist_tensor / create_nvl_single_owner_tensor /
177+# pad_dim0_for_alignment 在昇腾侧没有对应实现——NPU 不需要 NVLink 映射,
178+# 跨 rank 张量由 shmem 对称堆 + 上面的构造器/点读助手覆盖。
179+# 说明:buffer_c.create_vmm_physical / launch_* 等是低层内部实现,应用侧无需
180+# 直接 import npu_patch —— 与 tests/test_e2e_npu_gpu.py 的写法一致。
181+```
182+ 
183+## MoonEP Buffer API(shmem 对称内存)
184+ 
185+`moonep.Buffer`(NPU 上即 `npu_patch` 的实现,见前节)是 `moonep/api.py`
186+Buffer 类的昇腾移植:在 `Buffer` 构造时
187+一次性分配 shmem 对称通信内存(`hidden_buf` / 各 meta 独立缓冲 / plan 广播区,
188+各变量单独分配 shmem 地址,无合并 `meta_buf`、无 `xxx_off`)并实例化一组
189+`KernelOp` 算子对象,`dispatch` / `prefetch_weight` / `combine` / `reduce_grad`
190+调用时执行 `op.compute`。跨 rank 访问走对称寻址:host 侧 `put/get`(v1),
191+kernel 侧 `aclshmem_ptr`(AscendC 迁移接缝)。
192+ 
193+Ascend多卡传输每个对称块按实际 shape 精确分配
194+(各 meta 变量单独分配 shmem 地址),buffer-backed 对称堆的 descriptor
195+总大小按 VMM 粒度(2 MiB)对齐,这个对齐目前影响create_vmm_physical不支持创建epn * H * Hp * element_size < 2,097,152的场景。对称块不额外创建 shmem Buffer 对象:tensor
196+本身即对称块,下游算子通过 `tensor.data_ptr()` 获取对称基址(host 侧
197+put/get/signal/free 需要 Buffer 时现场构造)。
198+ 
199+### 使用流程
200+ 
201+当前只有 buffer-backed 初始化(`ShmemRuntime.init_with_buffer` /
202+`init_with_ip_port`):**先构造 Buffer 与框架侧全部对称 VMM chunk(登记进全局
203+descriptor 注册表),再做一次对称堆 init,之后 Buffer 在首次
204+dispatch/combine/prefetch/reduce_grad 时把 chunk 翻译成内核要的对称地址**。
205+顺序不可颠倒:init 的 descriptor 集在 init 时冻结,之后创建的 VMM chunk 不会
206+进入当前对称堆。
207+ 
208+```python
209+import torch.distributed as dist
210+from moonep import Buffer, ShmemRuntime
211+ 
212+dist.init_process_group(backend="hccl")
213+R = dist.get_world_size()
214+E, S, H, K = 64, 4096, 256, 16
215+epn = E // R
216+B = epn # prefetch / 归约槽位数,默认等于 epn
217+ 
218+# 1. 构造 Buffer(此时仅登记 VMM descriptor,shmem 尚未 init)
219+use_udma = True # False = MTE(AscendC);True = URMA/UDMA(仅 A5)
220+buffer = Buffer(S, H, K, E, R, B=B, num_sms=32, group=dist.group.WORLD,
221+ explicitly_destroy=True, use_udma=use_udma)
222+ 
223+# 2. 构造框架侧 full weight / full grad / reduce buffer(见下节,
224+# 同样必须在 init 之前登记 descriptor)。
225+ 
226+# 3. 一次性 buffer-backed 对称堆 init(单机 UID bootstrap;多机见下)。
227+# enable_udma 必须与 buffer 的 use_udma 一致;URMA 参考 qp_count=2。
228+ShmemRuntime.init_with_buffer(group=dist.group.WORLD,
229+ enable_udma=use_udma, qp_count=2)
230+ 
231+# 4. 首次 dispatch/combine/prefetch/reduce_grad 时 Buffer 自动翻译对称地址。
232+ 
233+# 5. 释放顺序:先 finalize 再 destroy(VMM 逆操作)。
234+ShmemRuntime.finalize()
235+buffer.destroy()
236+```
237+ 
238+### ubmem(MTE)与 urma(URMA/UDMA)路径:初始化与调用
239+ 
240+planning / dispatch / combine / prefetch / reduce_grad 各有两条 kernel 路径,
241+通过 `Buffer` 构造时的 `use_udma`(及每算子 `*_use_udma` 覆盖)选择:
242+ 
243+- **ubmem / MTE 路径**(`use_udma=False`,默认):AscendC kernel 走 MTE2/MTE3
244+ 搬运,无 UDRMA。无论传不传 `use_udma`,非 A5 芯片都会自动回落 MTE。
245+- **urma / UDMA 路径**(`use_udma=True`,仅 Ascend950/A5):dispatch / combine /
246+ prefetch / reduce_grad 走 UDRMA RDMA 直写;planning 默认保持 MTE
247+ (`planning_use_udma=False`)。
248+ 
249+`Buffer` 构造时会设置进程级环境变量(`ASCEND_MOONEP_USE_UDMA` 与每算子
250+`ASCEND_MOONEP_{OP}_USE_UDMA`),kernel launcher / 算子据此选择 native 或 UDMA
251+变体;无需手动 export,但可用环境变量临时覆盖。
252+ 
253+```python
254+# urma:dispatch/combine/prefetch/reduce_grad 走 URMA,planning 留 MTE
255+buffer = Buffer(S, H, K, E, R, B=B, num_sms=32, group=dist.group.WORLD,
256+ explicitly_destroy=True, use_udma=True, planning_use_udma=False)
257+# ubmem/mte 全路径:全部算子走 AscendC
258+buffer = Buffer(S, H, K, E, R, B=B, num_sms=32, group=dist.group.WORLD,
259+ explicitly_destroy=True, use_udma=False)
260+```
261+ 
262+初始化时 `enable_udma` 必须与 `use_udma` 一致(URMA 对称堆带 UDRMA/QP 配置),
263+URMA 用 `qp_count` 指定每 rank 的 Dispatch UDMA QP 数:
264+ 
265+```python
266+# urma:enable_udma=True + qp_count
267+ShmemRuntime.init_with_buffer(group=dist.group.WORLD, enable_udma=True, qp_count=2)
268+# ubmem/mte:enable_udma=False
269+ShmemRuntime.init_with_buffer(group=dist.group.WORLD, enable_udma=False, qp_count=0)
270+```
271+ 
272+测试侧统一入口是 `test_npu/kernel_test_utils.py::init_shmem`(自动选单机 UID /
273+多机 ip_port bootstrap,`enable_udma` 透传);调用仍走公共 Buffer 方法
274+`buffer.dispatch(...)` / `buffer.prefetch_weight(...)` / `buffer.combine(...)` /
275+`buffer.reduce_grad(...)`。端到端参考:`test_npu/mte/test_e2e.py`(ubmem)与
276+`test_npu/urma/test_e2e_urma.py`(urma)。
277+ 
278+### 框架层要创建的对象:Full Weight / Full Grad / Reduce Buffer
279+ 
280+调度侧(dispatch/combine)的通信 chunk 与 plan 由 `Buffer` 内部管理;框架层
281+需要为 **prefetch_weight(权重侧)** 和 **reduce_grad(梯度侧)** 准备三组对称
282+张量。下列构造器是 **NPU 专有**名字(仅由 `moonep.buffer` 在 NPU 后端
283+re-export,GPU 进程中不存在——GPU 侧等价的稠密 `[E+B]` / `[R,B,H,H']`
284+张量由框架/测试直接以 `torch.empty` 构造);在 NPU 上它们会登记进全局
285+descriptor 注册表并在首次算子调用时翻译成对称基址,
286+应用侧无需直接操作低层 `npu_patch.buffer_c`:
287+ 
288+- **Full Weight(pool)**:`buffer.prefetch_weight` 的 `full_gate_weight` /
289+ `full_up_weight` / `full_down_weight` **就是该 full_weight**——由
290+ `create_full_weight` 一步创建并填充的逻辑 `[E+B, H, H']` bf16 权重池(NPU 上即
291+ 本 rank home/slot chunk 的 `[E+B]` 投影,附 `_npu_home_chunk` / `_npu_slot_chunk` /
292+ `_projection`):从全局 expert 表把本 rank 拥有的权重写入 home 行、slot 清零,
293+ `source_offset` 为逐投影偏置(gate/up/down 取 0/1/2):
294+ 
295+ ```python
296+ B = E // R # prefetch / 归约槽位数,默认等于 epn
297+ full_weight = create_full_weight(E, B, H, Hp, rank, R, remote_expert,
298+ source_offset=source_offset,
299+ dtype=torch.bfloat16,
300+ device=torch.npu.current_device())
301+ ```
302+ 
303+- **Full Grad + Reduce Buffer**(`buffer.reduce_grad` 的 `full_gate_grad` /
304+ `full_up_grad` / `full_down_grad` 与 `gate_reduce_buffer` / `up_reduce_buffer` /
305+ `down_reduce_buffer`):用 `create_full_grad_and_reduce_buffer` 一并创建,返回
306+ `(full_grad, reduce_buffer)`;`full_grad` 为 `[E+B, H, H']` **fp32**(附
307+ `_npu_home_chunk` / `_npu_slot_chunk` / `_projection`),Ascend reduce_grad 只读
308+ 本 rank slot chunk 的对称基址。`grad_table` / `reduce_table` 分别是 rank 不变的
309+ `[E, H, H']` 梯度参考表与 `[R, B, H, H']` slot 参考表,本 rank 只拷贝自己的
310+ home / slot 切片:
311+ 
312+ ```python
313+ full_grad, reduce_buffer = create_full_grad_and_reduce_buffer(
314+ E, B, H, Hp, rank, R, grad_table, reduce_table,
315+ dtype=torch.float32, device=torch.npu.current_device())
316+ ```
317+ 
318+ 示例见 `tests/test_e2e_npu_gpu.py`:权重侧用 `make_prefetch_args`,梯度侧用
319+ `make_grad_reduce_args`。
320+ 
321+要点:
322+ 
323+- 三组对称张量(full_weight / home-slot 投影)必须在 `moonep.init_shmem`
324+ (`ShmemRuntime.init_with_buffer` / `init_with_ip_port`)**之前**创建——init 的
325+ descriptor 集在 init 时冻结,之后的 VMM chunk 不会进入当前对称堆。
326+- **init 之后**跨 rank 读取**免 bind**:`remote_home_rows` /
327+ `read_reduce_slot` / `expert_pool_row` 按需解析对端对称地址
328+ (`buffer_c.remote_view`),返回 live 零拷贝视图。
329+- NPU 上 full_weight / full_grad 的投影视图基址**未登记**
330+ buffer-backed init,不能直接作对称基址用;算子只读 home/slot chunk 的对称基址,
331+ 不读投影视图本体(投影段别名同一份物理内存)。
332+- `B`(prefetch / 归约槽位数)默认等于 `epn`;`Buffer` 内部的组合 `[E+B]` slot
333+ 布局假定 `B == epn`(benchmark runner 构造时会断言),而 pool 投影路径对 `B`
334+ 无此约束。
335+- 完整参考:`tests/test_e2e_npu_gpu.py` 的 `make_prefetch_args` /
336+ `make_grad_reduce_args`;benchmark 见「基准测试」一节。
337+ 
338+### Buffer dispatch / combine / grad reduce
339+ 
340+```python
341+# hidden_sh [S,H] bf16, route_weights_sk [S,K] fp32,
342+# topk_experts_sk [S,K] int32, tokens_per_expert [E] int32
343+hidden_nvsh, route_weights_nvs, cu_seqlens, plan = buffer.dispatch(
344+ hidden_sh, route_weights_sk, topk_experts_sk, tokens_per_expert,
345+)
346+assert isinstance(plan, MoonEPCommPlan)
347+ 
348+# GEMM 就地在 hidden_nvsh 上执行后:
349+out_sh, out_sk, _ = buffer.combine(
350+ plan=plan, hidden_nvsh=hidden_nvsh, route_weights_nvs=route_weights_nvs,
351+)
352+ 
353+# 复用 plan(跳过 planning,只重放 dispatch;返回同一个 plan 对象):
354+hidden_nvsh2, w2, cu2, plan2 = buffer.dispatch(hidden_sh, plan=plan)
355+ 
356+# 权重侧 prefetch(先构造好三份 full weight,见上节):
357+buffer.prefetch_weight(
358+ plan=plan,
359+ full_gate_weight=full_gate_weight,
360+ full_up_weight=full_up_weight,
361+ full_down_weight=full_down_weight,
362+)
363+ 
364+# 梯度侧 reduce(先构造好三份 full grad + reduce buffer):
365+buffer.reduce_grad(
366+ plan=plan,
367+ full_gate_grad=full_gate_grad, full_up_grad=full_up_grad,
368+ full_down_grad=full_down_grad,
369+ gate_reduce_buffer=gate_reduce_buffer, up_reduce_buffer=up_reduce_buffer,
370+ down_reduce_buffer=down_reduce_buffer,
371+)
372+```
373+ 
374+- `zero_copy=True`:dispatch 返回本地对称分片的视图(`hidden_buf_local` /
375+ `weights_buf_local`,远程 rank 已直接写入);combine 的 `hidden_nvsh` 必须
376+ 别名该视图(`data_ptr` 相同),否则断言失败。
377+- `async_finish=True`:返回 `torch.npu.Event`。dispatch/combine 与 prefetch 都在
378+ comm stream 上异步执行,host 不额外同步;prefetch 的跨 rank 顺序由 kernel 内的
379+ pre/post vector collective 保证(与 dispatch kernel 同一种实现)。所有 rank 必须
380+ 以相同顺序进入这些集合操作。
381+- 断言级参考见 `test_npu/mte/test_e2e.py` 与 `test_npu/urma/test_e2e_urma.py`
382+ (含 plan 复用、zero_copy、async、prefetch 投影读回、grad reduce 参考校验)。
383+ 
384+依赖 `shmem` Python 包(cann-shmem `src/python`)。Buffer 路径与 `_C` 必须复用
385+同一份 SHMEM runtime,不能在同一进程中再初始化 C++ `ShmemInstance`。
386+ 
387+### 多机运行(buffer-backed + ip_port bootstrap)
388+ 
389+单机默认走 UID bootstrap(`ShmemRuntime.init_with_buffer`:rank0 生成 UID 经
390+`torch.distributed` 广播)。多机(多节点)改用 ip_port / DEFAULT bootstrap:
391+全体 rank 传同一个 `tcp://<rank0_ip>:<port>`,rank0 建 config store server、
392+其余连 client——对称空间可跨节点。
393+ 
394+```python
395+from moonep import Buffer, ShmemRuntime
396+ 
397+# 构造完所有 Buffer / 对称 pool(moonep.buffer,登记 VMM descriptor)后:
398+ShmemRuntime.init_with_ip_port(
399+ group=dist.group.WORLD,
400+ ip_port="tcp://192.168.1.10:29501", # 缺省时从 MASTER_ADDR/MASTER_PORT 推导(端口 +1)
401+ descriptors=None, # None = 进程内已登记的 VMM 分配
402+)
403+# 或等价:ShmemRuntime.init_with_buffer(ip_port="tcp://192.168.1.10:29501")
404+```
405+ 
406+### 基准测试(npu_patch/benchmarks)
407+ 
408+`npu_patch/benchmarks` 提供 Ascend benchmark 集:`bench_comm`、
409+`bench_grad_reduce`、`bench_prefetch`、`bench_vs`、`bench_vs_all2all`、
410+`bench_barrier`、`bench_dispatch_maxvio`、`bench_grad_reduce_maxvio`,共享 `_bench_common.py`
411+助手与 `run_bench.sh`(torchrun wrapper)。每个 benchmark 都带
412+`--engine {ubmem,urma}`(默认 `ubmem` = MTE/UB 原生路径;`urma` = UDMA/URMA
413+路径,仅 A5/Ascend950),作用到 Buffer、原始 `launch_*` 入口与 SHMEM 堆 init。
414+`bench_vs_all2all` 是 dispatch/combine 的对手实验:以 `bench_vs.py` 为模板,
415+把 MoonEP 与直接基于 `torch.distributed` `all_to_all_single` 的“无 plan、无
416+prefetch”实现放在同一组 routing/计时下对比(`--libs moonep all2all`,也可
417+`--libs all2all` 单独验证该集合通信,此时不加载 Buffer / shmem 堆)。
418+ 
419+先构建,再运行:
420+ 
421+```bash
422+# Ascend910_93 / A3
423+bash npu_patch/scripts/build_a3.sh
424+# Ascend950 / A5(按硬件选择对应构建脚本)
425+bash npu_patch/scripts/build_a5.sh
426+ 
427+# 单机自动识别卡数(A3 为 16,A5 为 8),默认脚本 + 默认引擎(ubmem)
428+bash npu_patch/benchmarks/run_bench.sh
429+# 指定脚本
430+bash npu_patch/benchmarks/run_bench.sh bench_prefetch.py
431+# urma 引擎(仅 A5/Ascend950)
432+ENGINE=urma bash npu_patch/benchmarks/run_bench.sh bench_comm.py
433+```
434+ 
435+多机启动(`NODES>1` 各节点各执行一次,`MASTER_ADDR` 指向 rank0);多机 shmem
436+ip_port 缺省从 `MASTER_ADDR` / `MASTER_PORT` 自动推导(端口 +1),需要时可显式
437+指定 `SHMEM_IP_PORT="tcp://<ip>:<port>"`:
438+ 
439+```bash
440+# node 0
441+NODES=2 NODE_RANK=0 MASTER_ADDR=192.168.1.10 bash npu_patch/benchmarks/run_bench.sh bench_vs.py
442+# node 1
443+NODES=2 NODE_RANK=1 MASTER_ADDR=192.168.1.10 bash npu_patch/benchmarks/run_bench.sh bench_vs.py
444+ 
445+# MoonEP vs torch.distributed all_to_all(同样支持 NODES/NODE_RANK 多机)
446+bash npu_patch/benchmarks/run_bench.sh bench_vs_all2all.py
447+```
@@ -0,0 +1,178 @@
1+"""
2+npu_patch: Ascend (NPU) MoE expert-parallel communication runtime.
3+ 
4+Two usage paths share this package:
5+ 
6+1. **Call-chain ops** (C++ extension ``_C``): ``ShmemInstance`` + the
7+ ``Dispatch`` / ``Combine`` torch custom classes
8+ (ascend_deepep style). Business parameters (hidden/topk/expert shapes) are
9+ passed on every ``compute`` call.
10+ 
11+2. **MoonEP-style Buffer API** (Python, shmem symmetric memory): ``Buffer``
12+ pre-allocates the symmetric communication chunks and instantiates the kernel
13+ op objects at init; ``dispatch`` / ``prefetch_weight`` / ``combine`` /
14+ ``reduce_grad`` are the migrated ``moonep/api.py`` entry points. Runtime
15+ lifecycle is handled by ``ShmemRuntime`` (shmem Python package UID
16+ bootstrap), distinct from the C++ ``ShmemInstance``.
17+ 
18+When both paths are used in one process, the C++ extension reuses the SHMEM
19+runtime loaded by the Python package. A process must never load two independent
20+``libshmem.so`` instances because their PE state and symmetric heaps diverge.
21+"""
22+ 
23+import ctypes
24+import os
25+from pathlib import Path
26+ 
27+_PKG_DIR = Path(__file__).resolve().parent
28+ 
29+ 
30+def _load_package_shmem_libs():
31+ """Load the CANN SHMEM shared libraries shipped in ``lib/``.
32+ 
33+ The C++ ``_C`` extension links against ``libshmem.so`` (rpath
34+ ``$ORIGIN/lib``); loading the copies here with RTLD_GLOBAL makes them
35+ resolvable before ``_C`` is imported.
36+ 
37+ This fallback is only needed when the ``shmem`` Python package is not
38+ available. If Python SHMEM was loaded first, ``_C`` must reuse that runtime
39+ instead of loading another absolute-path copy from ``lib/``.
40+ """
41+ lib_dir = _PKG_DIR / "lib"
42+ required_libs = [
43+ "libshmem_utils.so",
44+ "aclshmem_bootstrap_config_store.so",
45+ "libshmem.so",
46+ ]
47+ optional_libs = [
48+ "aclshmem_bootstrap_uid.so",
49+ ]
50+ mode = getattr(os, "RTLD_NOW", 0) | getattr(ctypes, "RTLD_GLOBAL", 0)
51+ for lib_name in required_libs + optional_libs:
52+ lib_path = lib_dir / lib_name
53+ if not lib_path.exists():
54+ if lib_name in required_libs:
55+ raise ImportError(f"required SHMEM shared library not found: {lib_path}")
56+ continue
57+ try:
58+ ctypes.CDLL(str(lib_path), mode=mode)
59+ except OSError as exc:
60+ raise ImportError(f"failed to load SHMEM shared library {lib_path}: {exc}") from exc
61+ 
62+ 
63+def _promote_python_shmem_libs():
64+ from shmem.shmem_config import _get_lib_dir
65+ 
66+ lib_dir = Path(_get_lib_dir())
67+ mode = getattr(os, "RTLD_NOW", 0) | getattr(ctypes, "RTLD_GLOBAL", 0)
68+ for lib_name in (
69+ "libshmem_utils.so",
70+ "aclshmem_bootstrap_config_store.so",
71+ "libshmem.so",
72+ "aclshmem_bootstrap_uid.so",
73+ ):
74+ lib_path = lib_dir / lib_name
75+ if lib_path.exists():
76+ ctypes.CDLL(str(lib_path), mode=mode)
77+ 
78+ 
79+def _has_cpp_extension() -> bool:
80+ """True when the C++ ``_C`` extension has been built into the package."""
81+ return any(_PKG_DIR.glob("_C*.so")) or any(_PKG_DIR.glob("_C*.pyd"))
82+ 
83+ 
84+# The Buffer API (npu_patch.api) is built on the `shmem` Python package.
85+# Force its native libraries to load before the C++ `lib/` copies so the
86+# package's duplicate-libshmem guard sees a single instance. Pure C++ op users
87+# without the shmem Python package are unaffected (failure swallowed; this is
88+# only an ordering optimization).
89+_PYTHON_SHMEM_LOADED = False
90+try:
91+ import shmem as _shmem
92+ 
93+ _ = _shmem.aclshmem_get_unique_id # force the package's lazy native load
94+ del _
95+ _promote_python_shmem_libs()
96+ _PYTHON_SHMEM_LOADED = True
97+except Exception:
98+ _shmem = None
99+ 
100+if _has_cpp_extension():
101+ if not _PYTHON_SHMEM_LOADED:
102+ _load_package_shmem_libs()
103+ # Load torch/torch_npu first: _C.so's RUNPATH lacks the torch package lib
104+ # dir, so libc10/libtorch_cpu/libtorch_npu must be resolvable before _C is
105+ # linked (otherwise a bare ``import npu_patch`` fails with
106+ # "libtorch_npu.so: cannot open shared object").
107+ import torch
108+ import torch_npu
109+ 
110+ from . import _C as _C
111+ 
112+ ShmemInstance = torch.classes.AscendMoonEP.ShmemInstance
113+ GradReduce = torch.classes.AscendMoonEP.GradReduce
114+ PrefetchWeight = torch.classes.AscendMoonEP.PrefetchWeight
115+else:
116+ # The C++ extension is not built; the MoonEP-style Buffer API (Python,
117+ # shmem symmetric memory) still works. The call-chain classes are left as
118+ # None so callers can detect the missing extension.
119+ _C = None
120+ ShmemInstance = None
121+ GradReduce = None
122+ PrefetchWeight = None
123+ 
124+ 
125+def _load_buffer_api():
126+ """Import the MoonEP-style Buffer API modules on first access.
127+ 
128+ The import is deferred so that C++-ops-only users (who may not have the
129+ ``shmem`` Python package / ``torch_npu`` installed) can import this package
130+ without pulling in the buffer API stack.
131+ """
132+ from .shmem_runtime import ShmemRuntime, runtime_library_info
133+ from .planning import MoonEPCommPlan
134+ from .api import Buffer
135+ from .buffer_bindings import CommBuffers, ExpertPointerBinding
136+ 
137+ return {
138+ "Buffer": Buffer,
139+ "CommBuffers": CommBuffers,
140+ "ExpertPointerBinding": ExpertPointerBinding,
141+ "MoonEPCommPlan": MoonEPCommPlan,
142+ "ShmemRuntime": ShmemRuntime,
143+ "runtime_library_info": runtime_library_info,
144+ }
145+ 
146+ 
147+_BUFFER_API_NAMES = frozenset({
148+ "Buffer", "CommBuffers", "ExpertPointerBinding", "MoonEPCommPlan", "ShmemRuntime", "runtime_library_info"
149+})
150+_BUF_API_CACHE = None
151+ 
152+ 
153+def __getattr__(name):
154+ if name in _BUFFER_API_NAMES:
155+ global _BUF_API_CACHE
156+ if _BUF_API_CACHE is None:
157+ _BUF_API_CACHE = _load_buffer_api()
158+ return _BUF_API_CACHE[name]
159+ raise AttributeError(f"module 'npu_patch' has no attribute {name!r}")
160+ 
161+ 
162+from .launchers import launch_grad_reduce, launch_grad_reduce_targets, launch_prefetch, launch_prefetch_from_ptrs
163+ 
164+__all__ = [
165+ "ShmemInstance",
166+ "GradReduce",
167+ "launch_grad_reduce",
168+ "launch_grad_reduce_targets",
169+ "Buffer",
170+ "CommBuffers",
171+ "ExpertPointerBinding",
172+ "MoonEPCommPlan",
173+ "ShmemRuntime",
174+ "runtime_library_info",
175+ "PrefetchWeight",
176+ "launch_prefetch",
177+ "launch_prefetch_from_ptrs",
178+]
@@ -0,0 +1,662 @@
1+"""Provider-owned, versioned canonical integer geometry for the A5 R8 profile.
2+ 
3+This module is imported only when the explicit fast path is enabled. The
4+borrowed Gloo group and the existing Buffer remain the only runtime owners.
5+In particular, a successful enqueue is not a completion receipt. All four
6+control phases use the same fixed CPU all_gather envelope, including failures.
7+"""
8+ 
9+from dataclasses import dataclass, field
10+import hashlib
11+import os
12+import struct
13+import threading
14+ 
15+ 
16+VERSION = 1
17+MECHANISM = 'native-canonical-owner-v1'
18+MAGIC = 0x43475031
19+BACKEND = 3510
20+RANKS, EXPERTS, LOCAL_EXPERTS = 8, 48, 6
21+TOKENS, TOPK, ROUTES = 8192, 8, 65536
22+CHUNKS, CHUNK_ROUTES, JOBS = 32, 2048, 1536
23+STATUS_WORDS, DESCRIPTOR_WORDS, PACKET_WORDS = 8, 1248, 1312
24+PREPARE, SUBMITTED, READY, RETIRE = 1, 2, 3, 4
25+PARTIAL, PREPARED, ENQUEUED, NATIVE_READY, RETIRED, QUARANTINED = range(6)
26+OK, KNOWN_REJECT, UNKNOWN_SUBMISSION, UNKNOWN_COMPLETION, CONTROL_FAILURE = range(5)
27+_PRE_WORDS = JOBS * STATUS_WORDS
28+_POST_OFFSET = _PRE_WORDS
29+_DESCRIPTOR_OFFSET = _PRE_WORDS * 2
30+_META_OFFSET = _DESCRIPTOR_OFFSET + DESCRIPTOR_WORDS
31+_STORAGE_WORDS = _META_OFFSET + STATUS_WORDS
32+_UNAVAILABLE_COUNTS = (-1,) * EXPERTS
33+_UNAVAILABLE_DESCRIPTOR = (-1,) * DESCRIPTOR_WORDS
34+_FAILED_COORDINATORS = [] # Deliberate roots; never a retry/reuse pool.
35+ 
36+ 
37+class PrepareRejected(RuntimeError):
38+ """All participants rejected before any peer-native submission."""
39+ 
40+ 
41+class GeometryProtocolError(RuntimeError):
42+ """Invalid, stale, foreign or modified geometry; no implicit fallback."""
43+ 
44+ 
45+@dataclass(frozen=True, slots=True)
46+class PreparedInputs:
47+ plan: object
48+ cu_seqlens: object
49+ topk_flat: object
50+ payload: object = None
51+ versioned_inputs: tuple = ()
52+ 
53+ 
54+@dataclass(frozen=True, slots=True)
55+class CanonicalOwnerGeometry:
56+ owner_counts: tuple
57+ physical_rows: tuple
58+ owner_rows: tuple
59+ send_rows: object
60+ send_splits: tuple
61+ receive_splits: tuple
62+ expert_rows: tuple
63+ owner_row_count: int
64+ roots: tuple
65+ mechanism: str = MECHANISM
66+ version: int = VERSION
67+ 
68+ 
69+@dataclass(slots=True, eq=False)
70+class _Attachment:
71+ coordinator: object
72+ sequence: int
73+ cookie: object
74+ state: int = PARTIAL
75+ roots: list = field(default_factory=list)
76+ plan: object = None
77+ cu_seqlens: object = None
78+ topk_flat: object = None
79+ payload: object = None
80+ snapshot: object = None
81+ status_storage: object = None
82+ pre_status: object = None
83+ post_status: object = None
84+ descriptor_tensor: object = None
85+ meta_status: object = None
86+ ready_storage: object = None
87+ physical: object = None
88+ owner: object = None
89+ send: object = None
90+ expert_receive: object = None
91+ source_counts: tuple = _UNAVAILABLE_COUNTS
92+ descriptor: tuple = _UNAVAILABLE_DESCRIPTOR
93+ prepare_sources: tuple = ()
94+ producer_rows: int = -1
95+ owner_count: int = -1
96+ geometry: object = None
97+ versions: tuple = ()
98+ receipt_digest: str = ''
99+ attempted: bool = False
100+ 
@@ -0,0 +1,310 @@
1+"""
2+Ascend port shared helpers for ``npu_patch``.
3+ 
4+Replaces the VMM/multicast alignment and IPC-fd machinery of ``moonep/buffer.py``
5+with shmem (cann-shmem) symmetric-memory primitives. Everything here is
6+host-side; device-side symmetric addressing lives in the migrated kernels
7+(``aclshmem_ptr`` at the kernel seam).
8+ 
9+Import notes (verified against the vendored shmem source):
10+ - ``shmem.core`` re-exports only ``init_final``/``rma``/``memory`` names, so
11+ ``Buffer`` is NOT ``core.Buffer`` — import it from ``shmem.core.utils``.
12+ - ``my_pe``/``n_pes``/``SignalOp``/``ComparisonType``/``init_status`` live in
13+ ``shmem.core.direct`` (not re-exported at ``core`` level).
14+ - ``construct_tensor_from_ptr`` is NOT in ``shmem.__all__`` (and the module's
15+ ``__getattr__`` only loads natives for names in ``__all__``), so it is not
16+ a reliable ``shmem.construct_tensor_from_ptr`` accessor. Use the public
17+ ``shmem.aclshmem_create_tensor`` instead and recover the ``Buffer`` handle
18+ from the returned tensor's ``data_ptr()``.
19+"""
20+ 
21+from __future__ import annotations
22+ 
23+import os
24+ 
25+import torch
26+ 
27+from ._C import (
28+ acl_shmem_putmem,
29+ acl_shmem_getmem,
30+ acl_shmem_barrier_all,
31+ acl_shmem_barrier_all_on_stream,
32+)
33+ 
34+ 
35+ACLSHMEM_DATA_OP_MTE = 0x01
36+ACLSHMEM_DATA_OP_UDMA = 0x08
37+ 
38+ 
39+class SymBuffer:
40+ """Symmetric memory handle (addr + length), replacing
41+ shmem.core.utils.Buffer."""
42+ 
43+ __slots__ = ("addr", "length")
44+ 
45+ def __init__(self, addr: int, length: int):
46+ self.addr = int(addr)
47+ self.length = int(length)
48+ 
49+ 
50+# --- Original implementation (plan A: shmem Python package) ---
51+# import shmem.core as core
52+# from shmem.core.utils import Buffer as SymBuffer
53+ 
54+# shmem symmetric-heap page size (DEVICE_LARGE_PAGE_SIZE). Only the per-PE heap
55+# ``mem_size`` passed to ``core.init`` must be a multiple of this (see
56+# Troubleshooting_FAQs: non-2MiB-aligned mem_size fails). Individual allocations
57+# (``aclshmem_create_tensor`` / ``core.buffer``) need NO 2 MiB padding: the
58+# symmetric allocator aligns each allocation internally, so chunk sizes are used
59+# exactly as requested on Ascend.
60+SHMEM_LARGE_PAGE = 2 * 1024 * 1024
61+ 
62+_ELEM_SIZE = {
63+ torch.float32: 4,
64+ torch.bfloat16: 2,
65+ torch.int32: 4,
66+ torch.uint8: 1,
67+}
68+ 
69+ 
70+# ================================================================
71+# Symmetric-heap sizing.
72+#
73+# The per-PE ``mem_size`` passed to ``core.init`` must cover every symmetric
74+# allocation made in the process. Symmetric memory is collective: every rank
75+# reserves the same footprint on its own heap, so the required size depends only
76+# on the model config — seqlen (S), topk count (K), expert count (E), the hidden
77+# sizes (H, H') and the number of EP ranks (R). All sizes below are per rank.
78+# ================================================================
79+ 
80+# Barrier signal words per rank (dedicated symmetric ``barrier_buf`` chunk).
81+BARRIER_SLOTS = 3
82+# Default per-op symmetric workspace for the RMA-capable ops (dispatch/combine).
83+OP_WS_BYTES_DEFAULT = 16 * 1024 * 1024
84+ 
85+ 
86+def planning_symmetric_workspace_nbytes(E: int, NvS: int, R: int) -> int:
87+ """Bytes of Planning's per-rank symmetric communication workspace.
88+ 
89+ The regions hold local TPE, source-side duplicate payload metadata and the
90+ compact duplicate results exchanged between ranks. All offsets are aligned
91+ to 32 bytes, matching the host launcher and device kernel layout.
92+ """
93+ align_elems = 8
94+ 
95+ def align_up(value: int) -> int:
96+ return ((value + align_elems - 1) // align_elems) * align_elems
97+ 
98+ dup_rank_counts_off = align_up(E)
99+ # Count and prefix exchanges each reserve one 32-byte slot per peer.
100+ # Payload completion reserves one flag per source rank.
101+ dup_payload_done_off = dup_rank_counts_off + 2 * R * align_elems
102+ dup_groups_off = dup_payload_done_off + align_up(R)
103+ dup_loffs_off = dup_groups_off + align_up(NvS * 3)
104+ return (dup_loffs_off + align_up(NvS)) * 4
105+ 
106+ 
107+def compute_shmem_mem_size(
108+ S: int,
109+ H: int,
110+ K: int,
111+ E: int,
112+ H_prime: int,
113+ num_ep_ranks: int,
114+ *,
115+ op_ws_bytes: int = OP_WS_BYTES_DEFAULT,
116+ num_reduce_buffers: int = 3,
117+ num_prefetch_slots: int = 3,
118+ owner_weight_bytes: int = 0,
119+) -> int:
120+ """Per-PE symmetric heap bytes required to run MoonEP with the given config.
121+ 
122+ Sums every symmetric allocation the Buffer and the framework make, then
123+ rounds up to the 2 MiB large page (``core.init`` requires ``mem_size`` to be
124+ 2 MiB-aligned). With ``B = E // num_ep_ranks`` (this rank's expert share)
125+ and ``NvS = S * K``, the itemized calculation is:
126+ 
127+ Buffer symmetric chunks (per rank):
128+ hidden_buf [NvS, H] bf16 : NvS * H * 2
129+ weights_buf [NvS] int32: NvS * 4
130+ barrier_buf [BARRIER_SLOTS] int32: BARRIER_SLOTS * 4
131+ dispatch_sync_buffer : Token control + local Token AIV sync
132+ RMA op workspaces:
133+ Planning exact communication workspace
134+ dispatch + combine: 2 * op_ws_bytes
135+ Grad-reduce buffers [B, H, H'] fp32 : num_reduce_buffers * B * H * H' * 4
136+ Prefetch weight slots [B, H, H'] bf16 : num_prefetch_slots * B * H * H' * 2
137+ owner_weight_bytes: caller-supplied extra (e.g. single-owner weight tensors
138+ the framework allocates outside the Buffer).
139+ 
140+ The result is a lower bound for the default counts; a framework that
141+ allocates more or fewer extra symmetric tensors passes the matching
142+ parameters. Equal on every rank (B/R are global). Note: on the
143+ buffer-backed path the heap size is determined by the VMM descriptors
144+ registered with init_with_buffer; this function is a budgeting estimate
145+ only (legacy ``ShmemRuntime.init(mem_size=...)`` was removed).
146+ """
147+ R = num_ep_ranks
148+ assert E % R == 0, f"E ({E}) must be divisible by R ({R})"
149+ B = E // R
150+ NvS = S * K
151+ 
152+ buffer_chunks = (
153+ NvS * H * 2 # hidden_buf (bf16)
154+ + NvS * 4 # weights_buf (int32)
155+ + BARRIER_SLOTS * 4 # barrier_buf (int32)
156+ + R * 16 * 6 * 512 # dispatch_sync_buffer Token control region
157+ + 16 * 4 * 512 # four-round local sync region for 16 Token AIVs
158+ )
159+ op_workspaces = planning_symmetric_workspace_nbytes(E, NvS, R) + 2 * op_ws_bytes
160+ grad_reduce = num_reduce_buffers * B * H * H_prime * _ELEM_SIZE[torch.float32]
161+ prefetch = num_prefetch_slots * B * H * H_prime * _ELEM_SIZE[torch.bfloat16]
162+ 
163+ total = (
164+ buffer_chunks + op_workspaces + grad_reduce + prefetch
165+ + int(owner_weight_bytes)
166+ )
167+ # mem_size must be 2 MiB-aligned (only the heap itself needs this on Ascend).
168+ return ((total + SHMEM_LARGE_PAGE - 1) // SHMEM_LARGE_PAGE) * SHMEM_LARGE_PAGE
169+ 
170+ 
171+def sym_view(buf: SymBuffer, byte_off: int, nbytes: int) -> SymBuffer:
172+ """Return a sub-range of a local symmetric allocation as an shmem Buffer.
173+ 
174+ The address is the *local symmetric* address; ``put``/``get`` translate it
175+ to the target PE internally (pass ``pe``). Byte offsets follow the ``ctx``
176+ meta-layout constants, so the CUDA meta layout carries over unchanged.
177+ """
178+ return SymBuffer(buf.addr + byte_off, nbytes)
179+ 
180+ 
181+def tensor_buffer(t: torch.Tensor) -> SymBuffer:
182+ """Transient shmem Buffer view over a tensor.
183+ 
184+ For a tensor allocated from the shmem heap (``create_sym_dist_tensor`` /
185+ ``aclshmem_create_tensor``), ``t.data_ptr()`` is the local symmetric base;
186+ this wraps it in the ``Buffer`` handle the shmem Python API expects for
187+ put/get/signal and for ``core.free``. The handle is transient — the tensor
188+ remains the single owner of the address.
189+ """
190+ return SymBuffer(t.data_ptr(), t.numel() * t.element_size())
191+ 
192+ 
193+def sym_put(local_chunk: torch.Tensor, byte_off: int, src: SymBuffer, pe: int, stream: int) -> None:
194+ """Copy local ``src`` to ``pe``'s symmetric region at ``byte_off`` of ``local_chunk``.
195+ 
196+ Plan B: C-interface on_stream non-blocking RMA (aligned with core.put
197+ semantics; no quiet internally); the stream argument is kept and
198+ synchronization is the caller's responsibility via
199+ barrier/synchronize.
200+ """
201+ acl_shmem_putmem(local_chunk.data_ptr() + byte_off, src.addr, src.length,
202+ pe, stream)
203+ # --- Original implementation (plan A: core.put) ---
204+ # core.put(sym_view(tensor_buffer(local_chunk), byte_off, src.length), src, pe, stream)
205+ 
206+ 
207+def sym_get(local_chunk: torch.Tensor, byte_off: int, dst: SymBuffer, pe: int, stream: int) -> None:
208+ """Copy ``pe``'s symmetric region at ``byte_off`` of ``local_chunk`` into local ``dst``.
209+ 
210+ Plan B: C-interface on_stream non-blocking RMA (aligned with core.get
211+ semantics; no quiet internally); the stream argument is kept and
212+ synchronization is the caller's responsibility via
213+ barrier/synchronize.
214+ """
215+ acl_shmem_getmem(dst.addr, local_chunk.data_ptr() + byte_off, dst.length,
216+ pe, stream)
217+ # --- Original implementation (plan A: core.get) ---
218+ # core.get(dst, sym_view(tensor_buffer(local_chunk), byte_off, dst.length), pe, stream)
219+ 
220+ 
221+def sym_get_into(
222+ local_chunk: torch.Tensor, byte_off: int, dst_tensor: torch.Tensor, pe: int, stream: int
223+) -> None:
224+ """Materialize a remote rank's symmetric region into a local NPU tensor.
225+ 
226+ This is the Ascend replacement for CUDA's VMM "single-owner tensor visible
227+ everywhere": a remote rank's chunk (or chunk slice) is fetched into a local
228+ tensor via host RMA. Plan B: C-interface on_stream non-blocking
229+ implementation; the stream argument is kept and synchronization is the
230+ caller's responsibility.
231+ """
232+ nbytes = dst_tensor.numel() * dst_tensor.element_size()
233+ acl_shmem_getmem(dst_tensor.data_ptr(), local_chunk.data_ptr() + byte_off,
234+ nbytes, pe, stream)
235+ # --- Original implementation (plan A: core.get) ---
236+ # core.get(
237+ # tensor_buffer(dst_tensor),
238+ # sym_view(tensor_buffer(local_chunk), byte_off, dst_tensor.numel() * dst_tensor.element_size()),
239+ # pe, stream,
240+ # )
241+ 
242+ 
243+def sym_put_from(
244+ local_chunk: torch.Tensor, byte_off: int, src_tensor: torch.Tensor, pe: int, stream: int
245+) -> None:
246+ """Push a local NPU tensor into a remote rank's symmetric region.
247+ 
248+ Plan B: C-interface on_stream non-blocking implementation; the stream
249+ argument is kept and synchronization is the caller's responsibility.
250+ """
251+ nbytes = src_tensor.numel() * src_tensor.element_size()
252+ acl_shmem_putmem(local_chunk.data_ptr() + byte_off, src_tensor.data_ptr(),
253+ nbytes, pe, stream)
254+ # --- Original implementation (plan A: core.put) ---
255+ # core.put(
256+ # sym_view(tensor_buffer(local_chunk), byte_off, src_tensor.numel() * src_tensor.element_size()),
257+ # tensor_buffer(src_tensor),
258+ # pe,
259+ # stream,
260+ # )
261+ 
262+ 
263+def record_streams(tensors, stream: torch.Stream) -> None:
264+ """Record ``stream`` against tensors so torch does not free them early."""
265+ for t in tensors:
266+ if t is not None:
267+ t.record_stream(stream)
268+ 
269+ 
270+def _async_barrier_enabled() -> bool:
271+ """Whether the async (on-stream) cross-rank barrier primitive is used.
272+ 
273+ Defaults to on. Set ``ASCEND_MOONEP_ASYNC_BARRIER=0`` to fall back to the
274+ historical host-blocking ``acl_shmem_barrier_all()`` (correct but not
275+ async) if the on-stream primitive misbehaves on a given CANN/shmem build.
276+ """
277+ raw = os.environ.get("ASCEND_MOONEP_ASYNC_BARRIER")
278+ if raw is not None:
279+ return raw.strip().lower() in ("1", "true", "yes", "on")
280+ return True
281+ 
282+ 
283+def cross_rank_barrier(ctx: dict, stream: int) -> None:
284+ """Host-side cross-rank barrier (inter_rank_sync for dispatch/combine).
285+ 
286+ Async version (default): non-blocking -- enqueues the cross-rank full
287+ barrier onto ``stream`` via ``acl_shmem_barrier_all_on_stream`` (works
288+ with both buffer-backed bootstraps, UID and ip_port/DEFAULT). The
289+ device/stream aligns all ranks and drains the cross-rank RMA pending on
290+ that stream before releasing, during async execution. The host does not
291+ block; combined with the api async path launching kernels on a dedicated
292+ comm_stream this yields true async.
293+ 
294+ Each call advances the process-wide ``_barrier_round`` so back-to-back
295+ async ops drive distinct barrier generations (a slow rank's unfinished
296+ round cannot be wrongly consumed by a fast rank entering the next round;
297+ this avoids deadlocking on the shared sync_counter).
298+ 
299+ ``stream`` is the caller's current/comm stream ``npu_stream`` handle,
300+ forwarded verbatim to the on-stream primitive.
301+ ``ASCEND_MOONEP_ASYNC_BARRIER=0`` falls back to the historical
302+ host-blocking ``acl_shmem_barrier_all()`` (correct but not async; the
303+ fallback when the on-stream primitive is unavailable).
304+ """
305+ ctx['_barrier_round'] = int(ctx.get('_barrier_round', 0)) + 1
306+ if _async_barrier_enabled():
307+ acl_shmem_barrier_all_on_stream(stream)
308+ else:
309+ # Fallback: historical host-blocking global barrier + drains pending RMA.
310+ acl_shmem_barrier_all()
@@ -0,0 +1,121 @@
1+# SPDX-License-Identifier: Apache-2.0
2+"""Central NPU device-index resolution (rank -> device).
3+ 
4+Ascend semantics (CANN ``ASCEND_RT_VISIBLE_DEVICES``): the cards listed in the
5+mask are renumbered for the process to the *logical* indices ``0..N-1`` -- with
6+``ASCEND_RT_VISIBLE_DEVICES=2,3,4,5`` the tensor device ``npu:0`` addresses the
7+**physical** card 2, ``npu:1`` card 3, and so on. Two id spaces therefore
8+coexist:
9+ 
10+ - ``local_device_index`` (logical, renumbered 0..N-1): what
11+ ``torch.npu.set_device``, the ``npu:i`` tensor/stream device string, the
12+ ``dist`` ``device_id`` argument **and the VMM allocation APIs** expect
13+ (``aclrtMemGetAllocationGranularity`` / ``aclrtMallocPhysical`` /
14+ ``aclrtMapMem`` -- ``create_vmm_physical`` passes it as ``device``).
15+ - ``local_physical_id`` (the mask entry == npu-smi card id): what
16+ ``aclrtMemSetAccess``'s ``desc.location.id`` expects, and what logs / HCCL
17+ topology use. ``create_vmm_physical`` / ``create_full_projection_tensor``
18+ pass it as the access id.
19+ 
20+Measured on Ascend 950 with ``ASCEND_RT_VISIBLE_DEVICES=4,5``:
21+``aclrtGetDevice()`` returns ``0``; the allocation APIs accept ``0``/``1`` and
22+reject ``4``/``5`` (107001); ``aclrtMemSetAccess`` is the opposite -- ``0``/``1``
23+fail with 507899 while ``4``/``5`` succeed. Both numbers are needed; mixing
24+them up is the classic failure here. This module is the single source of truth
25+for rank -> device mapping; tests and benchmarks must not re-derive it.
26+"""
27+ 
28+import os
29+ 
30+import torch
31+ 
32+__all__ = [
33+ "visible_npu_ids",
34+ "visible_npu_count",
35+ "local_device_index",
36+ "local_physical_id",
37+]
38+ 
39+ 
40+def visible_npu_ids():
41+ """Physical NPU ids visible to this process, or ``None`` if no mask is set.
42+ 
43+ Parses ``ASCEND_RT_VISIBLE_DEVICES``, supporting comma-separated ids
44+ (``4,5``) and/or ``a-b`` intervals (``4-7`` == ``4,5,6,7``). Returns
45+ ``None`` when the variable is absent/empty so callers fall back to the full
46+ device list; malformed tokens are ignored.
47+ """
48+ mask = os.environ.get("ASCEND_RT_VISIBLE_DEVICES")
49+ if not mask:
50+ return None
51+ ids = []
52+ for token in mask.split(","):
53+ token = token.strip()
54+ if not token:
55+ continue
56+ if "-" in token:
57+ lo, _, hi = token.partition("-")
58+ lo_s, hi_s = lo.strip(), hi.strip()
59+ if not (lo_s.isdigit() and hi_s.isdigit() and int(lo_s) <= int(hi_s)):
60+ continue
61+ ids.extend(range(int(lo_s), int(hi_s) + 1))
62+ continue
63+ if token.isdigit():
64+ ids.append(int(token))
65+ return ids or None
66+ 
67+ 
68+def visible_npu_count() -> int:
69+ """Number of NPU devices visible to this process.
70+ 
71+ Uses the ``ASCEND_RT_VISIBLE_DEVICES`` mask when set, else
72+ ``torch.npu.device_count()``.
73+ """
74+ visible = visible_npu_ids()
75+ if visible is not None:
76+ return len(visible)
77+ if not torch.npu.is_available():
78+ return 0
79+ return int(torch.npu.device_count())
80+ 
81+ 
82+def _require_rank_in_range(local_rank: int, n_dev: int) -> int:
83+ if n_dev <= 0:
84+ raise RuntimeError("no Ascend NPU devices are visible to this process")
85+ if not 0 <= local_rank < n_dev:
86+ raise RuntimeError(
87+ f"local_rank={local_rank} out of range: only {n_dev} NPU device(s) "
88+ f"are visible (ASCEND_RT_VISIBLE_DEVICES="
89+ f"{os.environ.get('ASCEND_RT_VISIBLE_DEVICES', '')!r}). "
90+ f"Launch with nproc-per-node == the number of visible devices."
91+ )
92+ return local_rank
93+ 
94+ 
95+def local_device_index(local_rank: int) -> int:
96+ """Logical NPU device index for a torchrun-style local rank.
97+ 
98+ The visible cards are renumbered ``0..N-1``, so the rank's logical device
99+ index is its position in the visible set == ``local_rank``. Raises a clear
100+ error instead of an opaque "device not available" when more ranks than
101+ visible devices are requested (e.g. default ``NPROC=8`` with 4 visible
102+ cards).
103+ """
104+ local_rank = int(local_rank)
105+ return _require_rank_in_range(local_rank, visible_npu_count())
106+ 
107+ 
108+def local_physical_id(local_rank: int) -> int:
109+ """Physical card id behind ``local_rank`` (mask entry, npu-smi numbering).
110+ 
111+ Needs two different consumers: ``aclrtMemSetAccess`` takes this id (see the
112+ module docstring), while the allocation APIs take the process-visible index
113+ (``local_device_index``). Also handy for logs / HCCL topology / cross-node
114+ identification. Returns ``local_rank`` unchanged when no mask is set (the
115+ two spaces coincide there).
116+ """
117+ local_rank = int(local_rank)
118+ visible = visible_npu_ids()
119+ if visible is None:
120+ return local_rank
121+ return visible[_require_rank_in_range(local_rank, len(visible))]
@@ -0,0 +1,46 @@
1+{
2+ "schema": 2,
3+ "provider_abi": "expert-pointer-buffer-v11",
4+ "devices": [
5+ "Ascend 950DT",
6+ "Ascend 950PR"
7+ ],
8+ "activation_dtypes": [
9+ "bfloat16"
10+ ],
11+ "weight_dtypes": [
12+ "bfloat16"
13+ ],
14+ "gradient_target_dtypes": [
15+ "float32"
16+ ],
17+ "layout": "LOCAL_EXPERTS_AND_SLOTS",
18+ "ordinary_source_owner_push": true,
19+ "direct_owner_reduce": true,
20+ "explicit_comm_buffers": true,
21+ "completion_model": {
22+ "synchronous": "current_stream",
23+ "asynchronous": "comm_stream_event"
24+ },
25+ "vmm_granularity_query": true,
26+ "router_topk_max": null,
27+ "async": {
28+ "schema": 1,
29+ "completion_modes": [
30+ "collective"
31+ ],
32+ "lane_count": 1,
33+ "strict_zero_copy": true
34+ },
35+ "prefetch_engines": [
36+ "mte",
37+ "urma"
38+ ],
39+ "urma_push": {
40+ "schema": 1,
41+ "pointer_source": true,
42+ "completion_modes": [
43+ "collective"
44+ ]
45+ }
46+}
The file is empty
@@ -0,0 +1,268 @@
1+"""
2+Shared helpers for the MoonEP-Ascend operator benchmarks.
3+ 
4+Mirrors ``MoonEP/benchmarks`` (CUDA) but targets the Ascend port
5+(``npu_patch``): torch_npu devices, HCCL process group, cann-shmem
6+symmetric memory, and the public ``Buffer`` API (``dispatch`` /
7+``prefetch_weight`` / ``combine`` / ``reduce_grad``).
8+ 
9+Kernels are implemented; every flow runs a live Ascend kernel. ``measure_flow``
10+times a Buffer flow with npu events and returns a cross-rank mean latency;
11+``time_kernel`` is the same for a raw ``launch_*`` kernel (no Buffer flow
12+seam). Both return ``{status: "ok", us}``.
13+"""
14+ 
15+import argparse
16+import math
17+import os
18+import sys
19+ 
20+import torch
21+import torch_npu
22+import torch.distributed as dist
23+ 
24+# Make ``npu_patch`` (repo root) and the routing generator (test/) importable
25+# regardless of the cwd torchrun is launched from.
26+_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
27+_TEST = os.path.join(_ROOT, "test_npu")
28+for _p in (_ROOT, _TEST):
29+ if _p not in sys.path:
30+ sys.path.insert(0, _p)
31+ 
32+from generate_topk_routing import generate_topk_routing
33+ 
34+from npu_patch._device import local_device_index
35+ 
36+# Marker the op stubs embed in the NotImplementedError they raise at the seam.
37+KERNEL_NOT_IMPLEMENTED = "kernel not implemented"
38+ 
39+# Production 8-card EP shape (user-specified): S=4096, K=16, E=896, H=7168,
40+# H'=3072 (R=8, B=E//R=112). Default sweeps stay native-identical for direct
41+# comparison with MoonEP; these constants drive the ``--prod`` shortcuts.
42+PROD_S = 4096
43+PROD_K = 16
44+PROD_E = 896
45+PROD_H = 7168
46+PROD_HP = 3072
47+PROD_B = 112
48+ 
49+ 
50+def setup():
51+ """torchrun-style distributed init over HCCL (Ascend)."""
52+ local_rank = int(os.environ.get("LOCAL_RANK", 0))
53+ device = local_device_index(local_rank)
54+ torch.npu.set_device(device)
55+ dist.init_process_group(
56+ backend="hccl", device_id=torch.device(f"npu:{device}")
57+ )
58+ group = dist.group.WORLD
59+ dist.barrier(group=group)
60+ rank = dist.get_rank()
61+ world_size = dist.get_world_size()
62+ return rank, world_size, local_rank
63+ 
64+ 
65+def fmt4(x: float) -> str:
66+ """Format float to exactly 4 significant digits (reference ``fmt4``)."""
67+ if x != x: # NaN (stub flows)
68+ return " n/a"
69+ if x == 0:
70+ return "0.000"
71+ d = math.floor(math.log10(abs(x))) + 1 # digits before the decimal point
72+ return f"{x:.{max(0, 4 - d)}f}"
73+ 
74+ 
75+def time_kernel(fn, group, rank, *, warmup: int = 5, iters: int = 20,
76+ agg: str = "mean", cudagraph: bool = True):
77+ """Time a raw kernel launch (no Buffer-flow seam). Return ``{status, us}``.
78+ 
79+ ``warmup`` + ``iters`` launches timed with npu events on the current stream;
80+ cross-rank ``agg`` = ``mean`` (all ranks equal work) or ``max`` (worst rank,
81+ for rank-initiated prefetch / grad-reduce).
82+ 
83+ ``cudagraph=True`` (default) captures ``iters`` launches into a
84+ ``torch.npu.CUDAGraph`` and times the replay, removing per-launch host
85+ overhead (mirrors ``MoonEP/benchmarks/bench_comm.py::time_gpu_op``). If the
86+ flow is not capturable (e.g. a host-side cross-rank sync inside), it falls
87+ back to the eager loop with a rank-0 note.
88+ """
89+ for _ in range(warmup):
90+ fn()
91+ torch.npu.synchronize()
92+ dist.barrier(group=group)
93+ 
94+ start = torch.npu.Event(enable_timing=True)
95+ end = torch.npu.Event(enable_timing=True)
96+ 
97+ captured = False
98+ if cudagraph and hasattr(torch.npu, 'CUDAGraph') and hasattr(torch.npu, 'graph'):
99+ try:
100+ g = torch.npu.CUDAGraph()
101+ with torch.npu.graph(g):
102+ for _ in range(iters):
103+ fn()
104+ torch.npu.synchronize()
105+ dist.barrier(group=group)
106+ start.record()
107+ g.replay()
108+ end.record()
109+ captured = True
110+ except Exception:
111+ if rank == 0:
112+ print(' (note: flow not CUDA-graph capturable; eager timing)',
113+ flush=True)
114+ torch.npu.synchronize()
115+ dist.barrier(group=group)
116+ if not captured:
117+ start.record()
118+ for _ in range(iters):
119+ fn()
120+ end.record()
121+ end.synchronize()
122+ local_us = start.elapsed_time(end) / iters * 1e3 # ms -> us
123+ 
124+ dev = torch.device(f"npu:{torch.npu.current_device()}")
125+ ws = dist.get_world_size(group=group)
126+ t = torch.tensor([local_us], dtype=torch.float64, device=dev)
127+ outs = [torch.empty(1, dtype=torch.float64, device=dev) for _ in range(ws)]
128+ dist.all_gather(outs, t, group=group)
129+ cat = torch.cat(outs)
130+ us = cat.max().item() if agg == "max" else cat.mean().item()
131+ dist.barrier(group=group)
132+ return {"status": "ok", "us": us}
133+ 
134+ 
135+def measure_flow(
136+ label: str,
137+ expected_op: str,
138+ fn,
139+ group,
140+ rank: int,
141+ *,
142+ allow_stub: bool = True,
143+ warmup: int = 5,
144+ iters: int = 20,
145+ agg: str = "mean",
146+ cudagraph: bool = True,
147+):
148+ """Run a Buffer flow; return ``{status, op, us}``.
149+ 
150+ One probe call classifies the flow (kept stub-aware for safety):
151+ - ``NotImplementedError`` naming ``expected_op.compute`` and carrying the
152+ stub marker -> pre-launch plumbing reached the op seam. With
153+ ``allow_stub`` the flow is reported ``stub`` (``us`` = NaN); without it
154+ the exception propagates (fail).
155+ - any other error is a plumbing failure -> AssertionError (fail).
156+ - the flow completes (live kernel) -> ``time_kernel`` cross-rank
157+ ``agg`` = ``mean`` (all ranks equal work) or ``max``.
158+ """
159+ try:
160+ fn()
161+ except NotImplementedError as exc:
162+ msg = str(exc)
163+ assert f"{expected_op}.compute:" in msg, (
164+ f"rank {rank}: {label} reached a DIFFERENT op than {expected_op}:\n{msg}"
165+ )
166+ assert KERNEL_NOT_IMPLEMENTED in msg, (
167+ f"rank {rank}: {label} NotImplementedError outside the op seam:\n{msg}"
168+ )
169+ torch.npu.synchronize()
170+ dist.barrier(group=group)
171+ if not allow_stub:
172+ raise
173+ return {"status": "stub", "op": expected_op, "us": float("nan")}
174+ except Exception as exc: # surface any plumbing failure
175+ raise AssertionError(
176+ f"rank {rank}: {label} errored before/outside the op seam: {exc!r}"
177+ ) from exc
178+ 
179+ us = time_kernel(fn, group, rank, warmup=warmup, iters=iters, agg=agg,
180+ cudagraph=cudagraph)["us"]
181+ return {"status": "ok", "op": expected_op, "us": us}
182+ 
183+ 
184+def time_text(res: dict) -> str:
185+ """Render one flow result: ``<us>`` or ``stub``."""
186+ if res["status"] == "stub":
187+ return " stub"
188+ return fmt4(res["us"])
189+ 
190+ 
191+# ---------------------------------------------------------------------------
192+# Transport engine: ubmem (native MTE/UB path) vs urma (UDMA/URMA path)
193+# ---------------------------------------------------------------------------
194+# Every benchmark can target either transport of the same operator set:
195+# ubmem (default) - native MTE/UB path, available on every SoC.
196+# urma - UDMA/URMA path, A5 (Ascend950/SIMT) only.
197+# Buffer-backed benches pass ``use_udma=`` to ``Buffer``; benches driving the
198+# raw ``launch_*`` entry points (no Buffer; launchers read the engine from the
199+# environment) call ``apply_engine``, which publishes the
200+# ``ASCEND_MOONEP_*_USE_UDMA`` policy **through the library's own capability
201+# gate** (``npu_patch.api._is_ascend950``) - requesting urma on A2/A3 degrades
202+# to ubmem with a note instead of bypassing ``udma_supported``. run_test.sh
203+# enforces the same rule (``--use_urma`` rejected on non-A5).
204+ENGINES = ("ubmem", "urma")
205+_UDMA_OPS = ("planning", "dispatch", "combine", "prefetch", "grad_reduce")
206+ 
207+ 
208+def add_engine_args(parser: argparse.ArgumentParser) -> None:
209+ """Add the ``--engine`` switch shared by every benchmark."""
210+ parser.add_argument(
211+ "--engine", choices=ENGINES, default="ubmem",
212+ help="Transport engine: ubmem = MTE/UB native path (default), "
213+ "urma = UDMA/URMA path (A5/Ascend950 only).")
214+ 
215+ 
216+def _urma_supported() -> bool:
217+ """UDMA capability probe reusing the library's own check (api._is_ascend950)."""
218+ from npu_patch.api import _is_ascend950
219+ 
220+ device = int(torch.npu.current_device())
221+ return bool(_is_ascend950(device, torch.npu.get_device_properties(device)))
222+ 
223+ 
224+def apply_engine(engine: str) -> bool:
225+ """Publish the engine choice as the ``ASCEND_MOONEP_*_USE_UDMA`` policy.
226+ 
227+ Call it after ``setup()``: the udma probe reads the current device. Returns
228+ the **effective** flag (True = urma), which the callers thread into
229+ ``Buffer`` / ``ShmemRuntime.init_*`` so the operator choice and the symmetric
230+ heap agree.
231+ """
232+ want = engine == "urma"
233+ if want:
234+ try:
235+ supported = _urma_supported()
236+ except Exception as exc: # probe failure must not pick urma
237+ supported = False
238+ print(f"[bench] udma capability probe failed ({exc}).", flush=True)
239+ if not supported:
240+ print("[bench] --engine urma requested, but this device is not "
241+ "Ascend950 (no SIMT/UDMA): falling back to ubmem.", flush=True)
242+ want = False
243+ value = "1" if want else "0"
244+ os.environ["ASCEND_MOONEP_USE_UDMA"] = value
245+ for name in _UDMA_OPS:
246+ os.environ[f"ASCEND_MOONEP_{name.upper()}_USE_UDMA"] = value
247+ return want
248+ 
249+ 
250+def add_common_args(parser: argparse.ArgumentParser) -> None:
251+ """Arguments shared by all benchmarks."""
252+ add_engine_args(parser)
253+ parser.add_argument("--warmup", type=int, default=5, help="Warmup iterations per flow.")
254+ parser.add_argument("--iters", type=int, default=20, help="Timed iterations per flow.")
255+ parser.add_argument("--num-sms", type=int, default=None,
256+ help="SM count for the op launches (default: device max).")
257+ parser.add_argument("--ep-size", type=int, default=None,
258+ help="EP group size (default: world size = launched ranks). "
259+ "Must be <= world size; only ranks [0, ep) run the bench.")
260+ parser.add_argument("--no-allow-stub", dest="allow_stub", action="store_false",
261+ help="Treat op-seam NotImplementedError as a failure instead "
262+ "of reporting the flow as stub (use once kernels land).")
263+ parser.set_defaults(allow_stub=True)
264+ parser.add_argument("--no-cudagraph", dest="cudagraph", action="store_false",
265+ help="Use the eager timing loop instead of CUDA-graph capture "
266+ "(CUDA-graph removes per-launch host overhead).")
267+ parser.set_defaults(cudagraph=True)
268+ parser.add_argument("--out", default=None, help="Output CSV path (rank 0 only).")
@@ -0,0 +1,348 @@
1+"""Prepared L+B benchmarks; imports Ascend dependencies only for a live run."""
2+import argparse
3+from datetime import timedelta
4+import hashlib
5+import json
6+import math
7+import os
8+import socket
9+from pathlib import Path
10+import statistics
11+import subprocess
12+import sys
13+import time
14+ 
15+ 
16+# Keep native resources alive on failure; successful runs explicitly drain/free.
17+_ACTIVE_RESOURCES = []
18+ 
19+ 
20+def parse_args(operation, argv=None):
21+ parser = argparse.ArgumentParser(description=(
22+ "Time Buffer.prefetch_weight_from_ptrs pointer PUSH" if operation == "prefetch" else
23+ "Time Buffer.reduce_grad_to_ptrs(...) / GradReduceTargets"))
24+ parser.add_argument("--engine", choices=("ubmem", "urma"), default="urma")
25+ parser.add_argument("--mode", choices=("sync", "async"), default="async")
26+ parser.add_argument("--shmem-udma", choices=("on", "off"), default="on",
27+ help="keep SHMEM initialization identical across MTE/URMA arms (A5)")
28+ parser.add_argument("--barrier-mode", choices=("mixed", "aiv") if operation == "prefetch" else ("aiv",),
29+ help="Prefetch barrier selection; GradReduce is fixed to fused AIV")
30+ parser.add_argument("--epn", type=int, default=2, help="ordinary home tensors per rank")
31+ parser.add_argument("--B", type=int, help="symmetric slots; default: epn; targets requires B=epn")
32+ parser.add_argument("--H", type=int, default=128)
33+ parser.add_argument("--Hp", type=int, default=128)
34+ parser.add_argument("--pattern", choices=("balanced", "fan-in", "mixed", "local", "empty"),
35+ default="balanced")
36+ parser.add_argument("--active-slots", type=int, help="valid slots per rank; default: B")
37+ parser.add_argument("--remote-peers", type=int, help="balanced/mixed peer span; default: world-1")
38+ if operation == "grad_reduce":
39+ parser.add_argument("--num-sms", type=int, default=8, help="Buffer num_sms shared by Planning and GradReduce, 8..56")
40+ parser.add_argument("--warmup", type=int, default=10)
41+ parser.add_argument("--iters", type=int, default=50)
42+ parser.add_argument("--vmm-page-size", choices=("default", "2m"), default="2m",
43+ help="dev_npu uses the native 2 MiB VMM policy")
44+ parser.add_argument("--ip-port", help="SHMEM bootstrap URL for multi-node runs")
45+ parser.add_argument("--timeout", type=int, default=180, help="process-group timeout in seconds")
46+ parser.add_argument("--out", type=Path, help="new result directory, files must not already exist")
47+ parser.add_argument("--dry-run", action="store_true", help="print plan/buffer estimates without torch/NPU")
48+ parser.add_argument("--world-size", type=int, help="dry-run world size; live must match torchrun")
49+ args = parser.parse_args(argv)
50+ args.operation = operation
51+ args.B = args.epn if args.B is None else args.B
52+ args.active_slots = args.B if args.active_slots is None else args.active_slots
53+ args.barrier_mode = args.barrier_mode or ("aiv" if operation == "grad_reduce" or args.engine == "urma" else "mixed")
54+ args.num_sms = getattr(args, "num_sms", 1)
55+ for key in ("epn", "B", "H", "Hp", "iters", "timeout"):
56+ if getattr(args, key) <= 0:
57+ parser.error(key + " must be positive")
58+ if args.warmup < 0 or not 0 <= args.active_slots <= args.B:
59+ parser.error("warmup must be nonnegative and active-slots must be in 0..B")
60+ if operation == "grad_reduce" and not 8 <= args.num_sms <= 56:
61+ parser.error("num-sms must be in 8..56")
62+ if args.engine == "urma" and args.shmem_udma != "on":
63+ parser.error("URMA payload requires --shmem-udma on")
64+ if operation == "grad_reduce" and args.B != args.epn:
65+ parser.error("prepared GradReduceTargets currently requires B=epn")
66+ world = int(os.environ.get("WORLD_SIZE", args.world_size or 8))
67+ if args.world_size is not None and args.world_size != world:
68+ parser.error("world-size differs from torchrun WORLD_SIZE")
69+ if world < 2:
70+ parser.error("requires at least two ranks")
71+ args.world_size = world
72+ args.remote_peers = world - 1 if args.remote_peers is None else args.remote_peers
73+ if not 1 <= args.remote_peers < world:
74+ parser.error("remote-peers must be in 1..world-1")
75+ return args
76+ 
77+ 
78+def routing_rows(args):
79+ rows = []
80+ for rank in range(args.world_size):
81+ row = []
82+ for slot in range(args.B):
83+ if slot >= args.active_slots or args.pattern == "empty":
84+ row.append(-1)
85+ continue
86+ owner = (rank + 1 + slot % args.remote_peers) % args.world_size
87+ local = slot % args.epn
88+ if args.pattern == "fan-in":
89+ owner, local = 0, slot % args.epn
90+ elif args.pattern == "local" or (args.pattern == "mixed" and slot % 2 == 0):
91+ owner, local = rank, slot % args.epn
92+ row.append(owner * args.epn + local)
93+ rows.append(row)
94+ return rows
95+ 
96+ 
97+def slot_value(rank, slot, slots, iteration):
98+ return 1 + rank * slots + slot + iteration % 7
99+ 
100+ 
101+def grad_reference(rows, rank, epn, slots, iteration):
102+ values = [3 + local for local in range(epn)]
103+ for peer, row in enumerate(rows):
104+ for slot, expert in enumerate(row):
105+ if rank * epn <= expert < (rank + 1) * epn:
106+ values[expert - rank * epn] += slot_value(peer, slot, slots, iteration)
107+ return values
108+ 
109+ 
110+def case_description(args):
111+ rows = routing_rows(args)
112+ itemsize = 2 if args.operation == "prefetch" else 4
113+ matrix_bytes = args.H * args.Hp * itemsize
114+ remote = sum(expert >= 0 and expert // args.epn != rank
115+ for rank, row in enumerate(rows) for expert in row)
116+ valid = sum(expert >= 0 for row in rows for expert in row)
117+ scratch = (512 * 1024 * max(2 * args.num_sms, args.world_size * args.B) * 4
118+ if args.operation == "grad_reduce" and args.engine == "urma" else 0)
119+ return dict(operation=args.operation, engine=args.engine, mode=args.mode,
120+ shmem_udma_enabled=args.shmem_udma == "on", qp_count=2 if args.shmem_udma == "on" else 0,
121+ barrier_mode=args.barrier_mode, world_size=args.world_size,
122+ epn=args.epn, B=args.B, H=args.H, Hp=args.Hp, pattern=args.pattern,
123+ active_slots=args.active_slots, remote_peers=args.remote_peers,
124+ payload_aiv_blocks=(None if args.operation == "prefetch" and args.engine == "ubmem"
125+ else args.num_sms),
126+ payload_block_policy=("native VectorBlocks / ACL_DEV_ATTR_AICORE_CORE_NUM"
127+ if args.operation == "prefetch" and args.engine == "ubmem"
128+ else "fixed URMA PUSH=1" if args.operation == "prefetch"
129+ else "num_sms"),
130+ warmup=args.warmup, iters=args.iters,
131+ vmm_page_size=args.vmm_page_size, routing=rows,
132+ logical_remote_bytes_per_call=remote * matrix_bytes,
133+ logical_valid_bytes_per_call=valid * matrix_bytes,
134+ tensor_bytes_per_rank=(args.epn + args.B) * matrix_bytes,
135+ udma_scratch_bytes_per_rank=scratch,
136+ estimate_excludes="VMM rounding, Buffer control arenas, allocator/runtime overhead")
137+ 
138+ 
139+def refill(args, rows, rank, refs, slot, iteration):
140+ slot.fill_(-17)
141+ if args.operation == "grad_reduce":
142+ for index, ref in enumerate(refs):
143+ ref.fill_(3 + index)
144+ for index, expert in enumerate(rows[rank]):
145+ if expert >= 0:
146+ slot[index].fill_(slot_value(rank, index, args.B, iteration))
147+ 
148+ 
149+def measure_sample(torch, dist, prepare, submit, iteration):
150+ # Refill and producer completion are outside the timed interval.
151+ prepare(iteration)
152+ torch.npu.synchronize()
153+ dist.barrier()
154+ stream = torch.npu.current_stream()
155+ begin = torch.npu.Event(enable_timing=True)
156+ end = torch.npu.Event(enable_timing=True)
157+ begin.record(stream)
158+ host_begin = time.perf_counter_ns()
159+ done = submit()
160+ host_us = (time.perf_counter_ns() - host_begin) / 1000
161+ if done is not None:
162+ stream.wait_event(done)
163+ end.record(stream)
164+ end.synchronize()
165+ return dict(device_us=float(begin.elapsed_time(end)) * 1000, submit_us=host_us)
166+ 
167+ 
168+def summarize(per_rank, logical_remote_bytes):
169+ count = len(per_rank[0]["samples"])
170+ worst = [max(rank["samples"][i]["device_us"] for rank in per_rank) for i in range(count)]
171+ ordered = sorted(worst)
172+ median = statistics.median(worst)
173+ return dict(rank_count=len(per_rank), sample_count=count,
174+ worst_rank_samples_us=worst, median_us=median,
175+ p95_us=ordered[max(0, math.ceil(.95 * count) - 1)],
176+ min_us=min(worst), max_us=max(worst),
177+ submit_median_us_per_rank=[statistics.median(s["submit_us"] for s in rank["samples"])
178+ for rank in per_rank],
179+ aggregate_logical_remote_GiB_s=(logical_remote_bytes / (median * 1e-6) / 2**30
180+ if median > 0 else 0.0),
181+ timing="public Buffer submit through consumer event join; native barriers included",
182+ excludes="setup, refill, producer synchronize, external HCCL barrier, checks, teardown",
183+ graph_capture=False)
184+ 
185+ 
186+def source_identity(repo):
187+ def git(*args):
188+ result = subprocess.run(["git", *args], cwd=repo, capture_output=True, text=True)
189+ return result.stdout.strip() if result.returncode == 0 else None
190+ return dict(commit=git("rev-parse", "HEAD"),
191+ tracked_changes=git("diff", "HEAD", "--name-only"),
192+ benchmark_sha256={name: hashlib.sha256((Path(__file__).parent / name).read_bytes()).hexdigest()
193+ for name in ("_expert_pointer_bench.py", "bench_prefetch_push.py",
194+ "bench_grad_reduce_targets.py")})
195+ 
196+ 
197+def loaded_libraries(native):
198+ paths = {Path(native.__file__).resolve()}
199+ maps = Path("/proc/self/maps")
200+ if maps.exists():
201+ for line in maps.read_text().splitlines():
202+ name = line.split()[-1]
203+ if name.startswith("/") and any(s in name for s in ("libascend_moonep", "libshmem")):
204+ paths.add(Path(name).resolve())
205+ return [dict(path=str(p), sha256=hashlib.sha256(p.read_bytes()).hexdigest())
206+ for p in sorted(paths) if p.is_file()]
207+ 
208+ 
209+def _check(torch, dist, args, rows, rank, refs, slot, iteration):
210+ checks = []
211+ if args.operation == "prefetch":
212+ for index, expert in enumerate(rows[rank]):
213+ flat = slot[index].view(-1)
214+ value = -17 if expert < 0 else 1 + expert % 127
215+ marker = -17 if expert < 0 else -(1 + expert // 127)
216+ checks.extend((torch.all(flat[1:] == value), flat[0] == marker))
217+ else:
218+ for target, value in zip(refs, grad_reference(rows, rank, args.epn, args.B, iteration)):
219+ checks.append(torch.all(target == value))
220+ for index, expert in enumerate(rows[rank]):
221+ checks.append(torch.all(slot[index] == (0 if expert >= 0 else -17)))
222+ passed = torch.stack(checks).all().to(torch.int32)
223+ dist.all_reduce(passed, op=dist.ReduceOp.MIN)
224+ if not bool(passed.item()):
225+ raise RuntimeError("collective payload/reference or valid-slot clear check failed")
226+ 
227+ 
228+def run(args):
229+ if args.out:
230+ rank_file = args.out / ("rank_" + os.environ.get("RANK", "0") + ".json")
231+ if rank_file.exists() or (args.out / "summary.json").exists():
232+ raise FileExistsError("use a fresh --out directory for each independent run")
233+ repo = Path(__file__).resolve().parents[2]
234+ sys.path.insert(0, str(repo))
235+ import torch
236+ import torch_npu # noqa: F401 -- registers torch.npu
237+ import torch.distributed as dist
238+ from npu_patch import Buffer, ShmemRuntime, _C
239+ from npu_patch._device import local_device_index
240+ from npu_patch.buffer_c import create_vmm_physical, reset_symmetric_descriptors
241+ from npu_patch.planning import allocate_planning_outputs
242+ 
243+ if "WORLD_SIZE" not in os.environ:
244+ raise RuntimeError("launch a live run with torchrun or run_bench.sh")
245+ local = local_device_index(int(os.environ.get("LOCAL_RANK", 0)))
246+ torch.npu.set_device(local)
247+ device = torch.device("npu", local)
248+ dist.init_process_group("hccl", device_id=device, timeout=timedelta(seconds=args.timeout))
249+ rank = dist.get_rank()
250+ udma = args.engine == "urma"
251+ # Override inherited transport policy so the label cannot silently change.
252+ for name in ("PLANNING", "DISPATCH", "COMBINE", "PREFETCH", "GRAD_REDUCE"):
253+ os.environ["ASCEND_MOONEP_" + name + "_USE_UDMA"] = "0"
254+ os.environ["ASCEND_MOONEP_USE_UDMA"] = "0"
255+ flags = {"prefetch_use_udma": udma if args.operation == "prefetch" else False,
256+ "grad_reduce_use_udma": udma if args.operation == "grad_reduce" else False}
257+ buffer = Buffer(S=1, H=128, K=1, E=args.world_size * args.epn, B=args.B,
258+ num_ep_ranks=args.world_size, group=dist.group.WORLD,
259+ use_udma=False, num_sms=args.num_sms if args.operation == "grad_reduce" else 8,
260+ barrier_mode=args.barrier_mode,
261+ explicitly_destroy=True, **flags)
262+ _ACTIVE_RESOURCES.append(buffer)
263+ ctx = buffer._ctx
264+ key = "_prefetch_use_udma" if args.operation == "prefetch" else "_grad_reduce_use_udma"
265+ if bool(ctx[key]) != udma:
266+ raise RuntimeError("requested engine unavailable; refusing a mislabeled benchmark")
267+ dtype = torch.bfloat16 if args.operation == "prefetch" else torch.float32
268+ source, _, _ = create_vmm_physical((args.B, args.H, args.Hp), dtype, local)
269+ _ACTIVE_RESOURCES.append(source)
270+ refs = tuple(torch.empty((args.H, args.Hp), dtype=dtype, device=device)
271+ for _ in range(args.epn))
272+ if args.operation == "prefetch":
273+ refs = tuple(torch.nn.Parameter(ref, requires_grad=False) for ref in refs)
274+ _ACTIVE_RESOURCES.append(refs)
275+ rows = routing_rows(args)
276+ plan, _ = allocate_planning_outputs(ctx)
277+ plan.experts_to_copy.copy_(torch.tensor(rows, dtype=torch.int32, device=device))
278+ _ACTIVE_RESOURCES.append(plan)
279+ ShmemRuntime.init_with_buffer(group=dist.group.WORLD,
280+ enable_udma=args.shmem_udma == "on",
281+ qp_count=2 if args.shmem_udma == "on" else 0,
282+ ip_port=args.ip_port)
283+ buffer._ensure_shmem_views()
284+ binding = buffer.prepare_expert_binding(refs, source)
285+ _ACTIVE_RESOURCES.append(binding)
286+ slot = binding.comm_buffer
287+ if args.operation == "prefetch":
288+ for index, ref in enumerate(refs):
289+ expert = rank * args.epn + index
290+ ref.fill_(1 + expert % 127)
291+ ref.view(-1)[0] = -(1 + expert // 127)
292+ 
293+ def prepare(iteration):
294+ refill(args, rows, rank, refs, slot, iteration)
295+ 
296+ def submit():
297+ if args.operation == "prefetch":
298+ return buffer.prefetch_weight_from_ptrs(plan, binding, async_finish=args.mode == "async")
299+ return buffer.reduce_grad_to_ptrs(plan, binding, async_finish=args.mode == "async")
300+ 
301+ # Preflight twice with different GR payloads, then check the final timed call.
302+ for iteration in range(2):
303+ measure_sample(torch, dist, prepare, submit, iteration)
304+ _check(torch, dist, args, rows, rank, refs, slot, iteration)
305+ identity = source_identity(repo)
306+ identity["loaded_libraries"] = loaded_libraries(_C)
307+ identity["runtime"] = dict(hostname=socket.gethostname(), python=sys.version.split()[0],
308+ torch=str(torch.__version__),
309+ torch_npu=getattr(torch_npu, "__version__", None),
310+ ascend_home=os.environ.get("ASCEND_HOME_PATH"), argv=sys.argv)
311+ for iteration in range(args.warmup):
312+ measure_sample(torch, dist, prepare, submit, iteration)
313+ samples = [measure_sample(torch, dist, prepare, submit, iteration)
314+ for iteration in range(args.iters)]
315+ _check(torch, dist, args, rows, rank, refs, slot, args.iters - 1)
316+ result = dict(rank=rank, local_device=local, samples=samples, identity=identity,
317+ payload_checked=True, slot_refill_each_iteration=True)
318+ per_rank = [None] * args.world_size
319+ dist.all_gather_object(per_rank, result)
320+ torch.npu.synchronize()
321+ dist.barrier()
322+ ShmemRuntime.finalize()
323+ buffer.destroy()
324+ source._vmm_allocation.destroy()
325+ reset_symmetric_descriptors()
326+ dist.destroy_process_group()
327+ _ACTIVE_RESOURCES.clear()
328+ case = case_description(args)
329+ if args.out:
330+ args.out.mkdir(parents=True, exist_ok=True)
331+ with (args.out / ("rank_" + str(rank) + ".json")).open("x", encoding="utf-8") as file:
332+ json.dump(dict(schema=1, case=case, **result), file, indent=2)
333+ if rank == 0:
334+ report = dict(schema=1, case=case,
335+ summary=summarize(per_rank, case["logical_remote_bytes_per_call"]),
336+ ranks=per_rank)
337+ if args.out:
338+ with (args.out / "summary.json").open("x", encoding="utf-8") as file:
339+ json.dump(report, file, indent=2)
340+ print(json.dumps(report, indent=2), flush=True)
341+ 
342+ 
343+def main(operation, argv=None):
344+ args = parse_args(operation, argv)
345+ if args.dry_run:
346+ print(json.dumps(case_description(args), indent=2))
347+ return
348+ run(args)