Draft
[WIP]优化 Ascend950 URMA rank 去重在高 MaxVio 下的延时 #1
szm_thomasAdd on 5 days ago
[WIP]优化 Ascend950 URMA rank 去重在高 MaxVio 下的延时 #1
Draft
szm_thomasAdd on 5 days ago
Total: 48 files changed+16391-591
@@ -1,7 +1,7 @@
1[submodule "npu_patch/3rdparty/shmem"]1[submodule "npu_patch/3rdparty/shmem"]
2 path = npu_patch/3rdparty/shmem2 path = npu_patch/3rdparty/shmem
3- url = https://gitcode.com/cann/shmem.git3+ url = https://gitcode.com/vallenChen/shmem.git
4- branch = master4+ branch = fix_mult_sync_error
5[submodule "npu_patch/3rdparty/catlass"]5[submodule "npu_patch/3rdparty/catlass"]
6 path = npu_patch/3rdparty/catlass6 path = npu_patch/3rdparty/catlass
7 url = https://gitcode.com/cann/catlass.git7 url = https://gitcode.com/cann/catlass.git
Mnpu_patch/3rdparty/shmem+1-1File content is under review, please try again later
@@ -275,6 +275,19 @@ ShmemRuntime.init_with_buffer(group=dist.group.WORLD, enable_udma=False, qp_coun
275`buffer.reduce_grad(...)`。端到端参考:`test_npu/mte/test_e2e.py`(ubmem)与275`buffer.reduce_grad(...)`。端到端参考:`test_npu/mte/test_e2e.py`(ubmem)与
276`test_npu/urma/test_e2e_urma.py`(urma)。276`test_npu/urma/test_e2e_urma.py`(urma)。
277 277 
278+### URMA server dedup
279+ 
280+Pass `dedup_mode="server"` together with `use_udma=True` when constructing
281+a Buffer on Ascend950. Server dedup groups eight consecutive ranks and
282+uses two UDMA QPs per peer. Planning builds the server Combine execution plan
283+alongside routing. Call `Buffer.prepare_combine_plan(plan)` collectively before
284+using a manually constructed server plan for Combine.
285+ 
286+```bash
287+bash npu_patch/scripts/run_test.sh --use_urma --dedup-mode server
288+bash npu_patch/benchmarks/run_bench.sh bench_comm.py "--engine urma --dedup-mode server --prod"
289+```
290+ 
278### 框架层要创建的对象:Full Weight / Full Grad / Reduce Buffer291### 框架层要创建的对象:Full Weight / Full Grad / Reduce Buffer
279 292 
280调度侧(dispatch/combine)的通信 chunk 与 plan 由 `Buffer` 内部管理;框架层293调度侧(dispatch/combine)的通信 chunk 与 plan 由 `Buffer` 内部管理;框架层
@@ -416,6 +429,28 @@ ShmemRuntime.init_with_ip_port(
416prefetch”实现放在同一组 routing/计时下对比(`--libs moonep all2all`,也可429prefetch”实现放在同一组 routing/计时下对比(`--libs moonep all2all`,也可
417`--libs all2all` 单独验证该集合通信,此时不加载 Buffer / shmem 堆)。430`--libs all2all` 单独验证该集合通信,此时不加载 Buffer / shmem 堆)。
418 431 
432+`bench_rank_maxvio.py` 使用固定 Hy4-flash shape(BF16、H=Hp=1536、K=16、
433+E=512、S=8192 tokens/rank),测量 Ascend950 rank 去重在 MaxVio 1/30 下的通信
434+往返延时。Dispatch 和 Combine 使用 URMA 与双 QP,Prefetch 使用 UBMem。
435+每组 NPU Event 样本先取最慢 rank,再计算 P50/P95。往返包括 Planning、
436+前反向 Dispatch、两次 Combine 和两轮 Prefetch,省略 expert GEMM。
437+ 
438+以下命令在每台机器各执行一次,`NODE_RANK` 从 0 连续编号,
439+`MASTER_ADDR` 指向第 0 台。8P、16P、32P、64P 分别设置 `NODES=1`、`2`、`4`、`8`。
440+`--verify` 先校验 Planning、前反向 Dispatch、Combine hidden/weights 和
441+不同 BF16 路由值的逐元素求和。只校验精度时传 `--verify-only`。
442+ 
443+```bash
444+torchrun --nnodes="$NODES" --nproc-per-node=8 --node-rank="$NODE_RANK" \
445+ --master-addr="$MASTER_ADDR" --master-port="$MASTER_PORT" \
446+ npu_patch/benchmarks/bench_rank_maxvio.py --verify --out bench_rank_maxvio.json
447+```
448+ 
449+对比基线时,从 PR checkout 启动同一份 benchmark,把基线构建路径放在
450+`PYTHONPATH` 首位,再追加 PR checkout 的绝对路径,并传 `--legacy-placement`
451+使用原规划参考。用 JSON 中的 `routing_sha256` 核对
452+每档输入路由。加 `--maxvios 30,1` 可倒序复测。
453+ 
419先构建,再运行:454先构建,再运行:
420 455 
421```bash456```bash
@@ -24,6 +24,8 @@ import os
24 24 
25import torch25import torch
26 26 
27+from .planning import RANKS_PER_SERVER
28+ 
27from ._C import (29from ._C import (
28 acl_shmem_putmem,30 acl_shmem_putmem,
29 acl_shmem_getmem,31 acl_shmem_getmem,
@@ -83,7 +85,9 @@ BARRIER_SLOTS = 3
83OP_WS_BYTES_DEFAULT = 16 * 1024 * 102485OP_WS_BYTES_DEFAULT = 16 * 1024 * 1024
84 86 
85 87 
86-def planning_symmetric_workspace_nbytes(E: int, NvS: int, R: int) -> int:88+def planning_symmetric_workspace_nbytes(
89+ E: int, NvS: int, R: int, *, server_dedup: bool = False,
90+) -> int:
87 """Bytes of Planning's per-rank symmetric communication workspace.91 """Bytes of Planning's per-rank symmetric communication workspace.
88 92 
89 The regions hold local TPE, source-side duplicate payload metadata and the93 The regions hold local TPE, source-side duplicate payload metadata and the
@@ -101,7 +105,31 @@ def planning_symmetric_workspace_nbytes(E: int, NvS: int, R: int) -> int:
101 dup_payload_done_off = dup_rank_counts_off + 2 * R * align_elems105 dup_payload_done_off = dup_rank_counts_off + 2 * R * align_elems
102 dup_groups_off = dup_payload_done_off + align_up(R)106 dup_groups_off = dup_payload_done_off + align_up(R)
103 dup_loffs_off = dup_groups_off + align_up(NvS * 3)107 dup_loffs_off = dup_groups_off + align_up(NvS * 3)
104- return (dup_loffs_off + align_up(NvS)) * 4108+ dup_capacity = RANKS_PER_SERVER * NvS if server_dedup else NvS
109+ required_ints = dup_loffs_off + align_up(dup_capacity)
110+ assert required_ints <= 2**31 - 1, "planning symmetric workspace exceeds int32 device offsets"
111+ return required_ints * 4
112+ 
113+ 
114+# Weight aggregation gives each source an exclusive inbox and each worker AIV an exclusive local staging.
115+WEIGHT_AGG_REGION_BYTES = 256 * 1024
116+WEIGHT_AGG_STAGING_AIVS = 16
117+WEIGHT_AGG_STAGING_BYTES = 256 * 1024
118+WEIGHT_AGG_DEBUG_BYTES = 1024
119+ 
120+ 
121+def weight_agg_capacity_entries() -> int:
122+ # Keep in sync with the kernel region header, segment header, and per-record byte size.
123+ return (WEIGHT_AGG_REGION_BYTES - 64) // 8
124+ 
125+ 
126+def dispatch_sync_buffer_nbytes(R: int, *, server_dedup: bool = False) -> int:
127+ # Region order matches the address computation in the Dispatch UDMA kernel.
128+ token_control = R * 16 * 6 * 512 + 16 * 4 * 512
129+ if not server_dedup:
130+ return token_control
131+ return (token_control + R * WEIGHT_AGG_REGION_BYTES
132+ + WEIGHT_AGG_STAGING_AIVS * WEIGHT_AGG_STAGING_BYTES + WEIGHT_AGG_DEBUG_BYTES)
105 133 
106 134 
107def compute_shmem_mem_size(135def compute_shmem_mem_size(
@@ -25,6 +25,7 @@ from ._common import (
25 BARRIER_SLOTS,25 BARRIER_SLOTS,
26 OP_WS_BYTES_DEFAULT,26 OP_WS_BYTES_DEFAULT,
27 cross_rank_barrier,27 cross_rank_barrier,
28+ dispatch_sync_buffer_nbytes,
28 record_streams,29 record_streams,
29)30)
30from .buffer_c import (31from .buffer_c import (
@@ -35,7 +36,7 @@ from .buffer_c import (
35 create_vmm_physical,36 create_vmm_physical,
36 map_to_sym_ptr,37 map_to_sym_ptr,
37)38)
38-from .planning import MoonEPCommPlan, allocate_planning_outputs39+from .planning import RANKS_PER_SERVER, MoonEPCommPlan, allocate_planning_outputs
39from .ops import (40from .ops import (
40 CombineOp,41 CombineOp,
41 DispatchOp,42 DispatchOp,
@@ -44,7 +45,8 @@ from .ops import (
44 PrefetchOp,45 PrefetchOp,
45)46)
46from .launchers import planning_workspace_sizes47from .launchers import planning_workspace_sizes
47-from .shmem_runtime import ShmemRuntime48+from .combine import combine_put_workspace_bytes
49+from .shmem_runtime import ShmemRuntime, publish_dedup_env
48from .buffer_bindings import (50from .buffer_bindings import (
49 CommBuffers, ExpertPointerBinding, comm_context, overlaps, symmetric_source,51 CommBuffers, ExpertPointerBinding, comm_context, overlaps, symmetric_source,
50 tensor_signature, validate_unchanged,52 tensor_signature, validate_unchanged,
@@ -53,6 +55,8 @@ from .buffer_bindings import (
53logger = logging.getLogger(__name__)55logger = logging.getLogger(__name__)
54 56 
55_COMBINE_SYNC_BYTES_PER_RANK = 16 * 2 * 51257_COMBINE_SYNC_BYTES_PER_RANK = 16 * 2 * 512
58+_SERVER_COMBINE_SYNC_BYTES_PER_RANK = 16 * 6 * 512
59+_SERVER_COMBINE_LOCAL_SYNC_BYTES = 16 * 4 * 512
56 60 
57def _is_ascend950(device: int, props) -> bool:61def _is_ascend950(device: int, props) -> bool:
58 names = [os.environ.get("SOC_VERSION", ""), os.environ.get("ASCEND_SOC_VERSION", ""),62 names = [os.environ.get("SOC_VERSION", ""), os.environ.get("ASCEND_SOC_VERSION", ""),
@@ -102,10 +106,59 @@ def _op_ws_bytes_from_env(default: int = OP_WS_BYTES_DEFAULT) -> int:
102 return int(raw)106 return int(raw)
103 107 
104 108 
109+def _validate_dedup_config(
110+ dedup_mode: str,
111+ ranks_per_server: int,
112+ R: int,
113+ udma_supported: bool,
114+) -> None:
115+ """Validate the Buffer-level dedup domain.
116+ 
117+ The dedup domain is fixed once, at Buffer construction. Rank-level dedup is
118+ the default and reproduces the local code path; server-level dedup groups
119+ ``ranks_per_server`` consecutive ranks (8, the compiled kernel ABI) into one
120+ board. Per-op UDMA requirements are intentionally *not* checked here: a
121+ server plan can be used by Combine-only workloads (``use_udma=False`` with
122+ ``combine_use_udma=True``), and dispatch/combine validate their own engine
123+ at the call site.
124+ """
125+ if dedup_mode not in ("rank", "server"):
126+ raise ValueError(
127+ f"dedup_mode must be 'rank' or 'server', got {dedup_mode!r}")
128+ if isinstance(ranks_per_server, bool) or not isinstance(ranks_per_server, int):
129+ raise TypeError(
130+ "ranks_per_server must be an int, got "
131+ f"{type(ranks_per_server).__name__}")
132+ if ranks_per_server <= 0:
133+ raise ValueError(
134+ f"ranks_per_server must be positive, got {ranks_per_server}")
135+ if dedup_mode != "server":
136+ return
137+ if ranks_per_server != RANKS_PER_SERVER:
138+ raise NotImplementedError(
139+ "server dedup kernels are compiled for "
140+ f"{RANKS_PER_SERVER} ranks/server; got ranks_per_server="
141+ f"{ranks_per_server}. Changing this requires the kernel ABI to "
142+ "carry the server size (tiling), which is out of scope here.")
143+ if R <= 0 or R % ranks_per_server != 0:
144+ raise ValueError(
145+ f"server dedup requires num_ep_ranks divisible by "
146+ f"{ranks_per_server}, got {R}")
147+ if not udma_supported:
148+ raise RuntimeError(
149+ "server dedup requires the UDMA (Ascend 950) backend; this device "
150+ "does not support it")
151+ 
152+ 
105def _validate_plan_layout(ctx: dict, plan: MoonEPCommPlan) -> None:153def _validate_plan_layout(ctx: dict, plan: MoonEPCommPlan) -> None:
106- """Require a saved plan to match the Buffer's fixed token layout."""154+ """Require a saved plan to match the Buffer's layout and dedup domain."""
107 if not isinstance(plan, MoonEPCommPlan):155 if not isinstance(plan, MoonEPCommPlan):
108 raise TypeError("expected a MoonEPCommPlan")156 raise TypeError("expected a MoonEPCommPlan")
157+ dedup_mode = ctx.get('dedup_mode', 'rank')
158+ if plan.dedup_mode != dedup_mode:
159+ raise ValueError(
160+ f"plan uses {plan.dedup_mode} dedup, but this Buffer was "
161+ f"constructed with dedup_mode={dedup_mode!r}")
109 identity = (plan.N, plan.R, plan.E, plan.B, plan.NvS, plan.K)162 identity = (plan.N, plan.R, plan.E, plan.B, plan.NvS, plan.K)
110 expected = tuple(int(ctx[name]) for name in ('N', 'R', 'E', 'B', 'NvS', 'K'))163 expected = tuple(int(ctx[name]) for name in ('N', 'R', 'E', 'B', 'NvS', 'K'))
111 if tuple(int(value) for value in identity) != expected:164 if tuple(int(value) for value in identity) != expected:
@@ -179,6 +232,8 @@ def _create_context(
179 rank: int | None = None,232 rank: int | None = None,
180 use_udma: bool = True,233 use_udma: bool = True,
181 udma_flags: dict | None = None,234 udma_flags: dict | None = None,
235+ dedup_mode: str = "rank",
236+ ranks_per_server: int = RANKS_PER_SERVER,
182) -> dict:237) -> dict:
183 """Pre-allocate all shmem symmetric chunks and local temp buffers.238 """Pre-allocate all shmem symmetric chunks and local temp buffers.
184 239 
@@ -213,6 +268,16 @@ def _create_context(
213 max_sms = getattr(props, "multi_processor_count", 32)268 max_sms = getattr(props, "multi_processor_count", 32)
214 num_sms_dedup = _num_sms_dedup_from_env(max_sms)269 num_sms_dedup = _num_sms_dedup_from_env(max_sms)
215 udma_supported = _is_ascend950(device, props)270 udma_supported = _is_ascend950(device, props)
271+ _validate_dedup_config(dedup_mode, ranks_per_server, R, udma_supported)
272+ server_dedup = dedup_mode == "server"
273+ 
274+ ctx_udma_flags = {'planning': False, 'dispatch': True, 'combine': True,
275+ 'prefetch': True, 'grad_reduce': True}
276+ requested_udma = {name: bool(use_udma) for name in ctx_udma_flags}
277+ if udma_flags:
278+ requested_udma.update({name: bool(value) for name, value in udma_flags.items()})
279+ effective_udma = {name: bool(udma_supported and ctx_udma_flags[name] and requested_udma[name])
280+ for name in ctx_udma_flags}
216 281 
217 epn = E // R282 epn = E // R
218 assert E % R == 0, f"E ({E}) must be divisible by R ({R})"283 assert E % R == 0, f"E ({E}) must be divisible by R ({R})"
@@ -236,7 +301,7 @@ def _create_context(
236 f"S={S}, K={K}, S*K={N}, int32_max={int32_max}"301 f"S={S}, K={K}, S*K={N}, int32_max={int32_max}"
237 )302 )
238 planning_local_elems, planning_symmetric_bytes = planning_workspace_sizes(303 planning_local_elems, planning_symmetric_bytes = planning_workspace_sizes(
239- S, K, E, NvS, R, num_sms304+ S, K, E, NvS, R, num_sms, server_dedup=server_dedup
240 )305 )
241 # ================================================================306 # ================================================================
242 # Allocate communication chunks as CANN VMM physical chunks (collective).307 # Allocate communication chunks as CANN VMM physical chunks (collective).
@@ -261,17 +326,25 @@ def _create_context(
261 # Combine owns a separate grant/done cacheline pool. Keeping this distinct326 # Combine owns a separate grant/done cacheline pool. Keeping this distinct
262 # from dispatch prevents the two protocols from sharing flag generations or327 # from dispatch prevents the two protocols from sharing flag generations or
263 # becoming coupled through their unrelated layouts.328 # becoming coupled through their unrelated layouts.
264- combine_sync_buffer, _, _ = create_vmm_physical(329+ combine_sync_bytes = R * _COMBINE_SYNC_BYTES_PER_RANK
265- [R * _COMBINE_SYNC_BYTES_PER_RANK], torch.uint8, device)330+ if server_dedup:
331+ combine_sync_bytes = R * _SERVER_COMBINE_SYNC_BYTES_PER_RANK + _SERVER_COMBINE_LOCAL_SYNC_BYTES
332+ combine_sync_buffer, _, _ = create_vmm_physical([combine_sync_bytes], torch.uint8, device)
266 combine_sync_buffer.zero_()333 combine_sync_buffer.zero_()
267 vmm_chunks['combine_sync_buffer'] = combine_sync_buffer._vmm_allocation334 vmm_chunks['combine_sync_buffer'] = combine_sync_buffer._vmm_allocation
268 335 
269 # Dispatch sync_buffer: Token control region followed by the four-round336 # Dispatch sync_buffer: Token control region followed by the four-round
270 # local sync region for the 16 Token AIVs.337 # local sync region for the 16 Token AIVs.
271 dispatch_sync_buffer, _, _ = create_vmm_physical(338 dispatch_sync_buffer, _, _ = create_vmm_physical(
272- [R * 16 * 6 * 512 + 16 * 4 * 512], torch.uint8, device)339+ [dispatch_sync_buffer_nbytes(R, server_dedup=server_dedup)], torch.uint8, device)
273 dispatch_sync_buffer.zero_()340 dispatch_sync_buffer.zero_()
274 vmm_chunks['dispatch_sync_buffer'] = dispatch_sync_buffer._vmm_allocation341 vmm_chunks['dispatch_sync_buffer'] = dispatch_sync_buffer._vmm_allocation
342+ if server_dedup and effective_udma['combine']:
343+ combine_workspace, _, _ = create_vmm_physical(
344+ [combine_put_workspace_bytes(NvS, H, R, K)], torch.uint8, device)
345+ vmm_chunks['combine_workspace'] = combine_workspace._vmm_allocation
346+ else:
347+ combine_workspace = None
275 # Zero this rank's barrier words (writes through to the VMM source VA).348 # Zero this rank's barrier words (writes through to the VMM source VA).
276 barrier_buf.zero_()349 barrier_buf.zero_()
277 350 
@@ -290,13 +363,6 @@ def _create_context(
290 'prefetch': PrefetchOp(ws_bytes=0, num_sms=num_sms),363 'prefetch': PrefetchOp(ws_bytes=0, num_sms=num_sms),
291 'grad_reduce': GradReduceOp(ws_bytes=0, num_sms=num_sms),364 'grad_reduce': GradReduceOp(ws_bytes=0, num_sms=num_sms),
292 }365 }
293- ctx_udma_flags = {'planning': False, 'dispatch': True, 'combine': True,
294- 'prefetch': True, 'grad_reduce': True}
295- requested_udma = {name: bool(use_udma) for name in ctx_udma_flags}
296- if udma_flags:
297- requested_udma.update({name: bool(value) for name, value in udma_flags.items()})
298- effective_udma = {name: bool(udma_supported and ctx_udma_flags[name] and requested_udma[name])
299- for name in ctx_udma_flags}
300 os.environ['ASCEND_MOONEP_USE_UDMA'] = '1' if any(effective_udma.values()) else '0'366 os.environ['ASCEND_MOONEP_USE_UDMA'] = '1' if any(effective_udma.values()) else '0'
301 for name, enabled in effective_udma.items():367 for name, enabled in effective_udma.items():
302 os.environ[f'ASCEND_MOONEP_{name.upper()}_USE_UDMA'] = '1' if enabled else '0'368 os.environ[f'ASCEND_MOONEP_{name.upper()}_USE_UDMA'] = '1' if enabled else '0'
@@ -310,6 +376,8 @@ def _create_context(
310 'N': N, 'NvS': NvS,376 'N': N, 'NvS': NvS,
311 'num_sms': num_sms,377 'num_sms': num_sms,
312 'num_sms_dedup': num_sms_dedup,378 'num_sms_dedup': num_sms_dedup,
379+ 'dedup_mode': dedup_mode,
380+ 'ranks_per_server': ranks_per_server,
313 'device': device,381 'device': device,
314 '_udma_supported': udma_supported,382 '_udma_supported': udma_supported,
315 '_udma_ctx_flags': ctx_udma_flags,383 '_udma_ctx_flags': ctx_udma_flags,
@@ -325,6 +393,7 @@ def _create_context(
325 'weights_buf': weights_buf,393 'weights_buf': weights_buf,
326 'barrier_buf': barrier_buf,394 'barrier_buf': barrier_buf,
327 'combine_sync_buffer': combine_sync_buffer,395 'combine_sync_buffer': combine_sync_buffer,
396+ 'combine_workspace': combine_workspace,
328 'dispatch_sync_buffer': dispatch_sync_buffer,397 'dispatch_sync_buffer': dispatch_sync_buffer,
329 'shmem_chunks': [398 'shmem_chunks': [
330 hidden_buf,399 hidden_buf,
@@ -332,7 +401,7 @@ def _create_context(
332 barrier_buf,401 barrier_buf,
333 combine_sync_buffer,402 combine_sync_buffer,
334 dispatch_sync_buffer,403 dispatch_sync_buffer,
335- ],404+ ] + ([combine_workspace] if combine_workspace is not None else []),
336 # CANN VMM allocations (source_va + mem_handle + shareable_va):405 # CANN VMM allocations (source_va + mem_handle + shareable_va):
337 # collected by the framework for buffer-backed shmem init406 # collected by the framework for buffer-backed shmem init
338 # (ShmemRuntime.init_with_buffer); Buffer.destroy reverses the VMM ops.407 # (ShmemRuntime.init_with_buffer); Buffer.destroy reverses the VMM ops.
@@ -364,6 +433,7 @@ def _create_context(
364 ),433 ),
365 }434 }
366 _log_context_buffer_size(ctx)435 _log_context_buffer_size(ctx)
436+ publish_dedup_env(dedup_mode)
367 return ctx437 return ctx
368 438 
369 439 
@@ -425,6 +495,9 @@ class Buffer:
425 enable_pdl: bool = True,495 enable_pdl: bool = True,
426 explicitly_destroy: bool = False,496 explicitly_destroy: bool = False,
427 rank: int | None = None,497 rank: int | None = None,
498+ *,
499+ dedup_mode: str = "rank",
500+ ranks_per_server: int = RANKS_PER_SERVER,
428 **kwargs,501 **kwargs,
429 ):502 ):
430 """Allocate and hold all communication buffers.503 """Allocate and hold all communication buffers.
@@ -481,6 +554,8 @@ class Buffer:
481 rank=rank,554 rank=rank,
482 use_udma=use_udma,555 use_udma=use_udma,
483 udma_flags=udma_flags,556 udma_flags=udma_flags,
557+ dedup_mode=dedup_mode,
558+ ranks_per_server=ranks_per_server,
484 )559 )
485 # Buffer-backed: set True by _ensure_shmem_views after init_with_buffer.560 # Buffer-backed: set True by _ensure_shmem_views after init_with_buffer.
486 self._shmem_ready = False561 self._shmem_ready = False
@@ -493,6 +568,19 @@ class Buffer:
493 priority=self.comm_stream_priority,568 priority=self.comm_stream_priority,
494 )569 )
495 570 
571+ @property
572+ def dedup_mode(self) -> str:
573+ """Dedup domain of this Buffer (``"rank"`` or ``"server"``).
574+ 
575+ Fixed at construction; no Buffer method takes a dedup argument.
576+ """
577+ return self._require_ctx()['dedup_mode']
578+ 
579+ @property
580+ def ranks_per_server(self) -> int:
581+ """Number of cards in one server for server-level dedup (8)."""
582+ return int(self._require_ctx()['ranks_per_server'])
583+ 
496 @property584 @property
497 def destroyed(self) -> bool:585 def destroyed(self) -> bool:
498 return self._destroyed586 return self._destroyed
@@ -540,8 +628,11 @@ class Buffer:
540 'barrier_buf',628 'barrier_buf',
541 'combine_sync_buffer',629 'combine_sync_buffer',
542 'dispatch_sync_buffer',630 'dispatch_sync_buffer',
631+ 'combine_workspace',
543 ):632 ):
544- allocation = ctx['vmm_chunks'][name]633+ allocation = ctx['vmm_chunks'].get(name)
634+ if allocation is None:
635+ continue
545 sym = map_to_sym_ptr(allocation.source_va, name)636 sym = map_to_sym_ptr(allocation.source_va, name)
546 src = ctx[name]637 src = ctx[name]
547 ctx[name] = create_sym_tensor_from_ptr(638 ctx[name] = create_sym_tensor_from_ptr(
@@ -600,6 +691,7 @@ class Buffer:
600 'barrier_buf',691 'barrier_buf',
601 'combine_sync_buffer',692 'combine_sync_buffer',
602 'dispatch_sync_buffer',693 'dispatch_sync_buffer',
694+ 'combine_workspace',
603 ):695 ):
604 allocation = ctx['vmm_chunks'].get(name)696 allocation = ctx['vmm_chunks'].get(name)
605 if allocation is not None:697 if allocation is not None:
@@ -618,6 +710,7 @@ class Buffer:
618 'combine_sync_buffer',710 'combine_sync_buffer',
619 'planning_workspace',711 'planning_workspace',
620 'dispatch_sync_buffer',712 'dispatch_sync_buffer',
713+ 'combine_workspace',
621 ):714 ):
622 ctx.pop(key, None)715 ctx.pop(key, None)
623 ctx.clear()716 ctx.clear()
@@ -831,7 +924,7 @@ class Buffer:
831 if planning_args is not None:924 if planning_args is not None:
832 topk_flat, tokens_per_expert, cu_seqlens = planning_args925 topk_flat, tokens_per_expert, cu_seqlens = planning_args
833 ctx['kernels']['planning'].compute(926 ctx['kernels']['planning'].compute(
834- ctx, topk_flat, tokens_per_expert, cu_seqlens, plan,927+ ctx.get('_comm_owner_ctx', ctx), topk_flat, tokens_per_expert, cu_seqlens, plan,
835 shmem_instance_id=0)928 shmem_instance_id=0)
836 929 
837 ctx['kernels']['dispatch'].compute(930 ctx['kernels']['dispatch'].compute(
@@ -960,6 +1053,9 @@ class Buffer:
960 ``source = (expert%epn)*H*Hp`` (analysis §4.2).1053 ``source = (expert%epn)*H*Hp`` (analysis §4.2).
961 """1054 """
962 self._ensure_shmem_views()1055 self._ensure_shmem_views()
1056+ server_dedup = ctx['dedup_mode'] == 'server'
1057+ if server_dedup:
1058+ cross_rank_barrier(ctx, torch_npu.npu.current_stream().npu_stream)
963 E = int(ctx['E'])1059 E = int(ctx['E'])
964 local_experts = experts_to_copy[int(ctx['rank'])] # this rank's [B] row1060 local_experts = experts_to_copy[int(ctx['rank'])] # this rank's [B] row
965 # The op layer requires shmem tensors pointing at the "local part of1061 # The op layer requires shmem tensors pointing at the "local part of
@@ -1003,6 +1099,8 @@ class Buffer:
1003 local_experts,1099 local_experts,
1004 shmem_instance_id=0,1100 shmem_instance_id=0,
1005 )1101 )
1102+ if server_dedup:
1103+ cross_rank_barrier(ctx, torch_npu.npu.current_stream().npu_stream)
1006 1104 
1007 def _run_reduce_grad_on_current_stream(1105 def _run_reduce_grad_on_current_stream(
1008 self,1106 self,
@@ -1025,6 +1123,8 @@ class Buffer:
1025 ``experts_to_copy`` still carries the full ``[R, B]`` plan.1123 ``experts_to_copy`` still carries the full ``[R, B]`` plan.
1026 """1124 """
1027 self._ensure_shmem_views()1125 self._ensure_shmem_views()
1126+ if ctx['dedup_mode'] == 'server':
1127+ cross_rank_barrier(ctx, torch_npu.npu.current_stream().npu_stream)
1028 rank = int(ctx['rank'])1128 rank = int(ctx['rank'])
1029 E = int(ctx['E'])1129 E = int(ctx['E'])
1030 R = int(ctx['R'])1130 R = int(ctx['R'])
@@ -1109,6 +1209,9 @@ class Buffer:
1109 comm_buffers = getattr(self, '_comm_buffers', None)1209 comm_buffers = getattr(self, '_comm_buffers', None)
1110 self._ensure_shmem_views()1210 self._ensure_shmem_views()
1111 1211 
1212+ if ctx['dedup_mode'] == 'server' and not ctx['_dispatch_use_udma']:
1213+ raise ValueError('server dedup requires UDMA dispatch')
1214+ 
1112 if plan is None:1215 if plan is None:
1113 assert topk_experts_sk is not None and tokens_per_expert is not None1216 assert topk_experts_sk is not None and tokens_per_expert is not None
1114 topk_flat = topk_experts_sk.reshape(-1)1217 topk_flat = topk_experts_sk.reshape(-1)
@@ -1263,6 +1366,21 @@ class Buffer:
1263 1366 
1264 return done1367 return done
1265 1368 
1369+ def prepare_combine_plan(self, plan: MoonEPCommPlan):
1370+ """Collectively prepare manually built routes before UDMA combine.
1371+ 
1372+ All ranks call after dst is ready. Ordinary dispatch planning does this
1373+ automatically, and plan.clone() preserves those prepared tables locally.
1374+ No preparation is hidden inside the combine timed loop.
1375+ """
1376+ ctx = self._require_ctx()
1377+ self._ensure_shmem_views()
1378+ if not ctx['_combine_use_udma']:
1379+ raise RuntimeError('prepare_combine_plan requires UDMA combine')
1380+ _validate_plan_layout(ctx, plan)
1381+ from .planning import prepare_combine_plan
1382+ return prepare_combine_plan(ctx, plan)
1383+ 
1266 def combine(1384 def combine(
1267 self,1385 self,
1268 plan: MoonEPCommPlan | None = None,1386 plan: MoonEPCommPlan | None = None,
@@ -247,6 +247,23 @@ def apply_engine(engine: str) -> bool:
247 return want247 return want
248 248 
249 249 
250+def add_dedup_mode_arg(parser: argparse.ArgumentParser) -> None:
251+ parser.add_argument(
252+ "--dedup-mode", choices=("rank", "server"), default="rank",
253+ help="Deduplicate by rank or by a group of eight ranks (requires URMA).",
254+ )
255+ 
256+ 
257+def validate_dedup_mode(dedup_mode: str, use_udma: bool, ranks: int) -> None:
258+ if dedup_mode != "server":
259+ return
260+ from npu_patch.planning import RANKS_PER_SERVER
261+ 
262+ local_ranks = min(ranks, int(os.environ.get("LOCAL_WORLD_SIZE", ranks)))
263+ if not use_udma or ranks % RANKS_PER_SERVER or local_ranks % RANKS_PER_SERVER:
264+ raise SystemExit("--dedup-mode server requires URMA and complete eight-rank servers")
265+ 
266+ 
250def add_common_args(parser: argparse.ArgumentParser) -> None:267def add_common_args(parser: argparse.ArgumentParser) -> None:
251 """Arguments shared by all benchmarks."""268 """Arguments shared by all benchmarks."""
252 add_engine_args(parser)269 add_engine_args(parser)
@@ -7,6 +7,11 @@ per-route ``dst`` -> duplicate encoding), but is vectorized: the Python-loop
7reference needs ~1 minute per MaxVio point at benchmark scale7reference needs ~1 minute per MaxVio point at benchmark scale
8(R=8, S=8192, K=16, E=1024), while these models run in ~1 s.8(R=8, S=8192, K=16, E=1024), while these models run in ~1 s.
9 9 
10+The dedup domain is a parameter (``dedup_mode``): ``rank`` dedups per
11+destination rank (the Buffer default) and ``server`` dedups per 8-rank server,
12+where groups are owned by the primary's rank and the duplicate table stores
13+full ``dest * NvS + loff`` addresses so members may live on sibling ranks.
14+ 
10``plan_expectation`` returns the full expected plan for every rank;15``plan_expectation`` returns the full expected plan for every rank;
11``dispatch_expectation`` maps the gathered ``dst``/weights/hidden fingerprints16``dispatch_expectation`` maps the gathered ``dst``/weights/hidden fingerprints
12to the slot layout of one destination rank.17to the slot layout of one destination rank.
@@ -18,6 +23,9 @@ from dataclasses import dataclass
18 23 
19import torch24import torch
20 25 
26+# An Ascend server is 8 consecutive ranks; see npu_patch.planning.RANKS_PER_SERVER.
27+RANKS_PER_SERVER = 8
28+ 
21# Bound the [chunk, R] destination-search workspace of the route model: a29# Bound the [chunk, R] destination-search workspace of the route model: a
22# 65536-route chunk is 4 MiB of int64 boundaries for R=8.30# 65536-route chunk is 4 MiB of int64 boundaries for R=8.
23_ROUTE_CHUNK = 6553631_ROUTE_CHUNK = 65536
@@ -163,38 +171,74 @@ def plan_layout(
163 return cu, expert_off171 return cu, expert_off
164 172 
165 173 
166-def _first_route_per_destination(dest_sk: torch.Tensor) -> torch.Tensor:174+def _first_route_per_domain(
167- """``[S, K]`` bool: first top-k route of each token to a destination rank.175+ dest_sk: torch.Tensor, ranks_per_server: int = 1
176+) -> torch.Tensor:
177+ """``[S, K]`` bool: first top-k route of each token into a dedup domain.
168 178 
169- Stable: the first entry in top-k order is canonical; later routes to the179+ Stable: the first entry in top-k order is canonical; later routes into the
170- same destination rank are duplicates.180+ same domain (one rank, or one 8-rank server) are duplicates. Matches the
181+ planning kernel's ``DedupRouteTileSimt`` (first positive route per token and
182+ domain wins, later ones are encoded as ``~raw``).
171 """183 """
172- order = torch.argsort(dest_sk, dim=1, stable=True)184+ domain = dest_sk if ranks_per_server == 1 else dest_sk // ranks_per_server
173- sorted_dest = dest_sk.gather(1, order)185+ order = torch.argsort(domain, dim=1, stable=True)
174- first_sorted = torch.ones_like(sorted_dest, dtype=torch.bool)186+ sorted_domain = domain.gather(1, order)
175- first_sorted[:, 1:] = sorted_dest[:, 1:] != sorted_dest[:, :-1]187+ first_sorted = torch.ones_like(sorted_domain, dtype=torch.bool)
188+ first_sorted[:, 1:] = sorted_domain[:, 1:] != sorted_domain[:, :-1]
176 first = torch.empty_like(first_sorted)189 first = torch.empty_like(first_sorted)
177 first.scatter_(1, order, first_sorted)190 first.scatter_(1, order, first_sorted)
178 return first191 return first
179 192 
180 193 
194+def _first_route_per_destination(dest_sk: torch.Tensor) -> torch.Tensor:
195+ """Rank-level shorthand for :func:`_first_route_per_domain`."""
196+ return _first_route_per_domain(dest_sk, 1)
197+ 
198+ 
199+def stripe_rank_routes(boundaries, ordinals, dest, NvS, width=RANKS_PER_SERVER):
200+ """Permute hot expert ordinals and reselect their rank within the server."""
201+ rows = torch.arange(dest.numel(), device=dest.device)
202+ first = (dest // width) * width
203+ begin = torch.where(first > 0, boundaries[rows, (first - 1).clamp_min(0)], 0)
204+ end = boundaries[rows, first + width - 1]
205+ prev = torch.where(dest > 0, boundaries[rows, (dest - 1).clamp_min(0)], 0)
206+ count = end - begin
207+ active = (count >= NvS // 4) & ((prev != begin) | (boundaries[rows, dest] != end))
208+ relative = ordinals[active] - begin[active]
209+ count = count[active]
210+ lane = relative % 64
211+ striped = begin[active] + lane * (count // 64) + torch.minimum(lane, count % 64) + relative // 64
212+ ordinals = ordinals.clone()
213+ dest = dest.clone()
214+ ordinals[active] = striped
215+ dest[active] = (boundaries[active] <= striped[:, None]).sum(1)
216+ return ordinals, dest
217+ 
218+ 
181def _route_destinations(219def _route_destinations(
182 topk_all: torch.Tensor,220 topk_all: torch.Tensor,
183 tpe_all: torch.Tensor,221 tpe_all: torch.Tensor,
184 alloc: torch.Tensor,222 alloc: torch.Tensor,
185 expert_off: torch.Tensor,223 expert_off: torch.Tensor,
186 NvS: int,224 NvS: int,
225+ *,
226+ dedup_mode: str = "rank",
227+ ranks_per_server: int = RANKS_PER_SERVER,
228+ stripe_rank_placement: bool = False,
187) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:229) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
188 """Expected per-route destination/loff/canonical flags for every rank.230 """Expected per-route destination/loff/canonical flags for every rank.
189 231 
190 Returns ``(dest, loff, canonical, raw)``, each ``[R, N]`` with232 Returns ``(dest, loff, canonical, raw)``, each ``[R, N]`` with
191 ``N = S * K``: destination rank, offset inside the destination layout,233 ``N = S * K``: destination rank, offset inside the destination layout,
192- first-route-to-destination flag (canonical vs duplicate) and the234+ first-route-to-dedup-domain flag (canonical vs duplicate) and the
193 un-encoded ``dest * NvS + loff``.235 un-encoded ``dest * NvS + loff``.
194 """236 """
195 R, S, K = topk_all.shape237 R, S, K = topk_all.shape
196 N = S * K238 N = S * K
197 E = alloc.shape[0]239 E = alloc.shape[0]
240+ domain_width = ranks_per_server if dedup_mode == "server" else 1
241+ stripe = stripe_rank_placement and dedup_mode == "rank" and R in (32, 64)
198 alloc_cumsum = alloc.cumsum(1)242 alloc_cumsum = alloc.cumsum(1)
199 tpe_cumsum = tpe_all.to(torch.int64).cumsum(0)243 tpe_cumsum = tpe_all.to(torch.int64).cumsum(0)
200 prev_count = torch.zeros(R, E, dtype=torch.int64)244 prev_count = torch.zeros(R, E, dtype=torch.int64)
@@ -216,7 +260,12 @@ def _route_destinations(
216 for base in range(0, N, _ROUTE_CHUNK):260 for base in range(0, N, _ROUTE_CHUNK):
217 end = min(base + _ROUTE_CHUNK, N)261 end = min(base + _ROUTE_CHUNK, N)
218 boundaries = alloc_cumsum[experts[base:end]]262 boundaries = alloc_cumsum[experts[base:end]]
219- d[base:end] = (boundaries <= g[base:end, None]).sum(1)263+ ranks = (boundaries <= g[base:end, None]).sum(1)
264+ if stripe:
265+ ordinals, ranks = stripe_rank_routes(
266+ boundaries, g[base:end], ranks, NvS, ranks_per_server)
267+ g[base:end] = ordinals
268+ d[base:end] = ranks
220 dest[r] = d269 dest[r] = d
221 270 
222 prev_alloc = torch.where(271 prev_alloc = torch.where(
@@ -225,7 +274,9 @@ def _route_destinations(
225 torch.zeros_like(d),274 torch.zeros_like(d),
226 )275 )
227 loff[r] = expert_off[d, experts] + g - prev_alloc276 loff[r] = expert_off[d, experts] + g - prev_alloc
228- canonical[r] = _first_route_per_destination(d.view(S, K)).reshape(-1)277+ canonical[r] = _first_route_per_domain(
278+ d.view(S, K), domain_width
279+ ).reshape(-1)
229 280 
230 raw = dest * NvS + loff281 raw = dest * NvS + loff
231 return dest, loff, canonical, raw282 return dest, loff, canonical, raw
@@ -243,16 +294,34 @@ def dedup_pairs(
243 rank: int,294 rank: int,
244 S: int,295 S: int,
245 NvS: int,296 NvS: int,
246-) -> tuple[torch.Tensor, tuple[int, int]]:297+ *,
298+ dedup_mode: str = "rank",
299+ ranks_per_server: int = RANKS_PER_SERVER,
300+) -> tuple[torch.Tensor, torch.Tensor]:
247 """Expected dedup table for one destination rank, as semantic pairs.301 """Expected dedup table for one destination rank, as semantic pairs.
248 302 
249- Returns ``(pairs, (n_groups, n_dups))`` where ``pairs`` is a lexicographically303+ Returns ``(pairs, counts)``. ``pairs`` is a ``[n_dups, 2]`` int64 tensor of
250- sorted ``[n_dups, 2]`` int64 tensor of ``(primary_loff, duplicate_loff)``.304+ ``(primary_loff, duplicate_address)`` sorted by ``(primary, address)``.
251 Group order is irrelevant (the kernel assigns it with atomics), so only the305 Group order is irrelevant (the kernel assigns it with atomics), so only the
252- ``primary -> {dups}`` mapping is compared.306+ ``primary -> {dups}`` mapping is compared. ``counts`` is
307+ ``[n_groups, n_dups]`` for ``rank`` dedup and
308+ ``[n_groups, n_dups, P_0 .. P_{R-1}]`` for ``server`` dedup, where ``P_src``
309+ counts this rank's groups whose token source is below ``src`` (the dispatch
310+ kernel waits on that prefix).
311+ 
312+ ``duplicate_address`` is the in-rank loff for ``rank`` dedup and the full
313+ ``dest * NvS + loff`` address for ``server`` dedup, because a server group
314+ may own members on sibling ranks.
253 """315 """
254 R, N = dest.shape316 R, N = dest.shape
255 K = N // S317 K = N // S
318+ if dedup_mode == "server":
319+ return _server_dedup_pairs(
320+ dest, loff, canonical, rank, S, NvS, ranks_per_server
321+ )
322+ if dedup_mode != "rank":
323+ raise ValueError(f"unsupported dedup_mode: {dedup_mode!r}")
324+ 
256 src = torch.arange(R, dtype=torch.int64).view(R, 1).expand(R, N)325 src = torch.arange(R, dtype=torch.int64).view(R, 1).expand(R, N)
257 token = torch.arange(N, dtype=torch.int64).view(1, N) // K326 token = torch.arange(N, dtype=torch.int64).view(1, N) // K
258 # Group id: (src rank, token, destination rank).327 # Group id: (src rank, token, destination rank).
@@ -271,14 +340,79 @@ def dedup_pairs(
271 dup_loffs = loff[dup_mask]340 dup_loffs = loff[dup_mask]
272 n_dups = int(dup_keys.numel())341 n_dups = int(dup_keys.numel())
273 if n_dups == 0:342 if n_dups == 0:
274- empty = torch.zeros(0, 2, dtype=torch.int64)343+ return (torch.zeros(0, 2, dtype=torch.int64),
275- return empty, (0, 0)344+ torch.tensor([0, 0], dtype=torch.int64))
276 345 
277 uniq, inverse = torch.unique(dup_keys, return_inverse=True)346 uniq, inverse = torch.unique(dup_keys, return_inverse=True)
278 pair_primary = primary[uniq][inverse]347 pair_primary = primary[uniq][inverse]
279 pairs = torch.stack((pair_primary, dup_loffs), dim=1)348 pairs = torch.stack((pair_primary, dup_loffs), dim=1)
280 pairs = pairs[torch.argsort(pairs[:, 0] * NvS + pairs[:, 1])]349 pairs = pairs[torch.argsort(pairs[:, 0] * NvS + pairs[:, 1])]
281- return pairs, (int(uniq.numel()), n_dups)350+ counts = torch.tensor([int(uniq.numel()), n_dups], dtype=torch.int64)
351+ return pairs, counts
352+ 
353+ 
354+def _server_dedup_pairs(
355+ dest: torch.Tensor,
356+ loff: torch.Tensor,
357+ canonical: torch.Tensor,
358+ rank: int,
359+ S: int,
360+ NvS: int,
361+ ranks_per_server: int,
362+) -> tuple[torch.Tensor, torch.Tensor]:
363+ """Server-dedup tables for one destination rank (see :func:`dedup_pairs`).
364+ 
365+ Groups are keyed by ``(source rank, token, destination server)`` and owned
366+ by the group's primary destination rank; every non-primary member of an
367+ owned group appears in ``dup_loffs`` as a full address, including members
368+ that live on sibling ranks.
369+ """
370+ R, N = dest.shape
371+ K = N // S
372+ num_domains = (R + ranks_per_server - 1) // ranks_per_server
373+ domain = dest // ranks_per_server
374+ token = torch.arange(N, dtype=torch.int64).view(1, N) // K
375+ full = (dest * NvS + loff).reshape(-1)
376+ 
377+ per_source_groups = torch.zeros(R, dtype=torch.int64)
378+ pieces: list[torch.Tensor] = []
379+ for source in range(R):
380+ canon = canonical[source].reshape(-1)
381+ # Group key inside one source: (local token, destination server).
382+ key = token[0] * num_domains + domain[source].reshape(-1)
383+ size = S * num_domains
384+ prim_loff = torch.zeros(size, dtype=torch.int64)
385+ prim_dest = torch.zeros(size, dtype=torch.int64)
386+ prim_seen = torch.zeros(size, dtype=torch.bool)
387+ prim_loff[key[canon]] = loff[source].reshape(-1)[canon]
388+ prim_dest[key[canon]] = dest[source].reshape(-1)[canon]
389+ prim_seen[key[canon]] = True
390+ 
391+ dups = torch.nonzero(~canon, as_tuple=False).flatten()
392+ if dups.numel() == 0:
393+ continue
394+ dup_key = key[dups]
395+ owned = prim_seen[dup_key] & (prim_dest[dup_key] == rank)
396+ if not bool(owned.any()):
397+ continue
398+ dup_key = dup_key[owned]
399+ dup_index = source * N + dups[owned]
400+ pieces.append(torch.stack(
401+ (prim_loff[dup_key], full[dup_index]), dim=1))
402+ per_source_groups[source] = int(torch.unique(dup_key).numel())
403+ 
404+ if pieces:
405+ pairs = torch.cat(pieces)
406+ pairs = pairs[torch.argsort(pairs[:, 0] * (NvS * R) + pairs[:, 1])]
407+ else:
408+ pairs = torch.zeros(0, 2, dtype=torch.int64)
409+ prefixes = per_source_groups.cumsum(0) - per_source_groups
410+ counts = torch.cat((
411+ torch.tensor([int(per_source_groups.sum()), int(pairs.shape[0])],
412+ dtype=torch.int64),
413+ prefixes,
414+ ))
415+ return pairs, counts
282 416 
283 417 
284def plan_dedup_pairs(418def plan_dedup_pairs(
@@ -286,21 +420,59 @@ def plan_dedup_pairs(
286 dup_loffs: torch.Tensor,420 dup_loffs: torch.Tensor,
287 dup_counts: torch.Tensor,421 dup_counts: torch.Tensor,
288 NvS: int,422 NvS: int,
289-) -> tuple[torch.Tensor, tuple[int, int], list[str]]:423+ *,
424+ R: int | None = None,
425+ dedup_mode: str = "rank",
426+ ranks_per_server: int = RANKS_PER_SERVER,
427+) -> tuple[torch.Tensor, torch.Tensor, list[str]]:
290 """Normalize a kernel-plan dedup table to the same semantic pair form.428 """Normalize a kernel-plan dedup table to the same semantic pair form.
291 429 
292 Also validates the table's structure (compact prefixes, group ranges,430 Also validates the table's structure (compact prefixes, group ranges,
293- duplicate offsets in range), returning human-readable errors.431+ duplicate addresses in range) and returns the full count row, so both
432+ dedup modes compare with the reference model: ``[G, D]`` for ``rank`` and
433+ ``[G, D, P_0 .. P_{R-1}]`` for ``server``.
294 """434 """
295 errors: list[str] = []435 errors: list[str] = []
296- n_groups = int(dup_counts[0])436+ counts_all = dup_counts.to(torch.int64)
297- n_dups = int(dup_counts[1])437+ empty = torch.zeros(0, 2, dtype=torch.int64)
298- if not 0 <= n_groups <= NvS:438+ if dedup_mode == "rank":
299- errors.append(f"dup group count {n_groups} out of [0, {NvS}]")439+ if counts_all.numel() != 2:
300- if not 0 <= n_dups <= NvS:440+ errors.append(
301- errors.append(f"dup loff count {n_dups} out of [0, {NvS}]")441+ f"rank dedup dup_counts must have 2 entries, got {counts_all.numel()}")
442+ return empty, counts_all, errors
443+ group_capacity = NvS
444+ dup_capacity = NvS
445+ address_limit = NvS
446+ elif dedup_mode == "server":
447+ if R is None:
448+ raise ValueError("server dedup table checks require R")
449+ if counts_all.numel() != R + 2:
450+ errors.append(
451+ f"server dedup dup_counts must have R+2={R + 2} entries, "
452+ f"got {counts_all.numel()}")
453+ return empty, counts_all, errors
454+ group_capacity = NvS
455+ dup_capacity = ranks_per_server * NvS
456+ address_limit = R * NvS
457+ else:
458+ raise ValueError(f"unsupported dedup_mode: {dedup_mode!r}")
459+ 
460+ n_groups = int(counts_all[0])
461+ n_dups = int(counts_all[1])
462+ if not 0 <= n_groups <= group_capacity:
463+ errors.append(f"dup group count {n_groups} out of [0, {group_capacity}]")
464+ if not 0 <= n_dups <= dup_capacity:
465+ errors.append(f"dup loff count {n_dups} out of [0, {dup_capacity}]")
466+ if dedup_mode == "server":
467+ prefixes = counts_all[2:]
468+ if int(prefixes[0]) != 0:
469+ errors.append("server dup source prefixes must start at 0")
470+ if bool((prefixes[1:] < prefixes[:-1]).any()):
471+ errors.append("server dup source prefixes are not monotonic")
472+ if int(prefixes[-1]) > max(n_groups, 0):
473+ errors.append("server dup source prefix exceeds the group count")
302 if errors:474 if errors:
303- return torch.zeros(0, 2, dtype=torch.int64), (n_groups, n_dups), errors475+ return empty, counts_all, errors
304 476 
305 groups = dup_groups[:n_groups].to(torch.int64)477 groups = dup_groups[:n_groups].to(torch.int64)
306 prim = groups[:, 0]478 prim = groups[:, 0]
@@ -327,14 +499,17 @@ def plan_dedup_pairs(
327 errors.append("dup group references loffs outside the compact prefix")499 errors.append("dup group references loffs outside the compact prefix")
328 dup_idx = dup_idx.clamp(0, max(n_dups - 1, 0))500 dup_idx = dup_idx.clamp(0, max(n_dups - 1, 0))
329 dup_values = dup_loffs[dup_idx].to(torch.int64)501 dup_values = dup_loffs[dup_idx].to(torch.int64)
502+ if bool(((dup_values < 0) | (dup_values >= address_limit)).any()):
503+ errors.append(
504+ f"dup addresses out of [0, {address_limit}) for {dedup_mode} dedup")
330 pairs = torch.stack((torch.repeat_interleave(prim, counts), dup_values), 1)505 pairs = torch.stack((torch.repeat_interleave(prim, counts), dup_values), 1)
331 if int(torch.unique(dup_values).numel()) != total:506 if int(torch.unique(dup_values).numel()) != total:
332 errors.append("dup_loffs lists the same duplicate row twice")507 errors.append("dup_loffs lists the same duplicate row twice")
333- pairs = pairs[torch.argsort(pairs[:, 0] * NvS + pairs[:, 1])]508+ pairs = pairs[torch.argsort(pairs[:, 0] * address_limit + pairs[:, 1])]
334 else:509 else:
335- pairs = torch.zeros(0, 2, dtype=torch.int64)510+ pairs = empty
336 511 
337- return pairs, (n_groups, n_dups), errors512+ return pairs, counts_all, errors
338 513 
339 514 
340@dataclass(frozen=True)515@dataclass(frozen=True)
@@ -350,7 +525,8 @@ class PlanExpectation:
350 canonical: torch.Tensor # [R, N] bool525 canonical: torch.Tensor # [R, N] bool
351 dst: torch.Tensor # [R, N] expected encoded dst526 dst: torch.Tensor # [R, N] expected encoded dst
352 dedup_pairs: torch.Tensor # [n_dups, 2] for this rank's destination527 dedup_pairs: torch.Tensor # [n_dups, 2] for this rank's destination
353- dedup_counts: tuple[int, int]528+ dedup_counts: torch.Tensor # [2] rank / [R+2] server count row
529+ dedup_mode: str
354 tpe_global: torch.Tensor # [E]530 tpe_global: torch.Tensor # [E]
355 531 
356 532 
@@ -360,6 +536,9 @@ def plan_expectation(
360 *,536 *,
361 rank: int,537 rank: int,
362 NvS: int,538 NvS: int,
539+ dedup_mode: str = "rank",
540+ ranks_per_server: int = RANKS_PER_SERVER,
541+ stripe_rank_placement: bool = False,
363) -> PlanExpectation:542) -> PlanExpectation:
364 """Build the expected plan for every rank from the full routing."""543 """Build the expected plan for every rank from the full routing."""
365 topk_all = topk_all.to(torch.int64)544 topk_all = topk_all.to(torch.int64)
@@ -372,10 +551,15 @@ def plan_expectation(
372 experts_to_copy = prefetch_experts(alloc, R, E, B)551 experts_to_copy = prefetch_experts(alloc, R, E, B)
373 cu_seqlens, expert_off = plan_layout(alloc, experts_to_copy, R, E, B)552 cu_seqlens, expert_off = plan_layout(alloc, experts_to_copy, R, E, B)
374 dest, loff, canonical, raw = _route_destinations(553 dest, loff, canonical, raw = _route_destinations(
375- topk_all, tpe_all, alloc, expert_off, NvS554+ topk_all, tpe_all, alloc, expert_off, NvS,
555+ dedup_mode=dedup_mode, ranks_per_server=ranks_per_server,
556+ stripe_rank_placement=stripe_rank_placement,
376 )557 )
377 dst = encode_dst(raw, canonical)558 dst = encode_dst(raw, canonical)
378- pairs, counts = dedup_pairs(dest, loff, canonical, rank, S, NvS)559+ pairs, counts = dedup_pairs(
560+ dest, loff, canonical, rank, S, NvS,
561+ dedup_mode=dedup_mode, ranks_per_server=ranks_per_server,
562+ )
379 return PlanExpectation(563 return PlanExpectation(
380 alloc=alloc,564 alloc=alloc,
381 experts_to_copy=experts_to_copy,565 experts_to_copy=experts_to_copy,
@@ -387,6 +571,7 @@ def plan_expectation(
387 dst=dst,571 dst=dst,
388 dedup_pairs=pairs,572 dedup_pairs=pairs,
389 dedup_counts=counts,573 dedup_counts=counts,
574+ dedup_mode=dedup_mode,
390 tpe_global=tpe_all.sum(0),575 tpe_global=tpe_all.sum(0),
391 )576 )
392 577 
@@ -474,4 +659,4 @@ def row_fingerprint(
474 out[base:end, 1] = block.abs().sum(1)659 out[base:end, 1] = block.abs().sum(1)
475 out[base:end, 2] = (block * ramp).sum(1)660 out[base:end, 2] = (block * ramp).sum(1)
476 out[base:end, 3] = (block * block).sum(1)661 out[base:end, 3] = (block * block).sum(1)
477- return out662+ return out
@@ -32,6 +32,14 @@ size defaults to the launched world size (8 on a single node, 16 across two
32nodes) — override with ``--ep-size`` for a subgroup of ranks [0, ep). ``--prod``32nodes) — override with ``--ep-size`` for a subgroup of ranks [0, ep). ``--prod``
33runs just the production 8-card config (S=4096, K=16, E=896, H=7168).33runs just the production 8-card config (S=4096, K=16, E=896, H=7168).
34 34 
35+``--dedup-mode {rank,server}`` selects the Buffer's dedup domain, fixed at
36+construction (same rule as bench_vs.py). ``server`` groups 8 consecutive ranks
37+into one domain, needs ``--engine urma`` (effective UDMA), ``ep % 8 == 0`` and
38+``K >= 2``, and allocates the multi-GiB symmetric PUT combine workspace. The
39+planner emits the fused combine execution plan, so this benchmark can time the
40+server combine flow without an extra preparation step; a missing plan fails fast
41+before timing.
42+ 
35Every flow runs a live Ascend kernel and reports a cross-rank mean latency.43Every flow runs a live Ascend kernel and reports a cross-rank mean latency.
36 44 
37Run:45Run:
@@ -59,7 +67,9 @@ from _bench_common import (
59 PROD_K,67 PROD_K,
60 PROD_S,68 PROD_S,
61 add_common_args,69 add_common_args,
70+ add_dedup_mode_arg,
62 apply_engine,71 apply_engine,
72+ validate_dedup_mode,
63 fmt4,73 fmt4,
64 measure_flow,74 measure_flow,
65 setup,75 setup,
@@ -111,7 +121,8 @@ def bench_one(group, group_rank, R, S, K, E, H, bias_ratio, args, flows):
111 # capability and writes ASCEND_MOONEP_*_USE_UDMA, so init_with_buffer121 # capability and writes ASCEND_MOONEP_*_USE_UDMA, so init_with_buffer
112 # below just inherits that policy.122 # below just inherits that policy.
113 buffer = Buffer(S, H, K, E, R, num_sms=args.num_sms, group=group,123 buffer = Buffer(S, H, K, E, R, num_sms=args.num_sms, group=group,
114- use_udma=use_udma, explicitly_destroy=True)124+ use_udma=use_udma, explicitly_destroy=True,
125+ dedup_mode=args.dedup_mode)
115 ctx = buffer._require_ctx()126 ctx = buffer._require_ctx()
116 if not ShmemRuntime.is_initialized():127 if not ShmemRuntime.is_initialized():
117 ShmemRuntime.init_with_buffer(group=group, enable_udma=use_udma)128 ShmemRuntime.init_with_buffer(group=group, enable_udma=use_udma)
@@ -133,6 +144,18 @@ def bench_one(group, group_rank, R, S, K, E, H, bias_ratio, args, flows):
133 output_sh = torch.empty(S, H, dtype=torch.bfloat16, device=dev)144 output_sh = torch.empty(S, H, dtype=torch.bfloat16, device=dev)
134 output_sk = torch.empty(S, K, dtype=torch.float32, device=dev)145 output_sk = torch.empty(S, K, dtype=torch.float32, device=dev)
135 146 
147+ # Server dedup combine consumes the planning-produced execution plan. Run
148+ # one untimed planning here so an unsupported/missing plan fails fast with a
149+ # clear message instead of an ABI error inside the timed combine loop.
150+ if args.dedup_mode == "server" and any(
151+ flow.startswith("combine") for flow in flows):
152+ launch_planning(ctx, topk_flat, tpe, cu_seqlens, plan)
153+ torch_npu.npu.synchronize()
154+ if plan.combine_execution_plan is None:
155+ raise RuntimeError(
156+ "server dedup planning did not produce a combine execution "
157+ "plan; check that combine UDMA is enabled for this Buffer")
158+ 
136 # Global expert-load imbalance (max / mean over experts, all ranks summed).159 # Global expert-load imbalance (max / mean over experts, all ranks summed).
137 global_tpe = tpe.to(torch.int64)160 global_tpe = tpe.to(torch.int64)
138 dist.all_reduce(global_tpe, group=group)161 dist.all_reduce(global_tpe, group=group)
@@ -224,6 +247,7 @@ def parse_args():
224 ap.add_argument("--prod", action="store_true",247 ap.add_argument("--prod", action="store_true",
225 help="Run only the production 8-card config: "248 help="Run only the production 8-card config: "
226 "S=4096, K=16, E=896, H=7168, unbalance_ratio=1.0.")249 "S=4096, K=16, E=896, H=7168, unbalance_ratio=1.0.")
250+ add_dedup_mode_arg(ap)
227 return ap.parse_args()251 return ap.parse_args()
228 252 
229 253 
@@ -235,6 +259,12 @@ def main():
235 ep = args.ep_size if args.ep_size is not None else world_size259 ep = args.ep_size if args.ep_size is not None else world_size
236 assert ep >= 1, f"--ep-size must be >= 1, got {ep}"260 assert ep >= 1, f"--ep-size must be >= 1, got {ep}"
237 assert ep <= world_size, f"--ep-size {ep} exceeds world size {world_size}"261 assert ep <= world_size, f"--ep-size {ep} exceeds world size {world_size}"
262+ validate_dedup_mode(args.dedup_mode, args.use_udma, ep)
263+ if args.dedup_mode == "server":
264+ if args.topk is not None and args.topk < 2:
265+ raise SystemExit(
266+ "--dedup-mode server requires K >= 2 to exercise the "
267+ "intra-server forwarding path")
238 in_group = rank < ep268 in_group = rank < ep
239 269 
240 # Subgroup over ranks [0, ep); every world rank participates in new_group.270 # Subgroup over ranks [0, ep); every world rank participates in new_group.
@@ -262,7 +292,8 @@ def main():
262 292 
263 if rank == 0:293 if rank == 0:
264 print(f"=== bench_comm: world={world_size} ep={ep} nodesize={local_rank} "294 print(f"=== bench_comm: world={world_size} ep={ep} nodesize={local_rank} "
265- f"flows={flows} configs={len(configs)} ===", flush=True)295+ f"flows={flows} configs={len(configs)} "
296+ f"dedup={args.dedup_mode} engine={args.engine} ===", flush=True)
266 297 
267 # shmem init lives inside each config's bench_one: construct Buffer ->298 # shmem init lives inside each config's bench_one: construct Buffer ->
268 # ShmemRuntime.init_with_buffer -> run -> destroy -> finalize -> reset299 # ShmemRuntime.init_with_buffer -> run -> destroy -> finalize -> reset
@@ -43,7 +43,9 @@ import torch.distributed as dist
43 43 
44from _bench_common import (44from _bench_common import (
45 add_engine_args,45 add_engine_args,
46+ add_dedup_mode_arg,
46 apply_engine,47 apply_engine,
48+ validate_dedup_mode,
47 generate_topk_routing,49 generate_topk_routing,
48 setup,50 setup,
49)51)
@@ -146,7 +148,7 @@ class DispatchRunner:
146 """Own the Buffer, plan, and fixed dispatch inputs for one benchmark."""148 """Own the Buffer, plan, and fixed dispatch inputs for one benchmark."""
147 149 
148 def __init__(self, group, R, S, K, E, H, num_sms, local_rank, with_weights,150 def __init__(self, group, R, S, K, E, H, num_sms, local_rank, with_weights,
149- rank=None, use_udma=False):151+ rank=None, use_udma=False, dedup_mode="rank"):
150 self.group = group152 self.group = group
151 self.rank = rank if rank is not None else dist.get_rank(group=group)153 self.rank = rank if rank is not None else dist.get_rank(group=group)
152 self.R = R154 self.R = R
@@ -164,6 +166,7 @@ class DispatchRunner:
164 num_sms=num_sms,166 num_sms=num_sms,
165 group=group,167 group=group,
166 use_udma=use_udma,168 use_udma=use_udma,
169+ dedup_mode=dedup_mode,
167 explicitly_destroy=True,170 explicitly_destroy=True,
168 rank=rank,171 rank=rank,
169 )172 )
@@ -311,6 +314,7 @@ def setup_no_dist():
311def main():314def main():
312 parser = argparse.ArgumentParser(description=__doc__)315 parser = argparse.ArgumentParser(description=__doc__)
313 add_engine_args(parser)316 add_engine_args(parser)
317+ add_dedup_mode_arg(parser)
314 parser.add_argument(318 parser.add_argument(
315 "--out",319 "--out",
316 default="bench_dispatch_maxvio_results.csv",320 default="bench_dispatch_maxvio_results.csv",
@@ -362,6 +366,7 @@ def main():
362 local_rank = local_device_index(local_rank)366 local_rank = local_device_index(local_rank)
363 use_udma = apply_engine(args.engine)367 use_udma = apply_engine(args.engine)
364 R = world_size368 R = world_size
369+ validate_dedup_mode(args.dedup_mode, use_udma, R)
365 S, K, E, H = args.tokens, args.topk, args.experts, args.hidden370 S, K, E, H = args.tokens, args.topk, args.experts, args.hidden
366 dev = f"npu:{local_rank}"371 dev = f"npu:{local_rank}"
367 assert R >= 2, f"dispatch benchmark requires at least 2 ranks, got {R}"372 assert R >= 2, f"dispatch benchmark requires at least 2 ranks, got {R}"
@@ -386,6 +391,7 @@ def main():
386 with_weights=not args.no_weights,391 with_weights=not args.no_weights,
387 rank=rank if args.no_dist else None,392 rank=rank if args.no_dist else None,
388 use_udma=use_udma,393 use_udma=use_udma,
394+ dedup_mode=args.dedup_mode,
389 )395 )
390 if not ShmemRuntime.is_initialized():396 if not ShmemRuntime.is_initialized():
391 if args.no_dist:397 if args.no_dist:
@@ -0,0 +1,176 @@
1+"""Measure URMA rank-dedup roundtrip latency at Hy4-flash's 1536-wide shape."""
2+ 
3+import argparse
4+import hashlib
5+import json
6+import os
7+import statistics
8+from pathlib import Path
9+ 
10+import torch
11+import torch.distributed as dist
12+import torch_npu
13+ 
14+from _bench_common import apply_engine, generate_topk_routing, setup
15+from bench_vs import MoonEPRunner, _report_ok, solve_sigma_for_maxvio
16+from npu_patch import ShmemRuntime
17+from npu_patch._device import local_device_index
18+from npu_patch.buffer_c import reset_symmetric_descriptors
19+from npu_patch.launchers import launch_dispatch
20+from npu_patch.shmem_runtime import default_shmem_ip_port
21+ 
22+ 
23+def verify_combine_routes(runner, device):
24+ """Check the exact sum of route-dependent BF16 values."""
25+ routes_per_rank = runner.S * runner.K
26+ encoded = runner._all_gather_stack(runner.plan.dst).flatten().long()
27+ raw = torch.where(encoded >= 0, encoded, -encoded - 1)
28+ routes = (raw // routes_per_rank == runner.rank).nonzero().flatten()
29+ rows = torch.empty(routes_per_rank, dtype=torch.float32)
30+ rows[raw[routes] % routes_per_rank] = ((routes * 17) % 23 - 11).float()
31+ columns = torch.arange(runner.H, dtype=torch.float32, device=device) % 5 - 2
32+ runner.shard_view.copy_((rows.to(device)[:, None] + columns[None, :]) / 64)
33+ runner.combine_fwd()
34+ 
35+ start = runner.rank * routes_per_rank
36+ route_ids = torch.arange(start, start + routes_per_rank, device=device)
37+ summed = ((route_ids * 17) % 23 - 11).view(runner.S, runner.K).sum(1).float()
38+ expected = ((summed[:, None] + runner.K * columns[None, :]) / 64).bfloat16()
39+ if not _report_ok("combine distinct route values",
40+ torch.equal(runner.output_sh, expected),
41+ runner.rank, runner.group, device):
42+ raise AssertionError("incorrect Combine sum for route-dependent values")
43+ launch_dispatch(runner.ctx, runner.hidden, runner.weights, runner.plan, build_dedup_map=False)
44+ 
45+ 
46+def measure_roundtrip(runner, device, warmup, iters, block):
47+ def roundtrip():
48+ runner.dispatch_fwd()
49+ runner.combine_fwd()
50+ runner.dispatch_bwd()
51+ runner.combine_bwd()
52+ 
53+ for _ in range(warmup):
54+ roundtrip()
55+ torch.npu.synchronize()
56+ dist.barrier()
57+ 
58+ intervals = []
59+ for _ in range(iters):
60+ start = torch.npu.Event(enable_timing=True)
61+ end = torch.npu.Event(enable_timing=True)
62+ start.record()
63+ for _ in range(block):
64+ roundtrip()
65+ end.record()
66+ intervals.append((start, end))
67+ intervals[-1][1].synchronize()
68+ local = torch.tensor([start.elapsed_time(end) * 1000 / block for start, end in intervals],
69+ dtype=torch.float64, device=device)
70+ samples = runner._all_gather_stack(local)
71+ worst = samples.max(dim=0).values
72+ return dict(p50_us=statistics.median(worst.tolist()), p95_us=torch.quantile(worst, 0.95).item(),
73+ per_rank_samples_us=samples.tolist())
74+ 
75+ 
76+def main():
77+ parser = argparse.ArgumentParser(description=__doc__)
78+ parser.add_argument("--control-plane", choices=("gloo", "hccl"), default="gloo")
79+ parser.add_argument("--ip-port", help="SHMEM bootstrap endpoint; defaults to MASTER_PORT + 1")
80+ parser.add_argument("--maxvios", default="1,30", help="Comma-separated MaxVio targets")
81+ parser.add_argument("--warmup", type=int, default=8)
82+ parser.add_argument("--iters", type=int, default=40, help="Number of NPU-event samples")
83+ parser.add_argument("--block", type=int, default=6, help="Roundtrips per event sample")
84+ checks = parser.add_mutually_exclusive_group()
85+ checks.add_argument("--verify", action="store_true", help="Check precision before timing")
86+ checks.add_argument("--verify-only", action="store_true", help="Run only the precision checks")
87+ parser.add_argument("--legacy-placement", action="store_true",
88+ help="Use the pre-optimization Planner reference when testing a baseline build")
89+ parser.add_argument("--out", type=Path, default=Path("bench_rank_maxvio.json"))
90+ args = parser.parse_args()
91+ if args.warmup < 0 or args.iters < 1 or args.block < 1:
92+ parser.error("warmup must be nonnegative and iters and block must be positive")
93+ targets = [float(value) for value in args.maxvios.split(",")]
94+ world = int(os.environ["WORLD_SIZE"])
95+ if world not in (8, 16, 32, 64) or int(os.environ["LOCAL_WORLD_SIZE"]) != 8:
96+ parser.error("launch 8, 16, 32 or 64 ranks with eight NPUs per node")
97+ 
98+ local_rank = int(os.environ["LOCAL_RANK"])
99+ device_id = local_device_index(local_rank)
100+ device = torch.device(f"npu:{device_id}")
101+ tokens, hidden_size, topk_size, experts, hp = 8192, 1536, 16, 512, 1536
102+ verify = args.verify or args.verify_only
103+ runner = None
104+ results = []
105+ try:
106+ if args.control_plane == "gloo":
107+ torch.npu.set_device(device_id)
108+ dist.init_process_group("gloo")
109+ rank = dist.get_rank()
110+ else:
111+ rank, _, _ = setup()
112+ if not apply_engine("urma"):
113+ raise RuntimeError("This benchmark requires Ascend950 URMA")
114+ runner = MoonEPRunner(dist.group.WORLD, world, tokens, topk_size, experts, hidden_size,
115+ 32, device_id, hp=hp, use_udma=True, dedup_mode="rank",
116+ verify=verify, verify_stages=("plan", "dispatch", "combine"))
117+ if args.legacy_placement:
118+ runner.stripe_rank_placement = False
119+ os.environ["ASCEND_MOONEP_PREFETCH_USE_UDMA"] = "0"
120+ 
121+ # The VMM allocations above must exist before setting up SHMEM.
122+ dist.barrier()
123+ ip_port = args.ip_port or default_shmem_ip_port(
124+ os.environ["MASTER_ADDR"], int(os.environ["MASTER_PORT"]))
125+ ShmemRuntime.init_with_ip_port(group=dist.group.WORLD, ip_port=ip_port,
126+ enable_udma=True, qp_count=2)
127+ runner._prepare_shmem_views()
128+ generator = torch.Generator(device=device).manual_seed(7777 + rank)
129+ hidden = torch.randn(tokens, hidden_size, dtype=torch.bfloat16, device=device, generator=generator)
130+ weights = torch.rand(tokens, topk_size, dtype=torch.float32, device=device, generator=generator)
131+ 
132+ for target in targets:
133+ params = [None]
134+ if rank == 0:
135+ params[0] = solve_sigma_for_maxvio(target, tokens, topk_size, experts, world, device)
136+ dist.broadcast_object_list(params, src=0)
137+ sigma, _ = params[0]
138+ topk, tpe = generate_topk_routing(tokens, topk_size, experts, world, sigma, device, 1234, rank=rank)
139+ totals = runner._all_gather_stack(tpe).sum(0)
140+ realized = totals.max().item() / (totals.sum().item() / experts) - 1
141+ routing = runner._all_gather_stack(topk)
142+ digest = hashlib.sha256(routing.contiguous().numpy().tobytes()).hexdigest()
143+ runner.prepare(topk, tpe, hidden, weights)
144+ if verify:
145+ if not runner.verify_precision(hidden, weights):
146+ raise AssertionError(f"precision check failed at MaxVio {target:g}")
147+ verify_combine_routes(runner, device)
148+ result = dict(target_maxvio=target, maxvio=realized, sigma=sigma,
149+ routing_sha256=digest, verified=verify)
150+ if not args.verify_only:
151+ result.update(measure_roundtrip(runner, device, args.warmup, args.iters, args.block))
152+ results.append(result)
153+ if rank == 0:
154+ print({key: value for key, value in result.items() if key != "per_rank_samples_us"}, flush=True)
155+ finally:
156+ if ShmemRuntime.is_initialized():
157+ ShmemRuntime.finalize()
158+ if runner is not None:
159+ runner.destroy()
160+ reset_symmetric_descriptors()
161+ if dist.is_initialized():
162+ dist.destroy_process_group()
163+ 
164+ if rank == 0:
165+ by_target = {result["target_maxvio"]: result for result in results}
166+ report = dict(ep=world, S=tokens, H=hidden_size, Hp=hp, K=topk_size, E=experts,
167+ qp_count=2, control_plane=args.control_plane, block=args.block, results=results)
168+ if not args.verify_only and 1 in by_target and 30 in by_target:
169+ growth = (by_target[30]["p50_us"] / by_target[1]["p50_us"] - 1) * 100
170+ report["p50_growth_pct"] = growth
171+ print(f"MaxVio 1 -> 30 roundtrip P50 growth: {growth:.2f}%", flush=True)
172+ args.out.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
173+ 
174+ 
175+if __name__ == "__main__":
176+ main()
@@ -65,10 +65,12 @@ import torch_npu
65import torch.distributed as dist65import torch.distributed as dist
66 66 
67from _bench_common import (67from _bench_common import (
68+ add_dedup_mode_arg,
68 add_engine_args,69 add_engine_args,
69 apply_engine,70 apply_engine,
70 setup,71 setup,
71 time_kernel,72 time_kernel,
73+ validate_dedup_mode,
72)74)
73from _bench_common import generate_topk_routing # re-export75from _bench_common import generate_topk_routing # re-export
74from _verify_reference import (76from _verify_reference import (
@@ -139,7 +141,8 @@ _HIDDEN_FP_RTOL = 1e-3
139 141 
140def _report_ok(label, ok, rank, group, dev):142def _report_ok(label, ok, rank, group, dev):
141 """All-reduce the pass flag (MIN) and print the verdict on rank 0."""143 """All-reduce the pass flag (MIN) and print the verdict on rank 0."""
142- t = torch.tensor([1 if ok else 0], dtype=torch.int32, device=dev)144+ device = 'cpu' if dist.get_backend(group) == 'gloo' else dev
145+ t = torch.tensor([1 if ok else 0], dtype=torch.int32, device=device)
143 dist.all_reduce(t, op=dist.ReduceOp.MIN, group=group)146 dist.all_reduce(t, op=dist.ReduceOp.MIN, group=group)
144 passed = int(t.item()) == 1147 passed = int(t.item()) == 1
145 if rank == 0:148 if rank == 0:
@@ -213,7 +216,7 @@ class MoonEPRunner:
213 216 
214 def __init__(self, group, R, S, K, E, H, num_sms, local_rank, hp=2048,217 def __init__(self, group, R, S, K, E, H, num_sms, local_rank, hp=2048,
215 use_udma=False, pf_overlap=False, verify=False,218 use_udma=False, pf_overlap=False, verify=False,
216- verify_stages=None, verify_trace=False):219+ verify_stages=None, verify_trace=False, dedup_mode="rank"):
217 if pf_overlap and not _PREFETCH_HAS_RANK_BARRIERS:220 if pf_overlap and not _PREFETCH_HAS_RANK_BARRIERS:
218 raise RuntimeError(221 raise RuntimeError(
219 '--pf-overlap requires launch_prefetch rank_barriers support')222 '--pf-overlap requires launch_prefetch rank_barriers support')
@@ -240,8 +243,10 @@ class MoonEPRunner:
240 self.pf_overlap = pf_overlap243 self.pf_overlap = pf_overlap
241 self.pf_stream = torch.npu.Stream() if pf_overlap else None244 self.pf_stream = torch.npu.Stream() if pf_overlap else None
242 self.buffer = Buffer(S, H, K, E, R, num_sms=num_sms, group=group,245 self.buffer = Buffer(S, H, K, E, R, num_sms=num_sms, group=group,
243- use_udma=use_udma, explicitly_destroy=True)246+ use_udma=use_udma, dedup_mode=dedup_mode,
247+ explicitly_destroy=True)
244 self.ctx = self.buffer._require_ctx()248 self.ctx = self.buffer._require_ctx()
249+ self.stripe_rank_placement = bool(self.ctx['_dispatch_use_udma'])
245 # Pre-allocate the plan + outputs once (test_planning.py pattern): the250 # Pre-allocate the plan + outputs once (test_planning.py pattern): the
246 # timed ops reuse these instead of allocating per call.251 # timed ops reuse these instead of allocating per call.
247 self.plan, self.cu_seqlens = allocate_planning_outputs(self.ctx)252 self.plan, self.cu_seqlens = allocate_planning_outputs(self.ctx)
@@ -473,6 +478,8 @@ class MoonEPRunner:
473 478 
474 def _all_gather_stack(self, tensor):479 def _all_gather_stack(self, tensor):
475 """Collect this rank's tensor from every rank -> host ``[R, *shape]``."""480 """Collect this rank's tensor from every rank -> host ``[R, *shape]``."""
481+ if dist.get_backend(self.group) == 'gloo':
482+ tensor = tensor.cpu()
476 parts = [torch.empty_like(tensor) for _ in range(self.R)]483 parts = [torch.empty_like(tensor) for _ in range(self.R)]
477 dist.all_gather(parts, tensor.contiguous(), group=self.group)484 dist.all_gather(parts, tensor.contiguous(), group=self.group)
478 return torch.stack(parts).cpu()485 return torch.stack(parts).cpu()
@@ -513,7 +520,8 @@ class MoonEPRunner:
513 ])520 ])
514 try:521 try:
515 exp = plan_expectation(topk_all, tpe_from_topk, rank=self.rank,522 exp = plan_expectation(topk_all, tpe_from_topk, rank=self.rank,
516- NvS=NvS)523+ NvS=NvS, dedup_mode=self.buffer.dedup_mode,
524+ stripe_rank_placement=self.stripe_rank_placement)
517 except Exception as exc: # local reference model; deterministic per rank525 except Exception as exc: # local reference model; deterministic per rank
518 return _report_ok(f'plan (model error: {exc!r})', False,526 return _report_ok(f'plan (model error: {exc!r})', False,
519 self.rank, self.group, dev)527 self.rank, self.group, dev)
@@ -543,7 +551,7 @@ class MoonEPRunner:
543 551 
544 dedup_pairs_plan, dedup_counts_plan, dedup_errors = plan_dedup_pairs(552 dedup_pairs_plan, dedup_counts_plan, dedup_errors = plan_dedup_pairs(
545 self.plan.dup_groups.cpu(), self.plan.dup_loffs.cpu(),553 self.plan.dup_groups.cpu(), self.plan.dup_loffs.cpu(),
546- self.plan.dup_counts.cpu(), NvS)554+ self.plan.dup_counts.cpu(), NvS, R=R, dedup_mode=self.buffer.dedup_mode)
547 555 
548 checks = {556 checks = {
549 'routing': torch.equal(tpe_all.to(torch.int64), tpe_from_topk),557 'routing': torch.equal(tpe_all.to(torch.int64), tpe_from_topk),
@@ -554,7 +562,7 @@ class MoonEPRunner:
554 'prefetch': torch.equal(etc_all,562 'prefetch': torch.equal(etc_all,
555 exp.experts_to_copy.expand_as(etc_all)),563 exp.experts_to_copy.expand_as(etc_all)),
556 'slots': slots_ok,564 'slots': slots_ok,
557- 'dedup': (not dedup_errors and dedup_counts_plan == exp.dedup_counts565+ 'dedup': (not dedup_errors and torch.equal(dedup_counts_plan, exp.dedup_counts)
558 and torch.equal(dedup_pairs_plan, exp.dedup_pairs)),566 and torch.equal(dedup_pairs_plan, exp.dedup_pairs)),
559 }567 }
560 ok = all(checks.values())568 ok = all(checks.values())
@@ -783,6 +791,7 @@ class MoonEPRunner:
783def main():791def main():
784 ap = argparse.ArgumentParser(description=__doc__)792 ap = argparse.ArgumentParser(description=__doc__)
785 add_engine_args(ap)793 add_engine_args(ap)
794+ add_dedup_mode_arg(ap)
786 ap.add_argument('--libs', nargs='+', default=['moonep'], choices=['moonep'],795 ap.add_argument('--libs', nargs='+', default=['moonep'], choices=['moonep'],
787 help='Libraries to benchmark (Ascend: only moonep).')796 help='Libraries to benchmark (Ascend: only moonep).')
788 ap.add_argument('--out', default='bench_vs_results.csv',797 ap.add_argument('--out', default='bench_vs_results.csv',
@@ -832,6 +841,7 @@ def main():
832 rank, world_size, local_rank = setup()841 rank, world_size, local_rank = setup()
833 local_rank = local_device_index(local_rank)842 local_rank = local_device_index(local_rank)
834 use_udma = apply_engine(args.engine)843 use_udma = apply_engine(args.engine)
844+ validate_dedup_mode(args.dedup_mode, use_udma, world_size)
835 R = world_size845 R = world_size
836 group = dist.group.WORLD846 group = dist.group.WORLD
837 dev = f"npu:{local_rank}"847 dev = f"npu:{local_rank}"
@@ -855,7 +865,7 @@ def main():
855 hp=args.hp, use_udma=use_udma,865 hp=args.hp, use_udma=use_udma,
856 pf_overlap=args.pf_overlap, verify=args.verify,866 pf_overlap=args.pf_overlap, verify=args.verify,
857 verify_stages=args.verify_stages.split(','),867 verify_stages=args.verify_stages.split(','),
858- verify_trace=args.verify_trace)868+ verify_trace=args.verify_trace, dedup_mode=args.dedup_mode)
859 if not ShmemRuntime.is_initialized():869 if not ShmemRuntime.is_initialized():
860 if args.ip_port is not None or multi_node:870 if args.ip_port is not None or multi_node:
861 # Multi-node: ip_port/DEFAULT bootstrap; when ip_port is omitted it871 # Multi-node: ip_port/DEFAULT bootstrap; when ip_port is omitted it
@@ -130,10 +130,12 @@ import torch_npu
130import torch.distributed as dist130import torch.distributed as dist
131 131 
132from _bench_common import (132from _bench_common import (
133+ add_dedup_mode_arg,
133 add_engine_args,134 add_engine_args,
134 apply_engine,135 apply_engine,
135 setup,136 setup,
136 time_kernel,137 time_kernel,
138+ validate_dedup_mode,
137)139)
138from _bench_common import generate_topk_routing # re-export140from _bench_common import generate_topk_routing # re-export
139 141 
@@ -221,7 +223,7 @@ class MoonEPRunner:
221 NAME = 'moonep'223 NAME = 'moonep'
222 224 
223 def __init__(self, group, R, S, K, E, H, num_sms, local_rank,225 def __init__(self, group, R, S, K, E, H, num_sms, local_rank,
224- use_udma=False, hp=3072):226+ use_udma=False, hp=3072, dedup_mode="rank"):
225 self.group = group227 self.group = group
226 self.num_sms = num_sms228 self.num_sms = num_sms
227 self.rank = dist.get_rank(group)229 self.rank = dist.get_rank(group)
@@ -230,7 +232,8 @@ class MoonEPRunner:
230 self.use_udma = use_udma232 self.use_udma = use_udma
231 self.hp = hp233 self.hp = hp
232 self.buffer = Buffer(S, H, K, E, R, num_sms=num_sms, group=group,234 self.buffer = Buffer(S, H, K, E, R, num_sms=num_sms, group=group,
233- use_udma=use_udma, explicitly_destroy=True)235+ use_udma=use_udma, dedup_mode=dedup_mode,
236+ explicitly_destroy=True)
234 self.ctx = self.buffer._require_ctx()237 self.ctx = self.buffer._require_ctx()
235 # Pre-allocate the plan + outputs once (test_planning.py pattern): the238 # Pre-allocate the plan + outputs once (test_planning.py pattern): the
236 # timed ops reuse these instead of allocating per call.239 # timed ops reuse these instead of allocating per call.
@@ -605,6 +608,7 @@ RUNNERS = {
605def main():608def main():
606 ap = argparse.ArgumentParser(description=__doc__)609 ap = argparse.ArgumentParser(description=__doc__)
607 add_engine_args(ap)610 add_engine_args(ap)
611+ add_dedup_mode_arg(ap)
608 ap.add_argument('--libs', nargs='+', default=['moonep', 'all2all'],612 ap.add_argument('--libs', nargs='+', default=['moonep', 'all2all'],
609 choices=list(RUNNERS),613 choices=list(RUNNERS),
610 help='Libraries to benchmark (default: both). "all2all" '614 help='Libraries to benchmark (default: both). "all2all" '
@@ -650,6 +654,7 @@ def main():
650 rank, world_size, local_rank = setup()654 rank, world_size, local_rank = setup()
651 local_rank = local_device_index(local_rank)655 local_rank = local_device_index(local_rank)
652 use_udma = apply_engine(args.engine)656 use_udma = apply_engine(args.engine)
657+ validate_dedup_mode(args.dedup_mode, use_udma, world_size)
653 R = world_size658 R = world_size
654 group = dist.group.WORLD659 group = dist.group.WORLD
655 dev = f"npu:{local_rank}"660 dev = f"npu:{local_rank}"
@@ -672,7 +677,7 @@ def main():
672 if 'moonep' in args.libs:677 if 'moonep' in args.libs:
673 runners['moonep'] = MoonEPRunner(group, R, S, K, E, H, args.num_sms,678 runners['moonep'] = MoonEPRunner(group, R, S, K, E, H, args.num_sms,
674 local_rank, use_udma=use_udma,679 local_rank, use_udma=use_udma,
675- hp=args.hp)680+ hp=args.hp, dedup_mode=args.dedup_mode)
676 if 'all2all' in args.libs:681 if 'all2all' in args.libs:
677 runners['all2all'] = All2AllRunner(group, R, S, K, E, H,682 runners['all2all'] = All2AllRunner(group, R, S, K, E, H,
678 args.num_sms, local_rank)683 args.num_sms, local_rank)
@@ -90,6 +90,7 @@ def comm_context(ctx, buffers):
90 if not isinstance(buffers, CommBuffers):90 if not isinstance(buffers, CommBuffers):
91 raise TypeError("buffers must be CommBuffers")91 raise TypeError("buffers must be CommBuffers")
92 local = dict(ctx)92 local = dict(ctx)
93+ local['_comm_owner_ctx'] = ctx
93 local['hidden_buf'] = local['hidden_buf_local'] = buffers.hidden94 local['hidden_buf'] = local['hidden_buf_local'] = buffers.hidden
94 local['weights_buf'] = local['weights_buf_local'] = buffers.route95 local['weights_buf'] = local['weights_buf_local'] = buffers.route
95 return local96 return local
@@ -8,10 +8,91 @@ and K-sum into one launch.
8 8 
9from __future__ import annotations9from __future__ import annotations
10 10 
11-import torch11+from typing import TYPE_CHECKING
12 12 
13-from .launchers import _env_use_udma13+# Workspace sizing remains usable without loading the NPU runtime.
14-from .planning import MoonEPCommPlan14+# Runtime dependencies are imported only by launch and input-validation helpers.
15+if TYPE_CHECKING:
16+ import torch
17+ from .planning import MoonEPCommPlan
18+ 
19+ 
20+# ---- Workspace ABI and core roles (mirrors kernels/types.h) ----
21+# Combine only; does not change num_sms or launch core counts for dispatch/planning.
22+COMBINE_PUT_CORES = 64
23+COMBINE_PUT_SOURCE_LANES = 16
24+COMBINE_RING_STREAMS = 8
25+COMBINE_RING_DEPTH = 4
26+COMBINE_RING_GROUPS_PER_PAGE = 64
27+COMBINE_RING_PLAN_ABI = 6
28+ 
29+ 
30+def combine_put_roles(ranks: int) -> list:
31+ """Core ownership in the production kernel: relay/reduce/sender/final-only."""
32+ if ranks >= 128:
33+ return [0] * 8 + [1] * 16 + [2] * 32 + [3] * 8
34+ return [0] * 8 + [1] * 32 + [2] * 24
35+ 
36+ 
37+def combine_ring_geometry(n: int, h: int, ranks: int, topk: int = 16) -> dict:
38+ """Bounded relay geometry; no user-provided row-capacity override.
39+ 
40+ Each page holds up to 64 * topk contributor rows, packed as complete groups.
41+ Small groups can allow more than 64 groups to fit in one page.
42+ Planning may borrow the same phase arena before any payload becomes live.
43+ Reserve for either dedup mode because a Buffer may prepare both kinds.
44+ """
45+ if min(n, h, ranks, topk) <= 0 or topk > 16:
46+ raise ValueError("n/h/ranks must be positive and topk must be in [1,16]")
47+ align = lambda value: (value + 511) & ~511
48+ page_rows = COMBINE_RING_GROUPS_PER_PAGE * topk
49+ input_rows = COMBINE_RING_STREAMS * COMBINE_RING_DEPTH * page_rows
50+ input_bytes = align(input_rows * h * 2)
51+ result_bytes = align(n * h * 2)
52+ staging = max((ranks * n * (32 + 8 * width)
53+ for width in (1, 8)
54+ if ranks <= 128 and ranks * (32 + 8 * width) <= h * 16),
55+ default=0)
56+ return dict(page_rows=page_rows, input_rows=input_rows,
57+ input_bytes=input_bytes, result_bytes=result_bytes,
58+ planning_stage_bytes=staging,
59+ phase_bytes=align(max(staging, input_bytes + result_bytes)),
60+ max_pages=(n + 63) // 64 + ranks)
61+ 
62+ 
63+def combine_put_workspace_bytes(n: int, h: int, ranks: int, topk: int = 16) -> int:
64+ # Total symmetric workspace bytes per rank; N=n=S*K, H=h, R=ranks.
65+ # Matches the order and capacities in MakeCombinePutLayout in
66+ # include/ascend_moonep/kernels/types.h; reserves maximum slots regardless of deduplication or weights.
67+ ring = combine_ring_geometry(n, h, ranks, topk)
68+ align = lambda value: (value + 511) & ~511
69+ batches = (n + 63) // 64
70+ return (
71+# Final return data plus phase-exclusive Planning / input-ring+result arena.
72+ align(n * h * 2) + ring['phase_bytes']
73+ # Float weights[N]; N entries each for reverse/reverse_send/final_map/group_of_loff/tx_rows.
74+ + align(n * 4) + 5 * align(n * 64)
75+ # R entries each for source_counts/counts_send; 8*N each for contributor/relay_send/relay_publish.
76+ + 2 * align(ranks * 64) + 2 * align(8 * n * 64)
77+ + max(align(8 * n * 64), align(ranks * 64) + align(ring['max_pages'] * 64))
78+ # Two reserved count tables; source/reduce/final ready have 8*R/R*B/2*R slots, respectively.
79+ + 1024 + (8 * ranks + ranks * batches + 2 * ranks) * 512
80+ # R weight_ready slots and 64 core-private magic source slots; 512 bytes per slot, first 8 used.
81+ + ranks * 512 + COMBINE_PUT_CORES * 512
82+ + 2 * align(8 * ranks * 64) + ranks * 512
83+ # One rank-local final gate: core 0 fans in final_ready then broadcasts it.
84+ + 512
85+ # N independent 128-byte final descriptors; N/K are active, N covers K=1.
86+ + align(n * 128)
87+ # Per-stream epoch, producer-ready, credits, reducer-done, stable
88+ # PUT-source tickets, and persistent logical-page result readiness.
89+ + (COMBINE_RING_STREAMS
90+ + COMBINE_RING_STREAMS * COMBINE_RING_DEPTH * 8
91+ + COMBINE_RING_STREAMS * COMBINE_RING_DEPTH
92+ + COMBINE_RING_STREAMS * COMBINE_RING_DEPTH * 4
93+ + 8 * COMBINE_RING_STREAMS * COMBINE_RING_DEPTH
94+ + ring['max_pages']) * 512
95+ )
15 96 
16 97 
17def _check_tensor(98def _check_tensor(
@@ -35,10 +116,17 @@ def _check_combine_inputs(
35 plan: MoonEPCommPlan,116 plan: MoonEPCommPlan,
36 output_sk: torch.Tensor | None,117 output_sk: torch.Tensor | None,
37) -> None:118) -> None:
119+ import torch
120+ from .launchers import _env_use_udma
121+ from .planning import MoonEPCommPlan
122+ 
38 if not isinstance(plan, MoonEPCommPlan):123 if not isinstance(plan, MoonEPCommPlan):
39 raise TypeError("plan must be a MoonEPCommPlan")124 raise TypeError("plan must be a MoonEPCommPlan")
40 125 
41 use_udma = _env_use_udma("combine")126 use_udma = _env_use_udma("combine")
127+ # Server dedup consumes the Buffer's symmetric PUT workspace; the legacy
128+ # rank-level kernel keeps its own rank-local gather workspace in the op.
129+ server_dedup = plan.dedup_mode == "server"
42 required_ctx_keys = [130 required_ctx_keys = [
43 "rank", "R", "E", "B", "S", "H", "K", "NvS", "kernels",131 "rank", "R", "E", "B", "S", "H", "K", "NvS", "kernels",
44 ]132 ]
@@ -46,6 +134,8 @@ def _check_combine_inputs(
46 required_ctx_keys.extend((134 required_ctx_keys.extend((
47 "hidden_buf_local", "weights_buf_local", "combine_sync_buffer",135 "hidden_buf_local", "weights_buf_local", "combine_sync_buffer",
48 ))136 ))
137+ if server_dedup:
138+ required_ctx_keys.append("combine_workspace")
49 else:139 else:
50 required_ctx_keys.extend(("hidden_buf", "weights_buf"))140 required_ctx_keys.extend(("hidden_buf", "weights_buf"))
51 missing = [key for key in required_ctx_keys if key not in ctx]141 missing = [key for key in required_ctx_keys if key not in ctx]
@@ -67,12 +157,10 @@ def _check_combine_inputs(
67 if use_udma:157 if use_udma:
68 if H % 8 != 0:158 if H % 8 != 0:
69 raise ValueError("UDMA combine requires H to be a multiple of 8")159 raise ValueError("UDMA combine requires H to be a multiple of 8")
70- # Four bf16 rows plus fp32 accumulator/temp use 16 bytes per hidden160+ # Phase 1/3 tile large rows through UB; cap one bf16 token row at 8 MiB.
71- # element in the UDMA kernel's 128 KiB full-row double buffer.161+ if H * torch.bfloat16.itemsize > 8 * 1024 * 1024:
72- if H * 16 > 128 * 1024:
73 raise ValueError(162 raise ValueError(
74- "UDMA combine requires H<=8192 so its full-row double "163+ "UDMA combine requires one bf16 token row to be <=8 MiB"
75- "buffer fits in 128 KiB of UB"
76 )164 )
77 else:165 else:
78 if H % 16 != 0:166 if H % 16 != 0:
@@ -119,14 +207,14 @@ def _check_combine_inputs(
119 _check_tensor(207 _check_tensor(
120 plan.dup_loffs,208 plan.dup_loffs,
121 "plan.dup_loffs",209 "plan.dup_loffs",
122- (NvS,),210+ (8 * NvS if plan.dup_counts.numel() == plan.R + 2 else NvS,),
123 torch.int32,211 torch.int32,
124 output_sh.device,212 output_sh.device,
125 )213 )
126 _check_tensor(214 _check_tensor(
127 plan.dup_counts,215 plan.dup_counts,
128 "plan.dup_counts",216 "plan.dup_counts",
129- (2,),217+ (plan.R + 2 if plan.dup_counts.numel() == plan.R + 2 else 2,),
130 torch.int32,218 torch.int32,
131 output_sh.device,219 output_sh.device,
132 )220 )
@@ -150,6 +238,14 @@ def _check_combine_inputs(
150 )238 )
151 239 
152 if use_udma:240 if use_udma:
241+ if server_dedup:
242+ _check_tensor(
243+ ctx["combine_workspace"],
244+ "ctx.combine_workspace",
245+ (combine_put_workspace_bytes(NvS, H, plan.R, plan.K),),
246+ torch.uint8,
247+ output_sh.device,
248+ )
153 sync_buffer = ctx["combine_sync_buffer"]249 sync_buffer = ctx["combine_sync_buffer"]
154 if sync_buffer.dtype != torch.uint8 or not sync_buffer.is_contiguous():250 if sync_buffer.dtype != torch.uint8 or not sync_buffer.is_contiguous():
155 raise ValueError(251 raise ValueError(
@@ -188,3 +284,33 @@ def launch_combine(
188 plan,284 plan,
189 output_sk=output_sk,285 output_sk=output_sk,
190 )286 )
287+ 
288+ 
289+# ---- Launch an immutable execution plan produced by planning.py ----
290+def launch_combine_prepared(ctx, output_sh, plan, execution_plan, output_sk=None):
291+ import torch
292+ import torch_npu
293+ from .planning import CombineExecutionPlan, _routes, _key
294+ 
295+ if not isinstance(execution_plan, CombineExecutionPlan):
296+ raise TypeError('execution_plan must be returned by prepare_combine_plan')
297+ from .launchers import _env_use_udma
298+ if not _env_use_udma('combine'):
299+ raise ValueError('execution plans require UDMA combine')
300+ execution_plan.validate(ctx, plan)
301+ stream = torch_npu.npu.current_stream()
302+ stream.wait_event(execution_plan.ready)
303+ weights = ctx['weights_buf_local'].view(torch.float32) if output_sk is not None else None
304+ torch.classes.AscendMoonEP.CombineUrma().compute_prepared(
305+ ctx['hidden_buf_local'], weights, ctx['combine_sync_buffer'], ctx['combine_workspace'],
306+ *_routes(plan), output_sh, output_sk, execution_plan.storage, *_key(ctx))
307+ for tensor in (execution_plan.storage, *_routes(plan), ctx['hidden_buf_local'], weights,
308+ ctx['combine_workspace'], ctx['combine_sync_buffer'], output_sh,
309+ output_sk):
310+ if tensor is not None:
311+ tensor.record_stream(stream)
312+ # Also orders subsequent reuse on another stream. Overlapping calls sharing
313+ # the Buffer workspace remain unsupported, just like legacy combine.
314+ last_use = torch_npu.npu.Event()
315+ last_use.record(stream)
316+ execution_plan.ready = last_use
@@ -10,7 +10,7 @@ from __future__ import annotations
10 10 
11import torch11import torch
12 12 
13-from .planning import MoonEPCommPlan13+from .planning import MoonEPCommPlan, RANKS_PER_SERVER
14 14 
15 15 
16def _check_tensor(16def _check_tensor(
@@ -95,17 +95,25 @@ def _check_dispatch_inputs(
95 torch.int32,95 torch.int32,
96 hidden_sh.device,96 hidden_sh.device,
97 )97 )
98+ # The source prefix in counts marks the server protocol; rank plans keep their original capacity.
99+ server_dedup = plan.dedup_mode == "server"
100+ if server_dedup and R % RANKS_PER_SERVER != 0:
101+ raise ValueError("server dedup requires R divisible by 8")
102+ if server_dedup and not ctx.get("_dispatch_use_udma", False):
103+ raise ValueError("server dedup requires UDMA dispatch")
104+ dup_capacity = RANKS_PER_SERVER * NvS if server_dedup else NvS
105+ count_size = R + 2 if server_dedup else 2
98 _check_tensor(106 _check_tensor(
99 plan.dup_loffs,107 plan.dup_loffs,
100 "plan.dup_loffs",108 "plan.dup_loffs",
101- (NvS,),109+ (dup_capacity,),
102 torch.int32,110 torch.int32,
103 hidden_sh.device,111 hidden_sh.device,
104 )112 )
105 _check_tensor(113 _check_tensor(
106 plan.dup_counts,114 plan.dup_counts,
107 "plan.dup_counts",115 "plan.dup_counts",
108- (2,),116+ (count_size,),
109 torch.int32,117 torch.int32,
110 hidden_sh.device,118 hidden_sh.device,
111 )119 )
@@ -44,6 +44,8 @@ def planning_workspace_sizes(
44 num_max_tokens_per_rank: int,44 num_max_tokens_per_rank: int,
45 world_size: int,45 world_size: int,
46 core_num: int,46 core_num: int,
47+ *,
48+ server_dedup: bool = False,
47) -> tuple[int, int]:49) -> tuple[int, int]:
48 global _PLANNING50 global _PLANNING
49 if _PLANNING is None:51 if _PLANNING is None:
@@ -55,6 +57,7 @@ def planning_workspace_sizes(
55 num_experts,57 num_experts,
56 world_size,58 world_size,
57 core_num,59 core_num,
60+ server_dedup,
58 )61 )
59 )62 )
60 symmetric_bytes = int(63 symmetric_bytes = int(
@@ -62,6 +65,7 @@ def planning_workspace_sizes(
62 num_experts,65 num_experts,
63 num_max_tokens_per_rank,66 num_max_tokens_per_rank,
64 world_size,67 world_size,
68+ server_dedup,
65 )69 )
66 )70 )
67 return local_elements, symmetric_bytes71 return local_elements, symmetric_bytes
@@ -86,11 +90,23 @@ def launch_planning_op(
86 core_num: int,90 core_num: int,
87 rank: int,91 rank: int,
88 world_size: int,92 world_size: int,
89-) -> None:93+ server_dedup: bool = False,
94+ combine_workspace: torch.Tensor | None = None,
95+ hidden_size: int = 0,
96+ *,
97+ use_udma: bool = False,
98+) -> torch.Tensor | None:
99+ """Launch planning.
100+ 
101+ ``server_dedup`` selects the kernel family: ``True`` runs the server-level
102+ dedup planner (which can also emit the fused combine execution plan when
103+ ``combine_workspace`` is given), ``False`` runs the legacy rank-level
104+ planner and never produces a combine plan.
105+ """
90 global _PLANNING106 global _PLANNING
91 if _PLANNING is None:107 if _PLANNING is None:
92 _PLANNING = torch.classes.AscendMoonEP.Planning()108 _PLANNING = torch.classes.AscendMoonEP.Planning()
93- _PLANNING.compute(109+ args = (
94 topk_idx,110 topk_idx,
95 dst,111 dst,
96 cu_seqlens,112 cu_seqlens,
@@ -109,8 +125,13 @@ def launch_planning_op(
109 core_num,125 core_num,
110 rank,126 rank,
111 world_size,127 world_size,
112- _env_use_udma('planning'),128+ use_udma,
129+ bool(server_dedup),
113 )130 )
131+ if combine_workspace is not None:
132+ return _PLANNING.compute_fused(*args, combine_workspace, hidden_size)
133+ _PLANNING.compute(*args)
134+ return None
114 135 
115 136 
116def launch_dispatch_op(137def launch_dispatch_op(
@@ -129,6 +150,7 @@ def launch_dispatch_op(
129 world_size: int,150 world_size: int,
130 rank: int,151 rank: int,
131 num_sms: int = 32,152 num_sms: int = 32,
153+ server_dedup: bool = False,
132) -> None:154) -> None:
133 """Launch dispatch; num_sms controls only the MTE AIV launch width."""155 """Launch dispatch; num_sms controls only the MTE AIV launch width."""
134 global _DISPATCH156 global _DISPATCH
@@ -152,9 +174,7 @@ def launch_dispatch_op(
152 rank,174 rank,
153 use_udma,175 use_udma,
154 )176 )
155- if not use_udma:177+ _DISPATCH.compute(*args, num_sms, bool(server_dedup))
156- args += (num_sms,)
157- _DISPATCH.compute(*args)
158 178 
159 179 
160def launch_dispatch_profile_op(180def launch_dispatch_profile_op(
@@ -173,6 +193,7 @@ def launch_dispatch_profile_op(
173 num_topk: int,193 num_topk: int,
174 world_size: int,194 world_size: int,
175 rank: int,195 rank: int,
196+ server_dedup: bool = False,
176) -> None:197) -> None:
177 global _DISPATCH198 global _DISPATCH
178 if _DISPATCH is None:199 if _DISPATCH is None:
@@ -194,6 +215,7 @@ def launch_dispatch_profile_op(
194 world_size,215 world_size,
195 rank,216 rank,
196 _env_use_udma('dispatch'),217 _env_use_udma('dispatch'),
218+ bool(server_dedup),
197 )219 )
198 220 
199 221 
@@ -327,7 +349,6 @@ def launch_combine(
327def launch_inter_rank_sync(ctx: dict) -> None:349def launch_inter_rank_sync(ctx: dict) -> None:
328 """Ascend replacement for the CuTe DSL rank sync kernel: a host-side350 """Ascend replacement for the CuTe DSL rank sync kernel: a host-side
329 cross-rank signal barrier on the current stream."""351 cross-rank signal barrier on the current stream."""
330- from ._common import cross_rank_barrier
331 352 
332 cross_rank_barrier(ctx, torch_npu.npu.current_stream().npu_stream)353 cross_rank_barrier(ctx, torch_npu.npu.current_stream().npu_stream)
333 return None354 return None
@@ -160,5 +160,27 @@ ascend_moonep_add_kernel_library(
160 ${ASCEND_MOONEP_ARCH_DEFINITIONS}160 ${ASCEND_MOONEP_ARCH_DEFINITIONS}
161)161)
162 162 
163+if(ASCEND_MOONEP_UDMA)
164+ # Keep the rank and server implementations in separate unity builds.
165+ # Their device kernels use overlapping file-local helper names.
166+ ascend_moonep_add_kernel_library(
167+ ascend_moonep_kernels_server_dedup
168+ SOURCES
169+ kernels/moonep_combine_udma_server_dedup.cpp
170+ kernels/moonep_dispatch_udma_server_dedup.cpp
171+ kernels/planning_server_dedup.cpp
172+ INCLUDES
173+ include
174+ kernels
175+ ../3rdparty/catlass/include
176+ ../3rdparty/catlass
177+ COMPILE_DEFINITIONS
178+ CATLASS_ARCH=${ASCEND_MOONEP_CATLASS_ARCH}
179+ ${ASCEND_MOONEP_ARCH_DEFINITIONS}
180+ )
181+ 
182+ message(STATUS "ascend-moonep server-dedup kernel library: ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/libascend_moonep_kernels_server_dedup.so")
183+endif()
184+ 
163message(STATUS "ascend-moonep kernel library: ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/libascend_moonep_kernels.so")185message(STATUS "ascend-moonep kernel library: ${CMAKE_LIBRARY_OUTPUT_DIRECTORY}/libascend_moonep_kernels.so")
164message(STATUS "SHMEM installation: ${SHMEM_HOME_PATH}")186message(STATUS "SHMEM installation: ${SHMEM_HOME_PATH}")
@@ -79,7 +79,7 @@ void LaunchMoonEPDispatchKernel(
79 const_cast<ascend_moonep::MoonEPDispatchTilingData*>(&tiling)));79 const_cast<ascend_moonep::MoonEPDispatchTilingData*>(&tiling)));
80}80}
81 81 
82-void LaunchMoonEPDispatchUdmaKernel(82+void LaunchMoonEPDispatchUdmaLegacyKernel(
83 torch::Tensor hidden_sh,83 torch::Tensor hidden_sh,
84 torch::Tensor route_weights,84 torch::Tensor route_weights,
85 torch::Tensor dst,85 torch::Tensor dst,
@@ -117,7 +117,7 @@ void LaunchMoonEPDispatchUdmaKernel(
117#endif117#endif
118}118}
119 119 
120-void LaunchMoonEPDispatchUdmaProfileKernel(120+void LaunchMoonEPDispatchUdmaLegacyProfileKernel(
121 torch::Tensor hidden_sh,121 torch::Tensor hidden_sh,
122 torch::Tensor route_weights,122 torch::Tensor route_weights,
123 torch::Tensor dst,123 torch::Tensor dst,
@@ -158,7 +158,81 @@ void LaunchMoonEPDispatchUdmaProfileKernel(
158#endif158#endif
159}159}
160 160 
161-void LaunchPlanningKernel(161+void LaunchMoonEPDispatchUdmaServerDedupKernel(
162+ torch::Tensor hidden_sh,
163+ torch::Tensor route_weights,
164+ torch::Tensor dst,
165+ torch::Tensor dup_groups,
166+ torch::Tensor dup_loffs,
167+ torch::Tensor dup_counts,
168+ torch::Tensor hidden_buf,
169+ torch::Tensor route_weights_buf,
170+ torch::Tensor sync_buffer,
171+ const ascend_moonep::MoonEPDispatchTilingData& tiling,
172+ uint64_t magic) {
173+#if defined(ASCEND_MOONEP_UDMA)
174+ aclrtStream stream = GetCurrentAclStream();
175+ moonep_dispatch_udma_server_dedup_kernel_do(
176+ stream,
177+ BytePtr(hidden_sh.data_ptr()),
178+ BytePtr(route_weights.data_ptr()),
179+ BytePtr(dst.data_ptr()),
180+ BytePtr(dup_groups.data_ptr()),
181+ BytePtr(dup_loffs.data_ptr()),
182+ BytePtr(dup_counts.data_ptr()),
183+ BytePtr(hidden_buf.data_ptr()),
184+ BytePtr(route_weights_buf.data_ptr()),
185+ BytePtr(sync_buffer.data_ptr()),
186+ reinterpret_cast<uint8_t*>(
187+ const_cast<ascend_moonep::MoonEPDispatchTilingData*>(&tiling)),
188+ magic);
189+#else
190+ (void)hidden_sh; (void)route_weights; (void)dst; (void)dup_groups;
191+ (void)dup_loffs; (void)dup_counts; (void)hidden_buf; (void)route_weights_buf;
192+ (void)sync_buffer; (void)tiling; (void)magic;
193+ TORCH_CHECK(false, "This kernel requires an Ascend950 UDMA build");
194+#endif
195+}
196+ 
197+void LaunchMoonEPDispatchUdmaServerDedupProfileKernel(
198+ torch::Tensor hidden_sh,
199+ torch::Tensor route_weights,
200+ torch::Tensor dst,
201+ torch::Tensor dup_groups,
202+ torch::Tensor dup_loffs,
203+ torch::Tensor dup_counts,
204+ torch::Tensor hidden_buf,
205+ torch::Tensor route_weights_buf,
206+ torch::Tensor sync_buffer,
207+ torch::Tensor profile_cycles,
208+ const ascend_moonep::MoonEPDispatchTilingData& tiling,
209+ uint64_t magic) {
210+#if defined(ASCEND_MOONEP_UDMA)
211+ aclrtStream stream = GetCurrentAclStream();
212+ moonep_dispatch_udma_server_dedup_profile_kernel_do(
213+ stream,
214+ BytePtr(hidden_sh.data_ptr()),
215+ BytePtr(route_weights.data_ptr()),
216+ BytePtr(dst.data_ptr()),
217+ BytePtr(dup_groups.data_ptr()),
218+ BytePtr(dup_loffs.data_ptr()),
219+ BytePtr(dup_counts.data_ptr()),
220+ BytePtr(hidden_buf.data_ptr()),
221+ BytePtr(route_weights_buf.data_ptr()),
222+ BytePtr(sync_buffer.data_ptr()),
223+ BytePtr(profile_cycles.data_ptr()),
224+ reinterpret_cast<uint8_t*>(
225+ const_cast<ascend_moonep::MoonEPDispatchTilingData*>(&tiling)),
226+ magic);
227+#else
228+ (void)hidden_sh; (void)route_weights; (void)dst; (void)dup_groups;
229+ (void)dup_loffs; (void)dup_counts; (void)hidden_buf; (void)route_weights_buf;
230+ (void)sync_buffer; (void)profile_cycles; (void)tiling; (void)magic;
231+ TORCH_CHECK(false, "This kernel requires an Ascend950 UDMA build");
232+#endif
233+}
234+ 
235+void LaunchPlanningLegacyKernel(
162 torch::Tensor topk_idx,236 torch::Tensor topk_idx,
163 torch::Tensor dst,237 torch::Tensor dst,
164 torch::Tensor cu_seqlens,238 torch::Tensor cu_seqlens,
@@ -207,49 +281,126 @@ void LaunchPlanningKernel(
207 ffts_addr);281 ffts_addr);
208}282}
209 283 
210-void LaunchMoonEPUdmaCombineKernel(284+void LaunchPlanningServerDedupKernel(
211- torch::Tensor hidden_nvsh,285+ torch::Tensor topk_idx,
212- torch::Tensor route_weights_nvs,
213- torch::Tensor sync_buffer,
214 torch::Tensor dst,286 torch::Tensor dst,
287+ torch::Tensor cu_seqlens,
288+ torch::Tensor experts_to_copy,
215 torch::Tensor dup_groups,289 torch::Tensor dup_groups,
216 torch::Tensor dup_loffs,290 torch::Tensor dup_loffs,
217 torch::Tensor dup_counts,291 torch::Tensor dup_counts,
218- torch::Tensor output_sh,292+ torch::Tensor tpe_all,
219- torch::Tensor output_sk,293+ torch::Tensor tpe_prefix,
220- void* bandwidth_scratch,294+ torch::Tensor balance,
221- const ascend_moonep::MoonEPUdmaCombineTilingData& tiling,295+ torch::Tensor z_tensor,
222- void* local_workspace,296+ torch::Tensor alloc_tensor,
223- uint64_t invocation_magic) {297+ torch::Tensor alloc_cumsum,
298+ torch::Tensor expert_offsets,
299+ torch::Tensor core_expert_counts,
300+ torch::Tensor dup_workspace,
301+ torch::Tensor dup_key_workspace,
302+ const ascend_moonep::PlanningTilingData& tiling,
303+ void* symmetric_buffer,
304+ uint64_t ffts_addr) {
224#if defined(ASCEND_MOONEP_UDMA)305#if defined(ASCEND_MOONEP_UDMA)
225- TORCH_CHECK(local_workspace != nullptr, "local_workspace must not be null");306+ TORCH_CHECK(symmetric_buffer != nullptr,
226- TORCH_CHECK(bandwidth_scratch != nullptr,307+ "planning symmetric_buffer must not be null");
227- "bandwidth_scratch must not be null");
228- 
229 aclrtStream stream = GetCurrentAclStream();308 aclrtStream stream = GetCurrentAclStream();
230- moonep_udma_combine_kernel_do(309+ planning_server_dedup_kernel_do(
231 stream,310 stream,
232- BytePtr(hidden_nvsh.data_ptr()),311+ BytePtr(topk_idx.data_ptr()),
233- BytePtr(route_weights_nvs.data_ptr()),312+ BytePtr(symmetric_buffer),
234- BytePtr(sync_buffer.data_ptr()),
235 BytePtr(dst.data_ptr()),313 BytePtr(dst.data_ptr()),
314+ BytePtr(cu_seqlens.data_ptr()),
315+ BytePtr(experts_to_copy.data_ptr()),
236 BytePtr(dup_groups.data_ptr()),316 BytePtr(dup_groups.data_ptr()),
237 BytePtr(dup_loffs.data_ptr()),317 BytePtr(dup_loffs.data_ptr()),
238 BytePtr(dup_counts.data_ptr()),318 BytePtr(dup_counts.data_ptr()),
239- BytePtr(output_sh.data_ptr()),319+ BytePtr(tpe_all.data_ptr()),
240- BytePtr(output_sk.data_ptr()),320+ BytePtr(tpe_prefix.data_ptr()),
241- BytePtr(local_workspace),321+ BytePtr(balance.data_ptr()),
242- BytePtr(bandwidth_scratch),322+ BytePtr(z_tensor.data_ptr()),
323+ BytePtr(alloc_tensor.data_ptr()),
324+ BytePtr(alloc_cumsum.data_ptr()),
325+ BytePtr(expert_offsets.data_ptr()),
326+ BytePtr(core_expert_counts.data_ptr()),
327+ BytePtr(dup_workspace.data_ptr()),
328+ BytePtr(dup_key_workspace.data_ptr()),
243 reinterpret_cast<uint8_t*>(329 reinterpret_cast<uint8_t*>(
244- const_cast<ascend_moonep::MoonEPUdmaCombineTilingData*>(&tiling)),330+ const_cast<ascend_moonep::PlanningTilingData*>(&tiling)),
245- invocation_magic);331+ ffts_addr);
246#else332#else
247- (void)hidden_nvsh; (void)route_weights_nvs; (void)sync_buffer; (void)dst;333+ (void)topk_idx; (void)dst; (void)cu_seqlens; (void)experts_to_copy;
248- (void)dup_groups; (void)dup_loffs; (void)dup_counts; (void)output_sh;334+ (void)dup_groups; (void)dup_loffs; (void)dup_counts; (void)tpe_all;
249- (void)output_sk; (void)bandwidth_scratch; (void)tiling;335+ (void)tpe_prefix; (void)balance; (void)z_tensor; (void)alloc_tensor;
250- (void)local_workspace; (void)invocation_magic;336+ (void)alloc_cumsum; (void)expert_offsets; (void)core_expert_counts; (void)dup_workspace;
251- TORCH_CHECK(false,337+ (void)dup_key_workspace; (void)tiling; (void)symmetric_buffer; (void)ffts_addr;
252- "combine UDMA kernel support is not enabled in this build; "338+ TORCH_CHECK(false, "This kernel requires an Ascend950 UDMA build");
253- "A2/A3 do not provide the UDMA combine kernel");339+#endif
340+}
341+ 
342+void LaunchMoonEPUdmaCombineServerDedupKernel(
343+ torch::Tensor hidden, torch::Tensor weights, torch::Tensor dst,
344+ torch::Tensor groups, torch::Tensor dups, torch::Tensor counts,
345+ torch::Tensor out, torch::Tensor outw, torch::Tensor workspace,
346+ torch::Tensor plan,
347+ const ascend_moonep::MoonEPUdmaCombineTilingData& tiling,
348+ uint64_t magic) {
349+#if defined(ASCEND_MOONEP_UDMA)
350+ moonep_udma_combine_server_dedup_kernel_do(
351+ GetCurrentAclStream(), BytePtr(hidden.data_ptr()), BytePtr(weights.data_ptr()),
352+ BytePtr(dst.data_ptr()), BytePtr(groups.data_ptr()), BytePtr(dups.data_ptr()),
353+ BytePtr(counts.data_ptr()), BytePtr(out.data_ptr()), BytePtr(outw.data_ptr()),
354+ BytePtr(workspace.data_ptr()), BytePtr(plan.data_ptr()),
355+ reinterpret_cast<uint8_t*>(const_cast<ascend_moonep::MoonEPUdmaCombineTilingData*>(&tiling)),
356+ magic);
357+#else
358+ (void)hidden; (void)weights; (void)dst; (void)groups;
359+ (void)dups; (void)counts; (void)out; (void)outw;
360+ (void)workspace; (void)plan; (void)tiling; (void)magic;
361+ TORCH_CHECK(false, "This kernel requires an Ascend950 UDMA build");
362+#endif
363+}
364+ 
365+void LaunchMoonEPUdmaCombineLegacyKernel(
366+ torch::Tensor hidden, torch::Tensor weights, torch::Tensor sync_buffer,
367+ torch::Tensor dst, torch::Tensor groups, torch::Tensor dups,
368+ torch::Tensor counts, torch::Tensor out, torch::Tensor outw,
369+ void* bandwidth_scratch, void* local_workspace,
370+ const ascend_moonep::MoonEPUdmaCombineTilingData& tiling,
371+ uint64_t magic) {
372+#if defined(ASCEND_MOONEP_UDMA)
373+ TORCH_CHECK(bandwidth_scratch != nullptr,
374+ "bandwidth_scratch must not be null");
375+ TORCH_CHECK(local_workspace != nullptr, "local_workspace must not be null");
376+ moonep_udma_combine_kernel_do(
377+ GetCurrentAclStream(), BytePtr(hidden.data_ptr()), BytePtr(weights.data_ptr()),
378+ BytePtr(sync_buffer.data_ptr()),
379+ BytePtr(dst.data_ptr()), BytePtr(groups.data_ptr()), BytePtr(dups.data_ptr()),
380+ BytePtr(counts.data_ptr()), BytePtr(out.data_ptr()), BytePtr(outw.data_ptr()),
381+ BytePtr(local_workspace), BytePtr(bandwidth_scratch),
382+ reinterpret_cast<uint8_t*>(const_cast<ascend_moonep::MoonEPUdmaCombineTilingData*>(&tiling)),
383+ magic);
384+#else
385+ (void)hidden; (void)weights; (void)sync_buffer; (void)dst;
386+ (void)groups; (void)dups; (void)counts; (void)out;
387+ (void)outw; (void)bandwidth_scratch; (void)local_workspace; (void)tiling;
388+ (void)magic;
389+ TORCH_CHECK(false, "This kernel requires an Ascend950 UDMA build");
390+#endif
391+}
392+ 
393+void LaunchPlanningMetadataOnly(
394+ torch::Tensor dst, torch::Tensor groups, torch::Tensor dups, torch::Tensor counts,
395+ const ascend_moonep::PlanningTilingData& tiling) {
396+#if defined(ASCEND_MOONEP_UDMA)
397+ planning_server_dedup_kernel_do(GetCurrentAclStream(), nullptr, nullptr, BytePtr(dst.data_ptr()),
398+ nullptr, nullptr, BytePtr(groups.data_ptr()), BytePtr(dups.data_ptr()), BytePtr(counts.data_ptr()),
399+ nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
400+ reinterpret_cast<uint8_t*>(const_cast<ascend_moonep::PlanningTilingData*>(&tiling)), 0);
401+#else
402+ (void)dst; (void)groups; (void)dups; (void)counts;
403+ (void)tiling;
404+ TORCH_CHECK(false, "This kernel requires an Ascend950 UDMA build");
254#endif405#endif
255}406}
@@ -31,7 +31,7 @@ void LaunchMoonEPDispatchKernel(
31 torch::Tensor route_weights_buf,31 torch::Tensor route_weights_buf,
32 const ascend_moonep::MoonEPDispatchTilingData& tiling);32 const ascend_moonep::MoonEPDispatchTilingData& tiling);
33 33 
34-void LaunchMoonEPDispatchUdmaKernel(34+void LaunchMoonEPDispatchUdmaLegacyKernel(
35 torch::Tensor hidden_sh,35 torch::Tensor hidden_sh,
36 torch::Tensor route_weights,36 torch::Tensor route_weights,
37 torch::Tensor dst,37 torch::Tensor dst,
@@ -44,7 +44,7 @@ void LaunchMoonEPDispatchUdmaKernel(
44 const ascend_moonep::MoonEPDispatchTilingData& tiling,44 const ascend_moonep::MoonEPDispatchTilingData& tiling,
45 uint64_t magic);45 uint64_t magic);
46 46 
47-void LaunchMoonEPDispatchUdmaProfileKernel(47+void LaunchMoonEPDispatchUdmaLegacyProfileKernel(
48 torch::Tensor hidden_sh,48 torch::Tensor hidden_sh,
49 torch::Tensor route_weights,49 torch::Tensor route_weights,
50 torch::Tensor dst,50 torch::Tensor dst,
@@ -58,7 +58,35 @@ void LaunchMoonEPDispatchUdmaProfileKernel(
58 const ascend_moonep::MoonEPDispatchTilingData& tiling,58 const ascend_moonep::MoonEPDispatchTilingData& tiling,
59 uint64_t magic);59 uint64_t magic);
60 60 
61-void LaunchPlanningKernel(61+void LaunchMoonEPDispatchUdmaServerDedupKernel(
62+ torch::Tensor hidden_sh,
63+ torch::Tensor route_weights,
64+ torch::Tensor dst,
65+ torch::Tensor dup_groups,
66+ torch::Tensor dup_loffs,
67+ torch::Tensor dup_counts,
68+ torch::Tensor hidden_buf,
69+ torch::Tensor route_weights_buf,
70+ torch::Tensor sync_buffer,
71+ const ascend_moonep::MoonEPDispatchTilingData& tiling,
72+ uint64_t magic);
73+ 
74+void LaunchMoonEPDispatchUdmaServerDedupProfileKernel(
75+ torch::Tensor hidden_sh,
76+ torch::Tensor route_weights,
77+ torch::Tensor dst,
78+ torch::Tensor dup_groups,
79+ torch::Tensor dup_loffs,
80+ torch::Tensor dup_counts,
81+ torch::Tensor hidden_buf,
82+ torch::Tensor route_weights_buf,
83+ torch::Tensor sync_buffer,
84+ torch::Tensor profile_cycles,
85+ const ascend_moonep::MoonEPDispatchTilingData& tiling,
86+ uint64_t magic);
87+ 
88+// Legacy rank-level dedup planner (writes routing + rank dedup tables only).
89+void LaunchPlanningLegacyKernel(
62 torch::Tensor topk_idx,90 torch::Tensor topk_idx,
63 torch::Tensor dst,91 torch::Tensor dst,
64 torch::Tensor cu_seqlens,92 torch::Tensor cu_seqlens,
@@ -80,17 +108,47 @@ void LaunchPlanningKernel(
80 void* symmetric_buffer,108 void* symmetric_buffer,
81 uint64_t ffts_addr);109 uint64_t ffts_addr);
82 110 
83-void LaunchMoonEPUdmaCombineKernel(111+// Server-level dedup planner (routing + server dedup tables + combine plan).
84- torch::Tensor hidden_nvsh,112+void LaunchPlanningServerDedupKernel(
85- torch::Tensor route_weights_nvs,113+ torch::Tensor topk_idx,
86- torch::Tensor sync_buffer,
87 torch::Tensor dst,114 torch::Tensor dst,
115+ torch::Tensor cu_seqlens,
116+ torch::Tensor experts_to_copy,
88 torch::Tensor dup_groups,117 torch::Tensor dup_groups,
89 torch::Tensor dup_loffs,118 torch::Tensor dup_loffs,
90 torch::Tensor dup_counts,119 torch::Tensor dup_counts,
91- torch::Tensor output_sh,120+ torch::Tensor tpe_all,
92- torch::Tensor output_sk,121+ torch::Tensor tpe_prefix,
93- void* bandwidth_scratch,122+ torch::Tensor balance,
123+ torch::Tensor z_tensor,
124+ torch::Tensor alloc_tensor,
125+ torch::Tensor alloc_cumsum,
126+ torch::Tensor expert_offsets,
127+ torch::Tensor core_expert_counts,
128+ torch::Tensor dup_workspace,
129+ torch::Tensor dup_key_workspace,
130+ const ascend_moonep::PlanningTilingData& tiling,
131+ void* symmetric_buffer,
132+ uint64_t ffts_addr);
133+ 
134+void LaunchMoonEPUdmaCombineServerDedupKernel(
135+ torch::Tensor hidden, torch::Tensor weights, torch::Tensor dst,
136+ torch::Tensor groups, torch::Tensor dups, torch::Tensor counts,
137+ torch::Tensor out, torch::Tensor outw, torch::Tensor workspace,
138+ torch::Tensor plan,
94 const ascend_moonep::MoonEPUdmaCombineTilingData& tiling,139 const ascend_moonep::MoonEPUdmaCombineTilingData& tiling,
95- void* local_workspace,140+ uint64_t magic);
96- uint64_t invocation_magic);141+ 
142+// Legacy rank-level dedup combine: workspace and its bandwidth scratch tail are
143+// rank-local host tensors, not the symmetric PUT workspace.
144+void LaunchMoonEPUdmaCombineLegacyKernel(
145+ torch::Tensor hidden, torch::Tensor weights, torch::Tensor sync_buffer,
146+ torch::Tensor dst, torch::Tensor groups, torch::Tensor dups,
147+ torch::Tensor counts, torch::Tensor out, torch::Tensor outw,
148+ void* bandwidth_scratch, void* local_workspace,
149+ const ascend_moonep::MoonEPUdmaCombineTilingData& tiling,
150+ uint64_t magic);
151+ 
152+void LaunchPlanningMetadataOnly(
153+ torch::Tensor dst, torch::Tensor groups, torch::Tensor dups, torch::Tensor counts,
154+ const ascend_moonep::PlanningTilingData& tiling);
@@ -48,7 +48,8 @@ void MoonEPUdmaCombine(
48 int64_t K,48 int64_t K,
49 int64_t R,49 int64_t R,
50 int64_t rank,50 int64_t rank,
51- torch::Tensor local_workspace) {51+ torch::Tensor local_workspace,
52+ c10::optional<torch::Tensor> execution_plan) {
52 53 
53 CheckNpuContiguous(hidden_nvsh, "hidden_nvsh");54 CheckNpuContiguous(hidden_nvsh, "hidden_nvsh");
54 CheckNpuContiguous(sync_buffer, "sync_buffer");55 CheckNpuContiguous(sync_buffer, "sync_buffer");
@@ -61,19 +62,23 @@ void MoonEPUdmaCombine(
61 "S/H/K/R must be positive");62 "S/H/K/R must be positive");
62 TORCH_CHECK(rank >= 0 && rank < R, "rank must be in [0, R)");63 TORCH_CHECK(rank >= 0 && rank < R, "rank must be in [0, R)");
63 TORCH_CHECK(K <= 16, "K must be <= 16");64 TORCH_CHECK(K <= 16, "K must be <= 16");
65+ constexpr int64_t kSmallWorldGroupWidth = 8;
66+ constexpr int64_t kTwoFrameWorldSize = 128;
64 constexpr int64_t kMaxGroupWidth = 16;67 constexpr int64_t kMaxGroupWidth = 16;
65 TORCH_CHECK(68 TORCH_CHECK(
66 R == 1 ||69 R == 1 ||
67 (R % 2 == 0 &&70 (R % 2 == 0 &&
68- (R <= kMaxGroupWidth || R % kMaxGroupWidth == 0)),71+ ((R < kTwoFrameWorldSize &&
69- "grouped MoonEP UDMA combine requires R=1, an even R<=16, "72+ (R <= kSmallWorldGroupWidth ||
70- "or an R divisible by 16");73+ R % kSmallWorldGroupWidth == 0)) ||
71- constexpr int64_t kHiddenUbBytes = 128 * 1024;74+ (R >= kTwoFrameWorldSize && R % kMaxGroupWidth == 0))),
72- constexpr int64_t kFullRowDbBytesPerElement = 16;75+ "grouped MoonEP UDMA combine requires R=1, an even R<=8, "
76+ "an R<128 divisible by 8, or an R>=128 divisible by 16");
77+ constexpr uint64_t kMaxTokenBytes = 8ULL * 1024ULL * 1024ULL;
73 TORCH_CHECK(78 TORCH_CHECK(
74- H <= kHiddenUbBytes / kFullRowDbBytesPerElement,79+ static_cast<uint64_t>(H) <=
75- "MoonEP UDMA combine requires H<=8192 so its full-row "80+ kMaxTokenBytes / sizeof(c10::BFloat16),
76- "double buffer fits in 128 KiB of UB");81+ "MoonEP UDMA combine requires one bf16 token row to be <=8 MiB");
77 TORCH_CHECK(static_cast<uint64_t>(S) <= std::numeric_limits<uint32_t>::max() &&82 TORCH_CHECK(static_cast<uint64_t>(S) <= std::numeric_limits<uint32_t>::max() &&
78 static_cast<uint64_t>(H) <= std::numeric_limits<uint32_t>::max() &&83 static_cast<uint64_t>(H) <= std::numeric_limits<uint32_t>::max() &&
79 static_cast<uint64_t>(K) <= std::numeric_limits<uint32_t>::max() &&84 static_cast<uint64_t>(K) <= std::numeric_limits<uint32_t>::max() &&
@@ -85,8 +90,10 @@ void MoonEPUdmaCombine(
85 "S*K must fit in uint32");90 "S*K must fit in uint32");
86 TORCH_CHECK(num_output_slots_u64 <= std::numeric_limits<uint32_t>::max() / 3,91 TORCH_CHECK(num_output_slots_u64 <= std::numeric_limits<uint32_t>::max() / 3,
87 "S*K is too large for dup_groups indexing");92 "S*K is too large for dup_groups indexing");
88- TORCH_CHECK(static_cast<uint64_t>(R) * num_output_slots_u64 < (1ull << 31),93+ TORCH_CHECK(num_output_slots_u64 <= std::numeric_limits<uint32_t>::max() / 8,
89- "MoonEP combine requires R*NvS to fit in positive int32 encoding");94+ "S*K is too large for contiguous 8*N contributor scratch indexing");
95+ TORCH_CHECK(static_cast<uint64_t>(R) * num_output_slots_u64 < (1ull << 30),
96+ "PUT combine requires R*NvS < 2^30 for disjoint route tags");
90 const int64_t NvS = static_cast<int64_t>(num_output_slots_u64);97 const int64_t NvS = static_cast<int64_t>(num_output_slots_u64);
91 98 
92 TORCH_CHECK(hidden_nvsh.dim() == 2, "hidden_nvsh must be [NvS, H]");99 TORCH_CHECK(hidden_nvsh.dim() == 2, "hidden_nvsh must be [NvS, H]");
@@ -98,9 +105,13 @@ void MoonEPUdmaCombine(
98 CheckSameDevice(sync_buffer, hidden_nvsh, "sync_buffer");105 CheckSameDevice(sync_buffer, hidden_nvsh, "sync_buffer");
99 TORCH_CHECK(sync_buffer.scalar_type() == torch::kUInt8,106 TORCH_CHECK(sync_buffer.scalar_type() == torch::kUInt8,
100 "sync_buffer must be uint8");107 "sync_buffer must be uint8");
101- constexpr uint64_t kGroupSyncBytesPerRank = 16ULL * 2ULL * 512ULL;108+ constexpr uint64_t kGroupSignalBytesPerRank = 16ULL * 6ULL * 512ULL;
109+ constexpr uint64_t kLocalAivSyncBytes = 16ULL * 4ULL * 512ULL;
110+ const uint64_t required_sync_bytes =
111+ static_cast<uint64_t>(R) * kGroupSignalBytesPerRank +
112+ kLocalAivSyncBytes;
102 TORCH_CHECK(static_cast<uint64_t>(sync_buffer.numel()) >=113 TORCH_CHECK(static_cast<uint64_t>(sync_buffer.numel()) >=
103- static_cast<uint64_t>(R) * kGroupSyncBytesPerRank,114+ required_sync_bytes,
104 "sync_buffer is too small for grouped combine");115 "sync_buffer is too small for grouped combine");
105 CheckSameDevice(dup_groups, hidden_nvsh, "dup_groups");116 CheckSameDevice(dup_groups, hidden_nvsh, "dup_groups");
106 CheckSameDevice(dup_loffs, hidden_nvsh, "dup_loffs");117 CheckSameDevice(dup_loffs, hidden_nvsh, "dup_loffs");
@@ -137,12 +148,29 @@ void MoonEPUdmaCombine(
137 dup_groups.dim() == 2 &&148 dup_groups.dim() == 2 &&
138 dup_groups.size(0) == NvS && dup_groups.size(1) == 3,149 dup_groups.size(0) == NvS && dup_groups.size(1) == 3,
139 "dup_groups must be int32 [NvS, 3]");150 "dup_groups must be int32 [NvS, 3]");
151+ // Server plans store full rank*NvS+loff addresses for same-server
152+ // secondaries. Preserve the compact rank-plan format alongside them.
153+ const bool server_dedup =
154+ dup_counts.dim() == 1 && dup_counts.size(0) == R + 2;
155+ TORCH_CHECK(!server_dedup || R % kMoonEPDispatchRanksPerServer == 0,
156+ "server dedup combine requires R divisible by 8");
157+ TORCH_CHECK(
158+ !server_dedup || num_output_slots_u64 <= kMoonEPServerDupRouteLimit,
159+ "server dedup source route exceeds packed route capacity");
160+ TORCH_CHECK(
161+ !server_dedup ||
162+ static_cast<uint64_t>(R) * num_output_slots_u64 < (1ULL << 30),
163+ "server dedup requires R*NvS < 2^30 for streamed-primary dst encoding");
164+ const int64_t dup_capacity = server_dedup
165+ ? kMoonEPDispatchRanksPerServer * NvS : NvS;
140 TORCH_CHECK(dup_loffs.scalar_type() == torch::kInt32 &&166 TORCH_CHECK(dup_loffs.scalar_type() == torch::kInt32 &&
141- dup_loffs.dim() == 1 && dup_loffs.size(0) == NvS,167+ dup_loffs.dim() == 1 && dup_loffs.size(0) == dup_capacity,
142- "dup_loffs must be int32 [NvS]");168+ "dup_loffs must be int32 [", dup_capacity,
169+ "] for the selected dedup format");
143 TORCH_CHECK(dup_counts.scalar_type() == torch::kInt32 &&170 TORCH_CHECK(dup_counts.scalar_type() == torch::kInt32 &&
144- dup_counts.dim() == 1 && dup_counts.size(0) == 2,171+ dup_counts.dim() == 1 &&
145- "dup_counts must be int32 [2]");172+ dup_counts.size(0) == (server_dedup ? R + 2 : 2),
173+ "dup_counts must be int32 [2] or [R+2]");
146 TORCH_CHECK(H % 8 == 0, "H must be multiple of 8");174 TORCH_CHECK(H % 8 == 0, "H must be multiple of 8");
147 CheckNpuContiguous(local_workspace, "local_workspace");175 CheckNpuContiguous(local_workspace, "local_workspace");
148 CheckSameDevice(local_workspace, hidden_nvsh, "local_workspace");176 CheckSameDevice(local_workspace, hidden_nvsh, "local_workspace");
@@ -155,38 +183,27 @@ void MoonEPUdmaCombine(
155 "MoonEP UDMA combine hidden workspace size overflows uint64_t");183 "MoonEP UDMA combine hidden workspace size overflows uint64_t");
156 const uint64_t hidden_bytes =184 const uint64_t hidden_bytes =
157 num_output_slots_u64 * static_cast<uint64_t>(H) * sizeof(c10::BFloat16);185 num_output_slots_u64 * static_cast<uint64_t>(H) * sizeof(c10::BFloat16);
158- const uint64_t weight_regions = static_cast<uint64_t>(R);186+ const uint64_t ready_bytes =
187+ num_output_slots_u64 * sizeof(uint64_t);
188+ const uint64_t scratch_bytes =
189+ static_cast<uint64_t>(kCombinePutCores) *
190+ kMoonEPUdmaCombineScratchTilesPerAiv *
191+ kMoonEPUdmaCombineScratchTileElements * sizeof(c10::BFloat16);
159 TORCH_CHECK(192 TORCH_CHECK(
160- num_output_slots_u64 <=193+ hidden_bytes <= std::numeric_limits<uint64_t>::max() - ready_bytes &&
161- std::numeric_limits<uint64_t>::max() /194+ hidden_bytes + ready_bytes <=
162- weight_regions / sizeof(float),195+ std::numeric_limits<uint64_t>::max() - scratch_bytes,
163- "MoonEP UDMA combine gathered weight workspace size overflows uint64_t");
164- const uint64_t weight_bytes =
165- weight_regions * num_output_slots_u64 * sizeof(float);
166- TORCH_CHECK(
167- hidden_bytes <=
168- std::numeric_limits<uint64_t>::max() - weight_bytes,
169 "MoonEP UDMA combine workspace size overflows uint64_t");196 "MoonEP UDMA combine workspace size overflows uint64_t");
170- const uint64_t bandwidth_alignment =197+ TORCH_CHECK(hidden_bytes <= (std::numeric_limits<uint64_t>::max() / 16U),
171- ascend_moonep::kMoonEPUdmaCombineBandwidthScratchAlign;198+ "PUT combine workspace payload size overflows uint64_t");
172- TORCH_CHECK(199+ const uint64_t required_workspace_bytes = MakeCombinePutLayout(
173- hidden_bytes + weight_bytes <=200+ static_cast<uint32_t>(NvS), static_cast<uint32_t>(H),
174- std::numeric_limits<uint64_t>::max() - (bandwidth_alignment - 1),201+ static_cast<uint32_t>(R), static_cast<uint32_t>(K)).bytes;
175- "MoonEP UDMA combine workspace alignment overflows uint64_t");
176- const uint64_t bandwidth_offset =
177- (hidden_bytes + weight_bytes + bandwidth_alignment - 1) &
178- ~(bandwidth_alignment - 1);
179- TORCH_CHECK(
180- bandwidth_offset <= std::numeric_limits<uint64_t>::max() -
181- ascend_moonep::kMoonEPUdmaCombineBandwidthScratchBytes,
182- "MoonEP UDMA combine bandwidth scratch size overflows uint64_t");
183- const uint64_t required_workspace_bytes = bandwidth_offset +
184- ascend_moonep::kMoonEPUdmaCombineBandwidthScratchBytes;
185 const uint64_t local_workspace_bytes =202 const uint64_t local_workspace_bytes =
186 static_cast<uint64_t>(local_workspace.numel()) *203 static_cast<uint64_t>(local_workspace.numel()) *
187 static_cast<uint64_t>(local_workspace.element_size());204 static_cast<uint64_t>(local_workspace.element_size());
188 TORCH_CHECK(required_workspace_bytes <= local_workspace_bytes,205 TORCH_CHECK(required_workspace_bytes <= local_workspace_bytes,
189- "local workspace is too small: need ",206+ "combine workspace is too small: need ",
190 required_workspace_bytes, " bytes, got ",207 required_workspace_bytes, " bytes, got ",
191 local_workspace_bytes, " bytes");208 local_workspace_bytes, " bytes");
192 209 
@@ -202,17 +219,206 @@ void MoonEPUdmaCombine(
202 tiling.R = static_cast<uint32_t>(R);219 tiling.R = static_cast<uint32_t>(R);
203 tiling.rank = static_cast<uint32_t>(rank);220 tiling.rank = static_cast<uint32_t>(rank);
204 tiling.with_weights = with_weights ? 1u : 0u;221 tiling.with_weights = with_weights ? 1u : 0u;
205- tiling.reserved = 0;222+ tiling.server_dedup = server_dedup ? 1u : 0u;
206 223 
207- auto* workspace_ptr = static_cast<uint8_t*>(local_workspace.data_ptr());224+ TORCH_CHECK(execution_plan.has_value(), "UDMA combine requires the execution plan generated by PlanningOp");
225+ if (execution_plan.has_value()) {
226+ CheckNpuContiguous(*execution_plan, "execution_plan");
227+ CheckSameDevice(*execution_plan, hidden_nvsh, "execution_plan");
228+ const auto required = MakeCombineExecutionPlanLayout(NvS, R).bytes;
229+ TORCH_CHECK(execution_plan->scalar_type() == torch::kUInt8 &&
230+ execution_plan->dim() == 1 &&
231+ static_cast<uint64_t>(execution_plan->numel()) == required,
232+ "execution_plan has wrong dtype/shape/layout");
233+ TORCH_CHECK(!execution_plan->is_alias_of(local_workspace) &&
234+ !execution_plan->is_alias_of(hidden_nvsh) &&
235+ !execution_plan->is_alias_of(output_sh),
236+ "execution_plan must not alias mutable workspace/input/output");
237+ }
238+ 
239+ 
240+ LaunchMoonEPUdmaCombineServerDedupKernel(
241+ hidden_nvsh, route_weights_arg, dst, dup_groups, dup_loffs, dup_counts,
242+ output_sh, output_sk_arg, local_workspace, *execution_plan,
243+ tiling, NextCombineMagic());
244+}
245+ 
246+namespace {
247+ 
248+// The legacy rank-level combined op mirrors the workspace ABI of the frozen
249+// 2802271 kernel: gathered payload for the hidden rows, then one fp32 weight
250+// region per source rank, then a bandwidth-diagnostics tail. These constants
251+// are intentionally local so the server-dedup PUT layout stays independent.
252+constexpr uint64_t kLegacyCombineBandwidthScratchAlign = 64;
253+constexpr uint64_t kLegacyCombineBandwidthScratchBytes =
254+ uint64_t{32} * 8 * sizeof(int64_t); // 32 AIVs, 8 int64 counters each
255+ 
256+} // namespace
257+ 
258+void MoonEPUdmaCombineLegacy(
259+ torch::Tensor hidden_nvsh,
260+ c10::optional<torch::Tensor> route_weights_nvs,
261+ torch::Tensor sync_buffer,
262+ torch::Tensor dst,
263+ torch::Tensor dup_groups,
264+ torch::Tensor dup_loffs,
265+ torch::Tensor dup_counts,
266+ torch::Tensor output_sh,
267+ c10::optional<torch::Tensor> output_sk,
268+ int64_t S,
269+ int64_t H,
270+ int64_t K,
271+ int64_t R,
272+ int64_t rank,
273+ torch::Tensor workspace) {
274+ 
275+ CheckNpuContiguous(hidden_nvsh, "hidden_nvsh");
276+ CheckNpuContiguous(sync_buffer, "sync_buffer");
277+ CheckNpuContiguous(dst, "dst");
278+ CheckNpuContiguous(dup_groups, "dup_groups");
279+ CheckNpuContiguous(dup_loffs, "dup_loffs");
280+ CheckNpuContiguous(dup_counts, "dup_counts");
281+ 
282+ TORCH_CHECK(S > 0 && H > 0 && K > 0 && R > 0,
283+ "S/H/K/R must be positive");
284+ TORCH_CHECK(rank >= 0 && rank < R, "rank must be in [0, R)");
285+ TORCH_CHECK(K <= 16, "K must be <= 16");
286+ constexpr int64_t kMaxGroupWidth = 16;
287+ TORCH_CHECK(
288+ R == 1 ||
289+ (R % 2 == 0 && (R <= kMaxGroupWidth || R % kMaxGroupWidth == 0)),
290+ "grouped MoonEP UDMA combine requires R=1, an even R<=16, "
291+ "or an R divisible by 16");
292+ constexpr int64_t kHiddenUbBytes = 128 * 1024;
293+ constexpr int64_t kFullRowDbBytesPerElement = 16;
294+ TORCH_CHECK(
295+ H <= kHiddenUbBytes / kFullRowDbBytesPerElement,
296+ "MoonEP UDMA combine requires H<=8192 so its full-row "
297+ "double buffer fits in 128 KiB of UB");
298+ TORCH_CHECK(static_cast<uint64_t>(S) <= std::numeric_limits<uint32_t>::max() &&
299+ static_cast<uint64_t>(H) <= std::numeric_limits<uint32_t>::max() &&
300+ static_cast<uint64_t>(K) <= std::numeric_limits<uint32_t>::max() &&
301+ static_cast<uint64_t>(R) <= std::numeric_limits<uint32_t>::max(),
302+ "S/H/K/R must fit in uint32 tiling fields");
303+ const uint64_t num_output_slots_u64 =
304+ static_cast<uint64_t>(S) * static_cast<uint64_t>(K);
305+ TORCH_CHECK(num_output_slots_u64 <= std::numeric_limits<uint32_t>::max(),
306+ "S*K must fit in uint32");
307+ TORCH_CHECK(num_output_slots_u64 <= std::numeric_limits<uint32_t>::max() / 3,
308+ "S*K is too large for dup_groups indexing");
309+ TORCH_CHECK(static_cast<uint64_t>(R) * num_output_slots_u64 < (1ull << 31),
310+ "MoonEP combine requires R*NvS to fit in positive int32 encoding");
311+ const int64_t NvS = static_cast<int64_t>(num_output_slots_u64);
312+ 
313+ TORCH_CHECK(hidden_nvsh.dim() == 2, "hidden_nvsh must be [NvS, H]");
314+ TORCH_CHECK(hidden_nvsh.scalar_type() == torch::kBFloat16,
315+ "hidden_nvsh must be bf16");
316+ TORCH_CHECK(hidden_nvsh.size(0) == NvS && hidden_nvsh.size(1) == H,
317+ "hidden_nvsh shape mismatch");
318+ CheckSameDevice(dst, hidden_nvsh, "dst");
319+ CheckSameDevice(sync_buffer, hidden_nvsh, "sync_buffer");
320+ TORCH_CHECK(sync_buffer.scalar_type() == torch::kUInt8,
321+ "sync_buffer must be uint8");
322+ // The legacy kernel indexes 16x2 512-byte slots per rank; the Buffer's
323+ // group grant/done pool is a superset of that.
324+ constexpr uint64_t kLegacyGroupSyncBytesPerRank = 16ULL * 2ULL * 512ULL;
325+ TORCH_CHECK(static_cast<uint64_t>(sync_buffer.numel()) >=
326+ static_cast<uint64_t>(R) * kLegacyGroupSyncBytesPerRank,
327+ "sync_buffer is too small for the rank-level combine");
328+ CheckSameDevice(dup_groups, hidden_nvsh, "dup_groups");
329+ CheckSameDevice(dup_loffs, hidden_nvsh, "dup_loffs");
330+ CheckSameDevice(dup_counts, hidden_nvsh, "dup_counts");
331+ CheckNpuContiguous(output_sh, "output_sh");
332+ CheckSameDevice(output_sh, hidden_nvsh, "output_sh");
333+ TORCH_CHECK(output_sh.scalar_type() == torch::kBFloat16 &&
334+ output_sh.dim() == 2 &&
335+ output_sh.size(0) == S && output_sh.size(1) == H,
336+ "output_sh must be bf16 [S, H]");
337+ 
338+ const bool with_weights = route_weights_nvs.has_value();
339+ TORCH_CHECK(output_sk.has_value() == with_weights,
340+ "output_sk must be provided exactly when route_weights_nvs is provided");
341+ if (with_weights) {
342+ CheckNpuContiguous(*route_weights_nvs, "route_weights_nvs");
343+ CheckSameDevice(*route_weights_nvs, hidden_nvsh, "route_weights_nvs");
344+ TORCH_CHECK(route_weights_nvs->scalar_type() == torch::kFloat32,
345+ "route_weights_nvs must be fp32 when with_weights is true");
346+ TORCH_CHECK(route_weights_nvs->dim() == 1 &&
347+ route_weights_nvs->size(0) == NvS,
348+ "route_weights_nvs shape mismatch");
349+ CheckNpuContiguous(*output_sk, "output_sk");
350+ CheckSameDevice(*output_sk, hidden_nvsh, "output_sk");
351+ TORCH_CHECK(output_sk->scalar_type() == torch::kFloat32 &&
352+ output_sk->dim() == 2 &&
353+ output_sk->size(0) == S && output_sk->size(1) == K,
354+ "output_sk must be fp32 [S, K]");
355+ }
356+ TORCH_CHECK(dst.scalar_type() == torch::kInt32, "dst must be int32");
357+ TORCH_CHECK(dst.dim() == 1 && dst.size(0) == NvS, "dst must be int32 [S*K]");
358+ TORCH_CHECK(dup_groups.scalar_type() == torch::kInt32 &&
359+ dup_groups.dim() == 2 &&
360+ dup_groups.size(0) == NvS && dup_groups.size(1) == 3,
361+ "dup_groups must be int32 [NvS, 3]");
362+ TORCH_CHECK(dup_loffs.scalar_type() == torch::kInt32 &&
363+ dup_loffs.dim() == 1 && dup_loffs.size(0) == NvS,
364+ "dup_loffs must be int32 [NvS]");
365+ TORCH_CHECK(dup_counts.scalar_type() == torch::kInt32 &&
366+ dup_counts.dim() == 1 && dup_counts.size(0) == 2,
367+ "dup_counts must be int32 [2]");
368+ TORCH_CHECK(H % 8 == 0, "H must be multiple of 8");
369+ 
370+ CheckNpuContiguous(workspace, "local_workspace");
371+ CheckSameDevice(workspace, hidden_nvsh, "local_workspace");
372+ TORCH_CHECK(workspace.scalar_type() == torch::kUInt8,
373+ "local_workspace must be uint8");
374+ TORCH_CHECK(
375+ num_output_slots_u64 <=
376+ std::numeric_limits<uint64_t>::max() /
377+ static_cast<uint64_t>(H) / sizeof(c10::BFloat16),
378+ "MoonEP UDMA combine hidden workspace size overflows uint64_t");
379+ const uint64_t hidden_bytes =
380+ num_output_slots_u64 * static_cast<uint64_t>(H) * sizeof(c10::BFloat16);
381+ const uint64_t weight_regions = static_cast<uint64_t>(R);
382+ TORCH_CHECK(
383+ num_output_slots_u64 <=
384+ std::numeric_limits<uint64_t>::max() / weight_regions / sizeof(float),
385+ "MoonEP UDMA combine gathered weight workspace size overflows uint64_t");
386+ const uint64_t weight_bytes = weight_regions * num_output_slots_u64 * sizeof(float);
387+ const uint64_t bandwidth_offset =
388+ (hidden_bytes + weight_bytes + kLegacyCombineBandwidthScratchAlign - 1) &
389+ ~(kLegacyCombineBandwidthScratchAlign - 1);
390+ const uint64_t required_workspace_bytes =
391+ bandwidth_offset + kLegacyCombineBandwidthScratchBytes;
392+ const uint64_t local_workspace_bytes =
393+ static_cast<uint64_t>(workspace.numel()) *
394+ static_cast<uint64_t>(workspace.element_size());
395+ TORCH_CHECK(required_workspace_bytes <= local_workspace_bytes,
396+ "local workspace is too small: need ", required_workspace_bytes,
397+ " bytes, got ", local_workspace_bytes, " bytes");
398+ 
399+ const torch::Tensor& route_weights_arg =
400+ with_weights ? *route_weights_nvs : hidden_nvsh;
401+ const torch::Tensor& output_sk_arg =
402+ with_weights ? *output_sk : output_sh;
403+ 
404+ MoonEPUdmaCombineTilingData tiling{};
405+ tiling.S = static_cast<uint32_t>(S);
406+ tiling.H = static_cast<uint32_t>(H);
407+ tiling.K = static_cast<uint32_t>(K);
408+ tiling.R = static_cast<uint32_t>(R);
409+ tiling.rank = static_cast<uint32_t>(rank);
410+ tiling.with_weights = with_weights ? 1u : 0u;
411+ tiling.server_dedup = 0;
412+ 
413+ auto* workspace_ptr = static_cast<uint8_t*>(workspace.data_ptr());
208 void* bandwidth_scratch = workspace_ptr + bandwidth_offset;414 void* bandwidth_scratch = workspace_ptr + bandwidth_offset;
209 415 
210- LaunchMoonEPUdmaCombineKernel(416+ LaunchMoonEPUdmaCombineLegacyKernel(
211 hidden_nvsh, route_weights_arg, sync_buffer, dst,417 hidden_nvsh, route_weights_arg, sync_buffer, dst,
212 dup_groups, dup_loffs, dup_counts,418 dup_groups, dup_loffs, dup_counts,
213 output_sh, output_sk_arg,419 output_sh, output_sk_arg,
214- bandwidth_scratch,420+ bandwidth_scratch, workspace_ptr,
215- tiling, local_workspace.data_ptr(), NextCombineMagic());421+ tiling, NextCombineMagic());
216}422}
217 423 
218} // namespace ascend_moonep::ops424} // namespace ascend_moonep::ops
@@ -5,8 +5,8 @@
5namespace ascend_moonep::ops {5namespace ascend_moonep::ops {
6 6 
7// Caller-owned-output overload selected by ASCEND_MOONEP_COMBINE_USE_UDMA.7// Caller-owned-output overload selected by ASCEND_MOONEP_COMBINE_USE_UDMA.
8-// local_workspace is8+// local_workspace is a Buffer-owned symmetric tensor used as this rank's
9-// ordinary rank-local NPU memory; only the inputs are symmetric.9+// gathered payload staging area, allocated in the same SHMEM heap as inputs.
10void MoonEPUdmaCombine(10void MoonEPUdmaCombine(
11 torch::Tensor hidden_nvsh,11 torch::Tensor hidden_nvsh,
12 c10::optional<torch::Tensor> route_weights_nvs,12 c10::optional<torch::Tensor> route_weights_nvs,
@@ -22,6 +22,27 @@ void MoonEPUdmaCombine(
22 int64_t K,22 int64_t K,
23 int64_t R,23 int64_t R,
24 int64_t rank,24 int64_t rank,
25- torch::Tensor local_workspace);25+ torch::Tensor local_workspace,
26+ c10::optional<torch::Tensor> execution_plan = c10::nullopt);
27+ 
28+// Legacy rank-level dedup combine. `workspace` is one rank-local byte tensor
29+// that holds the gathered payload plus its bandwidth-scratch tail; the host op
30+// splits it, so the Buffer's symmetric PUT workspace is not used.
31+void MoonEPUdmaCombineLegacy(
32+ torch::Tensor hidden_nvsh,
33+ c10::optional<torch::Tensor> route_weights_nvs,
34+ torch::Tensor sync_buffer,
35+ torch::Tensor dst,
36+ torch::Tensor dup_groups,
37+ torch::Tensor dup_loffs,
38+ torch::Tensor dup_counts,
39+ torch::Tensor output_sh,
40+ c10::optional<torch::Tensor> output_sk,
41+ int64_t S,
42+ int64_t H,
43+ int64_t K,
44+ int64_t R,
45+ int64_t rank,
46+ torch::Tensor workspace);
26 47 
27} // namespace ascend_moonep::ops48} // namespace ascend_moonep::ops
@@ -47,7 +47,9 @@ CheckedDispatchArgs CheckDispatchArgs(
47 int64_t H,47 int64_t H,
48 int64_t K,48 int64_t K,
49 int64_t R,49 int64_t R,
50- int64_t rank) {50+ int64_t rank,
51+ bool use_udma,
52+ bool server_dedup) {
51 53 
52 CheckNpuContiguous(hidden_sh, "hidden_sh");54 CheckNpuContiguous(hidden_sh, "hidden_sh");
53 CheckNpuContiguous(dst, "dst");55 CheckNpuContiguous(dst, "dst");
@@ -118,12 +120,24 @@ CheckedDispatchArgs CheckDispatchArgs(
118 dup_groups.dim() == 2 &&120 dup_groups.dim() == 2 &&
119 dup_groups.size(0) == NvS && dup_groups.size(1) == 3,121 dup_groups.size(0) == NvS && dup_groups.size(1) == 3,
120 "dup_groups must be int32 [NvS, 3]");122 "dup_groups must be int32 [NvS, 3]");
123+ // Detect the protocol from the counts length; server plans go only to the already-adapted UDMA operator.
124+ const bool counts_server_dedup = dup_counts.dim() == 1 && dup_counts.size(0) == R + 2;
125+ TORCH_CHECK(server_dedup == counts_server_dedup,
126+ "dispatch dedup mode must match the plan tables: plan has ",
127+ counts_server_dedup ? "server" : "rank",
128+ " dedup tables");
129+ const bool server_dedup_tables = counts_server_dedup;
130+ TORCH_CHECK(!server_dedup_tables || use_udma, "server dedup requires UDMA dispatch");
131+ TORCH_CHECK(!server_dedup_tables || R % kMoonEPDispatchRanksPerServer == 0,
132+ "server dedup requires R divisible by 8");
133+ const int64_t dup_capacity = server_dedup_tables ? kMoonEPDispatchRanksPerServer * NvS : NvS;
134+ const int64_t count_size = server_dedup_tables ? R + 2 : 2;
121 TORCH_CHECK(dup_loffs.scalar_type() == torch::kInt32 &&135 TORCH_CHECK(dup_loffs.scalar_type() == torch::kInt32 &&
122- dup_loffs.dim() == 1 && dup_loffs.size(0) == NvS,136+ dup_loffs.dim() == 1 && dup_loffs.size(0) == dup_capacity,
123- "dup_loffs must be int32 [NvS]");137+ "dup_loffs must be int32 [", dup_capacity, "] for the selected dup format");
124 TORCH_CHECK(dup_counts.scalar_type() == torch::kInt32 &&138 TORCH_CHECK(dup_counts.scalar_type() == torch::kInt32 &&
125- dup_counts.dim() == 1 && dup_counts.size(0) == 2,139+ dup_counts.dim() == 1 && dup_counts.size(0) == count_size,
126- "dup_counts must be int32 [2]");140+ "dup_counts must be int32 [2] or [R+2]");
127 TORCH_CHECK(H % 8 == 0, "H must be multiple of 8");141 TORCH_CHECK(H % 8 == 0, "H must be multiple of 8");
128 TORCH_CHECK(static_cast<uint64_t>(H) * 2 <= 128ull * 1024ull,142 TORCH_CHECK(static_cast<uint64_t>(H) * 2 <= 128ull * 1024ull,
129 "H row bytes exceed MoonEP dispatch UB row capacity");143 "H row bytes exceed MoonEP dispatch UB row capacity");
@@ -139,7 +153,7 @@ CheckedDispatchArgs CheckDispatchArgs(
139 tiling.R = static_cast<uint32_t>(R);153 tiling.R = static_cast<uint32_t>(R);
140 tiling.rank = static_cast<uint32_t>(rank);154 tiling.rank = static_cast<uint32_t>(rank);
141 tiling.with_weights = with_weights ? 1u : 0u;155 tiling.with_weights = with_weights ? 1u : 0u;
142- tiling.reserved = 0;156+ tiling.server_dedup = server_dedup ? 1u : 0u;
143 157 
144 return {route_weights_arg, route_weights_buf_arg, tiling};158 return {route_weights_arg, route_weights_buf_arg, tiling};
145}159}
@@ -171,19 +185,15 @@ MoonEPDispatch(
171 int64_t R,185 int64_t R,
172 int64_t rank,186 int64_t rank,
173 bool use_udma,187 bool use_udma,
174- int64_t num_sms) {188+ int64_t num_sms,
189+ bool server_dedup) {
175 190 
176 auto args = CheckDispatchArgs(191 auto args = CheckDispatchArgs(
177 hidden_sh, route_weights, dst, dup_groups, dup_loffs, dup_counts,192 hidden_sh, route_weights, dst, dup_groups, dup_loffs, dup_counts,
178- hidden_buf, route_weights_buf, S, H, K, R, rank);193+ hidden_buf, route_weights_buf, S, H, K, R, rank, use_udma, server_dedup);
179 194 
180- if (use_udma) {195+ if (!use_udma) {
181- LaunchMoonEPDispatchUdmaKernel(196+ // Peer-to-peer MTE path: rank-level dedup only, no UDMA messaging.
182- hidden_sh, args.route_weights, dst,
183- dup_groups, dup_loffs, dup_counts,
184- hidden_buf, args.route_weights_buf, sync_buffer,
185- args.tiling, NextDispatchMagic());
186- } else {
187 TORCH_CHECK(num_sms > 0 &&197 TORCH_CHECK(num_sms > 0 &&
188 static_cast<uint64_t>(num_sms) <= std::numeric_limits<uint32_t>::max(),198 static_cast<uint64_t>(num_sms) <= std::numeric_limits<uint32_t>::max(),
189 "num_sms must be a positive uint32 launch width");199 "num_sms must be a positive uint32 launch width");
@@ -193,6 +203,22 @@ MoonEPDispatch(
193 dup_groups, dup_loffs, dup_counts,203 dup_groups, dup_loffs, dup_counts,
194 hidden_buf, args.route_weights_buf,204 hidden_buf, args.route_weights_buf,
195 args.tiling);205 args.tiling);
206+ } else if (server_dedup) {
207+ // Server-level dedup: the optimized kernel that forwards secondaries
208+ // inside an eight-rank board.
209+ LaunchMoonEPDispatchUdmaServerDedupKernel(
210+ hidden_sh, args.route_weights, dst,
211+ dup_groups, dup_loffs, dup_counts,
212+ hidden_buf, args.route_weights_buf, sync_buffer,
213+ args.tiling, NextDispatchMagic());
214+ } else {
215+ // Rank-level dedup: the legacy kernel, frozen before the server dedup
216+ // optimization so that rank-level results stay on the old baseline.
217+ LaunchMoonEPDispatchUdmaLegacyKernel(
218+ hidden_sh, args.route_weights, dst,
219+ dup_groups, dup_loffs, dup_counts,
220+ hidden_buf, args.route_weights_buf, sync_buffer,
221+ args.tiling, NextDispatchMagic());
196 }222 }
197}223}
198 224 
@@ -213,11 +239,12 @@ MoonEPDispatchProfile(
213 int64_t K,239 int64_t K,
214 int64_t R,240 int64_t R,
215 int64_t rank,241 int64_t rank,
216- bool use_udma) {242+ bool use_udma,
243+ bool server_dedup) {
217 244 
218 auto args = CheckDispatchArgs(245 auto args = CheckDispatchArgs(
219 hidden_sh, route_weights, dst, dup_groups, dup_loffs, dup_counts,246 hidden_sh, route_weights, dst, dup_groups, dup_loffs, dup_counts,
220- hidden_buf, route_weights_buf, S, H, K, R, rank);247+ hidden_buf, route_weights_buf, S, H, K, R, rank, use_udma, server_dedup);
221 CheckNpuContiguous(profile_cycles, "profile_cycles");248 CheckNpuContiguous(profile_cycles, "profile_cycles");
222 CheckSameDevice(profile_cycles, hidden_sh, "profile_cycles");249 CheckSameDevice(profile_cycles, hidden_sh, "profile_cycles");
223 250 
@@ -229,11 +256,19 @@ MoonEPDispatchProfile(
229 "profile_cycles must be int64 [32, ",256 "profile_cycles must be int64 [32, ",
230 kMoonEPDispatchUdmaProfileFields, "]");257 kMoonEPDispatchUdmaProfileFields, "]");
231 258 
232- LaunchMoonEPDispatchUdmaProfileKernel(259+ if (server_dedup) {
233- hidden_sh, args.route_weights, dst,260+ LaunchMoonEPDispatchUdmaServerDedupProfileKernel(
234- dup_groups, dup_loffs, dup_counts,261+ hidden_sh, args.route_weights, dst,
235- hidden_buf, args.route_weights_buf, sync_buffer, profile_cycles,262+ dup_groups, dup_loffs, dup_counts,
236- args.tiling, NextDispatchMagic());263+ hidden_buf, args.route_weights_buf, sync_buffer, profile_cycles,
264+ args.tiling, NextDispatchMagic());
265+ } else {
266+ LaunchMoonEPDispatchUdmaLegacyProfileKernel(
267+ hidden_sh, args.route_weights, dst,
268+ dup_groups, dup_loffs, dup_counts,
269+ hidden_buf, args.route_weights_buf, sync_buffer, profile_cycles,
270+ args.tiling, NextDispatchMagic());
271+ }
237 }272 }
238}273}
239 274 
@@ -23,7 +23,8 @@ MoonEPDispatch(
23 int64_t R,23 int64_t R,
24 int64_t rank,24 int64_t rank,
25 bool use_udma,25 bool use_udma,
26- int64_t num_sms = 32);26+ int64_t num_sms = 32,
27+ bool server_dedup = false);
27 28 
28void29void
29MoonEPDispatchProfile(30MoonEPDispatchProfile(
@@ -42,6 +43,7 @@ MoonEPDispatchProfile(
42 int64_t K,43 int64_t K,
43 int64_t R,44 int64_t R,
44 int64_t rank,45 int64_t rank,
45- bool use_udma);46+ bool use_udma,
47+ bool server_dedup);
46 48 
47} // namespace ascend_moonep::ops49} // namespace ascend_moonep::ops
@@ -14,6 +14,7 @@ namespace {
14constexpr int64_t kMinPlanningCores = 8;14constexpr int64_t kMinPlanningCores = 8;
15constexpr int64_t kMaxPlanningCores = 56;15constexpr int64_t kMaxPlanningCores = 56;
16constexpr int64_t kMaxPlanningRanks = 1024;16constexpr int64_t kMaxPlanningRanks = 1024;
17+constexpr int64_t kPlanningRanksPerServer = ascend_moonep::kMoonEPDispatchRanksPerServer;
17constexpr int64_t kInt32Bytes = 4;18constexpr int64_t kInt32Bytes = 4;
18constexpr int64_t kUbAlignBytes = 32;19constexpr int64_t kUbAlignBytes = 32;
19constexpr int64_t kAlignElems = kUbAlignBytes / kInt32Bytes;20constexpr int64_t kAlignElems = kUbAlignBytes / kInt32Bytes;
@@ -128,7 +129,8 @@ int64_t SourceDupPackChunkGroups(int64_t world_size, int64_t num_topk) {
128int64_t SourceDupUbBytes(129int64_t SourceDupUbBytes(
129 int64_t world_size,130 int64_t world_size,
130 int64_t num_topk,131 int64_t num_topk,
131- int64_t tokens_per_tile) {132+ int64_t tokens_per_tile,
133+ bool server_dedup) {
132 const int64_t route_tile_elems = CheckedMul(tokens_per_tile, num_topk, "route tile");134 const int64_t route_tile_elems = CheckedMul(tokens_per_tile, num_topk, "route tile");
133 const int64_t staging_elems = std::max(route_tile_elems + world_size * 7, world_size * 2);135 const int64_t staging_elems = std::max(route_tile_elems + world_size * 7, world_size * 2);
134 const int64_t prefix_bytes =136 const int64_t prefix_bytes =
@@ -163,13 +165,18 @@ int64_t SourceDupUbBytes(
163 const int64_t materialize_bytes =165 const int64_t materialize_bytes =
164 AlignUp(world_size * 2 * kInt32Bytes, kUbAlignBytes) +166 AlignUp(world_size * 2 * kInt32Bytes, kUbAlignBytes) +
165 2 * AlignUp(kDupSrcTileElems * kInt32Bytes, kUbAlignBytes);167 2 * AlignUp(kDupSrcTileElems * kInt32Bytes, kUbAlignBytes);
166- return std::max({prefix_bytes, group_bytes, materialize_bytes});168+ // The source prefix and the [G,D,P...] outputs occupy separate partitions in UB and must not overwrite each other.
169+ const int64_t destination_prefix_bytes = world_size * kSourceDupInboxSlotElems * kInt32Bytes +
170+ AlignUp((world_size + 2) * kInt32Bytes, kUbAlignBytes);
171+ return std::max({prefix_bytes, group_bytes, materialize_bytes,
172+ server_dedup ? destination_prefix_bytes : 0});
167}173}
168 174 
169uint32_t SelectSourceDupTokensPerTile(175uint32_t SelectSourceDupTokensPerTile(
170 int64_t world_size,176 int64_t world_size,
171 int64_t num_topk,177 int64_t num_topk,
172- uint64_t ub_size) {178+ uint64_t ub_size,
179+ bool server_dedup) {
173 int64_t preferred_tokens = std::max(kSourceDupPreferredTokens, kDupSrcTileElems / num_topk);180 int64_t preferred_tokens = std::max(kSourceDupPreferredTokens, kDupSrcTileElems / num_topk);
174 preferred_tokens = std::min(preferred_tokens, kSourceDupSimtMaxThreads);181 preferred_tokens = std::min(preferred_tokens, kSourceDupSimtMaxThreads);
175 if (preferred_tokens >= kSourceDupThreadAlign) {182 if (preferred_tokens >= kSourceDupThreadAlign) {
@@ -178,14 +185,14 @@ uint32_t SelectSourceDupTokensPerTile(
178 for (int64_t tokens = preferred_tokens;185 for (int64_t tokens = preferred_tokens;
179 tokens >= kSourceDupThreadAlign;186 tokens >= kSourceDupThreadAlign;
180 tokens -= kSourceDupThreadAlign) {187 tokens -= kSourceDupThreadAlign) {
181- if (SourceDupUbBytes(world_size, num_topk, tokens) <= static_cast<int64_t>(ub_size)) {188+ if (SourceDupUbBytes(world_size, num_topk, tokens, server_dedup) <= static_cast<int64_t>(ub_size)) {
182 return static_cast<uint32_t>(tokens);189 return static_cast<uint32_t>(tokens);
183 }190 }
184 }191 }
185 for (int64_t tokens = std::min(preferred_tokens, kSourceDupThreadAlign - 1);192 for (int64_t tokens = std::min(preferred_tokens, kSourceDupThreadAlign - 1);
186 tokens > 0;193 tokens > 0;
187 --tokens) {194 --tokens) {
188- if (SourceDupUbBytes(world_size, num_topk, tokens) <= static_cast<int64_t>(ub_size)) {195+ if (SourceDupUbBytes(world_size, num_topk, tokens, server_dedup) <= static_cast<int64_t>(ub_size)) {
189 return static_cast<uint32_t>(tokens);196 return static_cast<uint32_t>(tokens);
190 }197 }
191 }198 }
@@ -203,7 +210,8 @@ PlanningWorkspaceLayout MakePlanningWorkspaceLayout(
203 int64_t num_topk,210 int64_t num_topk,
204 int64_t num_experts,211 int64_t num_experts,
205 int64_t world_size,212 int64_t world_size,
206- int64_t core_num) {213+ int64_t core_num,
214+ bool server_dedup) {
207 TORCH_CHECK(num_tokens > 0, "num_tokens must be positive");215 TORCH_CHECK(num_tokens > 0, "num_tokens must be positive");
208 TORCH_CHECK(num_topk > 0, "num_topk must be positive");216 TORCH_CHECK(num_topk > 0, "num_topk must be positive");
209 TORCH_CHECK(num_experts > 0, "num_experts must be positive");217 TORCH_CHECK(num_experts > 0, "num_experts must be positive");
@@ -290,7 +298,7 @@ PlanningWorkspaceLayout MakePlanningWorkspaceLayout(
290 core_num,298 core_num,
291 static_cast<int64_t>(kPlanningUbSizeBytes));299 static_cast<int64_t>(kPlanningUbSizeBytes));
292 const int64_t source_dup_tokens_per_tile =300 const int64_t source_dup_tokens_per_tile =
293- SelectSourceDupTokensPerTile(world_size, num_topk, kPlanningUbSizeBytes);301+ SelectSourceDupTokensPerTile(world_size, num_topk, kPlanningUbSizeBytes, server_dedup);
294 const int64_t max_tokens_per_core = (num_tokens + core_num - 1) / core_num;302 const int64_t max_tokens_per_core = (num_tokens + core_num - 1) / core_num;
295 const int64_t max_tiles_per_core =303 const int64_t max_tiles_per_core =
296 (max_tokens_per_core + source_dup_tokens_per_tile - 1) /304 (max_tokens_per_core + source_dup_tokens_per_tile - 1) /
@@ -404,10 +412,14 @@ namespace ascend_moonep::ops {
404int64_t PlanningSymmetricWorkspaceBytes(412int64_t PlanningSymmetricWorkspaceBytes(
405 int64_t num_experts,413 int64_t num_experts,
406 int64_t num_max_tokens_per_rank,414 int64_t num_max_tokens_per_rank,
407- int64_t world_size) {415+ int64_t world_size,
416+ bool server_dedup) {
408 TORCH_CHECK(num_experts > 0, "num_experts must be positive");417 TORCH_CHECK(num_experts > 0, "num_experts must be positive");
409 TORCH_CHECK(num_max_tokens_per_rank > 0, "num_max_tokens_per_rank must be positive");418 TORCH_CHECK(num_max_tokens_per_rank > 0, "num_max_tokens_per_rank must be positive");
410 TORCH_CHECK(world_size > 0, "world_size must be positive");419 TORCH_CHECK(world_size > 0, "world_size must be positive");
420+ TORCH_CHECK(world_size <= kMaxPlanningRanks && num_experts <= std::numeric_limits<int32_t>::max() &&
421+ num_max_tokens_per_rank <= std::numeric_limits<int32_t>::max(),
422+ "planning workspace dimensions must fit device indices");
411 const int64_t dup_rank_counts_off = AlignUp(num_experts, kAlignElems);423 const int64_t dup_rank_counts_off = AlignUp(num_experts, kAlignElems);
412 const int64_t dup_payload_done_off = dup_rank_counts_off +424 const int64_t dup_payload_done_off = dup_rank_counts_off +
413 CheckedMul(425 CheckedMul(
@@ -418,8 +430,12 @@ int64_t PlanningSymmetricWorkspaceBytes(
418 dup_payload_done_off + AlignUp(world_size, kAlignElems);430 dup_payload_done_off + AlignUp(world_size, kAlignElems);
419 const int64_t dup_loffs_off =431 const int64_t dup_loffs_off =
420 dup_groups_off + AlignUp(num_max_tokens_per_rank * 3, kAlignElems);432 dup_groups_off + AlignUp(num_max_tokens_per_rank * 3, kAlignElems);
421- const int64_t required_ints =433+ const int64_t dup_capacity = server_dedup
422- dup_loffs_off + AlignUp(num_max_tokens_per_rank, kAlignElems);434+ ? CheckedMul(kPlanningRanksPerServer, num_max_tokens_per_rank, "server dup capacity")
435+ : num_max_tokens_per_rank;
436+ const int64_t required_ints = dup_loffs_off + AlignUp(dup_capacity, kAlignElems);
437+ TORCH_CHECK(required_ints <= std::numeric_limits<int32_t>::max(),
438+ "planning symmetric workspace exceeds int32 device offsets");
423 return CheckedMul(required_ints, kInt32Bytes, "planning symmetric workspace");439 return CheckedMul(required_ints, kInt32Bytes, "planning symmetric workspace");
424}440}
425 441 
@@ -428,12 +444,13 @@ int64_t PlanningLocalWorkspaceElements(
428 int64_t num_topk,444 int64_t num_topk,
429 int64_t num_experts,445 int64_t num_experts,
430 int64_t world_size,446 int64_t world_size,
431- int64_t core_num) {447+ int64_t core_num,
448+ bool server_dedup) {
432 return MakePlanningWorkspaceLayout(449 return MakePlanningWorkspaceLayout(
433- num_tokens, num_topk, num_experts, world_size, core_num).total_elems;450+ num_tokens, num_topk, num_experts, world_size, core_num, server_dedup).total_elems;
434}451}
435 452 
436-void Planning(453+torch::Tensor Planning(
437 torch::Tensor topk_idx,454 torch::Tensor topk_idx,
438 torch::Tensor dst,455 torch::Tensor dst,
439 torch::Tensor cu_seqlens,456 torch::Tensor cu_seqlens,
@@ -452,8 +469,7 @@ void Planning(
452 int64_t core_num,469 int64_t core_num,
453 int64_t rank,470 int64_t rank,
454 int64_t world_size,471 int64_t world_size,
455- bool use_udma) {472+ bool server_dedup, bool use_udma, torch::Tensor combine_workspace, int64_t hidden_size) {
456- (void)use_udma;
457 CheckNpuInt32(topk_idx, "topk_idx");473 CheckNpuInt32(topk_idx, "topk_idx");
458 CheckNpuInt32(dst, "dst");474 CheckNpuInt32(dst, "dst");
459 CheckNpuInt32(cu_seqlens, "cu_seqlens");475 CheckNpuInt32(cu_seqlens, "cu_seqlens");
@@ -497,8 +513,15 @@ void Planning(
497 CheckedMul(world_size, num_experts, "rank-expert table") <=513 CheckedMul(world_size, num_experts, "rank-expert table") <=
498 std::numeric_limits<int32_t>::max(),514 std::numeric_limits<int32_t>::max(),
499 "planning requires world_size * num_experts to fit int32 indexing");515 "planning requires world_size * num_experts to fit int32 indexing");
500- TORCH_CHECK(num_max_tokens_per_rank >= route_count,516+ // Detect the protocol from the counts length; rank mode still lets legacy callers reserve NvS larger than S*K.
501- "num_max_tokens_per_rank must be at least num_tokens * num_topk");517+ const bool counts_server_dedup = dup_counts.dim() == 1 && dup_counts.numel() == world_size + 2;
518+ TORCH_CHECK(server_dedup == counts_server_dedup,
519+ "planning dedup mode must match the plan tables: plan has ",
520+ counts_server_dedup ? "server" : "rank", " dedup tables");
521+ TORCH_CHECK(!server_dedup || world_size % kPlanningRanksPerServer == 0,
522+ "server planning requires world_size divisible by 8");
523+ TORCH_CHECK(num_max_tokens_per_rank >= route_count && (!server_dedup || num_max_tokens_per_rank == route_count),
524+ "server planning requires NvS == S*K; rank planning requires NvS >= S*K");
502 TORCH_CHECK(topk_idx.numel() == route_count,525 TORCH_CHECK(topk_idx.numel() == route_count,
503 "topk_idx numel must equal num_tokens * num_topk");526 "topk_idx numel must equal num_tokens * num_topk");
504 TORCH_CHECK(dst.numel() == route_count, "dst shape mismatch");527 TORCH_CHECK(dst.numel() == route_count, "dst shape mismatch");
@@ -506,11 +529,15 @@ void Planning(
506 "cu_seqlens shape mismatch");529 "cu_seqlens shape mismatch");
507 TORCH_CHECK(experts_to_copy.numel() == world_size * num_prefetch_slots,530 TORCH_CHECK(experts_to_copy.numel() == world_size * num_prefetch_slots,
508 "experts_to_copy shape mismatch");531 "experts_to_copy shape mismatch");
509- TORCH_CHECK(dup_groups.numel() == num_max_tokens_per_rank * 3,532+ const int64_t dup_capacity = server_dedup ? kPlanningRanksPerServer * num_max_tokens_per_rank :
510- "dup_groups shape mismatch");533+ num_max_tokens_per_rank;
511- TORCH_CHECK(dup_loffs.numel() == num_max_tokens_per_rank,534+ const int64_t count_size = server_dedup ? world_size + 2 : 2;
512- "dup_loffs shape mismatch");535+ TORCH_CHECK(dup_groups.dim() == 2 && dup_groups.size(0) == num_max_tokens_per_rank &&
513- TORCH_CHECK(dup_counts.numel() == 2, "dup_counts shape mismatch");536+ dup_groups.size(1) == 3, "dup_groups must be int32 [NvS, 3]");
537+ TORCH_CHECK(dup_loffs.dim() == 1 && dup_loffs.numel() == dup_capacity,
538+ "dup_loffs must be int32 [", dup_capacity, "] for the selected dup format");
539+ TORCH_CHECK(dup_counts.dim() == 1 && dup_counts.numel() == count_size,
540+ "dup_counts must be int32 [2] or [R+2]");
514 TORCH_CHECK(symmetric_workspace_addr != 0,541 TORCH_CHECK(symmetric_workspace_addr != 0,
515 "planning symmetric workspace address must not be zero");542 "planning symmetric workspace address must not be zero");
516 TORCH_CHECK(543 TORCH_CHECK(
@@ -518,12 +545,12 @@ void Planning(
518 "planning local workspace base must be 32-byte aligned");545 "planning local workspace base must be 32-byte aligned");
519 546 
520 const auto layout = MakePlanningWorkspaceLayout(547 const auto layout = MakePlanningWorkspaceLayout(
521- num_tokens, num_topk, num_experts, world_size, core_num);548+ num_tokens, num_topk, num_experts, world_size, core_num, server_dedup);
522 TORCH_CHECK(local_workspace.numel() >= layout.total_elems,549 TORCH_CHECK(local_workspace.numel() >= layout.total_elems,
523 "planning local workspace is too small: need ",550 "planning local workspace is too small: need ",
524 layout.total_elems, " int32 elements, got ", local_workspace.numel());551 layout.total_elems, " int32 elements, got ", local_workspace.numel());
525 const int64_t required_symmetric_bytes = PlanningSymmetricWorkspaceBytes(552 const int64_t required_symmetric_bytes = PlanningSymmetricWorkspaceBytes(
526- num_experts, num_max_tokens_per_rank, world_size);553+ num_experts, num_max_tokens_per_rank, world_size, server_dedup);
527 TORCH_CHECK(symmetric_workspace_bytes >= required_symmetric_bytes,554 TORCH_CHECK(symmetric_workspace_bytes >= required_symmetric_bytes,
528 "planning symmetric workspace is too small: need ",555 "planning symmetric workspace is too small: need ",
529 required_symmetric_bytes, " bytes, got ", symmetric_workspace_bytes);556 required_symmetric_bytes, " bytes, got ", symmetric_workspace_bytes);
@@ -541,14 +568,28 @@ void Planning(
541 tiling.symmetric_dup_rank_counts_offset =568 tiling.symmetric_dup_rank_counts_offset =
542 static_cast<uint32_t>(AlignUp(num_experts, kAlignElems));569 static_cast<uint32_t>(AlignUp(num_experts, kAlignElems));
543 tiling.source_dup_tokens_per_tile =570 tiling.source_dup_tokens_per_tile =
544- SelectSourceDupTokensPerTile(world_size, num_topk, kPlanningUbSizeBytes);571+ SelectSourceDupTokensPerTile(world_size, num_topk, kPlanningUbSizeBytes, server_dedup);
545 tiling.owner_reduce_tile_elems = static_cast<uint32_t>(572 tiling.owner_reduce_tile_elems = static_cast<uint32_t>(
546 SelectOwnerReduceTileElems(573 SelectOwnerReduceTileElems(
547 world_size,574 world_size,
548 num_experts / world_size,575 num_experts / world_size,
549 core_num,576 core_num,
550 static_cast<int64_t>(kPlanningUbSizeBytes)));577 static_cast<int64_t>(kPlanningUbSizeBytes)));
551- tiling.reserved = 0;578+ tiling.server_dedup = server_dedup ? 1U : 0U;
579+ tiling.stripe_rank_placement = use_udma && !server_dedup &&
580+ (world_size == 32 || world_size == 64) ? 1U : 0U;
581+ torch::Tensor combine_plan;
582+ TORCH_CHECK(server_dedup || !combine_workspace.defined(),
583+ "the legacy rank-level planner does not produce a combine "
584+ "execution plan; construct the Buffer with dedup_mode='server'");
585+ if (server_dedup && combine_workspace.defined()) {
586+ combine_plan = AllocateCombinePlan(combine_workspace, dst, dup_groups,
587+ dup_loffs, dup_counts, num_tokens, hidden_size, num_topk, world_size, rank);
588+ tiling.combine_mode = 1U;
589+ tiling.combine_h = hidden_size;
590+ tiling.combine_workspace = reinterpret_cast<uint64_t>(combine_workspace.data_ptr());
591+ tiling.combine_plan = reinterpret_cast<uint64_t>(combine_plan.data_ptr());
592+ }
552 593 
553 auto tpe_all = SliceWorkspace(local_workspace, layout.tpe_all);594 auto tpe_all = SliceWorkspace(local_workspace, layout.tpe_all);
554 auto tpe_prefix = SliceWorkspace(local_workspace, layout.tpe_prefix);595 auto tpe_prefix = SliceWorkspace(local_workspace, layout.tpe_prefix);
@@ -563,28 +604,93 @@ void Planning(
563 604 
564 // SHMEM initializes FFTS where required; A5 legitimately returns zero.605 // SHMEM initializes FFTS where required; A5 legitimately returns zero.
565 const uint64_t ffts_addr = shmemx_get_ffts_config();606 const uint64_t ffts_addr = shmemx_get_ffts_config();
607+ const auto launch_planning = [&](auto launcher) {
608+ launcher(
609+ topk_idx,
610+ dst,
611+ cu_seqlens,
612+ experts_to_copy,
613+ dup_groups,
614+ dup_loffs,
615+ dup_counts,
616+ tpe_all,
617+ tpe_prefix,
618+ balance,
619+ z,
620+ alloc,
621+ alloc_cumsum,
622+ expert_offsets,
623+ core_expert_counts,
624+ dup_workspace,
625+ dup_key_workspace,
626+ tiling,
627+ reinterpret_cast<void*>(static_cast<uintptr_t>(symmetric_workspace_addr)),
628+ ffts_addr);
629+ };
630+ if (server_dedup) {
631+ launch_planning(LaunchPlanningServerDedupKernel);
632+ } else {
633+ launch_planning(LaunchPlanningLegacyKernel);
634+ }
635+ return combine_plan;
636+}
566 637 
567- LaunchPlanningKernel(638+torch::Tensor AllocateCombinePlan(
568- topk_idx,639+ torch::Tensor workspace, torch::Tensor dst, torch::Tensor groups,
569- dst,640+ torch::Tensor dups, torch::Tensor counts,
570- cu_seqlens,641+ int64_t S, int64_t H, int64_t K, int64_t R, int64_t rank) {
571- experts_to_copy,642+ TORCH_CHECK(S > 0 && H > 0 && H % 8 == 0 && H <= 4 * 1024 * 1024 &&
572- dup_groups,643+ K > 0 && K <= 16 && R > 0 && R <= 1024 && rank >= 0 && rank < R &&
573- dup_loffs,644+ uint64_t(S) <= ((1ULL << 30) - 1) / uint64_t(K) / uint64_t(R),
574- dup_counts,645+ "invalid combine execution-plan dimensions");
575- tpe_all,646+ TORCH_CHECK(R == 1 || (R % 2 == 0 &&
576- tpe_prefix,647+ (R < 128 ? (R <= 8 || R % 8 == 0) : R % 16 == 0)),
577- balance,648+ "unsupported combine topology");
578- z,649+ const int64_t n = S * K;
579- alloc,650+ TORCH_CHECK(n <= std::numeric_limits<uint32_t>::max() / 8U,
580- alloc_cumsum,651+ "combine scratch index exceeds uint32");
581- expert_offsets,652+ for (const auto& tensor : {workspace, dst, groups, dups, counts}) {
582- core_expert_counts,653+ TORCH_CHECK(tensor.device().type() == c10::DeviceType::PrivateUse1 &&
583- dup_workspace,654+ tensor.device() == dst.device() && tensor.is_contiguous(),
584- dup_key_workspace,655+ "combine planning tensors must be contiguous on the same NPU");
585- tiling,656+ }
586- reinterpret_cast<void*>(static_cast<uintptr_t>(symmetric_workspace_addr)),657+ TORCH_CHECK(dst.scalar_type() == torch::kInt32 && dst.dim() == 1 && dst.numel() == n,
587- ffts_addr);658+ "dst must be int32 [S*K]");
659+ TORCH_CHECK(groups.scalar_type() == torch::kInt32 && groups.dim() == 2 &&
660+ groups.size(0) == n && groups.size(1) == 3, "groups must be int32 [S*K,3]");
661+ TORCH_CHECK(counts.scalar_type() == torch::kInt32 && counts.dim() == 1 &&
662+ (counts.numel() == 2 || counts.numel() == R + 2), "invalid dup counts");
663+ const bool server = counts.numel() == R + 2;
664+ TORCH_CHECK(!server || R % 8 == 0, "server planning requires full 8-rank servers");
665+ TORCH_CHECK(!server || uint64_t(n) <= kMoonEPServerDupRouteLimit,
666+ "server planning route exceeds packed capacity");
667+ TORCH_CHECK(dups.scalar_type() == torch::kInt32 && dups.dim() == 1 &&
668+ dups.numel() == (server ? 8 * n : n), "invalid dup member capacity");
669+ const auto p = MakeCombinePutLayout(n, H, R, K);
670+ TORCH_CHECK(workspace.scalar_type() == torch::kUInt8 && workspace.dim() == 1 &&
671+ uint64_t(workspace.numel()) >= p.bytes, "combine planning workspace too small");
672+ for (const auto& tensor : {dst, groups, dups, counts})
673+ TORCH_CHECK(!workspace.is_alias_of(tensor), "planning input must not alias exchange workspace");
674+ const auto q = MakeCombineExecutionPlanLayout(n, R);
675+ auto plan = torch::empty({static_cast<int64_t>(q.bytes)}, dst.options().dtype(torch::kUInt8));
676+ return plan;
677+}
678+ 
679+torch::Tensor PlanningPrepareCombinePlan(
680+ torch::Tensor workspace, torch::Tensor dst, torch::Tensor groups,
681+ torch::Tensor dups, torch::Tensor counts,
682+ int64_t S, int64_t H, int64_t K, int64_t R, int64_t rank) {
683+ auto plan = AllocateCombinePlan(workspace, dst, groups, dups, counts, S, H, K, R, rank);
684+ PlanningTilingData tiling{};
685+ tiling.num_tokens = S; tiling.num_topk = K; tiling.world_size = R;
686+ tiling.rank = rank; tiling.server_dedup = counts.numel() == R + 2;
687+ tiling.block_dim = kCombinePutCores;
688+ tiling.combine_mode = 2U; // Synthetic/precomputed routes: same planning entry.
689+ tiling.combine_h = H;
690+ tiling.combine_workspace = reinterpret_cast<uint64_t>(workspace.data_ptr());
691+ tiling.combine_plan = reinterpret_cast<uint64_t>(plan.data_ptr());
692+ LaunchPlanningMetadataOnly(dst, groups, dups, counts, tiling);
693+ return plan;
588}694}
589 695 
590} // namespace ascend_moonep::ops696} // namespace ascend_moonep::ops
@@ -9,16 +9,18 @@ namespace ascend_moonep::ops {
9int64_t PlanningSymmetricWorkspaceBytes(9int64_t PlanningSymmetricWorkspaceBytes(
10 int64_t num_experts,10 int64_t num_experts,
11 int64_t num_max_tokens_per_rank,11 int64_t num_max_tokens_per_rank,
12- int64_t world_size);12+ int64_t world_size,
13+ bool server_dedup = false);
13 14 
14int64_t PlanningLocalWorkspaceElements(15int64_t PlanningLocalWorkspaceElements(
15 int64_t num_tokens,16 int64_t num_tokens,
16 int64_t num_topk,17 int64_t num_topk,
17 int64_t num_experts,18 int64_t num_experts,
18 int64_t world_size,19 int64_t world_size,
19- int64_t core_num);20+ int64_t core_num,
21+ bool server_dedup = false);
20 22 
21-void Planning(23+torch::Tensor Planning(
22 torch::Tensor topk_idx,24 torch::Tensor topk_idx,
23 torch::Tensor dst,25 torch::Tensor dst,
24 torch::Tensor cu_seqlens,26 torch::Tensor cu_seqlens,
@@ -37,6 +39,18 @@ void Planning(
37 int64_t core_num,39 int64_t core_num,
38 int64_t rank,40 int64_t rank,
39 int64_t world_size,41 int64_t world_size,
40- bool use_udma);42+ bool server_dedup,
43+ bool use_udma,
44+ torch::Tensor combine_workspace = {}, int64_t hidden_size = 0);
45+ 
46+torch::Tensor AllocateCombinePlan(
47+ torch::Tensor workspace, torch::Tensor dst, torch::Tensor groups,
48+ torch::Tensor dups, torch::Tensor counts,
49+ int64_t S, int64_t H, int64_t K, int64_t R, int64_t rank);
50+ 
51+torch::Tensor PlanningPrepareCombinePlan(
52+ torch::Tensor workspace, torch::Tensor dst, torch::Tensor groups,
53+ torch::Tensor dups, torch::Tensor counts,
54+ int64_t S, int64_t H, int64_t K, int64_t R, int64_t rank);
41 55 
42} // namespace ascend_moonep::ops56} // namespace ascend_moonep::ops
@@ -46,6 +46,7 @@ void CheckShmem(const c10::intrusive_ptr<ShmemInstance>& shmem) {
46 TORCH_CHECK(shmem->Initialized(), "ShmemInstance is not initialized");46 TORCH_CHECK(shmem->Initialized(), "ShmemInstance is not initialized");
47}47}
48 48 
49+ 
49std::size_t MoonEPUdmaCombineWorkspaceBytes(50std::size_t MoonEPUdmaCombineWorkspaceBytes(
50 int64_t S,51 int64_t S,
51 int64_t H,52 int64_t H,
@@ -228,14 +229,45 @@ class Planning : public torch::jit::CustomClassHolder {
228public:229public:
229 Planning() = default;230 Planning() = default;
230 231 
232+ torch::Tensor compute_fused(
233+ torch::Tensor topk_idx, torch::Tensor dst, torch::Tensor cu_seqlens,
234+ torch::Tensor experts_to_copy, torch::Tensor dup_groups, torch::Tensor dup_loffs,
235+ torch::Tensor dup_counts, torch::Tensor local_workspace,
236+ int64_t symmetric_workspace_addr, int64_t symmetric_workspace_bytes,
237+ int64_t num_tokens, int64_t num_topk, int64_t num_experts,
238+ int64_t num_max_tokens_per_rank, int64_t num_prefetch_slots,
239+ int64_t core_num, int64_t rank, int64_t world_size, bool use_udma,
240+ bool server_dedup, torch::Tensor combine_workspace, int64_t hidden_size) {
241+ TORCH_CHECK(rank == aclshmem_my_pe() && world_size == aclshmem_n_pes(),
242+ "planning topology must match the active SHMEM runtime");
243+ return ascend_moonep::ops::Planning(topk_idx, dst, cu_seqlens, experts_to_copy,
244+ dup_groups, dup_loffs, dup_counts, local_workspace,
245+ symmetric_workspace_addr, symmetric_workspace_bytes,
246+ num_tokens, num_topk, num_experts, num_max_tokens_per_rank,
247+ num_prefetch_slots, core_num, rank, world_size, server_dedup, use_udma,
248+ combine_workspace, hidden_size);
249+ }
250+ 
251+ torch::Tensor prepare_combine_plan(
252+ torch::Tensor workspace, torch::Tensor dst, torch::Tensor groups,
253+ torch::Tensor dups, torch::Tensor counts,
254+ int64_t S, int64_t H, int64_t K, int64_t R, int64_t rank) {
255+ TORCH_CHECK(rank == aclshmem_my_pe() && R == aclshmem_n_pes(),
256+ "planning topology must match the active SHMEM runtime");
257+ return ascend_moonep::ops::PlanningPrepareCombinePlan(
258+ workspace, dst, groups, dups, counts, S, H, K, R, rank);
259+ }
260+ 
231 int64_t symmetric_workspace_bytes(261 int64_t symmetric_workspace_bytes(
232 int64_t num_experts,262 int64_t num_experts,
233 int64_t num_max_tokens_per_rank,263 int64_t num_max_tokens_per_rank,
234- int64_t world_size) const {264+ int64_t world_size,
265+ bool server_dedup) const {
235 return ascend_moonep::ops::PlanningSymmetricWorkspaceBytes(266 return ascend_moonep::ops::PlanningSymmetricWorkspaceBytes(
236 num_experts,267 num_experts,
237 num_max_tokens_per_rank,268 num_max_tokens_per_rank,
238- world_size);269+ world_size,
270+ server_dedup);
239 }271 }
240 272 
241 int64_t local_workspace_elements(273 int64_t local_workspace_elements(
@@ -243,13 +275,15 @@ public:
243 int64_t num_topk,275 int64_t num_topk,
244 int64_t num_experts,276 int64_t num_experts,
245 int64_t world_size,277 int64_t world_size,
246- int64_t core_num) const {278+ int64_t core_num,
279+ bool server_dedup) const {
247 return ascend_moonep::ops::PlanningLocalWorkspaceElements(280 return ascend_moonep::ops::PlanningLocalWorkspaceElements(
248 num_tokens,281 num_tokens,
249 num_topk,282 num_topk,
250 num_experts,283 num_experts,
251 world_size,284 world_size,
252- core_num);285+ core_num,
286+ server_dedup);
253 }287 }
254 288 
255 void compute(289 void compute(
@@ -271,7 +305,8 @@ public:
271 int64_t core_num,305 int64_t core_num,
272 int64_t rank,306 int64_t rank,
273 int64_t world_size,307 int64_t world_size,
274- bool use_udma) {308+ bool use_udma,
309+ bool server_dedup) {
275 TORCH_CHECK(310 TORCH_CHECK(
276 rank == aclshmem_my_pe(),311 rank == aclshmem_my_pe(),
277 "rank does not match the active CANN-SHMEM PE");312 "rank does not match the active CANN-SHMEM PE");
@@ -294,6 +329,7 @@ public:
294 core_num,329 core_num,
295 rank,330 rank,
296 world_size,331 world_size,
332+ server_dedup,
297 use_udma);333 use_udma);
298 }334 }
299};335};
@@ -318,7 +354,8 @@ public:
318 int64_t world_size,354 int64_t world_size,
319 int64_t rank,355 int64_t rank,
320 bool use_udma,356 bool use_udma,
321- int64_t num_sms = 32) {357+ int64_t num_sms,
358+ bool server_dedup) {
322 TORCH_CHECK(359 TORCH_CHECK(
323 rank == aclshmem_my_pe(),360 rank == aclshmem_my_pe(),
324 "rank does not match the active CANN-SHMEM PE");361 "rank does not match the active CANN-SHMEM PE");
@@ -338,7 +375,8 @@ public:
338 world_size,375 world_size,
339 rank,376 rank,
340 use_udma,377 use_udma,
341- num_sms);378+ num_sms,
379+ server_dedup);
342 }380 }
343 381 
344 void compute_profile(382 void compute_profile(
@@ -357,7 +395,8 @@ public:
357 int64_t num_topk,395 int64_t num_topk,
358 int64_t world_size,396 int64_t world_size,
359 int64_t rank,397 int64_t rank,
360- bool use_udma) {398+ bool use_udma,
399+ bool server_dedup) {
361 TORCH_CHECK(400 TORCH_CHECK(
362 rank == aclshmem_my_pe(),401 rank == aclshmem_my_pe(),
363 "rank does not match the active CANN-SHMEM PE");402 "rank does not match the active CANN-SHMEM PE");
@@ -377,7 +416,8 @@ public:
377 num_topk,416 num_topk,
378 world_size,417 world_size,
379 rank,418 rank,
380- use_udma);419+ use_udma,
420+ server_dedup);
381 }421 }
382};422};
383 423 
@@ -423,8 +463,6 @@ public:
423 }463 }
424};464};
425 465 
426-// Buffer-facing UDMA combine. Inputs are symmetric; gather scratch is an
427-// ordinary rank-local NPU tensor cached by this class instance.
428class CombineUrma : public torch::jit::CustomClassHolder {466class CombineUrma : public torch::jit::CustomClassHolder {
429public:467public:
430 CombineUrma() = default;468 CombineUrma() = default;
@@ -481,7 +519,7 @@ public:
481 .dtype(torch::kUInt8));519 .dtype(torch::kUInt8));
482 }520 }
483 521 
484- ascend_moonep::ops::MoonEPUdmaCombine(522+ ascend_moonep::ops::MoonEPUdmaCombineLegacy(
485 hidden_nvsh,523 hidden_nvsh,
486 route_weights_nvs,524 route_weights_nvs,
487 sync_buffer,525 sync_buffer,
@@ -499,6 +537,18 @@ public:
499 local_workspace_);537 local_workspace_);
500 }538 }
501 539 
540+ void compute_prepared(
541+ torch::Tensor hidden, c10::optional<torch::Tensor> weights,
542+ torch::Tensor sync, torch::Tensor workspace,
543+ torch::Tensor dst, torch::Tensor groups, torch::Tensor dups, torch::Tensor counts,
544+ torch::Tensor out, c10::optional<torch::Tensor> outw, torch::Tensor plan,
545+ int64_t S, int64_t H, int64_t K, int64_t R, int64_t rank) {
546+ TORCH_CHECK(rank == aclshmem_my_pe() && R == aclshmem_n_pes(),
547+ "plan topology must match the active SHMEM runtime");
548+ ascend_moonep::ops::MoonEPUdmaCombine(hidden, weights, sync, dst, groups,
549+ dups, counts, out, outw, S, H, K, R, rank, workspace, plan);
550+ }
551+ 
502private:552private:
503 torch::Tensor local_workspace_;553 torch::Tensor local_workspace_;
504};554};
@@ -539,11 +589,26 @@ static auto planning_registry =
539 .def(torch::jit::init<>())589 .def(torch::jit::init<>())
540 .def(590 .def(
541 "symmetric_workspace_bytes",591 "symmetric_workspace_bytes",
542- &ascend_moonep::torch_classes::Planning::symmetric_workspace_bytes)592+ &ascend_moonep::torch_classes::Planning::symmetric_workspace_bytes,
593+ "", {torch::arg("num_experts"), torch::arg("num_max_tokens_per_rank"),
594+ torch::arg("world_size"), torch::arg("server_dedup") = false})
543 .def(595 .def(
544 "local_workspace_elements",596 "local_workspace_elements",
545- &ascend_moonep::torch_classes::Planning::local_workspace_elements)597+ &ascend_moonep::torch_classes::Planning::local_workspace_elements,
546- .def("compute", &ascend_moonep::torch_classes::Planning::compute);598+ "", {torch::arg("num_tokens"), torch::arg("num_topk"), torch::arg("num_experts"),
599+ torch::arg("world_size"), torch::arg("core_num"),
600+ torch::arg("server_dedup") = false})
601+ .def("prepare_combine_plan", &ascend_moonep::torch_classes::Planning::prepare_combine_plan)
602+ .def("compute_fused", &ascend_moonep::torch_classes::Planning::compute_fused)
603+ .def("compute", &ascend_moonep::torch_classes::Planning::compute,
604+ "", {torch::arg("topk_idx"), torch::arg("dst"), torch::arg("cu_seqlens"),
605+ torch::arg("experts_to_copy"), torch::arg("dup_groups"), torch::arg("dup_loffs"),
606+ torch::arg("dup_counts"), torch::arg("local_workspace"),
607+ torch::arg("symmetric_workspace_addr"), torch::arg("symmetric_workspace_bytes"),
608+ torch::arg("num_tokens"), torch::arg("num_topk"), torch::arg("num_experts"),
609+ torch::arg("num_max_tokens_per_rank"), torch::arg("num_prefetch_slots"),
610+ torch::arg("core_num"), torch::arg("rank"), torch::arg("world_size"),
611+ torch::arg("use_udma"), torch::arg("server_dedup") = false});
547 612 
548static auto dispatch_registry =613static auto dispatch_registry =
549 torch::jit::class_<ascend_moonep::torch_classes::Dispatch>("AscendMoonEP", "Dispatch")614 torch::jit::class_<ascend_moonep::torch_classes::Dispatch>("AscendMoonEP", "Dispatch")
@@ -555,8 +620,14 @@ static auto dispatch_registry =
555 torch::arg("route_weights_buf"), torch::arg("sync_buffer"),620 torch::arg("route_weights_buf"), torch::arg("sync_buffer"),
556 torch::arg("num_tokens"), torch::arg("hidden_size"), torch::arg("num_topk"),621 torch::arg("num_tokens"), torch::arg("hidden_size"), torch::arg("num_topk"),
557 torch::arg("world_size"), torch::arg("rank"), torch::arg("use_udma"),622 torch::arg("world_size"), torch::arg("rank"), torch::arg("use_udma"),
558- torch::arg("num_sms") = 32})623+ torch::arg("num_sms") = 32, torch::arg("server_dedup") = false})
559- .def("compute_profile", &ascend_moonep::torch_classes::Dispatch::compute_profile);624+ .def("compute_profile", &ascend_moonep::torch_classes::Dispatch::compute_profile,
625+ "", {torch::arg("hidden_sh"), torch::arg("route_weights"), torch::arg("dst"),
626+ torch::arg("dup_groups"), torch::arg("dup_loffs"), torch::arg("dup_counts"),
627+ torch::arg("hidden_buf"), torch::arg("route_weights_buf"), torch::arg("sync_buffer"),
628+ torch::arg("profile_cycles"), torch::arg("num_tokens"), torch::arg("hidden_size"),
629+ torch::arg("num_topk"), torch::arg("world_size"), torch::arg("rank"),
630+ torch::arg("use_udma"), torch::arg("server_dedup") = false});
560 631 
561static auto combine_registry =632static auto combine_registry =
562 torch::jit::class_<ascend_moonep::torch_classes::Combine>("AscendMoonEP", "Combine")633 torch::jit::class_<ascend_moonep::torch_classes::Combine>("AscendMoonEP", "Combine")
@@ -572,5 +643,6 @@ static auto combine_registry =
572static auto combine_urma_registry =643static auto combine_urma_registry =
573 torch::jit::class_<ascend_moonep::torch_classes::CombineUrma>("AscendMoonEP", "CombineUrma")644 torch::jit::class_<ascend_moonep::torch_classes::CombineUrma>("AscendMoonEP", "CombineUrma")
574 .def(torch::jit::init<>())645 .def(torch::jit::init<>())
646+ .def("compute_prepared", &ascend_moonep::torch_classes::CombineUrma::compute_prepared)
575 .def("compute", &ascend_moonep::torch_classes::CombineUrma::compute)647 .def("compute", &ascend_moonep::torch_classes::CombineUrma::compute)
576 .def("destroy", &ascend_moonep::torch_classes::CombineUrma::destroy);648 .def("destroy", &ascend_moonep::torch_classes::CombineUrma::destroy);
@@ -29,21 +29,21 @@ ASCEND_MOONEP_EXPORT void moonep_combine_kernel_do(
29 uint8_t* route_weights_sk_out,29 uint8_t* route_weights_sk_out,
30 uint8_t* tiling_host);30 uint8_t* tiling_host);
31 31 
32+// Legacy rank-level dedup combine: gather scratch and bandwidth diagnostics are
33+// split out of one rank-local workspace by the host op.
32ASCEND_MOONEP_EXPORT void moonep_udma_combine_kernel_do(34ASCEND_MOONEP_EXPORT void moonep_udma_combine_kernel_do(
33- void* stream,35+ void* stream, uint8_t* hidden, uint8_t* weights, uint8_t* sync_buffer,
34- uint8_t* hidden_nvsh,36+ uint8_t* dst, uint8_t* groups, uint8_t* dups, uint8_t* counts,
35- uint8_t* route_weights_nvs,37+ uint8_t* out, uint8_t* outw, uint8_t* workspace, uint8_t* bandwidth_scratch,
36- uint8_t* sync_buffer,38+ uint8_t* tiling, uint64_t magic);
37- uint8_t* dst,39+ 
38- uint8_t* dup_groups,40+// Server-level dedup combine: consumes the execution plan produced by
39- uint8_t* dup_loffs,41+// planning_server_dedup_kernel_do.
40- uint8_t* dup_counts,42+ASCEND_MOONEP_EXPORT void moonep_udma_combine_server_dedup_kernel_do(
41- uint8_t* output_sh,43+ void* stream, uint8_t* hidden, uint8_t* weights, uint8_t* dst,
42- uint8_t* output_sk,44+ uint8_t* groups, uint8_t* dups, uint8_t* counts, uint8_t* out, uint8_t* outw,
43- uint8_t* local_workspace,45+ uint8_t* workspace, uint8_t* plan, uint8_t* tiling,
44- uint8_t* bandwidth_scratch,46+ uint64_t magic);
45- uint8_t* tiling_host,
46- uint64_t invocation_magic);
47 47 
48ASCEND_MOONEP_EXPORT void moonep_dispatch_kernel_do(48ASCEND_MOONEP_EXPORT void moonep_dispatch_kernel_do(
49 void* stream,49 void* stream,
@@ -86,6 +86,35 @@ ASCEND_MOONEP_EXPORT void moonep_dispatch_udma_profile_kernel_do(
86 uint8_t* tiling_host,86 uint8_t* tiling_host,
87 uint64_t magic);87 uint64_t magic);
88 88 
89+ASCEND_MOONEP_EXPORT void moonep_dispatch_udma_server_dedup_kernel_do(
90+ void* stream,
91+ uint8_t* hidden_sh,
92+ uint8_t* route_weights,
93+ uint8_t* dst,
94+ uint8_t* dup_groups,
95+ uint8_t* dup_loffs,
96+ uint8_t* dup_counts,
97+ uint8_t* hidden_buf,
98+ uint8_t* weights_buf,
99+ uint8_t* sync_buffer,
100+ uint8_t* tiling_host,
101+ uint64_t magic);
102+ 
103+ASCEND_MOONEP_EXPORT void moonep_dispatch_udma_server_dedup_profile_kernel_do(
104+ void* stream,
105+ uint8_t* hidden_sh,
106+ uint8_t* route_weights,
107+ uint8_t* dst,
108+ uint8_t* dup_groups,
109+ uint8_t* dup_loffs,
110+ uint8_t* dup_counts,
111+ uint8_t* hidden_buf,
112+ uint8_t* weights_buf,
113+ uint8_t* sync_buffer,
114+ uint8_t* profile_cycles,
115+ uint8_t* tiling_host,
116+ uint64_t magic);
117+ 
89ASCEND_MOONEP_EXPORT void planning_kernel_do(118ASCEND_MOONEP_EXPORT void planning_kernel_do(
90 void* stream,119 void* stream,
91 uint8_t* topk_idx,120 uint8_t* topk_idx,
@@ -109,6 +138,31 @@ ASCEND_MOONEP_EXPORT void planning_kernel_do(
109 uint8_t* tiling_host,138 uint8_t* tiling_host,
110 uint64_t ffts_addr);139 uint64_t ffts_addr);
111 140 
141+// Server-level dedup planner: also materializes the combine execution plan when
142+// the tiling requests the fused mode.
143+ASCEND_MOONEP_EXPORT void planning_server_dedup_kernel_do(
144+ void* stream,
145+ uint8_t* topk_idx,
146+ uint8_t* symmetric_buffer,
147+ uint8_t* dst,
148+ uint8_t* cu_seqlens,
149+ uint8_t* experts_to_copy,
150+ uint8_t* dup_groups,
151+ uint8_t* dup_loffs,
152+ uint8_t* dup_counts,
153+ uint8_t* tpe_all,
154+ uint8_t* tpe_prefix,
155+ uint8_t* balance,
156+ uint8_t* z_tensor,
157+ uint8_t* alloc_tensor,
158+ uint8_t* alloc_cumsum,
159+ uint8_t* expert_offsets,
160+ uint8_t* core_expert_counts,
161+ uint8_t* dup_workspace,
162+ uint8_t* dup_key_workspace,
163+ uint8_t* tiling_host,
164+ uint64_t ffts_addr);
165+ 
112ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce(166ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce(
113 void* stream,167 void* stream,
114 void* expert_grads,168 void* expert_grads,
@@ -4,9 +4,18 @@
4 4 
5namespace ascend_moonep {5namespace ascend_moonep {
6 6 
7-// Shared host/device launch width. Lives here so unity builds of multiple7+#if defined(__CCE_AICORE__) || defined(__CCE_KT_TEST__)
8-// kernels do not redefine a file-local kMoonEPAivNum.8+#define MOONEP_DEVICE_INLINE __forceinline__ __aicore__
9+#else
10+#define MOONEP_DEVICE_INLINE static inline constexpr
11+#endif
12+ 
13+// Default host/device launch width for the other operators. PUT UDMA combine
14+// uses its own 64-AIV schedule in moonep_combine_udma.cpp; do not change this
15+// shared default when tuning combine.
9inline constexpr uint32_t kMoonEPAivNum = 32;16inline constexpr uint32_t kMoonEPAivNum = 32;
17+// Server dedup groups 8 globally consecutive ranks into one board.
18+inline constexpr uint32_t kMoonEPDispatchRanksPerServer = 8;
10inline constexpr uint32_t kMoonEPUdmaCombineQpCount = 2;19inline constexpr uint32_t kMoonEPUdmaCombineQpCount = 2;
11inline constexpr uint32_t kMoonEPUdmaCombineBandwidthScratchAlign = 64;20inline constexpr uint32_t kMoonEPUdmaCombineBandwidthScratchAlign = 64;
12inline constexpr uint32_t kMoonEPUdmaCombineBandwidthStatsStride = 8;21inline constexpr uint32_t kMoonEPUdmaCombineBandwidthStatsStride = 8;
@@ -15,6 +24,48 @@ inline constexpr uint32_t kMoonEPUdmaCombineBandwidthStatsElems =
15inline constexpr uint32_t kMoonEPUdmaCombineBandwidthScratchBytes =24inline constexpr uint32_t kMoonEPUdmaCombineBandwidthScratchBytes =
16 kMoonEPUdmaCombineBandwidthStatsElems * sizeof(int64_t);25 kMoonEPUdmaCombineBandwidthStatsElems * sizeof(int64_t);
17 26 
27+// Plan dedup tables are identical in both dedup domains; the domain only
28+// changes the capacities and the duplicate address encoding:
29+// dup_groups[NvS, 3] = {primary loff on its owning rank, dup_start, dup_n}.
30+// dup_n counts the non-primary members (<= K-1); a group is owned and
31+// materialized by the primary route's destination rank.
32+// dup_loffs: rank domain has NvS entries holding the in-rank loff; server
33+// domain has 8*NvS entries holding the full destination address
34+// rank*NvS + loff, so a group may list members on sibling ranks of the
35+// same server. There is no packed count word.
36+// dup_counts: rank [n_groups, n_dups]; server appends R per-source group
37+// prefixes [P_0 .. P_{R-1}], where P_src counts this rank's groups whose
38+// token source rank is below src (dispatch waits on that prefix).
39+inline constexpr uint32_t kMoonEPServerDupRouteLimit = 1U << 26;
40+ 
41+// Combine-plan internal route tag: the fused planner's per-token packed tables
42+// (contributors / relays) mark a representative that lives on the reading rank
43+// with 0x80000000 | raw. It is disjoint from the public dst encoding (positive
44+// canonical route, ~raw duplicate) while R*NvS < 2^30, and public dst never
45+// carries it: dispatch and the metric tests only ever see the two-state form.
46+inline constexpr uint32_t kMoonEPServerForwardedRouteTag = 0x80000000U;
47+inline constexpr uint32_t kMoonEPServerRoutePayloadMask = 0x3fffffffU;
48+ 
49+MOONEP_DEVICE_INLINE int32_t EncodeMoonEPServerForwardedRoute(uint32_t raw) {
50+ return static_cast<int32_t>(kMoonEPServerForwardedRouteTag | raw);
51+}
52+ 
53+MOONEP_DEVICE_INLINE bool IsMoonEPServerForwardedRoute(int32_t encoded) {
54+ return (static_cast<uint32_t>(encoded) & 0xc0000000U) ==
55+ kMoonEPServerForwardedRouteTag;
56+}
57+ 
58+MOONEP_DEVICE_INLINE uint32_t DecodeMoonEPServerForwardedRoute(int32_t encoded) {
59+ return static_cast<uint32_t>(encoded) & kMoonEPServerRoutePayloadMask;
60+}
61+ 
62+// Legacy GET scratch constants retained for compatibility. The current PUT
63+// workspace ABI is defined by MakeCombinePutLayout in types.h.
64+inline constexpr uint32_t kMoonEPUdmaCombineScratchTileElements = 8192;
65+inline constexpr uint32_t kMoonEPUdmaCombineScratchTilesPerAiv = 2;
66+ 
67+#undef MOONEP_DEVICE_INLINE
68+ 
18struct alignas(8) MoonEPCombineTilingData {69struct alignas(8) MoonEPCombineTilingData {
19 uint32_t rank; // current rank70 uint32_t rank; // current rank
20 uint32_t world_size; // EP size71 uint32_t world_size; // EP size
@@ -33,7 +84,8 @@ struct alignas(8) MoonEPUdmaCombineTilingData {
33 uint32_t R;84 uint32_t R;
34 uint32_t rank;85 uint32_t rank;
35 uint32_t with_weights;86 uint32_t with_weights;
36- uint32_t reserved;87+ uint32_t server_dedup;
88+ uint32_t reserved; // Preserve the 32-byte host/device tiling structure size.
37};89};
38 90 
39struct alignas(8) MoonEPDispatchTilingData {91struct alignas(8) MoonEPDispatchTilingData {
@@ -43,7 +95,7 @@ struct alignas(8) MoonEPDispatchTilingData {
43 uint32_t R;95 uint32_t R;
44 uint32_t rank;96 uint32_t rank;
45 uint32_t with_weights;97 uint32_t with_weights;
46- uint32_t reserved;98+ uint32_t server_dedup;
47 uint32_t block_dim; // MTE only; occupies the former tail padding99 uint32_t block_dim; // MTE only; occupies the former tail padding
48};100};
49 101 
@@ -83,10 +135,242 @@ struct alignas(8) PlanningTilingData {
83 uint32_t symmetric_dup_rank_counts_offset;135 uint32_t symmetric_dup_rank_counts_offset;
84 uint32_t source_dup_tokens_per_tile;136 uint32_t source_dup_tokens_per_tile;
85 uint32_t owner_reduce_tile_elems;137 uint32_t owner_reduce_tile_elems;
86- uint32_t reserved;138+ uint32_t server_dedup;
139+ uint32_t combine_mode; // 0: base only; 1: fused tail; 2: precomputed-dst only.
140+ uint32_t combine_h;
141+ uint32_t stripe_rank_placement;
142+ uint64_t combine_workspace;
143+ uint64_t combine_plan;
87};144};
88 145 
89-static_assert(sizeof(PlanningTilingData) == 56,146+static_assert(sizeof(PlanningTilingData) == 80,
90- "PlanningTilingData ABI must remain 56 bytes");147+ "PlanningTilingData fused ABI must remain 80 bytes");
91 148 
92} // namespace ascend_moonep149} // namespace ascend_moonep
150+ 
151+// Shared combine ABI: launch/batch sizes, workspace/plan layouts and trace capacity.
152+// Used by host launchers, planning.cpp and moonep_combine_udma.cpp.
153+ 
154+// Shared launch/workspace capacities, also consumed by host and planning.
155+namespace ascend_moonep {
156+inline constexpr uint32_t kCombinePutCores = 64;
157+inline constexpr uint32_t kCombinePutBatchRows = 64;
158+// Capacity factor only: runtime pages are packed by actual contributor rows.
159+inline constexpr uint32_t kCombineRingGroupsPerPage = 64;
160+inline constexpr uint32_t kCombineRingDepth = 4;
161+inline constexpr uint32_t kCombineRingStreams = 8;
162+inline constexpr uint32_t kCombineRingMaxShards = 4;
163+} // namespace ascend_moonep
164+ 
165+// ---- Communication workspace layout ----
166+namespace ascend_moonep {
167+#if defined(__CCE_AICORE__) || defined(__CCE_KT_TEST__)
168+#define MOONEP_PUT_INLINE __forceinline__ __aicore__
169+#else
170+#define MOONEP_PUT_INLINE inline constexpr
171+#endif
172+ 
173+// Aligned PUT workspace ABI. All uint64 members except bytes are byte offsets
174+// relative to symmetric ws, NOT pointers or lengths. Host and Python mirror it.
175+// N=S*K, H=hidden, R=ranks, B=ceil(N/64), A(x)=ceil(x/512)*512.
176+// Meta(base,i) uses independent 64-byte records; Flag(base,i) uses 512-byte slots.
177+// Only the first uint64 of a flag carries magic; reducer MTE3 writes 32 bytes.
178+//
179+// Source=original token owner/final destination; producer=expert-output holder;
180+// ingress=server group reducer. The same rank can have all three roles.
181+// Workspace offsets are shared by Planning and Combine. Host, Python and
182+// device kernels MUST be rebuilt and installed together after layout changes.
183+struct CombinePutLayout {
184+ uint64_t final_hidden; // BF16[N,H], compact producer segments at each source.
185+ // Local-server routes include suppressed members too.
186+ uint64_t relay_hidden; // Phase pool: Planning staging, then BF16 input ring.
187+ // 8 streams * 4 pages * (64*K) rows; groups never cross pages.
188+ uint64_t relay_result; // BF16[N,H], stable sums indexed by the original TX index.
189+ uint64_t weights; // float[N], every original source route, no weight dedup.
190+ 
191+ uint64_t reverse; // Retired reverse-route records; offset reserved for ABI stability.
192+ uint64_t reverse_send;// Reserved N*64B arena; planner publishes contiguous dst[N]
193+ // in its first N*4B. Peers read it, never PUT reverse requests.
194+ uint64_t final_map; // Retired scalar final mapping arena, offset reserved.
195+ // Planner now builds final descriptors by partition prefixes.
196+ uint64_t group_of_loff;// Retired group lookup arena; offset reserved.
197+ uint64_t tx_rows; // N records in source/ordinal order:
198+ // {loff,group,scratchHead(-1 for DIRECT),contributorCount}.
199+ // DIRECT count=1; send original hidden without server reduction.
200+ uint64_t source_counts;// R records:
201+ // [0]=active result count, [1]=remote final segment base,
202+ // [2]=local tx base, [3]=DIRECT count,
203+ // [4]=scratch range start, [5]=scratch slot count,
204+ // [6]=ring page count, [7]=first logical ring page.
205+ // Scratch slots INCLUDE contributor holes; <=N/source.
206+ uint64_t counts_send; // Planner-local R records: {groupCount,groupPrefix} per source.
207+ uint64_t contributor; // 8*N records: word0 is {count:high32,txIndex:low32},
208+ // word1 is original global contributor address.
209+ // Only a group head has count>0; interior slots are zero.
210+ // 64-byte spacing prevents concurrent planner cacheline
211+ // writeback races. Reducer gathers 64 entries into UB.
212+ uint64_t relay_send; // 8*N requests at producer: [ingressLocal*N+ordinal]
213+ // -> {input loff,remote scratch slot}. Includes ingress
214+ // self contributors for planning; payload skips them because
215+ // Reduce reads their original input directly.
216+ uint64_t relay_publish;// Retired relay request PUT arena; offset reserved.
217+ uint64_t relay_counts, relay_counts_send; // Legacy reserved 8-record tables.
218+ 
219+ uint64_t relay_ready; // 8*R slots, producerLocal*R+source, source-level SO ready.
220+ // Empty producer streams MUST publish as well.
221+ uint64_t reduce_ready;// R*B slots, source*B+scratchBatch; MTE3-ordered after sum.
222+ // B uses N, NOT N/R: nonuniform input must fit safely.
223+ uint64_t final_ready; // 2*R slots, producer*2+QP lane. Both remote lanes close
224+ // DIRECT+RELAY even when empty. Local Phase A uses lane0.
225+ uint64_t weight_ready;// R slots, producer -> complete all original route weights.
226+ uint64_t magic; // 64 stable per-core SHMEM PUT-source flag slots.
227+ uint64_t relay_ranges;// 8*R records at producer: ingressLocal*R+source
228+ // -> {requestBegin,requestCount,receiverSourcePageCount}.
229+ uint64_t relay_ranges_send; // Planner-local 8*R stats records:
230+ // {scratchCount,requestCount,scratchPrefix,requestPrefix}.
231+ // After metadata completion, reused as R*512B final
232+ // histograms: 64 partition counts/prefixes + peer total.
233+ uint64_t source_input_ready;// R slots, shard1 waits all producers, wakes shard0.
234+ uint64_t final_gate; // One local slot: core0 publishes after it has
235+ // observed every final_ready; all other cores wait here.
236+ uint64_t final_routes; // N independent 128-byte source-final descriptors.
237+ // Each output token owns {count, route[16]}; route is either
238+ // local hidden loff (bit31 set) or final_hidden row. N records
239+ // reserve for K=1 too; the active prefix is N/K records.
240+ uint64_t ring_epoch; // 8 receiver/peer invocation epochs.
241+ uint64_t ring_ready; // [stream,slot,producerLocal], 8*4*8 flags.
242+ uint64_t ring_credit; // [stream,slot], 8*4 reusable input-page credits.
243+ uint64_t ring_done; // [stream,slot,shard], 8*4*4 reducer completion flags.
244+ uint64_t ring_ready_source; // [ingressLocal,stream,slot], 8*8*4 SO source flags.
245+ uint64_t ring_result_ready; // Persistent logical-page ready flags, never ring-indexed.
246+ uint64_t bytes; // Total bytes including all alignment/reserved arenas.
247+ uint32_t batches; // ceil(N/64), worst per-source scratch batch capacity.
248+ uint32_t ring_page_rows, ring_page_capacity;
249+};
250+ 
251+MOONEP_PUT_INLINE uint64_t CombinePutAlign(uint64_t bytes) {
252+ return (bytes + 511U) & ~uint64_t(511U);
253+}
254+MOONEP_PUT_INLINE uint32_t CombineRingPageCapacity(uint32_t n, uint32_t ranks) {
255+ // Each nonempty source can contribute a separate partial final page.
256+ return static_cast<uint32_t>((uint64_t(n) + kCombineRingGroupsPerPage - 1U) /
257+ kCombineRingGroupsPerPage + ranks);
258+}
259+MOONEP_PUT_INLINE uint64_t CombineRingLayoutFingerprint(uint32_t k) {
260+ // Bit 40 distinguishes row-packed plans from legacy 64-group pages.
261+ return (uint64_t(1U) << 40U) | (uint64_t(kCombineRingStreams) << 56U) |
262+ (uint64_t(kCombineRingDepth) << 48U) |
263+ (uint64_t(kCombineRingGroupsPerPage) << 32U) |
264+ uint64_t(kCombineRingGroupsPerPage) * k;
265+}
266+MOONEP_PUT_INLINE uint64_t CombinePlanningStageBytes(
267+ uint32_t n, uint32_t h, uint32_t ranks) {
268+ // Preserve the original rank/server staged eligibility. Buffer allocation
269+ // precedes the plan's mode, so reserve the largest eligible mode's staging.
270+ if (ranks > 128U) return 0U;
271+ const uint64_t server = 32U + 8U * 8U, rank = 32U + 8U;
272+ if (uint64_t(ranks) * server <= uint64_t(h) * 16U)
273+ return uint64_t(ranks) * n * server;
274+ if (uint64_t(ranks) * rank <= uint64_t(h) * 16U)
275+ return uint64_t(ranks) * n * rank;
276+ return 0U;
277+}
278+MOONEP_PUT_INLINE uint64_t CombineRingPublishBytes(uint32_t n, uint32_t ranks) {
279+ const uint64_t legacy = uint64_t(n) * 8U * 64U;
280+ const uint64_t mirror = CombinePutAlign(uint64_t(ranks) * 64U) +
281+ CombinePutAlign(uint64_t(CombineRingPageCapacity(n, ranks)) * 64U);
282+ return CombinePutAlign(legacy > mirror ? legacy : mirror);
283+}
284+MOONEP_PUT_INLINE CombinePutLayout MakeCombinePutLayout(
285+ uint32_t n, uint32_t h, uint32_t ranks, uint32_t k = 16U) {
286+ CombinePutLayout p{};
287+ const uint64_t row_bytes = uint64_t(n) * h * 2U; // all N rows, not one row
288+ const uint64_t meta = uint64_t(n) * 64U;
289+ p.batches = (uint64_t(n) + 63U) / 64U;
290+ p.ring_page_rows = kCombineRingGroupsPerPage * k;
291+ p.ring_page_capacity = CombineRingPageCapacity(n, ranks);
292+ p.final_hidden = 0;
293+ p.relay_hidden = CombinePutAlign(row_bytes);
294+ const uint64_t ring_bytes = CombinePutAlign(uint64_t(kCombineRingStreams) *
295+ kCombineRingDepth * p.ring_page_rows * h * 2U);
296+ p.relay_result = p.relay_hidden + ring_bytes;
297+ const uint64_t runtime_bytes = ring_bytes + CombinePutAlign(row_bytes);
298+ const uint64_t stage_bytes = CombinePutAlign(CombinePlanningStageBytes(n, h, ranks));
299+ p.weights = p.relay_hidden + (stage_bytes > runtime_bytes ? stage_bytes : runtime_bytes);
300+ p.reverse = p.weights + CombinePutAlign(uint64_t(n) * 4U);
301+ p.reverse_send = p.reverse + CombinePutAlign(meta);
302+ p.final_map = p.reverse_send + CombinePutAlign(meta);
303+ p.group_of_loff = p.final_map + CombinePutAlign(meta);
304+ p.tx_rows = p.group_of_loff + CombinePutAlign(meta);
305+ p.source_counts = p.tx_rows + CombinePutAlign(meta);
306+ p.counts_send = p.source_counts + CombinePutAlign(uint64_t(ranks) * 64U);
307+ p.contributor = p.counts_send + CombinePutAlign(uint64_t(ranks) * 64U);
308+ p.relay_send = p.contributor + CombinePutAlign(8U * meta);
309+ p.relay_publish = p.relay_send + CombinePutAlign(8U * meta);
310+ p.relay_counts = p.relay_publish + CombineRingPublishBytes(n, ranks);
311+ p.relay_counts_send = p.relay_counts + 512U;
312+ p.relay_ready = p.relay_counts_send + 512U;
313+ p.reduce_ready = p.relay_ready + uint64_t(8U) * ranks * 512U;
314+ p.final_ready = p.reduce_ready + uint64_t(ranks) * p.batches * 512U;
315+ p.weight_ready = p.final_ready + uint64_t(ranks) * 2U * 512U;
316+ p.magic = p.weight_ready + uint64_t(ranks) * 512U;
317+ p.relay_ranges = p.magic + uint64_t(kCombinePutCores) * 512U;
318+ p.relay_ranges_send = p.relay_ranges + CombinePutAlign(uint64_t(8U) * ranks * 64U);
319+ p.source_input_ready = p.relay_ranges_send + CombinePutAlign(uint64_t(8U) * ranks * 64U);
320+ p.final_gate = p.source_input_ready + uint64_t(ranks) * 512U;
321+ p.final_routes = p.final_gate + 512U;
322+ p.ring_epoch = p.final_routes + CombinePutAlign(uint64_t(n) * 128U);
323+ p.ring_ready = p.ring_epoch + uint64_t(8U) * 512U;
324+ p.ring_credit = p.ring_ready + uint64_t(kCombineRingStreams) * kCombineRingDepth * 8U * 512U;
325+ p.ring_done = p.ring_credit + uint64_t(kCombineRingStreams) * kCombineRingDepth * 512U;
326+ p.ring_ready_source = p.ring_done + uint64_t(kCombineRingStreams) *
327+ kCombineRingDepth * kCombineRingMaxShards * 512U;
328+ p.ring_result_ready = p.ring_ready_source + uint64_t(8U) *
329+ kCombineRingStreams * kCombineRingDepth * 512U;
330+ p.bytes = p.ring_result_ready + uint64_t(p.ring_page_capacity) * 512U;
331+ return p;
332+}
333+#undef MOONEP_PUT_INLINE
334+} // namespace ascend_moonep
335+ 
336+// ---- Immutable execution-plan layout ----
337+namespace ascend_moonep {
338+#if defined(__CCE_AICORE__) || defined(__CCE_KT_TEST__)
339+#define MOONEP_PLAN_INLINE __forceinline__ __aicore__
340+#else
341+#define MOONEP_PLAN_INLINE inline constexpr
342+#endif
343+// Rank-local immutable snapshot. No payload, ready flags, magic or QP state.
344+// Offsets are relative to this tensor, not the symmetric communication workspace.
345+// v6: append immutable whole-group input pages and producer request mappings.
346+// Existing TX/contributor/relay record strides are unchanged. Ready flags,
347+// invocation epochs and ring credits remain in the communication workspace.
348+// Regenerate plans and deploy host/device together; older snapshots are incompatible.
349+inline constexpr uint64_t kCombineExecutionPlanVersion = 0x4d45504300000006ULL;
350+inline constexpr uint32_t kCombinePlanTxBytes = 16U;
351+inline constexpr uint32_t kCombinePlanContributorBytes = 16U;
352+inline constexpr uint32_t kCombinePlanRelayBytes = 8U;
353+struct CombineExecutionPlanLayout {
354+ uint64_t tx_rows, source_counts, contributor, relay_send, relay_ranges;
355+ uint64_t final_routes, ring_pages, relay_page_map, bytes;
356+};
357+MOONEP_PLAN_INLINE CombineExecutionPlanLayout MakeCombineExecutionPlanLayout(
358+ uint32_t n, uint32_t ranks) {
359+ CombineExecutionPlanLayout q{};
360+ q.tx_rows = 512U; // Header: version,N,H,K,R,rank,server_dedup,ring fingerprint.
361+ q.source_counts = q.tx_rows + CombinePutAlign(uint64_t(n) * kCombinePlanTxBytes);
362+ q.contributor = q.source_counts + CombinePutAlign(uint64_t(ranks) * 64U);
363+ q.relay_send = q.contributor + CombinePutAlign(uint64_t(n) * 8U * kCombinePlanContributorBytes);
364+ q.relay_ranges = q.relay_send + CombinePutAlign(uint64_t(n) * 8U * kCombinePlanRelayBytes);
365+ q.final_routes = q.relay_ranges + CombinePutAlign(uint64_t(ranks) * 8U * 64U);
366+ // Weights read the existing dst directly; no dedicated weights table.
367+ q.ring_pages = q.final_routes + CombinePutAlign(uint64_t(n) * 128U);
368+ // Each 64B page begins {scratchBegin,scratchCount,groupCount,source}.
369+ q.relay_page_map = q.ring_pages +
370+ CombinePutAlign(uint64_t(CombineRingPageCapacity(n, ranks)) * 64U);
371+ // Parallel to relay_send[8*N], each packed 8B entry is {sourcePageSeq,rowOffset}.
372+ q.bytes = q.relay_page_map + CombinePutAlign(uint64_t(n) * 8U * 8U);
373+ return q;
374+}
375+#undef MOONEP_PLAN_INLINE
376+} // namespace ascend_moonep
@@ -2,7 +2,7 @@
2// UBMEM implementation — uses the SHMEM symmetric window for publication and2// UBMEM implementation — uses the SHMEM symmetric window for publication and
3// batched UDMA Get submission across two explicit QPs for the remote gather.3// batched UDMA Get submission across two explicit QPs for the remote gather.
4//4//
5-// Architecture: A5/Ascend950 (UDMA), fixed kCombineAivNum AIV cores.5+// Architecture: A5/Ascend950 (UDMA), 32 or 64 AIV cores.
6//6//
7// Inputs are already published in SHMEM symmetric allocations.7// Inputs are already published in SHMEM symmetric allocations.
8// Single-kernel design (inverse of moonep_dispatch):8// Single-kernel design (inverse of moonep_dispatch):
@@ -27,6 +27,7 @@ using bf16_t = bfloat16_t;
27#define MOONEP_UDMA_PROFILE_STATISTIC 027#define MOONEP_UDMA_PROFILE_STATISTIC 0
28static constexpr uint32_t kCombineAivNum =28static constexpr uint32_t kCombineAivNum =
29 ascend_moonep::kMoonEPAivNum;29 ascend_moonep::kMoonEPAivNum;
30+static constexpr uint32_t kCombineWideAivNum = 64;
30static constexpr uint32_t kCombineUdmaQpNum =31static constexpr uint32_t kCombineUdmaQpNum =
31 ascend_moonep::kMoonEPUdmaCombineQpCount;32 ascend_moonep::kMoonEPUdmaCombineQpCount;
32static_assert(kCombineUdmaQpNum == 2,33static_assert(kCombineUdmaQpNum == 2,
@@ -170,8 +171,8 @@ __forceinline__ __aicore__ void CombineSplitRange(
170// Match dispatch's 6:2 CLOS port ratio: each four route chunks use171// Match dispatch's 6:2 CLOS port ratio: each four route chunks use
171// QP0, QP0, QP0, and QP1. A single AIV owns both QPs for a remote PE.172// QP0, QP0, QP0, and QP1. A single AIV owns both QPs for a remote PE.
172__forceinline__ __aicore__ uint32_t CombineGetChunkQpIndex(173__forceinline__ __aicore__ uint32_t CombineGetChunkQpIndex(
173- uint32_t chunk_index) {174+ uint32_t chunk_index, uint32_t active_qps) {
174- return chunk_index % 4U == 3U ? 1U : 0U;175+ return active_qps == kCombineUdmaQpNum && chunk_index % 4U == 3U ? 1U : 0U;
175}176}
176 177 
177__forceinline__ __aicore__ uint32_t CombineGetGroupWidth(uint32_t world_size) {178__forceinline__ __aicore__ uint32_t CombineGetGroupWidth(uint32_t world_size) {
@@ -972,7 +973,10 @@ __aicore__ CombineGatherResult GatherToStagingPhase(
972 ub_base, kCombineUdmaStagingOffset, kCombineUdmaStagingBytes)));973 ub_base, kCombineUdmaStagingOffset, kCombineUdmaStagingBytes)));
973 974 
974 CombineGatherResult result{};975 CombineGatherResult result{};
975- CombineLocalAivBarrier();976+ // The preceding rank barrier already orders the prologue writes.
977+ if (core_num == kCombineAivNum) {
978+ CombineLocalAivBarrier();
979+ }
976#if MOONEP_UDMA_PROFILE_STATISTIC980#if MOONEP_UDMA_PROFILE_STATISTIC
977 const uint64_t hidden_submit_start_cycle = AscendC::GetSystemCycle();981 const uint64_t hidden_submit_start_cycle = AscendC::GetSystemCycle();
978#endif982#endif
@@ -1003,6 +1007,9 @@ __aicore__ CombineGatherResult GatherToStagingPhase(
1003 ? CombineGetGroupRankIndex(rank, R)1007 ? CombineGetGroupRankIndex(rank, R)
1004 : 0U;1008 : 0U;
1005 const bool reader_active = R > 1U && core_idx < group_width;1009 const bool reader_active = R > 1U && core_idx < group_width;
1010+ const uint32_t active_qps =
1011+ reader_active && aclshmemi_udma_qp_info_fetch()->qp_num == 1U
1012+ ? 1U : kCombineUdmaQpNum;
1006 uint64_t hidden_rows = 0;1013 uint64_t hidden_rows = 0;
1007 for (uint32_t group = 0; group < group_count && reader_active; ++group) {1014 for (uint32_t group = 0; group < group_count && reader_active; ++group) {
1008 const uint32_t dest_rank = CombineGetGroupSourceRank(1015 const uint32_t dest_rank = CombineGetGroupSourceRank(
@@ -1043,7 +1050,7 @@ __aicore__ CombineGatherResult GatherToStagingPhase(
1043 const uint32_t chunk_index =1050 const uint32_t chunk_index =
1044 chunk_start / kCombineSlotChunkCount;1051 chunk_start / kCombineSlotChunkCount;
1045 const uint32_t qp_idx =1052 const uint32_t qp_idx =
1046- CombineGetChunkQpIndex(chunk_index);1053+ CombineGetChunkQpIndex(chunk_index, active_qps);
1047 uint32_t chunk_count = NvS - chunk_start;1054 uint32_t chunk_count = NvS - chunk_start;
1048 if (chunk_count > kCombineSlotChunkCount) {1055 if (chunk_count > kCombineSlotChunkCount) {
1049 chunk_count = kCombineSlotChunkCount;1056 chunk_count = kCombineSlotChunkCount;
@@ -1169,7 +1176,7 @@ __aicore__ CombineGatherResult GatherToStagingPhase(
1169 const uint32_t chunk_index =1176 const uint32_t chunk_index =
1170 chunk_start / kCombineSlotChunkCount;1177 chunk_start / kCombineSlotChunkCount;
1171 const uint32_t qp_idx =1178 const uint32_t qp_idx =
1172- CombineGetChunkQpIndex(chunk_index);1179+ CombineGetChunkQpIndex(chunk_index, active_qps);
1173 aclshmemx_submit_state_t submit_state{};1180 aclshmemx_submit_state_t submit_state{};
1174 aclshmemx_defer_t defer_action(submit_state);1181 aclshmemx_defer_t defer_action(submit_state);
1175 aclshmemx_submit_t submit_action(submit_state);1182 aclshmemx_submit_t submit_action(submit_state);
@@ -1290,7 +1297,7 @@ __aicore__ CombineGatherResult GatherToStagingPhase(
1290 }1297 }
1291 if (dest_rank != rank) {1298 if (dest_rank != rank) {
1292 for (uint32_t qp_idx = 0;1299 for (uint32_t qp_idx = 0;
1293- qp_idx < kCombineUdmaQpNum;1300+ qp_idx < active_qps;
1294 ++qp_idx) {1301 ++qp_idx) {
1295 aclshmemx_udma_qp_quiet(1302 aclshmemx_udma_qp_quiet(
1296 static_cast<int32_t>(dest_rank), qp_idx);1303 static_cast<int32_t>(dest_rank), qp_idx);
@@ -1347,10 +1354,14 @@ __aicore__ CombineGatherResult GatherToStagingPhase(
1347 const uint64_t weight_assemble_end_cycle = AscendC::GetSystemCycle();1354 const uint64_t weight_assemble_end_cycle = AscendC::GetSystemCycle();
1348#endif1355#endif
1349 1356 
1357+ // The barrier before weight assembly joins all staging producers.
1358+ // Weight assembly and hidden accumulation use disjoint buffers.
1350#if MOONEP_UDMA_PROFILE_STATISTIC1359#if MOONEP_UDMA_PROFILE_STATISTIC
1351 const uint64_t hidden_quiet_end_cycle = AscendC::GetSystemCycle();1360 const uint64_t hidden_quiet_end_cycle = AscendC::GetSystemCycle();
1352#endif1361#endif
1353- CombineLocalAivBarrier();1362+ if (core_num == kCombineAivNum) {
1363+ CombineLocalAivBarrier();
1364+ }
1354#if MOONEP_UDMA_PROFILE_STATISTIC1365#if MOONEP_UDMA_PROFILE_STATISTIC
1355 const uint64_t final_sync_end_cycle = AscendC::GetSystemCycle();1366 const uint64_t final_sync_end_cycle = AscendC::GetSystemCycle();
1356 result.hidden_submit_cycles =1367 result.hidden_submit_cycles =
@@ -1804,6 +1815,7 @@ extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ void moonep_udma_
1804 uint32_t rank = tiling.rank;1815 uint32_t rank = tiling.rank;
1805 1816 
1806 uint32_t core_idx = get_block_idx();1817 uint32_t core_idx = get_block_idx();
1818+ const uint32_t core_count = GetBlockNum();
1807 1819 
1808 LocalTensor<uint8_t> ub_base;1820 LocalTensor<uint8_t> ub_base;
1809 ub_base.address_.logicPos = static_cast<uint8_t>(TPosition::VECIN);1821 ub_base.address_.logicPos = static_cast<uint8_t>(TPosition::VECIN);
@@ -1827,7 +1839,7 @@ extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ void moonep_udma_
1827 1839 
1828 PlanProloguePhase<bf16_t>(1840 PlanProloguePhase<bf16_t>(
1829 ub_base, published_hidden, dgrp, dloff, dcnt,1841 ub_base, published_hidden, dgrp, dloff, dcnt,
1830- H, NvS, core_idx, kCombineAivNum);1842+ H, NvS, core_idx, core_count);
1831 1843 
1832 // Every prologue GM write is already completed by the MTE3 dependency in1844 // Every prologue GM write is already completed by the MTE3 dependency in
1833 // CombineStoreAccAsBf16, and PlanProloguePhase ends with PIPE_ALL. Avoid1845 // CombineStoreAccAsBf16, and PlanProloguePhase ends with PIPE_ALL. Avoid
@@ -1843,7 +1855,7 @@ extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ void moonep_udma_
1843 workspace_gm, dst_ptr, output_sk,1855 workspace_gm, dst_ptr, output_sk,
1844 H, tiling.R, NvS, false,1856 H, tiling.R, NvS, false,
1845 invocation_magic * 2U,1857 invocation_magic * 2U,
1846- rank, core_idx, kCombineAivNum);1858+ rank, core_idx, core_count);
1847 }1859 }
1848 const uint64_t gather_start_cycle = AscendC::GetSystemCycle();1860 const uint64_t gather_start_cycle = AscendC::GetSystemCycle();
1849#endif1861#endif
@@ -1857,7 +1869,7 @@ extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ void moonep_udma_
1857 workspace_gm, dst_ptr, output_sk,1869 workspace_gm, dst_ptr, output_sk,
1858 H, tiling.R, NvS, with_weights != 0,1870 H, tiling.R, NvS, with_weights != 0,
1859 invocation_magic * 2U + 1U,1871 invocation_magic * 2U + 1U,
1860- rank, core_idx, kCombineAivNum);1872+ rank, core_idx, core_count);
1861 gather_result.hidden_bytes += iter_result.hidden_bytes;1873 gather_result.hidden_bytes += iter_result.hidden_bytes;
1862#if MOONEP_UDMA_PROFILE_STATISTIC1874#if MOONEP_UDMA_PROFILE_STATISTIC
1863 gather_result.hidden_submit_cycles +=1875 gather_result.hidden_submit_cycles +=
@@ -1880,14 +1892,14 @@ extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ void moonep_udma_
1880 rank,1892 rank,
1881 tiling.R,1893 tiling.R,
1882 core_idx,1894 core_idx,
1883- kCombineAivNum);1895+ core_count);
1884#endif1896#endif
1885 1897 
1886 GatherAccumulatePhase<bf16_t>(1898 GatherAccumulatePhase<bf16_t>(
1887 ub_base, published_hidden,1899 ub_base, published_hidden,
1888 workspace_gm, dst_ptr, output_sh,1900 workspace_gm, dst_ptr, output_sh,
1889 S, H, K, tiling.R, NvS,1901 S, H, K, tiling.R, NvS,
1890- rank, core_idx, kCombineAivNum);1902+ rank, core_idx, core_count);
1891 PipeBarrier<PIPE_ALL>();1903 PipeBarrier<PIPE_ALL>();
1892 aclshmemx_barrier_all_vec();1904 aclshmemx_barrier_all_vec();
1893}1905}
@@ -1916,7 +1928,13 @@ void moonep_udma_combine_kernel_do(
1916{1928{
1917 auto* td = reinterpret_cast<ascend_moonep::MoonEPUdmaCombineTilingData*>(tiling_host);1929 auto* td = reinterpret_cast<ascend_moonep::MoonEPUdmaCombineTilingData*>(tiling_host);
1918 1930 
1919- moonep_udma_combine_kernel<<<kCombineAivNum, nullptr, stream>>>(1931+ // Keep the peer-reader group width and spread prologue, weight assembly
1932+ // and final reduction across more AIVs. Profiling uses the original
1933+ // per-core scratch capacity.
1934+ const bool use_wide = td->R == 8 || td->R == 16 || td->R == 32 || td->R == 64;
1935+ const uint32_t block_dim = use_wide && !MOONEP_UDMA_PROFILE_STATISTIC
1936+ ? kCombineWideAivNum : kCombineAivNum;
1937+ moonep_udma_combine_kernel<<<block_dim, nullptr, stream>>>(
1920 hidden_nvsh,1938 hidden_nvsh,
1921 route_weights_nvs,1939 route_weights_nvs,
1922 dst,1940 dst,
@@ -58,6 +58,7 @@ constexpr uint32_t kWeightSimtThreadCount = kWeightsPerGmConflictGroup;
58// Epilogue metadata tile stays a fixed 16KiB, independent of Weight slot size.58// Epilogue metadata tile stays a fixed 16KiB, independent of Weight slot size.
59constexpr uint32_t kMteUbBytes = 16 * 1024;59constexpr uint32_t kMteUbBytes = 16 * 1024;
60constexpr uint32_t kLocalCopyTileBytes = 16 * 1024;60constexpr uint32_t kLocalCopyTileBytes = 16 * 1024;
61+constexpr uint32_t kLocalCopyBufferBytes = 24 * 1024;
61constexpr uint32_t slotChunkCount = 8192;62constexpr uint32_t slotChunkCount = 8192;
62constexpr uint32_t kSlotTensorBytes = slotChunkCount * sizeof(int32_t);63constexpr uint32_t kSlotTensorBytes = slotChunkCount * sizeof(int32_t);
63constexpr uint32_t kSlotCompareMaskBytes = ((slotChunkCount / 8 + 31) / 32) * 32;64constexpr uint32_t kSlotCompareMaskBytes = ((slotChunkCount / 8 + 31) / 32) * 32;
@@ -135,7 +136,7 @@ static_assert(kWeightGmConflictGroupBytes % sizeof(float) == 0);
135static_assert(kWeightSimtThreadCount == 128);136static_assert(kWeightSimtThreadCount == 128);
136static_assert(kDuplicateHiddenStagingBytes <= kSlotSelectUbBytes);137static_assert(kDuplicateHiddenStagingBytes <= kSlotSelectUbBytes);
137// SIMT VF also needs the framework-reserved 8KiB immediate data UB.138// SIMT VF also needs the framework-reserved 8KiB immediate data UB.
138-static_assert(kUdmaWqeScratchBytes + kMteUbBytes + kLocalCopyTileBytes + kSlotSelectUbBytes <=139+static_assert(kUdmaWqeScratchBytes + kMteUbBytes + kLocalCopyBufferBytes + kSlotSelectUbBytes <=
139 kAivUbCapacityBytes - 8 * 1024);140 kAivUbCapacityBytes - 8 * 1024);
140 141 
141// Alignment of the routes processed per chunk.142// Alignment of the routes processed per chunk.
@@ -733,9 +734,54 @@ __aicore__ inline bool CanUseVectorSlotSelect(int64_t route_count)
733 return slot_shift <= 31;734 return slot_shift <= 31;
734}735}
735 736 
736-// Phase 1: vector-select the primary dst and batch-issue token WQEs.737+// Caller supplies an MTE-accessible window and publishes completion after
737-// template <bool Profile>, matching the UBMEM version, replaces the constexpr switch;738+// the MTE writes are visible to peers.
738-// with Profile=false the GetSystemCycle timing compiles to no-op, counters come via reference params.739+__aicore__ inline void CopySelectedHiddenMte(
740+ AscendC::LocalTensor<int32_t> selected_routes, AscendC::LocalTensor<int32_t> destinations,
741+ uint32_t selected_count, int64_t chunk_start, int64_t route_count, int64_t topk, uint32_t row_bytes,
742+ __gm__ uint8_t *hidden, __gm__ uint8_t *receive_window,
743+ AscendC::LocalTensor<uint8_t> staging, uint32_t staging_bytes)
744+{
745+ if (selected_count == 0) {
746+ return;
747+ }
748+ const uint32_t stride = (row_bytes + 31U) & ~31U;
749+ const bool double_buffer = stride <= staging_bytes / 2U;
750+ const uint32_t bank_bytes = double_buffer ? staging_bytes / 2U : staging_bytes;
751+ const uint32_t rows_per_batch = bank_bytes / stride;
752+ AscendC::GlobalTensor<uint8_t> src, dst;
753+ src.SetGlobalBuffer(hidden);
754+ dst.SetGlobalBuffer(receive_window);
755+ const AscendC::DataCopyExtParams copy{1, row_bytes, 0, 0, 0};
756+ const AscendC::DataCopyPadExtParams<uint8_t> pad{false, 0, 0, 0};
757+ AscendC::SetFlag<AscendC::HardEvent::MTE3_MTE2>(EVENT_ID0);
758+ AscendC::SetFlag<AscendC::HardEvent::MTE3_MTE2>(EVENT_ID1);
759+ uint32_t bank = 0;
760+ for (uint32_t first = 0; first < selected_count; first += rows_per_batch) {
761+ const uint32_t remaining = selected_count - first;
762+ const uint32_t count = remaining < rows_per_batch ? remaining : rows_per_batch;
763+ const AscendC::TEventID event = bank == 0 ? EVENT_ID0 : EVENT_ID1;
764+ auto buffer = staging[bank * bank_bytes];
765+ AscendC::WaitFlag<AscendC::HardEvent::MTE3_MTE2>(event);
766+ for (uint32_t row = 0; row < count; ++row) {
767+ const int64_t route = selected_routes.GetValue(first + row);
768+ AscendC::DataCopyPad(buffer[row * stride], src[(route / topk) * row_bytes], copy, pad);
769+ }
770+ AscendC::SetFlag<AscendC::HardEvent::MTE2_MTE3>(event);
771+ AscendC::WaitFlag<AscendC::HardEvent::MTE2_MTE3>(event);
772+ for (uint32_t row = 0; row < count; ++row) {
773+ const int64_t route = selected_routes.GetValue(first + row);
774+ const int64_t offset = destinations.GetValue(route - chunk_start) % route_count;
775+ AscendC::DataCopyPad(dst[offset * row_bytes], buffer[row * stride], copy);
776+ }
777+ AscendC::SetFlag<AscendC::HardEvent::MTE3_MTE2>(event);
778+ bank ^= static_cast<uint32_t>(double_buffer);
779+ }
780+ AscendC::WaitFlag<AscendC::HardEvent::MTE3_MTE2>(EVENT_ID0);
781+ AscendC::WaitFlag<AscendC::HardEvent::MTE3_MTE2>(EVENT_ID1);
782+}
783+ 
784+// Phase 1: vector-select the primary dst and scatter the hidden rows.
739template <bool Profile>785template <bool Profile>
740__aicore__ inline uint64_t DispatchScatterToken(786__aicore__ inline uint64_t DispatchScatterToken(
741 GM_ADDR hidden_gm,787 GM_ADDR hidden_gm,
@@ -767,8 +813,11 @@ __aicore__ inline uint64_t DispatchScatterToken(
767 sync_buffer + static_cast<uint64_t>(world_size) * kRankSyncSlotBytes;813 sync_buffer + static_cast<uint64_t>(world_size) * kRankSyncSlotBytes;
768 const uint32_t group_rank_index = static_cast<uint32_t>(aiv_index) % group_width;814 const uint32_t group_rank_index = static_cast<uint32_t>(aiv_index) % group_width;
769 const uint32_t current_rank_index = GetGroupRankIndex(current_rank, world_size);815 const uint32_t current_rank_index = GetGroupRankIndex(current_rank, world_size);
770- // Rank count is fixed for the kernel run, so compute the strict group sync switch once.816+ const bool use_mte = (world_size == 16 || world_size == 32 || world_size == 64) &&
771- const bool enable_strict_group_sync = world_size <= kStrictGroupSyncMaxWorldSize;817+ hidden_row_bytes > 0 && hidden_row_bytes <= kLocalCopyTileBytes;
818+ // The per-peer completion credit still gates each later round.
819+ const bool enable_strict_group_sync = world_size <= kStrictGroupSyncMaxWorldSize &&
820+ world_size != 32 && world_size != 64;
772 uint64_t transferred_bytes = 0;821 uint64_t transferred_bytes = 0;
773 822 
774 // Step 0: Token AIVs init their dedicated signals and start issuing after the local strict sync.823 // Step 0: Token AIVs init their dedicated signals and start issuing after the local strict sync.
@@ -802,6 +851,16 @@ __aicore__ inline uint64_t DispatchScatterToken(
802 for (uint32_t group = 0; group < group_count; ++group) {851 for (uint32_t group = 0; group < group_count; ++group) {
803 const int32_t dst_rank = GetGroupDstRank(current_rank, world_size, group, group_rank_index);852 const int32_t dst_rank = GetGroupDstRank(current_rank, world_size, group, group_rank_index);
804 853 
854+ constexpr auto ranks_per_server = ascend_moonep::kMoonEPDispatchRanksPerServer;
855+ __gm__ uint8_t *mte_window = nullptr;
856+ if (use_mte && dst_rank / ranks_per_server == current_rank / ranks_per_server) {
857+ if (dst_rank == current_rank) {
858+ mte_window = hidden_window;
859+ } else if (aclshmemi_get_state()->p2p_device_heap_base[dst_rank] != nullptr) {
860+ mte_window = reinterpret_cast<__gm__ uint8_t *>(aclshmem_ptr(hidden_window, dst_rank));
861+ }
862+ }
863+ 
805 // Later peers consume only the current-generation credit the destination published for this source rank.864 // Later peers consume only the current-generation credit the destination published for this source rank.
806 if (group > 0U) {865 if (group > 0U) {
807 WaitPeerCredit(866 WaitPeerCredit(
@@ -856,7 +915,8 @@ __aicore__ inline uint64_t DispatchScatterToken(
856 transferred_bytes += local_selected_count * static_cast<uint64_t>(hidden_row_bytes);915 transferred_bytes += local_selected_count * static_cast<uint64_t>(hidden_row_bytes);
857 916 
858 // Step 4: one QP for the whole chunk; the select list only generates and batch-submits WQEs.917 // Step 4: one QP for the whole chunk; the select list only generates and batch-submits WQEs.
859- const bool profile_wqe_submit = dst_rank != current_rank && local_selected_count > 0;918+ const bool profile_wqe_submit = mte_window == nullptr &&
919+ dst_rank != current_rank && local_selected_count > 0;
860 uint64_t wqe_submit_start_cycle = UdmaDetailedProfileStart<Profile>();920 uint64_t wqe_submit_start_cycle = UdmaDetailedProfileStart<Profile>();
861 if constexpr (Profile && kEnableDetailedProfile) {921 if constexpr (Profile && kEnableDetailedProfile) {
862 // Count only remote WQE generation/submission; local copies are not on the send path.922 // Count only remote WQE generation/submission; local copies are not on the send path.
@@ -866,7 +926,11 @@ __aicore__ inline uint64_t DispatchScatterToken(
866 }926 }
867 927 
868 // dst_rank is constant across the select list; branch once instead of per route.928 // dst_rank is constant across the select list; branch once instead of per route.
869- if (dst_rank == current_rank) {929+ if (mte_window != nullptr) {
930+ CopySelectedHiddenMte(selected_route_indices, dst_local, local_selected_count, chunk_start,
931+ route_count, num_topk, hidden_row_bytes, hidden, mte_window, local_copy_buffer.Get<uint8_t>(),
932+ kLocalCopyBufferBytes);
933+ } else if (dst_rank == current_rank) {
870 // Local copy. Could be folded into the duplicate phase, but kept separate:934 // Local copy. Could be folded into the duplicate phase, but kept separate:
871 // single-core UB copies there would drag bandwidth down.935 // single-core UB copies there would drag bandwidth down.
872 for (uint64_t selected = 0; selected < local_selected_count; ++selected) {936 for (uint64_t selected = 0; selected < local_selected_count; ++selected) {
@@ -935,6 +999,9 @@ __aicore__ inline uint64_t DispatchScatterToken(
935 }999 }
936 }1000 }
937 1001 
1002+ if (mte_window != nullptr) {
1003+ aclshmemx_mte_quiet();
1004+ }
938 // Step 5: append completion SO on the same dst/QP; after waiting the incoming1005 // Step 5: append completion SO on the same dst/QP; after waiting the incoming
939 // completion and forwarding the next-round credit, reclaim CQEs together.1006 // completion and forwarding the next-round credit, reclaim CQEs together.
940 uint64_t sync_start_cycle = UdmaDetailedProfileStart<Profile>();1007 uint64_t sync_start_cycle = UdmaDetailedProfileStart<Profile>();
@@ -1317,7 +1384,7 @@ __forceinline__ __aicore__ void MoonEPDispatchUdmaKernelImpl(
1317 AscendC::TBuf<AscendC::QuePosition::VECCALC> slot_select_buffer;1384 AscendC::TBuf<AscendC::QuePosition::VECCALC> slot_select_buffer;
1318 pipe.InitBuffer(udma_wqe_buffer, DispatchMoonep::kUdmaWqeScratchBytes);1385 pipe.InitBuffer(udma_wqe_buffer, DispatchMoonep::kUdmaWqeScratchBytes);
1319 pipe.InitBuffer(mte_buffer, DispatchMoonep::kMteUbBytes);1386 pipe.InitBuffer(mte_buffer, DispatchMoonep::kMteUbBytes);
1320- pipe.InitBuffer(local_copy_buffer, DispatchMoonep::kLocalCopyTileBytes);1387+ pipe.InitBuffer(local_copy_buffer, DispatchMoonep::kLocalCopyBufferBytes);
1321 pipe.InitBuffer(slot_select_buffer, DispatchMoonep::kSlotSelectUbBytes);1388 pipe.InitBuffer(slot_select_buffer, DispatchMoonep::kSlotSelectUbBytes);
1322 __ubuf__ uint8_t *udma_wqe =1389 __ubuf__ uint8_t *udma_wqe =
1323 reinterpret_cast<__ubuf__ uint8_t *>(udma_wqe_buffer.Get<uint8_t>().GetPhyAddr());1390 reinterpret_cast<__ubuf__ uint8_t *>(udma_wqe_buffer.Get<uint8_t>().GetPhyAddr());
@@ -657,12 +657,45 @@ BuildSourceDupCorePrefixesSimt(
657 }657 }
658}658}
659 659 
660+template <typename BoundaryPtr>
661+__simt_callee__ inline void StripeRankPlacement(BoundaryPtr boundaries, int32_t min_rows,
662+ int32_t &ordinal, int32_t &rank, int32_t &previous) {
663+ constexpr int32_t width = ascend_moonep::kMoonEPDispatchRanksPerServer;
664+ const int32_t first = rank / width * width;
665+ const int32_t last = first + width - 1;
666+ const int32_t begin = first == 0 ? 0 : boundaries[first - 1];
667+ const int32_t end = boundaries[last];
668+ const int32_t count = end - begin;
669+ if (count < min_rows || (previous == begin && boundaries[rank] == end)) {
670+ return;
671+ }
672+ 
673+ // Interleave source ordinals within this server, keeping each rank's
674+ // assigned capacity and each token's destination server unchanged.
675+ constexpr int32_t lanes = 64;
676+ const int32_t relative = ordinal - begin;
677+ const int32_t lane = relative % lanes;
678+ const int32_t remainder = count % lanes;
679+ ordinal = begin + lane * (count / lanes) + (lane < remainder ? lane : remainder) + relative / lanes;
680+ int32_t low = first;
681+ int32_t high = last;
682+ while (low < high) {
683+ const int32_t middle = low + (high - low) / 2;
684+ if (ordinal < boundaries[middle]) {
685+ high = middle;
686+ } else {
687+ low = middle + 1;
688+ }
689+ }
690+ rank = low;
691+ previous = rank == first ? begin : boundaries[rank - 1];
692+}
693+ 
660__simt_vf__ __launch_bounds__(kDstSimtMaxThreads) inline void BuildDstTileSimt(694__simt_vf__ __launch_bounds__(kDstSimtMaxThreads) inline void BuildDstTileSimt(
661 __ubuf__ int32_t* workspace,695 __ubuf__ int32_t* workspace,
662 int32_t context_offset,696 int32_t context_offset,
663- int32_t tile_base,697+ uint32_t stripe_rank_placement,
664 int32_t tile_len) {698 int32_t tile_len) {
665- (void)tile_base;
666 const int32_t thread = static_cast<int32_t>(threadIdx.x);699 const int32_t thread = static_cast<int32_t>(threadIdx.x);
667 __ubuf__ int32_t* context = workspace + context_offset;700 __ubuf__ int32_t* context = workspace + context_offset;
668 __ubuf__ int32_t* topk_tile = workspace + context[kDstSimtTopkOffset];701 __ubuf__ int32_t* topk_tile = workspace + context[kDstSimtTopkOffset];
@@ -712,7 +745,7 @@ __simt_vf__ __launch_bounds__(kDstSimtMaxThreads) inline void BuildDstTileSimt(
712 745 
713 const int32_t prior_chunk_count =746 const int32_t prior_chunk_count =
714 chunk == 0 ? 0 : chunk_prefix[(chunk - 1) * hist_stride + expert];747 chunk == 0 ? 0 : chunk_prefix[(chunk - 1) * hist_stride + expert];
715- const int32_t global_ordinal =748+ int32_t global_ordinal =
716 ordinal_base[expert] + prior_chunk_count + rank_in_chunk;749 ordinal_base[expert] + prior_chunk_count + rank_in_chunk;
717 750 
718 int32_t dst_rank = rank_count - 1;751 int32_t dst_rank = rank_count - 1;
@@ -725,6 +758,10 @@ __simt_vf__ __launch_bounds__(kDstSimtMaxThreads) inline void BuildDstTileSimt(
725 }758 }
726 previous_boundary = current_boundary;759 previous_boundary = current_boundary;
727 }760 }
761+ if (stripe_rank_placement) {
762+ StripeRankPlacement(alloc_cumsum + expert * rank_count, max_tokens_per_rank / 4,
763+ global_ordinal, dst_rank, previous_boundary);
764+ }
728 const int32_t dst_base = expert_offsets[dst_rank * expert_count + expert];765 const int32_t dst_base = expert_offsets[dst_rank * expert_count + expert];
729 dst_tile[route] = dst_rank * max_tokens_per_rank + dst_base +766 dst_tile[route] = dst_rank * max_tokens_per_rank + dst_base +
730 (global_ordinal - previous_boundary);767 (global_ordinal - previous_boundary);
@@ -741,7 +778,8 @@ __simt_vf__ __launch_bounds__(kDstSimtMaxThreads) inline void BuildDstTileFromGm
741 int32_t tile_len,778 int32_t tile_len,
742 int32_t rank_count,779 int32_t rank_count,
743 int32_t expert_count,780 int32_t expert_count,
744- int32_t max_tokens_per_rank) {781+ int32_t max_tokens_per_rank,
782+ uint32_t stripe_rank_placement) {
745 const int32_t thread = static_cast<int32_t>(threadIdx.x);783 const int32_t thread = static_cast<int32_t>(threadIdx.x);
746 784 
747 // A single thread assigns stable ordinals in input-route order. The785 // A single thread assigns stable ordinals in input-route order. The
@@ -759,7 +797,7 @@ __simt_vf__ __launch_bounds__(kDstSimtMaxThreads) inline void BuildDstTileFromGm
759 for (int32_t route = thread; route < tile_len;797 for (int32_t route = thread; route < tile_len;
760 route += kDstSimtMaxThreads) {798 route += kDstSimtMaxThreads) {
761 const int32_t expert = topk_tile[route];799 const int32_t expert = topk_tile[route];
762- const int32_t global_ordinal = dst_tile[route];800+ int32_t global_ordinal = dst_tile[route];
763 const int32_t cumsum_base = expert * rank_count;801 const int32_t cumsum_base = expert * rank_count;
764 802 
765 int32_t low = 0;803 int32_t low = 0;
@@ -773,10 +811,14 @@ __simt_vf__ __launch_bounds__(kDstSimtMaxThreads) inline void BuildDstTileFromGm
773 }811 }
774 }812 }
775 813 
776- const int32_t dst_rank = low < rank_count ? low : rank_count - 1;814+ int32_t dst_rank = low < rank_count ? low : rank_count - 1;
777- const int32_t previous_boundary = dst_rank == 0815+ int32_t previous_boundary = dst_rank == 0
778 ? 0816 ? 0
779 : alloc_cumsum[cumsum_base + dst_rank - 1];817 : alloc_cumsum[cumsum_base + dst_rank - 1];
818+ if (stripe_rank_placement) {
819+ StripeRankPlacement(alloc_cumsum + cumsum_base, max_tokens_per_rank / 4,
820+ global_ordinal, dst_rank, previous_boundary);
821+ }
780 const int32_t dst_base =822 const int32_t dst_base =
781 expert_offsets[dst_rank * expert_count + expert];823 expert_offsets[dst_rank * expert_count + expert];
782 dst_tile[route] = dst_rank * max_tokens_per_rank + dst_base +824 dst_tile[route] = dst_rank * max_tokens_per_rank + dst_base +
@@ -2757,7 +2799,7 @@ extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ void planning_ker
2757 dim3(static_cast<uint32_t>(kDstSimtMaxThreads)),2799 dim3(static_cast<uint32_t>(kDstSimtMaxThreads)),
2758 (__ubuf__ int32_t*)work_ub.GetPhyAddr(),2800 (__ubuf__ int32_t*)work_ub.GetPhyAddr(),
2759 dst_layout.context_offset / kInt32Bytes,2801 dst_layout.context_offset / kInt32Bytes,
2760- base,2802+ tiling.stripe_rank_placement,
2761 len);2803 len);
2762 AscendC::SetFlag<AscendC::HardEvent::V_MTE2>(EVENT_ID1);2804 AscendC::SetFlag<AscendC::HardEvent::V_MTE2>(EVENT_ID1);
2763 AscendC::PipeBarrier<PIPE_V>();2805 AscendC::PipeBarrier<PIPE_V>();
@@ -2828,7 +2870,8 @@ extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ void planning_ker
2828 len,2870 len,
2829 R,2871 R,
2830 E,2872 E,
2831- NvS);2873+ NvS,
2874+ tiling.stripe_rank_placement);
2832 AscendC::SetFlag<AscendC::HardEvent::V_MTE3>(EVENT_ID0);2875 AscendC::SetFlag<AscendC::HardEvent::V_MTE3>(EVENT_ID0);
2833 AscendC::WaitFlag<AscendC::HardEvent::V_MTE3>(EVENT_ID0);2876 AscendC::WaitFlag<AscendC::HardEvent::V_MTE3>(EVENT_ID0);
2834 2877 
@@ -11,6 +11,7 @@ dispatch-epilogue / combine-prologue steps are folded into ``DispatchOp`` and
11import torch11import torch
12 12 
13from .kernel_op import KernelOp13from .kernel_op import KernelOp
14+from .planning import RANKS_PER_SERVER
14from .launchers import (15from .launchers import (
15 launch_combine_op,16 launch_combine_op,
16 launch_dispatch_op,17 launch_dispatch_op,
@@ -71,6 +72,10 @@ class PlanningOp(KernelOp):
71 B = int(ctx["B"])72 B = int(ctx["B"])
72 N = S * K73 N = S * K
73 NvS = int(ctx["NvS"])74 NvS = int(ctx["NvS"])
75+ # Planning output capacity depends on the dedup domain; rank and server share the same operator entry.
76+ server_dedup = plan.dedup_mode == "server"
77+ dup_capacity = RANKS_PER_SERVER * NvS if server_dedup else NvS
78+ count_size = R + 2 if server_dedup else 2
74 _collect_inputs(79 _collect_inputs(
75 "PlanningOp",80 "PlanningOp",
76 tensors=(81 tensors=(
@@ -82,8 +87,8 @@ class PlanningOp(KernelOp):
82 ("plan.zero_fill_ranges", plan.zero_fill_ranges, [E + B, 2], torch.int32),87 ("plan.zero_fill_ranges", plan.zero_fill_ranges, [E + B, 2], torch.int32),
83 ("plan.remote_stats", plan.remote_stats, [2], torch.int32),88 ("plan.remote_stats", plan.remote_stats, [2], torch.int32),
84 ("plan.dup_groups", plan.dup_groups, [NvS, 3], torch.int32),89 ("plan.dup_groups", plan.dup_groups, [NvS, 3], torch.int32),
85- ("plan.dup_loffs", plan.dup_loffs, [NvS], torch.int32),90+ ("plan.dup_loffs", plan.dup_loffs, [dup_capacity], torch.int32),
86- ("plan.dup_counts", plan.dup_counts, [2], torch.int32),91+ ("plan.dup_counts", plan.dup_counts, [count_size], torch.int32),
87 ("ctx.planning_workspace", ctx["planning_workspace"], None, torch.int32),92 ("ctx.planning_workspace", ctx["planning_workspace"], None, torch.int32),
88 ),93 ),
89 scalars=(("shmem_instance_id", shmem_instance_id),),94 scalars=(("shmem_instance_id", shmem_instance_id),),
@@ -92,7 +97,22 @@ class PlanningOp(KernelOp):
92 workspace = self.sym_workspace()97 workspace = self.sym_workspace()
93 if workspace is None:98 if workspace is None:
94 raise RuntimeError("PlanningOp requires a symmetric workspace")99 raise RuntimeError("PlanningOp requires a symmetric workspace")
95- launch_planning_op(100+ # Custom NPU writes do not bump Tensor._version; invalidate prepared plans
101+ # explicitly whenever the supported planner rebuilds this plan's routing.
102+ if server_dedup:
103+ ctx['_combine_plan_generation'] = ctx.get('_combine_plan_generation', 0) + 1
104+ object.__setattr__(plan, '_planning_generation', ctx['_combine_plan_generation'])
105+ object.__setattr__(plan, 'combine_execution_plan', None)
106+ ctx.pop('_planning_timing_events', None)
107+ if ctx.get('_planning_timing_enabled', False):
108+ from .planning import begin_base_planning_timing
109+ begin_base_planning_timing(ctx, plan)
110+ fused = server_dedup and ctx['_combine_use_udma']
111+ fused_timing = None
112+ if fused:
113+ from .planning import begin_fused_combine_plan
114+ fused_timing = begin_fused_combine_plan()
115+ storage = launch_planning_op(
96 topk_flat,116 topk_flat,
97 plan.dst,117 plan.dst,
98 cu_seqlens,118 cu_seqlens,
@@ -111,7 +131,19 @@ class PlanningOp(KernelOp):
111 int(self.num_sms),131 int(self.num_sms),
112 rank,132 rank,
113 R,133 R,
134+ server_dedup,
135+ combine_workspace=ctx['combine_workspace'] if fused else None,
136+ hidden_size=int(ctx['H']) if fused else 0,
137+ use_udma=ctx['_dispatch_use_udma'],
114 )138 )
139+ # One planning kernel produces routing AND combine tables. This only
140+ # attaches its output/event; it does not launch a second kernel.
141+ if ctx.get('_planning_timing_enabled', False):
142+ from .planning import end_base_planning_timing
143+ end_base_planning_timing(ctx)
144+ if fused:
145+ from .planning import prepare_combine_plan
146+ prepare_combine_plan(ctx, plan, storage=storage, fused_timing=fused_timing)
115 147 
116 148 
117class DispatchOp(KernelOp):149class DispatchOp(KernelOp):
@@ -152,6 +184,7 @@ class DispatchOp(KernelOp):
152 int(ctx["R"]),184 int(ctx["R"]),
153 int(ctx["rank"]),185 int(ctx["rank"]),
154 num_sms=self.num_sms,186 num_sms=self.num_sms,
187+ server_dedup=plan.dedup_mode == "server",
155 )188 )
156 189 
157 def compute_profile(self, ctx, hidden_sh, route_weights_sk, plan,190 def compute_profile(self, ctx, hidden_sh, route_weights_sk, plan,
@@ -177,6 +210,7 @@ class DispatchOp(KernelOp):
177 int(ctx["K"]),210 int(ctx["K"]),
178 int(ctx["R"]),211 int(ctx["R"]),
179 int(ctx["rank"]),212 int(ctx["rank"]),
213+ plan.dedup_mode == "server",
180 )214 )
181 215 
182 216 
@@ -189,12 +223,22 @@ class CombineOp(KernelOp):
189 - reads remote rows from symmetric ``ctx['hidden_buf']`` via shmem_ptr223 - reads remote rows from symmetric ``ctx['hidden_buf']`` via shmem_ptr
190 - optional weight gather from ``ctx['weights_buf']`` into user-facing224 - optional weight gather from ``ctx['weights_buf']`` into user-facing
191 output_sk [S, K] fp32225 output_sk [S, K] fp32
192- - launcher selects native/UDMA from ASCEND_MOONEP_COMBINE_USE_UDMA226+ - launcher selects native / legacy-rank UDMA / server-dedup UDMA
227+ from the environment and the plan's dedup mode
193 - MTE launch width follows self.num_sms; UDMA keeps its fixed schedule228 - MTE launch width follows self.num_sms; UDMA keeps its fixed schedule
194 """229 """
195 230 
196 def compute(self, ctx, output_sh, plan, output_sk=None,231 def compute(self, ctx, output_sh, plan, output_sk=None,
197 shmem_instance_id: int = 0):232 shmem_instance_id: int = 0):
233+ server_dedup = plan.dedup_mode == "server"
234+ if server_dedup:
235+ if not ctx['_combine_use_udma']:
236+ raise ValueError('server dedup requires UDMA combine')
237+ from .combine import launch_combine_prepared
238+ if plan.combine_execution_plan is None:
239+ raise ValueError('UDMA combine requires PlanningOp to generate its execution plan first')
240+ return launch_combine_prepared(ctx, output_sh, plan,
241+ plan.combine_execution_plan, output_sk)
198 weight_buf = (242 weight_buf = (
199 ctx["weights_buf"].view(torch.float32)243 ctx["weights_buf"].view(torch.float32)
200 if output_sk is not None else None244 if output_sk is not None else None
@@ -217,6 +261,7 @@ class CombineOp(KernelOp):
217 num_sms=self.num_sms,261 num_sms=self.num_sms,
218 )262 )
219 263 
264+ 
220class PrefetchOp(KernelOp):265class PrefetchOp(KernelOp):
221 """Corresponds to ``moonep.launch_prefetch``.266 """Corresponds to ``moonep.launch_prefetch``.
222 267 
@@ -5,12 +5,17 @@ Local, CUDA-free mirror of the ``moonep/planning.py`` data structures.
5they depend only on torch (device comes from ``ctx``), so this module imports5they depend only on torch (device comes from ``ctx``), so this module imports
6cleanly without CUDA/CuTe. The planning *kernel* itself is provided by the6cleanly without CUDA/CuTe. The planning *kernel* itself is provided by the
7``PlanningOp`` (AscendC kernel migration).7``PlanningOp`` (AscendC kernel migration).
8+ 
9+This module also defines the shape conventions of the Ascend rank/server dedup plans.
8"""10"""
9 11 
10-from dataclasses import dataclass12+from dataclasses import dataclass, field
11 13 
12import torch14import torch
13 15 
16+# An Ascend server contains 8 ranks; the server dedup protocol sizes its capacity accordingly.
17+RANKS_PER_SERVER = 8
18+ 
14 19 
15@dataclass(frozen=True, slots=True)20@dataclass(frozen=True, slots=True)
16class MoonEPCommPlan:21class MoonEPCommPlan:
@@ -28,9 +33,15 @@ class MoonEPCommPlan:
28 # Dedup structures materialized by the dispatch builder and consumed by the33 # Dedup structures materialized by the dispatch builder and consumed by the
29 # dispatch epilogue / combine prologue. dup_counts = [n_groups, n_dup_loffs];34 # dispatch epilogue / combine prologue. dup_counts = [n_groups, n_dup_loffs];
30 # only the compact prefix of dup_groups/dup_loffs is valid.35 # only the compact prefix of dup_groups/dup_loffs is valid.
36+ # Server mode additionally stores full destination encodings and [G,D,P...]; the counts shape tells the modes apart.
31 dup_groups: torch.Tensor37 dup_groups: torch.Tensor
32 dup_loffs: torch.Tensor38 dup_loffs: torch.Tensor
33 dup_counts: torch.Tensor39 dup_counts: torch.Tensor
40+ # Produced by PlanningOp for UDMA combine; clone() copies its immutable tables.
41+ combine_execution_plan: object | None = field(default=None, repr=False, compare=False)
42+ # Native routing writes do not advance Tensor._version. Track this plan only,
43+ # so rebuilding a different plan does not invalidate independent snapshots.
44+ _planning_generation: int = field(default=0, repr=False, compare=False)
34 45 
35 def __post_init__(self) -> None:46 def __post_init__(self) -> None:
36 N = int(self.N)47 N = int(self.N)
@@ -38,6 +49,11 @@ class MoonEPCommPlan:
38 E = int(self.E)49 E = int(self.E)
39 B = int(self.B)50 B = int(self.B)
40 NvS = int(self.NvS)51 NvS = int(self.NvS)
52+ server_dedup = self.dedup_mode == "server"
53+ assert NvS >= N and (not server_dedup or NvS == N), "invalid NvS for the selected dedup mode"
54+ # Server mode requires a complete 8-rank board; rank mode keeps the original small-scale test capability.
55+ if server_dedup:
56+ assert R > 0 and R % RANKS_PER_SERVER == 0
41 assert self.dst.dtype == torch.int32 and self.dst.is_contiguous()57 assert self.dst.dtype == torch.int32 and self.dst.is_contiguous()
42 assert self.dst.numel() == N58 assert self.dst.numel() == N
43 assert self.experts_to_copy.dtype == torch.int32 and self.experts_to_copy.is_contiguous()59 assert self.experts_to_copy.dtype == torch.int32 and self.experts_to_copy.is_contiguous()
@@ -49,14 +65,30 @@ class MoonEPCommPlan:
49 assert self.dup_groups.dtype == torch.int32 and self.dup_groups.is_contiguous()65 assert self.dup_groups.dtype == torch.int32 and self.dup_groups.is_contiguous()
50 assert tuple(self.dup_groups.shape) == (NvS, 3)66 assert tuple(self.dup_groups.shape) == (NvS, 3)
51 assert self.dup_loffs.dtype == torch.int32 and self.dup_loffs.is_contiguous()67 assert self.dup_loffs.dtype == torch.int32 and self.dup_loffs.is_contiguous()
52- assert tuple(self.dup_loffs.shape) == (NvS,)68+ dup_capacity = RANKS_PER_SERVER * NvS if server_dedup else NvS
69+ count_size = R + 2 if server_dedup else 2
70+ assert tuple(self.dup_loffs.shape) == (dup_capacity,)
53 assert self.dup_counts.dtype == torch.int32 and self.dup_counts.is_contiguous()71 assert self.dup_counts.dtype == torch.int32 and self.dup_counts.is_contiguous()
54- assert tuple(self.dup_counts.shape) == (2,)72+ assert tuple(self.dup_counts.shape) == (count_size,)
73+ 
74+ @property
75+ def dedup_mode(self) -> str:
76+ """Distinguish the protocol from the counts shape, avoiding a separate mode field that could go stale."""
77+ return "server" if tuple(self.dup_counts.shape) == (self.R + 2,) else "rank"
55 78 
56 def clone(self) -> "MoonEPCommPlan":79 def clone(self) -> "MoonEPCommPlan":
57- """Deep-clone every plan tensor (mirrors ``moonep.planning``; the tests80+ """Copy routing and any prepared combine tables locally, without communication.
58- snapshot plans with ``plan.clone()``)."""81+ 
59- return type(self)(82+ The snapshot remains bound to the same Buffer and its reusable workspace;
83+ overlapping combine calls on that workspace are still unsupported.
84+ """
85+ execution = self.combine_execution_plan
86+ if execution is not None:
87+ execution.validate(execution.owner_ctx, self)
88+ import torch_npu
89+ stream = torch_npu.npu.current_stream()
90+ stream.wait_event(execution.ready)
91+ snapshot = type(self)(
60 dst=self.dst.clone(),92 dst=self.dst.clone(),
61 experts_to_copy=self.experts_to_copy.clone(),93 experts_to_copy=self.experts_to_copy.clone(),
62 zero_fill_ranges=self.zero_fill_ranges.clone(),94 zero_fill_ranges=self.zero_fill_ranges.clone(),
@@ -70,7 +102,148 @@ class MoonEPCommPlan:
70 B=self.B,102 B=self.B,
71 NvS=self.NvS,103 NvS=self.NvS,
72 K=self.K,104 K=self.K,
105+ _planning_generation=self._planning_generation,
73 )106 )
107+ if execution is not None:
108+ storage = execution.storage.clone()
109+ ready = torch_npu.npu.Event()
110+ ready.record(stream)
111+ for plan in (self, snapshot):
112+ for tensor in (plan.dst, plan.experts_to_copy, plan.zero_fill_ranges,
113+ plan.remote_stats, plan.dup_groups, plan.dup_loffs,
114+ plan.dup_counts):
115+ tensor.record_stream(stream)
116+ execution.storage.record_stream(stream)
117+ storage.record_stream(stream)
118+ copied_execution = CombineExecutionPlan(
119+ storage=storage, routing_id=id(snapshot), workspace=execution.workspace,
120+ key=execution.key, route_stamps=tuple(map(_stamp, _routes(snapshot))),
121+ storage_stamp=_stamp(storage), generation=snapshot._planning_generation,
122+ ready=ready, owner_ctx=execution.owner_ctx,
123+ prepare_begin=execution.prepare_begin, prepare_end=execution.prepare_end,
124+ fused=execution.fused,
125+ )
126+ object.__setattr__(snapshot, 'combine_execution_plan', copied_execution)
127+ return snapshot
128+ 
129+ 
130+# ---- Immutable combine execution-plan ownership and validation ----
131+# Reuse across hidden/weight updates is allowed; routing changes require all
132+# ranks to prepare again, in the same collective order.
133+def _routes(plan):
134+ return (plan.dst, plan.dup_groups, plan.dup_loffs, plan.dup_counts)
135+ 
136+ 
137+def _stamp(tensor):
138+ try:
139+ version = tensor._version
140+ except RuntimeError: # Inference tensors have no version counter.
141+ version = None
142+ return (tensor.data_ptr(), tuple(tensor.shape), tensor.dtype, tensor.device, version)
143+ 
144+ 
145+def _key(ctx):
146+ return tuple(int(ctx[name]) for name in ('S', 'H', 'K', 'R', 'rank'))
147+ 
148+ 
149+def _execution_key(ctx):
150+ # Keep the five native launch arguments stable. The local cached-plan key
151+ # also binds the private ring ABI and workspace geometry.
152+ from .combine import (COMBINE_RING_PLAN_ABI, COMBINE_RING_STREAMS,
153+ COMBINE_RING_DEPTH, COMBINE_RING_GROUPS_PER_PAGE)
154+ return (*_key(ctx), COMBINE_RING_PLAN_ABI, COMBINE_RING_STREAMS,
155+ COMBINE_RING_DEPTH, COMBINE_RING_GROUPS_PER_PAGE,
156+ int(ctx['combine_workspace'].numel()))
157+ 
158+ 
159+@dataclass
160+class CombineExecutionPlan:
161+ storage: torch.Tensor
162+ routing_id: int # Avoid plan -> execution -> plan cycles retaining large tensors.
163+ workspace: torch.Tensor
164+ key: tuple
165+ route_stamps: tuple
166+ storage_stamp: tuple
167+ generation: int
168+ ready: object
169+ owner_ctx: dict
170+ prepare_begin: object = None
171+ prepare_end: object = None
172+ fused: bool = False
173+ 
174+ def validate(self, ctx, plan):
175+ if (ctx.get('_comm_owner_ctx', ctx) is not self.owner_ctx
176+ or _execution_key(ctx) != self.key):
177+ raise ValueError('execution plan belongs to a different Buffer/topology/shape')
178+ if ctx['combine_workspace'].data_ptr() != self.workspace.data_ptr():
179+ raise ValueError('combine workspace changed; collectively prepare a new plan')
180+ if id(plan) != self.routing_id or tuple(map(_stamp, _routes(plan))) != self.route_stamps:
181+ raise ValueError('routing changed; all ranks must prepare a new execution plan')
182+ if plan._planning_generation != self.generation:
183+ raise ValueError('planning was rerun; all ranks must prepare a new execution plan')
184+ if _stamp(self.storage) != self.storage_stamp:
185+ raise ValueError('execution plan storage was modified')
186+ 
187+ 
188+# Optional timing hooks: record on the current stream without synchronizing.
189+# Benchmark code reads and reports the samples outside timed combine calls.
190+def begin_base_planning_timing(ctx, plan):
191+ import torch_npu
192+ stream = torch_npu.npu.current_stream()
193+ begin = torch_npu.npu.Event(enable_timing=True)
194+ end = torch_npu.npu.Event(enable_timing=True)
195+ ctx['_planning_timing_events'] = dict(
196+ begin=begin, end=end, stream=stream, routing_id=id(plan),
197+ generation=ctx.get('_combine_plan_generation', 0))
198+ begin.record(stream)
199+ 
200+ 
201+def end_base_planning_timing(ctx):
202+ events = ctx['_planning_timing_events']
203+ events['end'].record(events['stream'])
204+ 
205+ 
206+def begin_fused_combine_plan():
207+ import torch_npu
208+ stream = torch_npu.npu.current_stream()
209+ begin = torch_npu.npu.Event(enable_timing=True)
210+ end = torch_npu.npu.Event(enable_timing=True)
211+ begin.record(stream)
212+ return begin, end, stream
213+ 
214+ 
215+def prepare_combine_plan(ctx, plan, *, storage=None, fused_timing=None):
216+ """Attach fused planning output, or prepare explicitly hand-built routes.
217+ 
218+ Also available for callers which construct dst/dup_* manually. All ranks
219+ must call after routing changes; this reads metadata only, not hidden/weights.
220+ """
221+ from .launchers import _env_use_udma
222+ if not _env_use_udma('combine'):
223+ raise ValueError('execution plans require UDMA combine')
224+ if plan.dedup_mode != "server":
225+ raise ValueError(
226+ 'combine execution plans are a server-level dedup feature; '
227+ 'rank-level dedup uses the legacy combine kernel')
228+ object.__setattr__(plan, 'combine_execution_plan', None)
229+ fused = fused_timing is not None
230+ begin, end, stream = fused_timing if fused else begin_fused_combine_plan()
231+ tensors = _routes(plan)
232+ if fused:
233+ if storage is None:
234+ raise ValueError('fused planner did not return execution storage')
235+ else:
236+ storage = torch.classes.AscendMoonEP.Planning().prepare_combine_plan(
237+ ctx['combine_workspace'], *tensors, *_key(ctx))
238+ end.record(stream)
239+ for tensor in (storage, *tensors, ctx['combine_workspace']):
240+ tensor.record_stream(stream)
241+ execution = CombineExecutionPlan(storage, id(plan), ctx['combine_workspace'], _execution_key(ctx),
242+ tuple(map(_stamp, tensors)), _stamp(storage),
243+ plan._planning_generation, end, ctx, begin, end)
244+ execution.fused = fused
245+ object.__setattr__(plan, 'combine_execution_plan', execution)
246+ return execution
74 247 
75 248 
76def _round4(n: int) -> int:249def _round4(n: int) -> int:
@@ -82,6 +255,14 @@ def allocate_planning_outputs(ctx: dict):
82 255 
83 The plan-owned dedup tensors are allocated here; the Ascend Planning kernel256 The plan-owned dedup tensors are allocated here; the Ascend Planning kernel
84 materializes their compact prefixes together with ``dup_counts``.257 materializes their compact prefixes together with ``dup_counts``.
258+ 
259+ The dedup domain is a property of the Buffer, fixed at construction:
260+ ``ctx['dedup_mode']`` is ``"rank"`` (the default, same as the local
261+ rank-level code path) or ``"server"``, and ``ctx['ranks_per_server']`` is
262+ the server size (8 by default and currently the only compiled value).
263+ There is deliberately no per-call override: dispatching with a dedup mode
264+ that differs from the Buffer's would mix two workspace/layout contracts.
265+ Synthetic contexts that predate these keys keep the rank-level behavior.
85 """266 """
86 E = ctx['E']267 E = ctx['E']
87 B = ctx.get('B', 0)268 B = ctx.get('B', 0)
@@ -89,6 +270,27 @@ def allocate_planning_outputs(ctx: dict):
89 K = ctx['K']270 K = ctx['K']
90 N = S * K271 N = S * K
91 NvS = ctx['NvS']272 NvS = ctx['NvS']
273+ R = ctx['R']
274+ dedup_mode = ctx.get('dedup_mode', 'rank')
275+ ranks_per_server = ctx.get('ranks_per_server', RANKS_PER_SERVER)
276+ if dedup_mode not in ('rank', 'server'):
277+ raise ValueError("dedup_mode must be 'rank' or 'server'")
278+ if isinstance(ranks_per_server, bool) or not isinstance(ranks_per_server, int):
279+ raise TypeError("ranks_per_server must be an int")
280+ if ranks_per_server <= 0:
281+ raise ValueError("ranks_per_server must be positive")
282+ server_dedup = dedup_mode == 'server'
283+ # Server mode addresses physical boards; an incomplete board cannot be treated as one dedup domain.
284+ if server_dedup:
285+ if ranks_per_server != RANKS_PER_SERVER:
286+ raise NotImplementedError(
287+ "server dedup kernels are compiled for "
288+ f"{RANKS_PER_SERVER} ranks/server, got {ranks_per_server}")
289+ if R <= 0 or R % ranks_per_server != 0:
290+ raise ValueError(
291+ f"server planning requires R divisible by {ranks_per_server}")
292+ if NvS < N or (server_dedup and NvS != N):
293+ raise ValueError("invalid NvS for the selected dedup mode")
92 dev = ctx['weights_buf'].device294 dev = ctx['weights_buf'].device
93 295 
94 # Over-allocate output tensors to a multiple of 4 and then slice, avoiding296 # Over-allocate output tensors to a multiple of 4 and then slice, avoiding
@@ -105,8 +307,11 @@ def allocate_planning_outputs(ctx: dict):
105 dup_groups = torch.empty(307 dup_groups = torch.empty(
106 _round4(NvS * 3), dtype=torch.int32, device=dev308 _round4(NvS * 3), dtype=torch.int32, device=dev
107 )[:NvS * 3].view(NvS, 3)309 )[:NvS * 3].view(NvS, 3)
108- dup_loffs = torch.empty(_round4(NvS), dtype=torch.int32, device=dev)[:NvS]310+ # Only server mode enlarges the secondary list and reserves a group start for each source.
109- dup_counts = torch.empty(_round4(2), dtype=torch.int32, device=dev)[:2]311+ dup_capacity = ranks_per_server * NvS if server_dedup else NvS
312+ count_size = R + 2 if server_dedup else 2
313+ dup_loffs = torch.empty(_round4(dup_capacity), dtype=torch.int32, device=dev)[:dup_capacity]
314+ dup_counts = torch.empty(_round4(count_size), dtype=torch.int32, device=dev)[:count_size]
110 315 
111 plan = MoonEPCommPlan(316 plan = MoonEPCommPlan(
112 dst=dst,317 dst=dst,
@@ -11,6 +11,7 @@
11# 2. git submodule update --init --recursive (cann/shmem, catlass)11# 2. git submodule update --init --recursive (cann/shmem, catlass)
12# 3. build cann/shmem for the SoC -> npu_patch/3rdparty/shmem/install12# 3. build cann/shmem for the SoC -> npu_patch/3rdparty/shmem/install
13# 4. cmake -S npu_patch/native -B <build dir> -> ascend_moonep_kernels13# 4. cmake -S npu_patch/native -B <build dir> -> ascend_moonep_kernels
14+# plus ascend_moonep_kernels_server_dedup on Ascend950
14# 5. stage the kernel + shmem .so into npu_patch/lib15# 5. stage the kernel + shmem .so into npu_patch/lib
15# 6. pip install -e . (compiles the npu_patch._C NPU extension)16# 6. pip install -e . (compiles the npu_patch._C NPU extension)
16#17#
@@ -136,7 +137,7 @@ if [[ ! -f "${RUNTIME_INCLUDE_DIR}/rt.h" ]]; then
136fi137fi
137 138 
138# 2. Dependency trees (git submodules).139# 2. Dependency trees (git submodules).
139-if [[ -d "${ROOT_DIR}/.git" ]]; then140+if [[ -e "${ROOT_DIR}/.git" ]]; then
140 echo "[INFO] git submodule update --init --recursive"141 echo "[INFO] git submodule update --init --recursive"
141 git -C "${ROOT_DIR}" submodule update --init --recursive || \142 git -C "${ROOT_DIR}" submodule update --init --recursive || \
142 echo "[WARN] submodule update failed; continue if 3rdparty is already present."143 echo "[WARN] submodule update failed; continue if 3rdparty is already present."
@@ -179,10 +180,16 @@ if [[ -n "${ASCEND_MOONEP_RUNTIME_INCLUDE_DIR:-}" ]]; then
179 CMAKE_ARGS+=(-DASCEND_MOONEP_RUNTIME_INCLUDE_DIR="${ASCEND_MOONEP_RUNTIME_INCLUDE_DIR}")180 CMAKE_ARGS+=(-DASCEND_MOONEP_RUNTIME_INCLUDE_DIR="${ASCEND_MOONEP_RUNTIME_INCLUDE_DIR}")
180fi181fi
181cmake "${CMAKE_ARGS[@]}"182cmake "${CMAKE_ARGS[@]}"
182-cmake --build "${BUILD_DIR}" --target ascend_moonep_kernels --parallel183+kernel_targets=(ascend_moonep_kernels)
184+if [[ "${ARCH}" == "a5" ]]; then
185+ kernel_targets+=(ascend_moonep_kernels_server_dedup)
186+fi
187+cmake --build "${BUILD_DIR}" --target "${kernel_targets[@]}" --parallel
183 188 
184mkdir -p "${LIB_TARGET}"189mkdir -p "${LIB_TARGET}"
185-cp "${BUILD_DIR}/lib/libascend_moonep_kernels.so" "${LIB_TARGET}/"190+for target in "${kernel_targets[@]}"; do
191+ cp "${BUILD_DIR}/lib/lib${target}.so" "${LIB_TARGET}/"
192+done
186find "${SHMEM_HOME_PATH}/shmem/lib" \193find "${SHMEM_HOME_PATH}/shmem/lib" \
187 -maxdepth 1 \( -type f -o -type l \) \( -name "*.so" -o -name "*.so.*" \) \194 -maxdepth 1 \( -type f -o -type l \) \( -name "*.so" -o -name "*.so.*" \) \
188 -exec cp -P {} "${LIB_TARGET}/" \;195 -exec cp -P {} "${LIB_TARGET}/" \;
@@ -210,4 +217,6 @@ python -m pip install -e . --no-build-isolation --no-deps
210popd >/dev/null217popd >/dev/null
211 218 
212echo "[INFO] Build completed."219echo "[INFO] Build completed."
213-echo "[INFO] Kernel library: ${LIB_TARGET}/libascend_moonep_kernels.so"220+for target in "${kernel_targets[@]}"; do
221+ echo "[INFO] Kernel library: ${LIB_TARGET}/lib${target}.so"
222+done
@@ -4,6 +4,7 @@
4# Usage (the script locates itself; run from the repo root):4# Usage (the script locates itself; run from the repo root):
5# bash npu_patch/scripts/run_test.sh # mte/ubmem engine (default)5# bash npu_patch/scripts/run_test.sh # mte/ubmem engine (default)
6# bash npu_patch/scripts/run_test.sh --use_urma # urma engine (A5/Ascend950 only)6# bash npu_patch/scripts/run_test.sh --use_urma # urma engine (A5/Ascend950 only)
7+# bash npu_patch/scripts/run_test.sh --use_urma --dedup-mode server
7# bash npu_patch/scripts/run_test.sh --soc_type Ascend910_93 # A38# bash npu_patch/scripts/run_test.sh --soc_type Ascend910_93 # A3
8# BUILD=1 bash npu_patch/scripts/run_test.sh # rebuild _C before running tests9# BUILD=1 bash npu_patch/scripts/run_test.sh # rebuild _C before running tests
9# NPROC=4 RANK_N=4 bash npu_patch/scripts/run_test.sh # set card count10# NPROC=4 RANK_N=4 bash npu_patch/scripts/run_test.sh # set card count
@@ -62,10 +63,16 @@ cd "$REPO_ROOT"
62# Args / environment63# Args / environment
63# ---------------------------------------------------------------------------64# ---------------------------------------------------------------------------
64USE_URMA=065USE_URMA=0
66+DEDUP_MODE=rank
65SOC_TYPE="${SOC_TYPE:-Ascend950}"67SOC_TYPE="${SOC_TYPE:-Ascend950}"
66while [[ $# -gt 0 ]]; do68while [[ $# -gt 0 ]]; do
67 case "$1" in69 case "$1" in
68 --use_urma) USE_URMA=1; shift ;;70 --use_urma) USE_URMA=1; shift ;;
71+ --dedup-mode)
72+ case "${2:-}" in
73+ rank|server) DEDUP_MODE="$2"; shift 2 ;;
74+ *) echo "[ERROR] --dedup-mode requires rank or server"; exit 1 ;;
75+ esac ;;
69 --soc_type|-soc_type)76 --soc_type|-soc_type)
70 if [[ $# -lt 2 ]]; then77 if [[ $# -lt 2 ]]; then
71 echo "[ERROR] --soc_type requires a value, for example: --soc_type Ascend950"78 echo "[ERROR] --soc_type requires a value, for example: --soc_type Ascend950"
@@ -74,7 +81,7 @@ while [[ $# -gt 0 ]]; do
74 SOC_TYPE="$2"; shift 2 ;;81 SOC_TYPE="$2"; shift 2 ;;
75 *)82 *)
76 echo "[ERROR] Unknown argument: $1"83 echo "[ERROR] Unknown argument: $1"
77- echo "Usage: bash npu_patch/scripts/run_test.sh [--use_urma] [--soc_type {Ascend910B|Ascend910_93|Ascend950}]"84+ echo "Usage: bash npu_patch/scripts/run_test.sh [--use_urma] [--dedup-mode rank|server] [--soc_type {Ascend910B|Ascend910_93|Ascend950}]"
78 exit 1 ;;85 exit 1 ;;
79 esac86 esac
80done87done
@@ -87,6 +94,11 @@ case "${SOC_TYPE}" in
87 exit 1 ;;94 exit 1 ;;
88esac95esac
89 96 
97+if [[ "$DEDUP_MODE" == server && "$USE_URMA" != 1 ]]; then
98+ echo "[ERROR] --dedup-mode server requires --use_urma"
99+ exit 1
100+fi
101+ 
90# urma/udma ops are A5(SIMT)-only: dispatch_udma uses __simt_vf__ +102# urma/udma ops are A5(SIMT)-only: dispatch_udma uses __simt_vf__ +
91# simt_api/device_sync_functions.h; A2/A3 do not define ASCEND_MOONEP_UDMA.103# simt_api/device_sync_functions.h; A2/A3 do not define ASCEND_MOONEP_UDMA.
92if [ "$USE_URMA" = 1 ] && [ "$SOC_TYPE" != "Ascend950" ]; then104if [ "$USE_URMA" = 1 ] && [ "$SOC_TYPE" != "Ascend950" ]; then
@@ -121,6 +133,10 @@ _count_visible_devices() {
121VISIBLE="$(_count_visible_devices)"133VISIBLE="$(_count_visible_devices)"
122NPROC="${NPROC:-$VISIBLE}"134NPROC="${NPROC:-$VISIBLE}"
123RANK_N="${RANK_N:-$NPROC}"135RANK_N="${RANK_N:-$NPROC}"
136+if [[ "$DEDUP_MODE" == server ]] && (( NPROC % 8 != 0 || RANK_N % 8 != 0 )); then
137+ echo "[ERROR] Server dedup requires complete eight-rank servers"
138+ exit 1
139+fi
124FAILED=0140FAILED=0
125PASSED=0141PASSED=0
126 142 
@@ -205,13 +221,23 @@ if [ "$USE_URMA" = 1 ]; then
205 # dispatch_udma has no --B; dispatch_combine_udma_joint has no --mode/--B.221 # dispatch_udma has no --B; dispatch_combine_udma_joint has no --mode/--B.
206 # R is RANK_N for all.222 # R is RANK_N for all.
207 run_cmd "test_moonep_combine_udma_with_plan (kernel)" \223 run_cmd "test_moonep_combine_udma_with_plan (kernel)" \
208- python test_npu/urma/test_moonep_combine_udma_with_plan.py --mode kernel --R "$RANK_N" --S 8192 --K 8 --H 7168 --E 384 --plan-mode cyclic224+ python test_npu/urma/test_moonep_combine_udma_with_plan.py --mode kernel --combine-engine udma \
209- run_cmd "test_moonep_dispatch_udma_with_plan (kernel)" \225+ --R "$RANK_N" --S 8192 --K 8 --H 7168 --E 384 --plan-mode cyclic --dedup-mode "$DEDUP_MODE"
210- python test_npu/urma/test_moonep_dispatch_udma_with_plan.py --mode kernel --R "$RANK_N" --S 8192 --K 8 --H 7168 --E 384 --plan-mode cyclic226+ for plan_source in golden kernel; do
227+ run_cmd "test_moonep_dispatch_udma_with_plan ($plan_source plan)" \
228+ python test_npu/urma/test_moonep_dispatch_udma_with_plan.py --mode kernel --plan-source "$plan_source" \
229+ --R "$RANK_N" --S 8192 --K 8 --H 7168 --E 384 --plan-mode cyclic --dedup-mode "$DEDUP_MODE"
230+ done
211 run_cmd "test_dispatch_combine_udma_joint" \231 run_cmd "test_dispatch_combine_udma_joint" \
212- python test_npu/urma/test_dispatch_combine_udma_joint.py --R "$RANK_N" --S 8192 --K 8 --H 7168 --E 384 --plan-mode cyclic232+ python test_npu/urma/test_dispatch_combine_udma_joint.py --R "$RANK_N" --S 8192 --K 8 --H 7168 --E 384 --plan-mode cyclic --dedup-mode "$DEDUP_MODE"
213 run_cmd "pytest test_npu/urma/test_e2e_urma.py (NPROC=$NPROC)" \233 run_cmd "pytest test_npu/urma/test_e2e_urma.py (NPROC=$NPROC)" \
214- torchrun --nproc-per-node="$NPROC" -m pytest -s test_npu/urma/test_e2e_urma.py234+ torchrun --nproc-per-node="$NPROC" -m pytest -s test_npu/urma/test_e2e_urma.py -k "$DEDUP_MODE"
235+ if [[ "$DEDUP_MODE" == server ]]; then
236+ run_cmd "pytest server dedup QP policy" \
237+ python -m pytest -q test_npu/buffer_test/test_dedup_env_qp.py
238+ run_cmd "pytest prepared communication buffers (server)" \
239+ torchrun --nproc-per-node="$NPROC" -m pytest -s test_npu/buffer_test/test_buffer_comm_buffers.py -k server
240+ fi
215else241else
216 run_cmd "pytest test_npu/mte/test_grad_reduce.py (NPROC=$NPROC)" \242 run_cmd "pytest test_npu/mte/test_grad_reduce.py (NPROC=$NPROC)" \
217 torchrun --nproc-per-node="$NPROC" -m pytest -s test_npu/mte/test_grad_reduce.py243 torchrun --nproc-per-node="$NPROC" -m pytest -s test_npu/mte/test_grad_reduce.py
@@ -254,4 +280,4 @@ fi
254 280 
255log "Summary"281log "Summary"
256echo "PASSED=$PASSED FAILED=$FAILED ENGINE=$ENGINE_KW SOC_TYPE=$SOC_TYPE NPROC=$NPROC"282echo "PASSED=$PASSED FAILED=$FAILED ENGINE=$ENGINE_KW SOC_TYPE=$SOC_TYPE NPROC=$NPROC"
257-[ "$FAILED" -eq 0 ]283+[ "$FAILED" -eq 0 ]
@@ -16,8 +16,10 @@ Two mutually exclusive build paths:
16 16 
172. Ascend / NPU (when an Ascend toolchain is detected): compiles the172. Ascend / NPU (when an Ascend toolchain is detected): compiles the
18 vendored `npu_patch._C` extension from `npu_patch/native/csrc/` and18 vendored `npu_patch._C` extension from `npu_patch/native/csrc/` and
19- links the AscendC kernel library (`npu_patch/lib/libascend_moonep_kernels.so`)19+ links the AscendC kernel libraries
20- built by `npu_patch/scripts/build_base.sh` (wrapper: `build_a5.sh`). The GPU20+ (`npu_patch/lib/libascend_moonep_kernels.so` and
21+ `npu_patch/lib/libascend_moonep_kernels_server_dedup.so` on Ascend950) built by
22+ `npu_patch/scripts/build_base.sh` (wrapper: `build_a5.sh`). The GPU
21 logic is unchanged.23 logic is unchanged.
22 24 
23The backend is selected at build time by `_is_ascend_build()`: it prefers an25The backend is selected at build time by `_is_ascend_build()`: it prefers an
@@ -85,11 +87,17 @@ def _npu_extension():
85 kernel_lib_dir = Path(87 kernel_lib_dir = Path(
86 os.environ.get("ASCEND_MOONEP_KERNEL_LIB_DIR", ROOT / "npu_patch" / "lib")88 os.environ.get("ASCEND_MOONEP_KERNEL_LIB_DIR", ROOT / "npu_patch" / "lib")
87 )89 )
88- if not (kernel_lib_dir / "libascend_moonep_kernels.so").exists():90+ use_udma = os.environ.get("ASCEND_MOONEP_UDMA", "0").strip() == "1"
89- raise RuntimeError(91+ kernel_libraries = ["ascend_moonep_kernels"]
90- f"Kernel library not found in {kernel_lib_dir}. Run "92+ if use_udma:
91- "npu_patch/scripts/build_base.sh -soc_type <SOC_TYPE> first."93+ kernel_libraries.append("ascend_moonep_kernels_server_dedup")
92- )94+ for library in kernel_libraries:
95+ kernel_lib = f"lib{library}.so"
96+ if not (kernel_lib_dir / kernel_lib).exists():
97+ raise RuntimeError(
98+ f"Kernel library {kernel_lib} not found in {kernel_lib_dir}. Run "
99+ "npu_patch/scripts/build_base.sh -soc_type <SOC_TYPE> first."
100+ )
93 torch_npu_root = Path(torch_npu.__file__).resolve().parent101 torch_npu_root = Path(torch_npu.__file__).resolve().parent
94 native = ROOT / "npu_patch" / "native"102 native = ROOT / "npu_patch" / "native"
95 103 
@@ -152,7 +160,7 @@ def _npu_extension():
152 ]160 ]
153 # Pass the build script's UDMA flag to the C++ extension.161 # Pass the build script's UDMA flag to the C++ extension.
154 define_macros = []162 define_macros = []
155- if os.environ.get("ASCEND_MOONEP_UDMA", "0").strip() == "1":163+ if use_udma:
156 define_macros.append(("ASCEND_MOONEP_UDMA", "1"))164 define_macros.append(("ASCEND_MOONEP_UDMA", "1"))
157 # Product architecture macro for acl_shared_buffer.cpp's VMM export path165 # Product architecture macro for acl_shared_buffer.cpp's VMM export path
158 # (A2 -> SHMEM does V2 DEFAULT; A3/A5 -> pre-export Fabric V2). build_base.sh166 # (A2 -> SHMEM does V2 DEFAULT; A3/A5 -> pre-export Fabric V2). build_base.sh
@@ -170,7 +178,7 @@ def _npu_extension():
170 define_macros=define_macros,178 define_macros=define_macros,
171 include_dirs=include_dirs,179 include_dirs=include_dirs,
172 library_dirs=library_dirs,180 library_dirs=library_dirs,
173- libraries=["ascend_moonep_kernels", "torch_npu", "ascendcl", "runtime", "shmem", "dl"],181+ libraries=kernel_libraries + ["torch_npu", "ascendcl", "runtime", "shmem", "dl"],
174 extra_compile_args=["-O2", "-std=c++20"],182 extra_compile_args=["-O2", "-std=c++20"],
175 extra_link_args=["-Wl,-rpath,$ORIGIN/lib"]183 extra_link_args=["-Wl,-rpath,$ORIGIN/lib"]
176 + [f"-Wl,-rpath,{path}" for path in rpath_dirs],184 + [f"-Wl,-rpath,{path}" for path in rpath_dirs],