Closed
[WIP]dev_server_dedup_async_migrate #3
&NewgateAdd on 26 days agoClosed at 25 days ago
[WIP]dev_server_dedup_async_migrate #3
Closed
&NewgateAdd on 26 days agoClosed at 25 days ago
Total: 41 files changed+3833-145
@@ -132,9 +132,12 @@ def _load_buffer_api():
132 from .shmem_runtime import ShmemRuntime, runtime_library_info132 from .shmem_runtime import ShmemRuntime, runtime_library_info
133 from .planning import MoonEPCommPlan133 from .planning import MoonEPCommPlan
134 from .api import Buffer134 from .api import Buffer
135+ from .native_async import CommBuffers, LPlusBBinding
135 136 
136 return {137 return {
137 "Buffer": Buffer,138 "Buffer": Buffer,
139+ "CommBuffers": CommBuffers,
140+ "LPlusBBinding": LPlusBBinding,
138 "MoonEPCommPlan": MoonEPCommPlan,141 "MoonEPCommPlan": MoonEPCommPlan,
139 "ShmemRuntime": ShmemRuntime,142 "ShmemRuntime": ShmemRuntime,
140 "runtime_library_info": runtime_library_info,143 "runtime_library_info": runtime_library_info,
@@ -142,7 +145,7 @@ def _load_buffer_api():
142 145 
143 146 
144_BUFFER_API_NAMES = frozenset({147_BUFFER_API_NAMES = frozenset({
145- "Buffer", "MoonEPCommPlan", "ShmemRuntime", "runtime_library_info"148+ "Buffer", "CommBuffers", "LPlusBBinding", "MoonEPCommPlan", "ShmemRuntime", "runtime_library_info"
146})149})
147_BUF_API_CACHE = None150_BUF_API_CACHE = None
148 151 
@@ -156,16 +159,23 @@ def __getattr__(name):
156 raise AttributeError(f"module 'npu_patch' has no attribute {name!r}")159 raise AttributeError(f"module 'npu_patch' has no attribute {name!r}")
157 160 
158 161 
159-from .launchers import launch_grad_reduce, launch_prefetch162+from .launchers import launch_grad_reduce, launch_grad_reduce_targets, launch_prefetch, launch_prefetch_push
160 163 
161__all__ = [164__all__ = [
162 "ShmemInstance",165 "ShmemInstance",
163 "GradReduce",166 "GradReduce",
164 "launch_grad_reduce",167 "launch_grad_reduce",
168+ "launch_grad_reduce_targets",
165 "Buffer",169 "Buffer",
170+ "CommBuffers",
171+ "LPlusBBinding",
166 "MoonEPCommPlan",172 "MoonEPCommPlan",
167 "ShmemRuntime",173 "ShmemRuntime",
168 "runtime_library_info",174 "runtime_library_info",
169 "PrefetchWeight",175 "PrefetchWeight",
170 "launch_prefetch",176 "launch_prefetch",
177+ "launch_prefetch_push",
171]178]
179+ 
180+from .prefetch_pointer import launch_prefetch_push_ptrs, drain_prefetch_push
181+__all__ += ["launch_prefetch_push_ptrs", "drain_prefetch_push"]
@@ -0,0 +1,13 @@
1+"""Setup-owned scratch for canonical UDMA GradReduce (ABI v3)."""
2+ 
3+ 
4+def workspace_elements(ranks, slots, blocks):
5+ if any(type(value) is not int for value in (ranks, slots, blocks)):
6+ raise TypeError('GradReduce workspace dimensions must be integers')
7+ if ranks <= 0 or slots < 0 or blocks <= 0:
8+ raise ValueError('GradReduce workspace requires positive ranks/blocks and nonnegative slots')
9+ # Keep the ABI v3 minimum shared with existing native bindings.
10+ elements = 512 * 1024 * max(2 * blocks, ranks * slots)
11+ if elements > ((1 << 63) - 1) // 4:
12+ raise OverflowError('GradReduce FP32 workspace byte count exceeds int64')
13+ return elements
@@ -0,0 +1,57 @@
1+{
2+ "schema": 1,
3+ "provider_abi": "lplusb-buffer-sync-v2",
4+ "build_sha": "source-tree",
5+ "devices": [
6+ "Ascend 950DT",
7+ "Ascend 950PR"
8+ ],
9+ "activation_dtypes": [
10+ "bfloat16"
11+ ],
12+ "weight_dtypes": [
13+ "bfloat16"
14+ ],
15+ "gradient_target_dtypes": [
16+ "float32"
17+ ],
18+ "layout": "LOCAL_L_PLUS_B",
19+ "lane_count": 1,
20+ "ordinary_source_owner_push": true,
21+ "direct_owner_reduce": true,
22+ "completion_model": "current_stream_synchronous",
23+ "strict_zero_copy_edges": [
24+ "Z1",
25+ "Z2",
26+ "Z3",
27+ "Z4",
28+ "R1"
29+ ],
30+ "vmm_granularity_query": true,
31+ "router_topk_max": null,
32+ "public_api_unchanged": true,
33+ "async": {
34+ "schema": 1,
35+ "completion_modes": [
36+ "collective",
37+ "required_owners_v1"
38+ ],
39+ "owner_ready_native_abi": 1,
40+ "lane_count": 1,
41+ "repeatable_steps": true,
42+ "strict_zero_copy": true
43+ },
44+ "prefetch_engines": [
45+ "mte",
46+ "urma"
47+ ],
48+ "urma_push": {
49+ "schema": 1,
50+ "pointer_source": true,
51+ "native_abi": 1,
52+ "completion_modes": [
53+ "collective"
54+ ],
55+ "shared_core_sha256": "26e966899f19fe199148b73c00920c126da7a64f2aff3eb1ea20283340cd84b2"
56+ }
57+}
@@ -0,0 +1,24 @@
1+# SPDX-License-Identifier: Apache-2.0
2+"""Metadata-only validation: never synchronizes or reads an accelerator tensor."""
3+ 
4+def validate_push_layout(home, slots, plan, num_sms, *, bf16, int32):
5+ if type(num_sms) is not int or num_sms <= 0:
6+ raise ValueError("num_sms must be a positive integer")
7+ if any(t.device.type != "npu" for t in (home, slots, plan)):
8+ raise ValueError("URMA PUSH inputs must be NPU tensors")
9+ if not home.device == slots.device == plan.device:
10+ raise ValueError("URMA PUSH inputs must share one NPU")
11+ if home.dtype != bf16 or slots.dtype != bf16 or plan.dtype != int32:
12+ raise TypeError("URMA PUSH requires BF16 weights and INT32 plan")
13+ if home.ndim != 3 or slots.ndim != 3 or plan.ndim != 2:
14+ raise ValueError("expected home[E,M,N], slots[B,M,N], plan[EP,B]")
15+ if any(not t.is_contiguous() for t in (home, slots, plan)):
16+ raise ValueError("URMA PUSH inputs must be contiguous")
17+ if not 0 < home.shape[0] <= 2147483647 or min(home.shape[1:]) <= 0:
18+ raise ValueError("invalid expert count or projection dimensions")
19+ if home.shape[1:] != slots.shape[1:] or slots.shape[0] != plan.shape[1]:
20+ raise ValueError("incompatible projection or slot shapes")
21+ if not 0 < plan.shape[0] <= 2147483647:
22+ raise ValueError("plan EP must be positive and fit int32")
23+ if slots.shape[0] > 15736:
24+ raise ValueError("plan exceeds URMA PUSH UB scratch capacity")
@@ -220,7 +220,7 @@ def _check_combine_inputs(
220 )220 )
221 hidden_key = "hidden_buf_local" if use_udma else "hidden_buf"221 hidden_key = "hidden_buf_local" if use_udma else "hidden_buf"
222 _check_tensor(222 _check_tensor(
223- ctx[hidden_key],223+ ctx[hidden_key][:NvS],
224 f"ctx.{hidden_key}",224 f"ctx.{hidden_key}",
225 (NvS, H),225 (NvS, H),
226 torch.bfloat16,226 torch.bfloat16,
@@ -228,7 +228,7 @@ def _check_combine_inputs(
228 )228 )
229 if output_sk is not None:229 if output_sk is not None:
230 weights_key = "weights_buf_local" if use_udma else "weights_buf"230 weights_key = "weights_buf_local" if use_udma else "weights_buf"
231- weights_buf = ctx[weights_key].view(torch.float32)231+ weights_buf = ctx[weights_key].view(torch.float32)[:NvS]
232 _check_tensor(232 _check_tensor(
233 weights_buf,233 weights_buf,
234 f"ctx.{weights_key}(fp32 view)",234 f"ctx.{weights_key}(fp32 view)",
@@ -290,7 +290,8 @@ def launch_combine(
290def launch_combine_prepared(ctx, output_sh, plan, execution_plan, output_sk=None):290def launch_combine_prepared(ctx, output_sh, plan, execution_plan, output_sk=None):
291 import torch291 import torch
292 import torch_npu292 import torch_npu
293- from .planning import CombineExecutionPlan, _routes, _key293+ from .planning import (CombineExecutionPlan, _routes, _key,
294+ _combine_workspace_layout, prepare_combine_plan)
294 295 
295 if not isinstance(execution_plan, CombineExecutionPlan):296 if not isinstance(execution_plan, CombineExecutionPlan):
296 raise TypeError('execution_plan must be returned by prepare_combine_plan')297 raise TypeError('execution_plan must be returned by prepare_combine_plan')
@@ -300,11 +301,21 @@ def launch_combine_prepared(ctx, output_sh, plan, execution_plan, output_sk=None
300 execution_plan.validate(ctx, plan)301 execution_plan.validate(ctx, plan)
301 stream = torch_npu.npu.current_stream()302 stream = torch_npu.npu.current_stream()
302 stream.wait_event(execution_plan.ready)303 stream.wait_event(execution_plan.ready)
303- weights = ctx['weights_buf_local'].view(torch.float32) if output_sk is not None else None304+ if ('_capacity_ctx' in ctx and
305+ ctx['_capacity_ctx'].get('_combine_workspace_layout') != _combine_workspace_layout(ctx)):
306+ # Buffer's ordered communication lane may revisit an older, shorter
307+ # route after planning/combining a different size. Its immutable tables
308+ # remain valid, but that intervening layout can overwrite its ready
309+ # slots with payload. Rebuild through the upstream collective planner
310+ # before payload launch; every rank follows the same logical sizes.
311+ execution_plan = prepare_combine_plan(ctx, plan)
312+ n = int(ctx['NvS'])
313+ hidden = ctx['hidden_buf_local'][:n]
314+ weights = ctx['weights_buf_local'].view(torch.float32)[:n] if output_sk is not None else None
304 torch.classes.AscendMoonEP.CombineUrma().compute_prepared(315 torch.classes.AscendMoonEP.CombineUrma().compute_prepared(
305- ctx['hidden_buf_local'], weights, ctx['combine_sync_buffer'], ctx['combine_workspace'],316+ hidden, weights, ctx['combine_sync_buffer'], ctx['combine_workspace'],
306 *_routes(plan), output_sh, output_sk, execution_plan.storage, *_key(ctx))317 *_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,318+ for tensor in (execution_plan.storage, *_routes(plan), hidden, weights,
308 ctx['combine_workspace'], ctx['combine_sync_buffer'], output_sh,319 ctx['combine_workspace'], ctx['combine_sync_buffer'], output_sh,
309 output_sk):320 output_sk):
310 if tensor is not None:321 if tensor is not None:
@@ -118,14 +118,14 @@ def _check_dispatch_inputs(
118 hidden_sh.device,118 hidden_sh.device,
119 )119 )
120 _check_tensor(120 _check_tensor(
121- ctx["hidden_buf"],121+ ctx["hidden_buf"][:NvS],
122 "ctx.hidden_buf",122 "ctx.hidden_buf",
123 (NvS, H),123 (NvS, H),
124 torch.bfloat16,124 torch.bfloat16,
125 hidden_sh.device,125 hidden_sh.device,
126 )126 )
127 if route_weights_sk is not None:127 if route_weights_sk is not None:
128- weights_buf = ctx["weights_buf"].view(torch.float32)128+ weights_buf = ctx["weights_buf"].view(torch.float32)[:NvS]
129 _check_tensor(129 _check_tensor(
130 weights_buf,130 weights_buf,
131 "ctx.weights_buf(fp32 view)",131 "ctx.weights_buf(fp32 view)",
@@ -9,10 +9,11 @@ keep the ported Ascend tests minimal: they resolve the op object from
9``launch_dispatch_epilogue`` / ``launch_combine_prologue`` steps are folded into9``launch_dispatch_epilogue`` / ``launch_combine_prologue`` steps are folded into
10``launch_dispatch`` / ``launch_combine`` and no longer have their own shims.10``launch_dispatch`` / ``launch_combine`` and no longer have their own shims.
11 11 
12-Two launchers are intentionally *not* shimmed through a Buffer ctx because the12+These launchers are intentionally *not* shimmed through a Buffer ctx because the
13standalone stage tests call them without one:13standalone stage tests call them without one:
14 - ``launch_prefetch(remote_expert, prefetch_buffers, experts_to_copy, num_sms)``14 - ``launch_prefetch(remote_expert, prefetch_buffers, experts_to_copy, num_sms)``
15 - ``launch_grad_reduce(remote_expert_grads, reduce_buffers, plan, rank, ...)``15 - ``launch_grad_reduce(remote_expert_grads, reduce_buffers, plan, rank, ...)``
16+ - ``launch_grad_reduce_targets(target_ptrs, reduce_buffers, plan, rank, num_sms)``
16Their Ascend contracts are described in ``ops.py``.17Their Ascend contracts are described in ``ops.py``.
17"""18"""
18 19 
@@ -404,6 +405,33 @@ def launch_prefetch(
404 num_experts, num_sms, 0, _env_use_udma('prefetch'), rank_barriers)405 num_experts, num_sms, 0, _env_use_udma('prefetch'), rank_barriers)
405 406 
406 407 
408+def launch_prefetch_push(remote_expert, prefetch_buffers, experts_to_copy, num_sms):
409+ """Collectively push BF16 owner weights into symmetric consumer slots.
410+ 
411+ All ranks call with the same contiguous INT32 [EP,B] plan (-1 means empty).
412+ Returns the destination tensor after enqueueing completion barriers on the
413+ current stream. Retain inputs and backing through a completion event; order
414+ producer writes and previous slot consumers before this call.
415+ Requires ShmemRuntime.init_with_buffer(enable_udma=True, qp_count=2).
416+ """
417+ from ._prefetch_contract import validate_push_layout
418+ from .shmem_runtime import ShmemRuntime
419+ validate_push_layout(remote_expert, prefetch_buffers, experts_to_copy, num_sms,
420+ bf16=torch.bfloat16, int32=torch.int32)
421+ if not ShmemRuntime.is_initialized() or not ShmemRuntime._udma_enabled:
422+ raise RuntimeError("URMA PUSH requires an initialized URMA SHMEM runtime")
423+ if "950" not in torch.npu.get_device_name(remote_expert.device):
424+ raise RuntimeError("URMA PUSH requires Ascend950")
425+ global _PREFETCH_WEIGHT
426+ if _PREFETCH_WEIGHT is None:
427+ _PREFETCH_WEIGHT = torch.classes.AscendMoonEP.PrefetchWeight(0)
428+ if not _PREFETCH_WEIGHT.push_available():
429+ raise RuntimeError("native build does not provide URMA PUSH")
430+ return _PREFETCH_WEIGHT.compute_push(
431+ remote_expert, prefetch_buffers, experts_to_copy,
432+ int(remote_expert.shape[0]), num_sms, 0, True)
433+ 
434+ 
407def launch_grad_reduce(435def launch_grad_reduce(
408 remote_expert_grads: torch.Tensor,436 remote_expert_grads: torch.Tensor,
409 remote_reduce_buffers: torch.Tensor,437 remote_reduce_buffers: torch.Tensor,
@@ -474,3 +502,78 @@ def launch_grad_reduce(
474 min(num_sms, 64),502 min(num_sms, 64),
475 _env_use_udma('grad_reduce'),503 _env_use_udma('grad_reduce'),
476 )504 )
505+ 
506+ 
507+def launch_grad_reduce_targets(
508+ target_ptrs: torch.Tensor,
509+ reduce_buffers: torch.Tensor,
510+ experts_to_copy: torch.Tensor,
511+ rank: int,
512+ num_sms: int,
513+ udma_workspace: torch.Tensor | None = None,
514+ *,
515+ use_udma: bool | None = None,
516+) -> None:
517+ """Explicit canonical-pointer contract, distinct from the dense entry.
518+ 
519+ ``target_ptrs`` is a setup-frozen contiguous INT64 [epn] table of local
520+ FP32 matrix addresses. Each target is contiguous [H, H']; targets remain
521+ alive, disjoint and address-stable until completion. They need not be
522+ symmetric or adjacent. Only ``reduce_buffers[B,H,H']`` is a symmetric
523+ source bank. The Buffer supplies its configured backend. Standalone
524+ callers can omit it to use the grad_reduce environment flag. UDMA needs
525+ setup-owned local FP32 scratch of at least
526+ 512*1024*max(2*min(num_sms,64),R*B) elements through completion.
527+ MTE uses ordered addition; UDMA retains dense UDMA's atomic-add ordering.
528+ Both use pre/post barriers and clear only valid slots.
529+ """
530+ if reduce_buffers.numel() == 0 or experts_to_copy.numel() == 0:
531+ return
532+ 
533+ assert target_ptrs.dtype == torch.int64
534+ assert target_ptrs.is_contiguous() and target_ptrs.ndim == 1
535+ assert reduce_buffers.dtype == torch.float32
536+ assert reduce_buffers.is_contiguous() and reduce_buffers.ndim == 3
537+ assert experts_to_copy.dtype == torch.int32
538+ assert experts_to_copy.is_contiguous() and experts_to_copy.ndim == 2
539+ assert isinstance(rank, int)
540+ assert isinstance(num_sms, int) and num_sms > 0
541+ epn = int(target_ptrs.numel())
542+ B, H, Hp = (int(value) for value in reduce_buffers.shape)
543+ R, plan_B = (int(value) for value in experts_to_copy.shape)
544+ assert plan_B == B
545+ assert 0 <= rank < R
546+ device = target_ptrs.device
547+ assert device.type == "npu"
548+ assert reduce_buffers.device == device
549+ assert experts_to_copy.device == device
550+ 
551+ from . import _C
552+ abi = getattr(_C, "GRAD_REDUCE_POINTER_ABI", None)
553+ if type(abi) is not int or abi != 1:
554+ raise RuntimeError("rebuild native GradReduceOp canonical pointer ABI v1")
555+ if use_udma is None:
556+ use_udma = _env_use_udma('grad_reduce')
557+ blocks = min(num_sms, 64)
558+ udma_abi = getattr(_C, "GRAD_REDUCE_POINTER_UDMA_ABI", None)
559+ unified_backend = type(udma_abi) is int and udma_abi in (2, 3)
560+ if use_udma:
561+ from ._grad_reduce_contract import workspace_elements
562+ if type(udma_abi) is not int or udma_abi != 3:
563+ raise RuntimeError("rebuild native GradReduceOp canonical pointer UDMA ABI v3")
564+ required_elements = workspace_elements(R, B, blocks)
565+ if (udma_workspace is None or udma_workspace.dtype != torch.float32 or
566+ udma_workspace.device != device or not udma_workspace.is_contiguous() or
567+ udma_workspace.numel() < required_elements):
568+ raise ValueError("canonical UDMA requires setup-owned local FP32 workspace "
569+ "with at least 512*1024*max(2*blocks,R*B) elements")
570+ global _GRAD_REDUCE
571+ if _GRAD_REDUCE is None:
572+ _GRAD_REDUCE = torch.classes.AscendMoonEP.GradReduce()
573+ # Older extensions retain the MTE-only signature; updated builds expose
574+ # the same method with optional backend/workspace arguments.
575+ backend_args = ((use_udma, udma_workspace if use_udma else None)
576+ if unified_backend else ())
577+ _GRAD_REDUCE.compute_targets(
578+ target_ptrs, reduce_buffers, experts_to_copy,
579+ epn, H, Hp, R, B, rank, blocks, *backend_args)
@@ -85,6 +85,7 @@ include("${CMAKE_SOURCE_DIR}/cmake/AscendMoonEPKernel.cmake")
85ascend_moonep_add_kernel_library(85ascend_moonep_add_kernel_library(
86 ascend_moonep_kernels86 ascend_moonep_kernels
87 SOURCES87 SOURCES
88+ kernels/lplusb_runtime.cpp
88 kernels/barrier_bench.cpp89 kernels/barrier_bench.cpp
89 kernels/moonep_combine.cpp90 kernels/moonep_combine.cpp
90 kernels/moonep_combine_udma.cpp91 kernels/moonep_combine_udma.cpp
@@ -95,6 +96,8 @@ ascend_moonep_add_kernel_library(
95 kernels/planning.cpp96 kernels/planning.cpp
96 kernels/prefetch.cpp97 kernels/prefetch.cpp
97 kernels/prefetch_udma.cpp98 kernels/prefetch_udma.cpp
99+ kernels/prefetch_push_udma.cpp
100+ kernels/prefetch_pointer_push_udma.cpp
98 INCLUDES101 INCLUDES
99 include102 include
100 kernels103 kernels
@@ -13,6 +13,7 @@
13 13 
14#include "acl/acl.h"14#include "acl/acl.h"
15#include "shmem.h"15#include "shmem.h"
16+#include "ascend_moonep/kernels/launch.h"
16 17 
17namespace ascend_moonep {18namespace ascend_moonep {
18 19 
@@ -773,4 +774,10 @@ void acl_shmem_barrier_all_on_stream(int64_t stream) {
773 reinterpret_cast<aclrtStream>(static_cast<uintptr_t>(stream)));774 reinterpret_cast<aclrtStream>(static_cast<uintptr_t>(stream)));
774}775}
775 776 
777+void acl_shmem_barrier_all_aiv_on_stream(int64_t stream) {
778+ TORCH_CHECK(moonep_async_stream_barrier_vec(
779+ reinterpret_cast<void*>(static_cast<uintptr_t>(stream))) == ACL_SUCCESS,
780+ "asynchronous collective AIV barrier launch failed");
781+}
782+ 
776}783}
@@ -130,4 +130,5 @@ int acl_shmem_init_with_buffers_ip_port(
130 const std::vector<std::tuple<int64_t, int64_t, int64_t, std::string>>& descriptors,130 const std::vector<std::tuple<int64_t, int64_t, int64_t, std::string>>& descriptors,
131 int device_id, bool enable_udma = false, uint32_t qp_count = 0);131 int device_id, bool enable_udma = false, uint32_t qp_count = 0);
132void acl_shmem_barrier_all_on_stream(int64_t stream);132void acl_shmem_barrier_all_on_stream(int64_t stream);
133+void acl_shmem_barrier_all_aiv_on_stream(int64_t stream);
133}134}
@@ -0,0 +1,192 @@
1+#include "csrc/lplusb_runtime.h"
2+#include "csrc/ops/prefetch.h"
3+ 
4+#include <acl/acl.h>
5+#include <limits>
6+ 
7+#include <torch_npu/csrc/core/npu/NPUStream.h>
8+ 
9+#include "ascend_moonep/kernels/launch.h"
10+#include "csrc/common/check.h"
11+#include "shmem.h"
12+ 
13+namespace ascend_moonep {
14+namespace {
15+ 
16+void CheckCommon(
17+ const torch::Tensor& pointer_table,
18+ const torch::Tensor& slots,
19+ const torch::Tensor& plan,
20+ int64_t rank,
21+ int64_t local_experts)
22+{
23+ TORCH_CHECK(pointer_table.device().type() == c10::DeviceType::PrivateUse1,
24+ "pointer table must be an NPU tensor");
25+ TORCH_CHECK(slots.device().type() == c10::DeviceType::PrivateUse1,
26+ "slot arena must be an NPU tensor");
27+ TORCH_CHECK(plan.device().type() == c10::DeviceType::PrivateUse1,
28+ "experts_to_copy must be an NPU tensor");
29+ TORCH_CHECK(pointer_table.device() == slots.device() && slots.device() == plan.device(),
30+ "pointer table, slot arena and plan must be on the same NPU");
31+ TORCH_CHECK(pointer_table.scalar_type() == torch::kInt64 &&
32+ pointer_table.dim() == 1 && pointer_table.is_contiguous(),
33+ "pointer table must be contiguous INT64 [L]");
34+ TORCH_CHECK(plan.scalar_type() == torch::kInt32 && plan.dim() == 2 && plan.is_contiguous(),
35+ "experts_to_copy must be contiguous INT32 [R,B]");
36+ TORCH_CHECK(slots.is_contiguous() && slots.dim() >= 2,
37+ "slot arena must be contiguous [B,...]");
38+ TORCH_CHECK(local_experts > 0 && pointer_table.numel() == local_experts,
39+ "pointer table length must equal local_experts");
40+ TORCH_CHECK(plan.size(1) == slots.size(0) && plan.size(0) > 0,
41+ "plan [R,B] must match the slot arena B dimension");
42+ TORCH_CHECK(rank >= 0 && rank < plan.size(0), "rank is outside the EP group");
43+ for (int64_t dim = 1; dim < slots.dim(); ++dim) {
44+ TORCH_CHECK(slots.size(dim) > 0, "slot rows must have positive dimensions");
45+ }
46+ TORCH_CHECK(local_experts <= std::numeric_limits<int32_t>::max() &&
47+ plan.size(0) <= std::numeric_limits<int32_t>::max() &&
48+ plan.size(1) <= std::numeric_limits<int32_t>::max(),
49+ "L/R/B exceeds the private kernel int32 contract");
50+}
51+ 
52+int64_t RowElements(const torch::Tensor& slots) {
53+ int64_t elements = 1;
54+ for (int64_t dim = 1; dim < slots.dim(); ++dim) {
55+ TORCH_CHECK(elements <= std::numeric_limits<int64_t>::max() / slots.size(dim),
56+ "slot row extent overflows INT64");
57+ elements *= slots.size(dim);
58+ }
59+ return elements;
60+}
61+ 
62+int32_t VectorBlocks()
63+{
64+ int32_t device_id = 0;
65+ int64_t cores = 0;
66+ ASCEND_MOONEP_CHECK_ACL(aclrtGetDevice(&device_id));
67+ ASCEND_MOONEP_CHECK_ACL(
68+ aclrtGetDeviceInfo(device_id, ACL_DEV_ATTR_AICORE_CORE_NUM, &cores));
69+ TORCH_CHECK(cores > 0 && cores <= std::numeric_limits<int32_t>::max(),
70+ "current NPU reports an invalid AICore count");
71+ return static_cast<int32_t>(cores);
72+}
73+ 
74+} // namespace
75+ 
76+// Compatibility with earlier private L+B ABI; transport belongs to #9.
77+bool LPlusBUrmaAvailable() { return ops::PrefetchPushPointersAvailable(); }
78+ 
79+void LPlusBOwnerPushUrmaContiguous(torch::Tensor home, torch::Tensor slots,
80+ torch::Tensor plan, int64_t rank, int64_t global_experts) {
81+ TORCH_CHECK(rank == aclshmem_my_pe(), "rank differs from SHMEM");
82+ ops::LaunchPrefetchPushLocal(home, slots, plan, global_experts);
83+}
84+ 
85+void LPlusBOwnerPushUrma(torch::Tensor pointers, torch::Tensor slots,
86+ torch::Tensor plan, int64_t rank, int64_t local_experts) {
87+ TORCH_CHECK(rank == aclshmem_my_pe(), "rank differs from SHMEM");
88+ ops::LaunchPrefetchPushPointers(pointers, slots, plan, local_experts);
89+}
90+ 
91+void LPlusBOwnerPush(
92+ torch::Tensor source_ptrs,
93+ torch::Tensor weight_slots,
94+ torch::Tensor experts_to_copy,
95+ int64_t rank,
96+ int64_t local_experts)
97+{
98+ CheckCommon(source_ptrs, weight_slots, experts_to_copy, rank, local_experts);
99+ TORCH_CHECK(weight_slots.scalar_type() == torch::kBFloat16,
100+ "weight slot arena must be BF16");
101+ aclrtStream stream = c10_npu::getCurrentNPUStream().stream();
102+ aclshmemx_barrier_all_on_stream(stream);
103+ const int ret = moonep_lplusb_owner_push(
104+ stream,
105+ reinterpret_cast<const uint64_t*>(source_ptrs.data_ptr<int64_t>()),
106+ weight_slots.data_ptr(), experts_to_copy.data_ptr<int32_t>(),
107+ RowElements(weight_slots),
108+ static_cast<int32_t>(local_experts), static_cast<int32_t>(experts_to_copy.size(0)),
109+ static_cast<int32_t>(experts_to_copy.size(1)), static_cast<int32_t>(rank),
110+ VectorBlocks());
111+ TORCH_CHECK(ret == 0, "L+B owner-push kernel failed with ACL error: ", ret);
112+ // On return, all writes are peer-visible on the same ordered stream.
113+ aclshmemx_barrier_all_on_stream(stream);
114+}
115+ 
116+void LPlusBOwnerReadyInit(torch::Tensor ready)
117+{
118+ TORCH_CHECK(ready.device().type() == c10::DeviceType::PrivateUse1 &&
119+ ready.scalar_type() == torch::kInt32 && ready.is_contiguous() &&
120+ ready.dim() == 2 && ready.size(0) > 0 && ready.size(1) == 16,
121+ "owner-ready initialization requires INT32 [R,16] on NPU");
122+ // Setup only, before SHMEM init. Synchronous memset has no pending stream
123+ // writer to an allocation which a failed setup may need to unwind.
124+ const size_t bytes = static_cast<size_t>(ready.numel()) * sizeof(int32_t);
125+ ASCEND_MOONEP_CHECK_ACL(aclrtMemset(ready.data_ptr(), bytes, 0, bytes));
126+}
127+ 
128+void LPlusBOwnerPushReady(
129+ torch::Tensor source_ptrs, torch::Tensor weight_slots,
130+ torch::Tensor experts_to_copy, torch::Tensor ready,
131+ int64_t rank, int64_t local_experts, int64_t epoch)
132+{
133+ CheckCommon(source_ptrs, weight_slots, experts_to_copy, rank, local_experts);
134+ TORCH_CHECK(weight_slots.scalar_type() == torch::kBFloat16, "weight slot arena must be BF16");
135+ TORCH_CHECK(ready.device() == weight_slots.device() && ready.scalar_type() == torch::kInt32 &&
136+ ready.is_contiguous() && ready.dim() == 2 &&
137+ ready.size(0) == experts_to_copy.size(0) && ready.size(1) == 16 &&
138+ reinterpret_cast<uintptr_t>(ready.data_ptr()) % 64 == 0,
139+ "owner-ready bank must be aligned INT32 [R,16] on the slot NPU");
140+ TORCH_CHECK(epoch > 0 && epoch <= std::numeric_limits<int32_t>::max(),
141+ "owner-ready epoch must be positive INT32; wrapping is forbidden");
142+ TORCH_CHECK(local_experts <= std::numeric_limits<int32_t>::max() / experts_to_copy.size(0),
143+ "global expert IDs exceed INT32");
144+ aclrtStream stream = c10_npu::getCurrentNPUStream().stream();
145+ // Preserve the existing source/plan readiness rendezvous. Bank reuse also
146+ // retains the caller's separate peer-final-use collective.
147+ aclshmemx_barrier_all_on_stream(stream);
148+ const int push_ret = moonep_lplusb_owner_push(
149+ stream, reinterpret_cast<const uint64_t*>(source_ptrs.data_ptr<int64_t>()),
150+ weight_slots.data_ptr(), experts_to_copy.data_ptr<int32_t>(),
151+ RowElements(weight_slots),
152+ static_cast<int32_t>(local_experts), static_cast<int32_t>(experts_to_copy.size(0)),
153+ static_cast<int32_t>(experts_to_copy.size(1)), static_cast<int32_t>(rank), VectorBlocks());
154+ TORCH_CHECK(push_ret == 0, "L+B owner-push kernel failed with ACL error: ", push_ret);
155+ const int ready_ret = moonep_lplusb_owner_ready(
156+ stream, ready.data_ptr<int32_t>(), experts_to_copy.data_ptr<int32_t>(),
157+ static_cast<int32_t>(local_experts), static_cast<int32_t>(experts_to_copy.size(0)),
158+ static_cast<int32_t>(experts_to_copy.size(1)), static_cast<int32_t>(rank),
159+ static_cast<int32_t>(epoch));
160+ TORCH_CHECK(ready_ret == 0, "L+B owner-ready kernel failed with ACL error: ", ready_ret);
161+ // Q0's next event now proves this receiver's required incoming writes.
162+ // Do not add a global post-barrier here: it would defeat that admission.
163+}
164+ 
165+void LPlusBOwnerReduce(
166+ torch::Tensor target_ptrs,
167+ torch::Tensor grad_slots,
168+ torch::Tensor experts_to_copy,
169+ int64_t rank,
170+ int64_t local_experts)
171+{
172+ CheckCommon(target_ptrs, grad_slots, experts_to_copy, rank, local_experts);
173+ TORCH_CHECK(grad_slots.scalar_type() == torch::kFloat32,
174+ "gradient slot arena must be FP32");
175+ aclrtStream stream = c10_npu::getCurrentNPUStream().stream();
176+ // Publish local pointer-target GMM writes before any owner reads peer slots.
177+ aclshmemx_barrier_all_on_stream(stream);
178+ const int ret = moonep_lplusb_owner_reduce(
179+ stream,
180+ reinterpret_cast<const uint64_t*>(target_ptrs.data_ptr<int64_t>()),
181+ grad_slots.data_ptr(), experts_to_copy.data_ptr<int32_t>(),
182+ RowElements(grad_slots),
183+ static_cast<int32_t>(local_experts), static_cast<int32_t>(experts_to_copy.size(0)),
184+ static_cast<int32_t>(experts_to_copy.size(1)), static_cast<int32_t>(rank),
185+ VectorBlocks());
186+ TORCH_CHECK(ret == 0, "L+B owner-reduce kernel failed with ACL error: ", ret);
187+ // Kernel-internal collective proves all peer reads ended; this barrier
188+ // publishes local target accumulation and slot clearing to the caller.
189+ aclshmemx_barrier_all_on_stream(stream);
190+}
191+ 
192+} // namespace ascend_moonep
@@ -0,0 +1,34 @@
1+#pragma once
2+ 
3+#include <torch/extension.h>
4+ 
5+namespace ascend_moonep {
6+ 
7+bool LPlusBUrmaAvailable();
8+void LPlusBOwnerPushUrmaContiguous(torch::Tensor home, torch::Tensor slots,
9+ torch::Tensor plan, int64_t rank, int64_t global_experts);
10+void LPlusBOwnerPushUrma(torch::Tensor pointers, torch::Tensor slots,
11+ torch::Tensor plan, int64_t rank, int64_t local_experts);
12+ 
13+void LPlusBOwnerReadyInit(torch::Tensor ready);
14+ 
15+void LPlusBOwnerPush(
16+ torch::Tensor source_ptrs,
17+ torch::Tensor weight_slots,
18+ torch::Tensor experts_to_copy,
19+ int64_t rank,
20+ int64_t local_experts);
21+ 
22+void LPlusBOwnerReduce(
23+ torch::Tensor target_ptrs,
24+ torch::Tensor grad_slots,
25+ torch::Tensor experts_to_copy,
26+ int64_t rank,
27+ int64_t local_experts);
28+ 
29+void LPlusBOwnerPushReady(
30+ torch::Tensor source_ptrs, torch::Tensor weight_slots,
31+ torch::Tensor experts_to_copy, torch::Tensor ready,
32+ int64_t rank, int64_t local_experts, int64_t epoch);
33+ 
34+} // namespace ascend_moonep
@@ -1,11 +1,13 @@
1#include "csrc/ops/grad_reduce.h"1#include "csrc/ops/grad_reduce.h"
2 2 
3+#include <algorithm>
3#include <limits>4#include <limits>
4 5 
5#include <torch/extension.h>6#include <torch/extension.h>
6#include <torch_npu/csrc/core/npu/NPUStream.h>7#include <torch_npu/csrc/core/npu/NPUStream.h>
7 8 
8#include "ascend_moonep/kernels/launch.h"9#include "ascend_moonep/kernels/launch.h"
10+#include "shmem.h"
9 11 
10namespace ascend_moonep::ops {12namespace ascend_moonep::ops {
11 13 
@@ -82,9 +84,6 @@ void GradReduce(
82 int64_t rank,84 int64_t rank,
83 int64_t blocks,85 int64_t blocks,
84 bool use_udma) {86 bool use_udma) {
85- // The current grad-reduce implementation has no separate UDMA kernel.
86- // Keep the unified ABI and deliberately use the existing SHMEM path.
87- (void)use_udma;
88 aclrtStream stream = c10_npu::getCurrentNPUStream().stream();87 aclrtStream stream = c10_npu::getCurrentNPUStream().stream();
89 88 
90 CheckNpuContiguous(expert_grads, "expert_grads");89 CheckNpuContiguous(expert_grads, "expert_grads");
@@ -145,4 +144,97 @@ void GradReduce(
145 }144 }
146}145}
147 146 
147+void GradReduceTargets(
148+ torch::Tensor target_ptrs,
149+ torch::Tensor reduce_buffers,
150+ torch::Tensor experts_to_copy,
151+ int64_t epn,
152+ int64_t hidden,
153+ int64_t projection,
154+ int64_t ranks,
155+ int64_t slots,
156+ int64_t rank,
157+ int64_t blocks,
158+ bool use_udma,
159+ torch::Tensor udma_workspace) {
160+ aclrtStream stream = c10_npu::getCurrentNPUStream().stream();
161+ CheckNpuContiguous(target_ptrs, "target_ptrs");
162+ TORCH_CHECK(
163+ target_ptrs.scalar_type() == torch::kInt64 &&
164+ target_ptrs.dim() == 1 && target_ptrs.numel() == epn,
165+ "canonical target pointers must be contiguous INT64 [epn]");
166+ TORCH_CHECK(
167+ target_ptrs.device() == reduce_buffers.device(),
168+ "target_ptrs and reduce_buffers must be on the same device");
169+ CheckCommon(reduce_buffers, experts_to_copy, hidden, projection,
170+ ranks, slots, rank, blocks);
171+ TORCH_CHECK(epn > 0, "epn must be positive");
172+ CheckInt32(epn, "epn");
173+ 
174+ if (use_udma) {
175+ TORCH_CHECK(udma_workspace.defined(), "UDMA grad_reduce requires setup-owned workspace");
176+ CheckNpuContiguous(udma_workspace, "udma_workspace");
177+ TORCH_CHECK(udma_workspace.scalar_type() == torch::kFloat32 &&
178+ udma_workspace.device() == reduce_buffers.device() &&
179+ ranks <= std::numeric_limits<int64_t>::max() / std::max<int64_t>(slots, 1),
180+ "udma_workspace device/dtype or rank-slot product is invalid");
181+ const int64_t regions = std::max<int64_t>(blocks * 2, ranks * slots);
182+ constexpr int64_t tile = 512 * 1024;
183+ TORCH_CHECK(regions <= std::numeric_limits<int64_t>::max() / (tile * sizeof(float)),
184+ "ordered UDMA workspace byte count exceeds int64");
185+ TORCH_CHECK(udma_workspace.numel() >= tile * regions,
186+ "udma_workspace must be local FP32 scratch with at least "
187+ "512*1024*max(blocks*2,ranks*slots) elements on the source device");
188+ }
189+ 
190+ // Publish Q1 slots before peer reads, then publish target updates and
191+ // cleared valid slots before the caller records its completion event.
192+ // UDMA scratch is owned by the caller and allocated during setup, never
193+ // inside this hot submission. Its lifetime covers the entire Q0 operation.
194+ if (use_udma) {
195+ const int barrier_status = moonep_grad_reduce_native_barrier(stream);
196+ TORCH_CHECK(barrier_status == ACL_SUCCESS,
197+ "GR native barrier launch failed: ", barrier_status);
198+ } else {
199+ aclshmemx_barrier_all_on_stream(stream);
200+ }
201+ if (use_udma) {
202+ const int ret = moonep_shmem_grad_reduce_targets_udma(
203+ stream,
204+ target_ptrs.data_ptr(),
205+ reduce_buffers.data_ptr(),
206+ udma_workspace.data_ptr(),
207+ experts_to_copy.data_ptr<int32_t>(),
208+ static_cast<int32_t>(epn),
209+ static_cast<int32_t>(hidden),
210+ static_cast<int32_t>(projection),
211+ static_cast<int32_t>(ranks),
212+ static_cast<int32_t>(slots),
213+ static_cast<int32_t>(rank),
214+ static_cast<int32_t>(blocks));
215+ TORCH_CHECK(ret == 0, "canonical grad_reduce kernel failed with ACL error: ", ret);
216+ } else {
217+ const int ret = moonep_shmem_grad_reduce_targets(
218+ stream,
219+ target_ptrs.data_ptr(),
220+ reduce_buffers.data_ptr(),
221+ experts_to_copy.data_ptr<int32_t>(),
222+ static_cast<int32_t>(epn),
223+ static_cast<int32_t>(hidden),
224+ static_cast<int32_t>(projection),
225+ static_cast<int32_t>(ranks),
226+ static_cast<int32_t>(slots),
227+ static_cast<int32_t>(rank),
228+ static_cast<int32_t>(blocks));
229+ TORCH_CHECK(ret == 0, "canonical grad_reduce kernel failed with ACL error: ", ret);
230+ }
231+ if (use_udma) {
232+ const int barrier_status = moonep_grad_reduce_native_barrier(stream);
233+ TORCH_CHECK(barrier_status == ACL_SUCCESS,
234+ "GR native barrier launch failed: ", barrier_status);
235+ } else {
236+ aclshmemx_barrier_all_on_stream(stream);
237+ }
238+}
239+ 
148} // namespace ascend_moonep::ops240} // namespace ascend_moonep::ops
@@ -19,4 +19,21 @@ void GradReduce(
19 int64_t blocks,19 int64_t blocks,
20 bool use_udma);20 bool use_udma);
21 21 
22+// Extension for canonical targets; the dense entry and its backend contract
23+// remain unchanged. use_udma selects MTE or UDMA; UDMA requires caller-owned
24+// local workspace. Both use pre/post barriers.
25+void GradReduceTargets(
26+ torch::Tensor target_ptrs,
27+ torch::Tensor reduce_buffers,
28+ torch::Tensor experts_to_copy,
29+ int64_t epn,
30+ int64_t hidden,
31+ int64_t projection,
32+ int64_t ranks,
33+ int64_t slots,
34+ int64_t rank,
35+ int64_t blocks,
36+ bool use_udma = false,
37+ torch::Tensor udma_workspace = {});
38+ 
22} // namespace ascend_moonep::ops39} // namespace ascend_moonep::ops
@@ -3,6 +3,7 @@
3#include <acl/acl.h>3#include <acl/acl.h>
4#include <algorithm>4#include <algorithm>
5#include <cstdint>5#include <cstdint>
6+#include <limits>
6 7 
7#include <torch_npu/csrc/core/npu/NPUStream.h>8#include <torch_npu/csrc/core/npu/NPUStream.h>
8 9 
@@ -13,6 +14,15 @@
13 14 
14namespace {15namespace {
15 16 
17+void PrefetchBarrier(aclrtStream stream, bool aiv_only) {
18+ if (aiv_only) {
19+ TORCH_CHECK(moonep_prefetch_barrier_vec(stream) == ACL_SUCCESS,
20+ "URMA prefetch AIV barrier launch failed");
21+ } else {
22+ aclshmemx_barrier_all_on_stream(stream);
23+ }
24+}
25+ 
16void CheckNpuContiguous(const torch::Tensor& tensor, const char* name) {26void CheckNpuContiguous(const torch::Tensor& tensor, const char* name) {
17 TORCH_CHECK(27 TORCH_CHECK(
18 tensor.device().type() == c10::DeviceType::PrivateUse1,28 tensor.device().type() == c10::DeviceType::PrivateUse1,
@@ -41,6 +51,9 @@ torch::Tensor LaunchPrefetch(
41 bool use_udma,51 bool use_udma,
42 bool rank_barriers) {52 bool rank_barriers) {
43 // The current SHMEM runtime is a single global instance.53 // The current SHMEM runtime is a single global instance.
54+ 
55+ TORCH_CHECK(!use_udma || prefetch_weight_push_udma_available() == 1,
56+ "requested URMA GET is unavailable in this native build");
44 (void)instance_id;57 (void)instance_id;
45 (void)num_sms;58 (void)num_sms;
46 // remote_expert is a logical cross-PE view. Its data pointer is the local59 // remote_expert is a logical cross-PE view. Its data pointer is the local
@@ -122,4 +135,108 @@ torch::Tensor LaunchPrefetch(
122 return prefetch_buffers;135 return prefetch_buffers;
123}136}
124 137 
138+ 
139+torch::Tensor LaunchPrefetchPush(
140+ torch::Tensor home, torch::Tensor slots, torch::Tensor plan,
141+ int64_t num_sms, int64_t instance_id, bool use_udma) {
142+ TORCH_CHECK(use_udma, "compute_push requires URMA; no MTE fallback");
143+ TORCH_CHECK(prefetch_weight_push_udma_available() == 1,
144+ "URMA PUSH requires a native Ascend950 build");
145+ TORCH_CHECK(instance_id == 0 && num_sms > 0, "invalid instance_id or num_sms");
146+ CheckNpuContiguous(home, "home");
147+ CheckNpuContiguous(slots, "slots");
148+ CheckNpuContiguous(plan, "plan");
149+ TORCH_CHECK(home.device() == slots.device() && home.device() == plan.device(),
150+ "home, slots and plan must share an NPU");
151+ TORCH_CHECK(home.scalar_type() == torch::kBFloat16 &&
152+ slots.scalar_type() == torch::kBFloat16 &&
153+ plan.scalar_type() == torch::kInt32, "expected BF16 weights and INT32 plan");
154+ TORCH_CHECK(home.dim() == 3 && slots.dim() == 3 && plan.dim() == 2,
155+ "expected home[E,M,N], slots[B,M,N], plan[EP,B]");
156+ TORCH_CHECK(home.size(0) > 0 && home.size(0) <= INT32_MAX &&
157+ home.size(1) > 0 && home.size(2) > 0,
158+ "home dimensions must be positive");
159+ TORCH_CHECK(home.size(1) == slots.size(1) && home.size(2) == slots.size(2) &&
160+ slots.size(0) == plan.size(1), "incompatible projection or slot shapes");
161+ TORCH_CHECK(plan.size(0) == aclshmem_n_pes() && plan.size(0) > 0 &&
162+ plan.size(0) <= INT32_MAX,
163+ "plan EP must match the initialized SHMEM group");
164+ // Reserve the official WQE scratch plus a full local-copy tile below 188 KiB.
165+ TORCH_CHECK(slots.size(0) <= 15736, "plan exceeds URMA PUSH UB scratch capacity");
166+ aclrtStream stream = c10_npu::getCurrentNPUStream().stream();
167+ aclshmemx_barrier_all_on_stream(stream);
168+ ASCEND_MOONEP_CHECK_ACL(prefetch_weight_push_udma_do(stream,
169+ static_cast<uint8_t*>(home.data_ptr()), static_cast<uint8_t*>(slots.data_ptr()),
170+ static_cast<uint8_t*>(plan.data_ptr()), home.size(0),
171+ home.size(1) * home.size(2), slots.size(0)));
172+ aclshmemx_barrier_all_on_stream(stream);
173+ return slots;
174+}
175+ 
176+bool PrefetchPushPointersAvailable() {
177+ return prefetch_pointer_push_udma_available() == 1;
178+}
179+ 
180+namespace {
181+int64_t CheckPushProjection(const torch::Tensor& source, const torch::Tensor& slots,
182+ const torch::Tensor& plan, int64_t local_experts) {
183+ CheckNpuContiguous(source, "source");
184+ CheckNpuContiguous(slots, "slots");
185+ CheckNpuContiguous(plan, "plan");
186+ TORCH_CHECK(source.device() == slots.device() && slots.device() == plan.device(),
187+ "source, slots and plan must share one NPU");
188+ TORCH_CHECK(slots.scalar_type() == torch::kBFloat16 &&
189+ plan.scalar_type() == torch::kInt32 && slots.dim() == 3 && plan.dim() == 2,
190+ "expected BF16 slots[B,M,N] and INT32 plan[EP,B]");
191+ const int64_t ep = plan.size(0);
192+ TORCH_CHECK(ep > 0 && ep == aclshmem_n_pes() && local_experts > 0 &&
193+ local_experts <= INT32_MAX / ep,
194+ "local expert count or SHMEM topology differs");
195+ TORCH_CHECK(plan.size(1) == slots.size(0) && slots.size(0) <= 15736 &&
196+ slots.size(1) > 0 && slots.size(2) > 0 &&
197+ slots.size(1) <= std::numeric_limits<int64_t>::max() / slots.size(2),
198+ "invalid projection, slots or URMA UB extent");
199+ return slots.size(1) * slots.size(2);
200+}
201+}
202+ 
203+torch::Tensor LaunchPrefetchPushPointers(torch::Tensor pointers, torch::Tensor slots,
204+ torch::Tensor plan, int64_t local_experts, bool aiv_barrier) {
205+ TORCH_CHECK(PrefetchPushPointersAvailable(), "URMA pointer PUSH unavailable; no MTE fallback");
206+ const int64_t elements = CheckPushProjection(pointers, slots, plan, local_experts);
207+ TORCH_CHECK(pointers.scalar_type() == torch::kInt64 && pointers.dim() == 1 &&
208+ pointers.numel() == local_experts, "expected INT64 pointer table[L]");
209+ aclrtStream stream = c10_npu::getCurrentNPUStream().stream();
210+ PrefetchBarrier(stream, aiv_barrier);
211+ ASCEND_MOONEP_CHECK_ACL(moonep_prefetch_pointer_push_udma(stream,
212+ reinterpret_cast<uint8_t*>(pointers.data_ptr()),
213+ reinterpret_cast<uint8_t*>(slots.data_ptr()),
214+ reinterpret_cast<uint8_t*>(plan.data_ptr()),
215+ local_experts * plan.size(0), elements, slots.size(0)));
216+ PrefetchBarrier(stream, aiv_barrier);
217+ return slots;
218+}
219+ 
220+torch::Tensor LaunchPrefetchPushLocal(torch::Tensor home, torch::Tensor slots,
221+ torch::Tensor plan, int64_t global_experts, bool aiv_barrier) {
222+ TORCH_CHECK(prefetch_weight_push_udma_available() == 1,
223+ "URMA contiguous PUSH unavailable; no MTE fallback");
224+ TORCH_CHECK(home.dim() == 3 && home.scalar_type() == torch::kBFloat16 &&
225+ plan.dim() == 2 && plan.size(0) > 0 && global_experts > 0 &&
226+ global_experts % plan.size(0) == 0 &&
227+ home.size(0) == global_experts / plan.size(0),
228+ "expected legal local_home[L,M,N] and explicit global E");
229+ const int64_t elements = CheckPushProjection(home, slots, plan, home.size(0));
230+ TORCH_CHECK(home.size(1) == slots.size(1) && home.size(2) == slots.size(2),
231+ "home and slots projection differs");
232+ aclrtStream stream = c10_npu::getCurrentNPUStream().stream();
233+ PrefetchBarrier(stream, aiv_barrier);
234+ ASCEND_MOONEP_CHECK_ACL(prefetch_weight_push_udma_do(stream,
235+ reinterpret_cast<uint8_t*>(home.data_ptr()),
236+ reinterpret_cast<uint8_t*>(slots.data_ptr()),
237+ reinterpret_cast<uint8_t*>(plan.data_ptr()),
238+ global_experts, elements, slots.size(0)));
239+ PrefetchBarrier(stream, aiv_barrier);
240+ return slots;
241+}
125} // namespace ascend_moonep::ops242} // namespace ascend_moonep::ops
@@ -13,4 +13,14 @@ torch::Tensor LaunchPrefetch(
13 bool use_udma,13 bool use_udma,
14 bool rank_barriers = true);14 bool rank_barriers = true);
15 15 
16+ 
17+torch::Tensor LaunchPrefetchPush(
18+ torch::Tensor home, torch::Tensor slots, torch::Tensor plan,
19+ int64_t num_sms, int64_t instance_id, bool use_udma);
20+// Stateless submissions: caller owns Tensor/table lifetime and consumer final use.
21+bool PrefetchPushPointersAvailable();
22+torch::Tensor LaunchPrefetchPushPointers(torch::Tensor pointers, torch::Tensor slots,
23+ torch::Tensor plan, int64_t local_experts, bool aiv_barrier = false);
24+torch::Tensor LaunchPrefetchPushLocal(torch::Tensor home, torch::Tensor slots,
25+ torch::Tensor plan, int64_t global_experts, bool aiv_barrier = false);
16} // namespace ascend_moonep::ops26} // namespace ascend_moonep::ops
@@ -2,7 +2,9 @@
2 2 
3#include "acl_shared_buffer.h"3#include "acl_shared_buffer.h"
4#include "launcher.h"4#include "launcher.h"
5+#include "lplusb_runtime.h"
5#include "shmem.h"6#include "shmem.h"
7+#include "csrc/ops/prefetch.h"
6 8 
7PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {9PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
8 m.doc() = "MoonEP NPU symmetric-memory extension (shmem C++ backend)";10 m.doc() = "MoonEP NPU symmetric-memory extension (shmem C++ backend)";
@@ -12,6 +14,46 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
12 py::int_(sizeof(aclshmemx_buffer_optional_attr_t));14 py::int_(sizeof(aclshmemx_buffer_optional_attr_t));
13 15 
14 using py::arg;16 using py::arg;
17+ m.attr("PREFETCH_PUSH_POINTER_ABI") = py::int_(1);
18+ m.attr("PREFETCH_PUSH_LOCAL_ABI") = py::int_(1);
19+ m.attr("PREFETCH_PUSH_BARRIER_ABI") = py::int_(1);
20+ m.def("_prefetch_push_available", &ascend_moonep::ops::PrefetchPushPointersAvailable);
21+ m.def("_prefetch_push_pointers", &ascend_moonep::ops::LaunchPrefetchPushPointers,
22+ arg("source_ptrs"), arg("slots"), arg("plan"), arg("local_experts"), arg("aiv_barrier") = false);
23+ m.def("_prefetch_push_local", &ascend_moonep::ops::LaunchPrefetchPushLocal,
24+ arg("local_home"), arg("slots"), arg("plan"), arg("global_experts"), arg("aiv_barrier") = false);
25+ m.def("_prefetch_push_pointers_aiv", [](torch::Tensor p, torch::Tensor s, torch::Tensor plan, int64_t l) {
26+ return ascend_moonep::ops::LaunchPrefetchPushPointers(p, s, plan, l, true);
27+ });
28+ m.def("_prefetch_push_local_aiv", [](torch::Tensor h, torch::Tensor s, torch::Tensor plan, int64_t e) {
29+ return ascend_moonep::ops::LaunchPrefetchPushLocal(h, s, plan, e, true);
30+ });
31+ 
32+ // Private MindSpeed integration. Kept out of Python __all__ and public
33+ // Buffer signatures so existing MoonEP callers are unaffected.
34+ m.attr("LPLUS_B_BUFFER_SYNC_ABI") = py::int_(2);
35+ m.attr("LPLUS_B_URMA_PUSH_ABI") = py::int_(1);
36+ m.attr("LPLUS_B_URMA_CONTIGUOUS_ABI") = py::int_(1);
37+ m.def("_lplusb_owner_push_urma_contiguous", &ascend_moonep::LPlusBOwnerPushUrmaContiguous,
38+ arg("local_home"), arg("weight_slots"), arg("experts_to_copy"),
39+ arg("rank"), arg("global_experts"));
40+ m.def("_lplusb_urma_push_available", &ascend_moonep::LPlusBUrmaAvailable);
41+ m.def("_lplusb_owner_push_urma", &ascend_moonep::LPlusBOwnerPushUrma,
42+ arg("source_ptrs"), arg("weight_slots"), arg("experts_to_copy"),
43+ arg("rank"), arg("local_experts"));
44+ m.attr("GRAD_REDUCE_POINTER_ABI") = py::int_(1);
45+ m.attr("GRAD_REDUCE_POINTER_UDMA_ABI") = py::int_(3);
46+ m.attr("LPLUS_B_OWNER_READY_ABI") = py::int_(1);
47+ m.def("_lplusb_owner_ready_init", &ascend_moonep::LPlusBOwnerReadyInit, arg("ready"));
48+ m.def("_lplusb_owner_push_ready", &ascend_moonep::LPlusBOwnerPushReady,
49+ arg("source_ptrs"), arg("weight_slots"), arg("experts_to_copy"), arg("ready"),
50+ arg("rank"), arg("local_experts"), arg("epoch"));
51+ m.def("_lplusb_owner_push", &ascend_moonep::LPlusBOwnerPush,
52+ arg("source_ptrs"), arg("weight_slots"), arg("experts_to_copy"),
53+ arg("rank"), arg("local_experts"));
54+ m.def("_lplusb_owner_reduce", &ascend_moonep::LPlusBOwnerReduce,
55+ arg("target_ptrs"), arg("grad_slots"), arg("experts_to_copy"),
56+ arg("rank"), arg("local_experts"));
15 57 
16 m.def("launch_device_barrier_bench", &LaunchDeviceBarrierBench,58 m.def("launch_device_barrier_bench", &LaunchDeviceBarrierBench,
17 arg("iterations"), arg("block_dim") = 32,59 arg("iterations"), arg("block_dim") = 32,
@@ -151,4 +193,9 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
151 &ascend_moonep::acl_shmem_barrier_all_on_stream,193 &ascend_moonep::acl_shmem_barrier_all_on_stream,
152 arg("stream"),194 arg("stream"),
153 "Global shmem barrier issued on the given aclrtStream");195 "Global shmem barrier issued on the given aclrtStream");
196+ m.attr("ASYNC_STREAM_BARRIER_ABI") = py::int_(1);
197+ m.def("_acl_shmem_barrier_all_aiv_on_stream",
198+ &ascend_moonep::acl_shmem_barrier_all_aiv_on_stream,
199+ arg("stream"),
200+ "Same collective completion using a single AIV participant");
154}201}
@@ -12,6 +12,7 @@
12#include <torch/script.h>12#include <torch/script.h>
13 13 
14#include "shmem.h"14#include "shmem.h"
15+#include "ascend_moonep/kernels/launch.h"
15 16 
16#include "csrc/common/check.h"17#include "csrc/common/check.h"
17#include "csrc/launcher.h"18#include "csrc/launcher.h"
@@ -105,7 +106,15 @@ private:
105 106 
106class PrefetchWeight : public torch::jit::CustomClassHolder {107class PrefetchWeight : public torch::jit::CustomClassHolder {
107public:108public:
109+ 
108 explicit PrefetchWeight(int64_t /*local_mem_size*/) {}110 explicit PrefetchWeight(int64_t /*local_mem_size*/) {}
111+ bool push_available() { return prefetch_weight_push_udma_available() == 1; }
112+ torch::Tensor compute_push(torch::Tensor home, torch::Tensor slots, torch::Tensor plan,
113+ int64_t num_experts, int64_t num_sms, int64_t instance_id, bool use_udma) {
114+ TORCH_CHECK(home.dim() == 3 && home.size(0) == num_experts, "invalid num_experts");
115+ return ascend_moonep::ops::LaunchPrefetchPush(
116+ home, slots, plan, num_sms, instance_id, use_udma);
117+ }
109 118 
110 void destroy() {}119 void destroy() {}
111 120 
@@ -162,6 +171,19 @@ public:
162 blocks,171 blocks,
163 use_udma);172 use_udma);
164 }173 }
174+ 
175+ void compute_targets(
176+ torch::Tensor target_ptrs, torch::Tensor reduce_buffers,
177+ torch::Tensor experts_to_copy, int64_t epn, int64_t hidden,
178+ int64_t projection, int64_t ranks, int64_t slots, int64_t rank,
179+ int64_t blocks, bool use_udma = false,
180+ c10::optional<torch::Tensor> workspace = c10::nullopt) {
181+ TORCH_CHECK(rank == aclshmem_my_pe(),
182+ "rank does not match the active CANN-SHMEM PE");
183+ ascend_moonep::ops::GradReduceTargets(target_ptrs, reduce_buffers, experts_to_copy,
184+ epn, hidden, projection, ranks, slots, rank, blocks, use_udma,
185+ workspace.value_or(torch::Tensor()));
186+ }
165};187};
166 188 
167class Planning : public torch::jit::CustomClassHolder {189class Planning : public torch::jit::CustomClassHolder {
@@ -576,12 +598,21 @@ static auto prefetch_weight_registry =
576 torch::jit::class_<ascend_moonep::torch_classes::PrefetchWeight>("AscendMoonEP", "PrefetchWeight")598 torch::jit::class_<ascend_moonep::torch_classes::PrefetchWeight>("AscendMoonEP", "PrefetchWeight")
577 .def(torch::jit::init<int64_t>())599 .def(torch::jit::init<int64_t>())
578 .def("compute", &ascend_moonep::torch_classes::PrefetchWeight::compute)600 .def("compute", &ascend_moonep::torch_classes::PrefetchWeight::compute)
601+ .def("compute_push", &ascend_moonep::torch_classes::PrefetchWeight::compute_push)
602+ .def("push_available", &ascend_moonep::torch_classes::PrefetchWeight::push_available)
579 .def("destroy", &ascend_moonep::torch_classes::PrefetchWeight::destroy);603 .def("destroy", &ascend_moonep::torch_classes::PrefetchWeight::destroy);
580 604 
581static auto grad_reduce_registry =605static auto grad_reduce_registry =
582 torch::jit::class_<ascend_moonep::torch_classes::GradReduce>("AscendMoonEP", "GradReduce")606 torch::jit::class_<ascend_moonep::torch_classes::GradReduce>("AscendMoonEP", "GradReduce")
583 .def(torch::jit::init<>())607 .def(torch::jit::init<>())
584- .def("compute", &ascend_moonep::torch_classes::GradReduce::compute);608+ .def("compute", &ascend_moonep::torch_classes::GradReduce::compute)
609+ .def("compute_targets", &ascend_moonep::torch_classes::GradReduce::compute_targets,
610+ "", {torch::arg("target_ptrs"), torch::arg("reduce_buffers"),
611+ torch::arg("experts_to_copy"), torch::arg("epn"),
612+ torch::arg("hidden"), torch::arg("projection"),
613+ torch::arg("ranks"), torch::arg("slots"), torch::arg("rank"),
614+ torch::arg("blocks"), torch::arg("use_udma") = false,
615+ torch::arg("workspace") = c10::IValue()});
585 616 
586static auto planning_registry =617static auto planning_registry =
587 torch::jit::class_<ascend_moonep::torch_classes::Planning>("AscendMoonEP", "Planning")618 torch::jit::class_<ascend_moonep::torch_classes::Planning>("AscendMoonEP", "Planning")
@@ -10,6 +10,9 @@
10 10 
11extern "C" {11extern "C" {
12 12 
13+// Experimental native GR barrier; public tensor/SPI ABI remains unchanged.
14+ASCEND_MOONEP_EXPORT int moonep_grad_reduce_native_barrier(void* stream);
15+ 
13ASCEND_MOONEP_EXPORT void device_barrier_bench_kernel_do(16ASCEND_MOONEP_EXPORT void device_barrier_bench_kernel_do(
14 void* stream,17 void* stream,
15 int32_t iterations,18 int32_t iterations,
@@ -174,6 +177,19 @@ ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce(
174 int32_t rank,177 int32_t rank,
175 int32_t blocks);178 int32_t blocks);
176 179 
180+// Local canonical target pointer table; source slots remain symmetric.
181+ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_targets(
182+ void* stream, void* target_ptrs, void* reduce_buffers,
183+ const int32_t* experts_to_copy, int32_t epn, int32_t hidden,
184+ int32_t projection, int32_t ranks, int32_t slots, int32_t rank,
185+ int32_t blocks);
186+ 
187+ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_targets_udma(
188+ void* stream, void* target_ptrs, void* reduce_buffers, void* workspace,
189+ const int32_t* experts_to_copy, int32_t epn, int32_t hidden,
190+ int32_t projection, int32_t ranks, int32_t slots, int32_t rank,
191+ int32_t blocks);
192+ 
177ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_udma(193ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_udma(
178 void* stream,194 void* stream,
179 void* expert_grads,195 void* expert_grads,
@@ -210,4 +226,45 @@ ASCEND_MOONEP_EXPORT void prefetch_weight_kernel_udma_do(
210 int64_t num_slots,226 int64_t num_slots,
211 int64_t block_dim);227 int64_t block_dim);
212 228 
229+ASCEND_MOONEP_EXPORT int moonep_lplusb_owner_push(
230+ void* stream,
231+ const uint64_t* source_ptrs,
232+ void* weight_slots,
233+ const int32_t* experts_to_copy,
234+ int64_t row_elements,
235+ int32_t local_experts,
236+ int32_t ranks,
237+ int32_t slots,
238+ int32_t rank,
239+ int32_t blocks);
240+ 
241+ASCEND_MOONEP_EXPORT int moonep_lplusb_owner_ready(
242+ void* stream, int32_t* ready, const int32_t* experts_to_copy,
243+ int32_t local_experts, int32_t ranks, int32_t slots, int32_t rank, int32_t epoch);
244+ 
245+ASCEND_MOONEP_EXPORT int moonep_lplusb_owner_reduce(
246+ void* stream,
247+ const uint64_t* target_ptrs,
248+ void* grad_slots,
249+ const int32_t* experts_to_copy,
250+ int64_t row_elements,
251+ int32_t local_experts,
252+ int32_t ranks,
253+ int32_t slots,
254+ int32_t rank,
255+ int32_t blocks);
256+ 
257+ 
258+ASCEND_MOONEP_EXPORT int prefetch_pointer_push_udma_available();
259+ASCEND_MOONEP_EXPORT int moonep_prefetch_barrier_vec(void* stream);
260+ASCEND_MOONEP_EXPORT int moonep_async_stream_barrier_vec(void* stream);
261+ASCEND_MOONEP_EXPORT int moonep_prefetch_pointer_push_udma(
262+ void* stream, uint8_t* pointers, uint8_t* slots, uint8_t* plan,
263+ int64_t experts, int64_t row_elements, int64_t num_slots);
264+ 
265+ASCEND_MOONEP_EXPORT int prefetch_weight_push_udma_available();
266+ASCEND_MOONEP_EXPORT int prefetch_weight_push_udma_do(
267+ void* stream, uint8_t* source, uint8_t* slots, uint8_t* plan,
268+ int64_t experts, int64_t row_elements, int64_t num_slots);
269+ 
213} // extern "C"270} // extern "C"
@@ -92,6 +92,9 @@ struct alignas(8) MoonEPDispatchTilingData {
92 uint32_t server_dedup;92 uint32_t server_dedup;
93};93};
94 94 
95+static_assert(sizeof(MoonEPDispatchTilingData) == 32, "dispatch tiling ABI must remain 32 bytes");
96+static_assert(sizeof(MoonEPCombineTilingData) == 32, "combine tiling ABI must remain 32 bytes");
97+ 
95// Udma dispatch profile ABI (mirrors the UBMEM template-<bool Profile> pattern98// Udma dispatch profile ABI (mirrors the UBMEM template-<bool Profile> pattern
96// from the timing branch): moonep_dispatch_udma_profile_kernel writes each AIV's99// from the timing branch): moonep_dispatch_udma_profile_kernel writes each AIV's
97// metrics as an int64 row into a [kMoonEPAivNum, kMoonEPDispatchUdmaProfileFields]100// metrics as an int64 row into a [kMoonEPAivNum, kMoonEPDispatchUdmaProfileFields]
@@ -0,0 +1,159 @@
1+// SPDX-License-Identifier: Apache-2.0
2+// Shared by the standalone contiguous-home and provider pointer-source bindings.
3+// No allocations, SHMEM initialization, or custom queue protocol belong here.
4+#pragma once
5+#include <cstdint>
6+#include "kernel_operator.h"
7+#include "shmem.h"
8+#include "opdev/bfloat16.h"
9+ 
10+namespace moonep_urma_push {
11+using namespace AscendC;
12+constexpr int32_t kUdmaCannShmemInternalUbStartBytes = 188 * 1024;
13+constexpr int64_t kUdmaPrefetchUbScratchOffset = 64;
14+constexpr int32_t kUdmaUbExpertTabOffset = kUdmaPrefetchUbScratchOffset;
15+constexpr int32_t kUdmaUbAlignBytes = 32;
16+constexpr int64_t kUdmaMaxTransferBytes = 256LL * 1024 * 1024;
17+constexpr uint32_t kUdmaLocalCopyMaxBytes = 65504;
18+constexpr uint32_t kUdmaWqeElements = 256;
19+ 
20+__aicore__ inline int32_t UdmaAlignUp(int32_t value, int32_t alignment)
21+{
22+ return (value + alignment - 1) / alignment * alignment;
23+}
24+ 
25+__aicore__ inline int32_t UdmaAivWorkerIndex()
26+{
27+ const int32_t sub_blocks = static_cast<int32_t>(GetSubBlockNum());
28+ return sub_blocks > 0 ?
29+ static_cast<int32_t>(GetBlockIdx()) / sub_blocks : 0;
30+}
31+ 
32+__aicore__ inline void UdmaCopyLocalExpertChunk(
33+ __gm__ bfloat16_t* destination,
34+ __gm__ bfloat16_t* source,
35+ uint32_t elements,
36+ __ubuf__ bfloat16_t* ub)
37+{
38+ GlobalTensor<bfloat16_t> local_src;
39+ GlobalTensor<bfloat16_t> local_dst;
40+ local_src.SetGlobalBuffer(source, elements);
41+ local_dst.SetGlobalBuffer(destination, elements);
42+ 
43+ LocalTensor<bfloat16_t> local_ub;
44+ local_ub.address_.logicPos = static_cast<uint8_t>(TPosition::VECIN);
45+ local_ub.address_.bufferAddr = reinterpret_cast<uint64_t>(ub);
46+ 
47+ for (uint32_t copied = 0; copied < elements;) {
48+ uint32_t copy_elems = elements - copied;
49+ const uint32_t max_elems = kUdmaLocalCopyMaxBytes / sizeof(bfloat16_t);
50+ if (copy_elems > max_elems) {
51+ copy_elems = max_elems;
52+ }
53+ const DataCopyExtParams copy_params{
54+ 1, static_cast<uint32_t>(copy_elems * sizeof(bfloat16_t)), 0, 0, 0};
55+ const DataCopyPadExtParams<bfloat16_t> pad_params{false, 0, 0, 0};
56+ DataCopyPad(local_ub, local_src[copied], copy_params, pad_params);
57+ SetFlag<HardEvent::MTE2_MTE3>(EVENT_ID1);
58+ WaitFlag<HardEvent::MTE2_MTE3>(EVENT_ID1);
59+ DataCopyPad(local_dst[copied], local_ub, copy_params);
60+ SetFlag<HardEvent::MTE3_MTE2>(EVENT_ID1);
61+ WaitFlag<HardEvent::MTE3_MTE2>(EVENT_ID1);
62+ copied += copy_elems;
63+ }
64+}
65+ 
66+ 
67+template<bool PointerSource>
68+__aicore__ inline void Run(
69+ GM_ADDR source_addr, GM_ADDR slots_addr, GM_ADDR plan_addr,
70+ int64_t experts, int64_t row_elements, int64_t slots)
71+{
72+ if ASCEND_IS_AIC { return; }
73+ if (UdmaAivWorkerIndex() != 0) { return; }
74+ auto* home = reinterpret_cast<__gm__ bfloat16_t*>(source_addr);
75+ auto* pointers = reinterpret_cast<__gm__ uint64_t*>(source_addr);
76+ auto* destination = reinterpret_cast<__gm__ bfloat16_t*>(slots_addr);
77+ auto* plan = reinterpret_cast<__gm__ int32_t*>(plan_addr);
78+ const int32_t ranks = aclshmem_n_pes();
79+ const int32_t rank = aclshmem_my_pe();
80+ const int64_t epn = (experts + ranks - 1) / ranks;
81+ const int32_t data_offset = UdmaAlignUp(
82+ kUdmaUbExpertTabOffset + UdmaAlignUp(
83+ static_cast<int32_t>(2 * slots * sizeof(int32_t)), 32), 32);
84+ TPipe pipe;
85+ TBuf<TPosition::VECOUT> tab_buf, wqe_buf, ub_buf;
86+ pipe.InitBuffer(tab_buf, data_offset);
87+ pipe.InitBuffer(wqe_buf, kUdmaWqeElements * sizeof(bfloat16_t));
88+ pipe.InitBuffer(ub_buf, kUdmaCannShmemInternalUbStartBytes -
89+ data_offset - kUdmaWqeElements * sizeof(bfloat16_t));
90+ auto tab = tab_buf.Get<int32_t>();
91+ auto wqe = wqe_buf.Get<bfloat16_t>();
92+ auto local = ub_buf.Get<bfloat16_t>();
93+ auto* expert_tab = reinterpret_cast<__ubuf__ int32_t*>(tab.GetPhyAddr());
94+ auto* slot_tab = expert_tab + slots;
95+ auto* scratch = reinterpret_cast<__ubuf__ bfloat16_t*>(wqe.GetPhyAddr());
96+ auto* ub = reinterpret_cast<__ubuf__ bfloat16_t*>(local.GetPhyAddr());
97+ Duplicate(wqe, static_cast<bfloat16_t>(0), kUdmaWqeElements);
98+ // SDK WQE construction uses scalar stores through the same raw UB pointer.
99+ // Order the vector clear before those stores; Tensor auto-sync cannot
100+ // infer this pointer handoff. SDK and local-copy events use IDs 0 and 1.
101+ SetFlag<HardEvent::V_S>(EVENT_ID2);
102+ WaitFlag<HardEvent::V_S>(EVENT_ID2);
103+ // Validate the complete plan before this owner submits any payload.
104+ for (int64_t i = 0; i < ranks * slots; ++i) {
105+ if (plan[i] < -1 || plan[i] >= experts) {
106+ AscendC::printf("URMA_PUSH_INVALID_EXPERT rank=%d entry=%ld expert=%d\n",
107+ rank, i, plan[i]);
108+ trap();
109+ }
110+ }
111+ const int64_t max_elements = kUdmaMaxTransferBytes / sizeof(bfloat16_t);
112+ for (int32_t peer = 0; peer < ranks; ++peer) {
113+ int64_t active = 0;
114+ for (int64_t slot = 0; slot < slots; ++slot) {
115+ const int32_t expert = plan[peer * slots + slot];
116+ if (expert >= 0 && expert / epn == rank) {
117+ expert_tab[active] = expert % epn;
118+ slot_tab[active++] = slot;
119+ }
120+ }
121+ for (int64_t i = 0; i < active; ++i) {
122+ __gm__ bfloat16_t* source;
123+ if constexpr (PointerSource) {
124+ source = reinterpret_cast<__gm__ bfloat16_t*>(pointers[expert_tab[i]]);
125+ if (source == nullptr) {
126+ AscendC::printf("URMA_PUSH_NULL_SOURCE rank=%d expert=%d\n",
127+ rank, expert_tab[i]);
128+ trap();
129+ }
130+ } else {
131+ source = home + expert_tab[i] * row_elements;
132+ }
133+ for (int64_t offset = 0; offset < row_elements; offset += max_elements) {
134+ const uint32_t count = static_cast<uint32_t>(
135+ row_elements - offset < max_elements ? row_elements - offset : max_elements);
136+ auto* dst = destination + slot_tab[i] * row_elements + offset;
137+ if (peer == rank) {
138+ UdmaCopyLocalExpertChunk(dst, source + offset, count, ub);
139+ } else {
140+ aclshmemx_udma_put_nbi(dst, source + offset, scratch,
141+ count, peer, EVENT_ID0);
142+ }
143+ }
144+ }
145+ }
146+ // One AIV issues all peers before waiting for their payloads. The SDK has
147+ // finished publishing each UB-staged WQE before put_nbi returns; the WQE
148+ // refers to the retained GM source, not this reusable UB scratch. Queue
149+ // credit and any overflow drain remain owned by the default SDK path.
150+ // No peer-visible publication is permitted until every required quiet has
151+ // returned. The caller's post barrier and consumer events are unchanged.
152+ for (int32_t peer = 0; peer < ranks; ++peer) {
153+ if (peer != rank) {
154+ aclshmemx_udma_quiet(peer);
155+ }
156+ }
157+ aclshmem_quiet();
158+}
159+} // namespace moonep_urma_push
@@ -0,0 +1,292 @@
1+// Private L+B provider kernels. These symbols are deliberately absent from
2+// npu_patch.__all__; MindSpeed reaches them through the private extension.
3+ 
4+#include <cstdint>
5+ 
6+#include "acl/acl.h"
7+#include "kernel_operator.h"
8+#include "shmem.h"
9+ 
10+#include "ascend_moonep/kernels/launch.h"
11+#include "opdev/bfloat16.h"
12+ 
13+using namespace AscendC;
14+ 
15+namespace {
16+ 
17+constexpr int32_t kLPlusBUbBytes = 188 * 1024;
18+constexpr uint64_t kLPlusBUbOffset = 64;
19+constexpr int32_t kLPlusBFp32Tile = 12 * 1024;
20+constexpr int32_t kLPlusBFp32TileBytes = kLPlusBFp32Tile * sizeof(float);
21+ 
22+__aicore__ inline int32_t LPlusBWorkerIndex()
23+{
24+ const int32_t sub_blocks = static_cast<int32_t>(GetSubBlockNum());
25+ return sub_blocks > 0 ? static_cast<int32_t>(GetBlockIdx()) / sub_blocks : 0;
26+}
27+ 
28+__aicore__ inline int64_t LPlusBCeilDiv(int64_t value, int64_t divisor)
29+{
30+ return (value + divisor - 1) / divisor;
31+}
32+ 
33+template <typename T>
34+__aicore__ inline LocalTensor<T> LPlusBLocalAt(__ubuf__ T* ptr, int32_t elements, TPosition position)
35+{
36+ LocalTensor<T> tensor;
37+ tensor.address_.logicPos = static_cast<uint8_t>(position);
38+ tensor.address_.bufferAddr = reinterpret_cast<uint64_t>(ptr);
39+ tensor.address_.dataLen = static_cast<uint32_t>((elements * sizeof(T) + 31) & ~31);
40+ return tensor;
41+}
42+ 
43+__aicore__ inline void LPlusBLoadLocalFp32(__ubuf__ float* dst, __gm__ float* src, int32_t elements)
44+{
45+ GlobalTensor<float> source;
46+ source.SetGlobalBuffer(src);
47+ auto local = LPlusBLocalAt(dst, elements, TPosition::VECIN);
48+ DataCopyExtParams params(1, static_cast<uint32_t>(elements * sizeof(float)), 0, 0, 0);
49+ DataCopyPadExtParams<float> pad{false, 0, 0, 0};
50+ DataCopyPad(local, source, params, pad);
51+ PipeBarrier<PIPE_ALL>();
52+}
53+ 
54+__aicore__ inline void LPlusBStoreLocalFp32(__gm__ float* dst, __ubuf__ float* src, int32_t elements)
55+{
56+ GlobalTensor<float> destination;
57+ destination.SetGlobalBuffer(dst);
58+ auto local = LPlusBLocalAt(src, elements, TPosition::VECOUT);
59+ DataCopyExtParams params(1, static_cast<uint32_t>(elements * sizeof(float)), 0, 0, 0);
60+ PipeBarrier<PIPE_ALL>();
61+ DataCopyPad(destination, local, params);
62+ PipeBarrier<PIPE_ALL>();
63+}
64+ 
65+} // namespace
66+ 
67+extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__
68+void MoonEPLPlusBOwnerPush(
69+ GM_ADDR source_ptrs_addr,
70+ GM_ADDR weight_slots_addr,
71+ GM_ADDR experts_to_copy_addr,
72+ int64_t row_elements,
73+ int32_t local_experts,
74+ int32_t ranks,
75+ int32_t slots,
76+ int32_t rank)
77+{
78+ if ASCEND_IS_AIC {
79+ return;
80+ }
81+ auto* source_ptrs = reinterpret_cast<__gm__ uint64_t*>(source_ptrs_addr);
82+ auto* weight_slots = reinterpret_cast<__gm__ bfloat16_t*>(weight_slots_addr);
83+ auto* plan = reinterpret_cast<__gm__ int32_t*>(experts_to_copy_addr);
84+ const int32_t block = LPlusBWorkerIndex();
85+ const int32_t block_count = GetBlockNum();
86+ const int32_t tile_elements = (kLPlusBUbBytes - static_cast<int32_t>(kLPlusBUbOffset)) /
87+ static_cast<int32_t>(sizeof(bfloat16_t)) / 2;
88+ const int64_t chunks = LPlusBCeilDiv(row_elements, tile_elements);
89+ const int64_t entries = static_cast<int64_t>(ranks) * slots;
90+ const int32_t local_begin = rank * local_experts;
91+ auto* ping = reinterpret_cast<__ubuf__ bfloat16_t*>(kLPlusBUbOffset);
92+ auto* pong = ping + tile_elements;
93+ int32_t buffer = 0;
94+ SetFlag<HardEvent::MTE3_MTE2>(EVENT_ID0);
95+ SetFlag<HardEvent::MTE3_MTE2>(EVENT_ID1);
96+ for (int64_t task = block; task < entries * chunks; task += block_count) {
97+ const int64_t entry = task / chunks;
98+ const int64_t chunk = task % chunks;
99+ const int32_t expert = plan[entry];
100+ if (expert < local_begin || expert >= local_begin + local_experts) {
101+ continue;
102+ }
103+ const int32_t local_expert = expert - local_begin;
104+ const int32_t destination_pe = static_cast<int32_t>(entry / slots);
105+ const int32_t destination_slot = static_cast<int32_t>(entry % slots);
106+ const int64_t begin = chunk * tile_elements;
107+ const int32_t elements = static_cast<int32_t>(
108+ row_elements - begin < tile_elements ? row_elements - begin : tile_elements);
109+ const TEventID event = buffer == 0 ? EVENT_ID0 : EVENT_ID1;
110+ auto* ub = buffer == 0 ? ping : pong;
111+ WaitFlag<HardEvent::MTE3_MTE2>(event);
112+ auto* src = reinterpret_cast<__gm__ bfloat16_t*>(source_ptrs[local_expert]) + begin;
113+ auto* dst = weight_slots + static_cast<int64_t>(destination_slot) * row_elements + begin;
114+ aclshmemx_mte_put_nbi(
115+ dst, src, ub,
116+ static_cast<uint32_t>(tile_elements * sizeof(bfloat16_t)),
117+ static_cast<uint32_t>(elements), destination_pe, event);
118+ SetFlag<HardEvent::MTE3_MTE2>(event);
119+ buffer = 1 - buffer;
120+ }
121+ WaitFlag<HardEvent::MTE3_MTE2>(EVENT_ID0);
122+ WaitFlag<HardEvent::MTE3_MTE2>(EVENT_ID1);
123+ aclshmem_quiet();
124+}
125+ 
126+extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__
127+void MoonEPLPlusBOwnerReady(
128+ GM_ADDR ready_addr, GM_ADDR experts_to_copy_addr,
129+ int32_t local_experts, int32_t ranks, int32_t slots, int32_t rank, int32_t epoch)
130+{
131+ if ASCEND_IS_AIC {
132+ return;
133+ }
134+ // One publisher, launched AFTER every worker of OwnerPush has completed.
135+ // Publishing from one worker inside OwnerPush would race the other workers.
136+ if (GetBlockIdx() != 0) {
137+ return;
138+ }
139+ constexpr int32_t stride = 64 / sizeof(int32_t);
140+ static_assert(SCALAR_DATA_CACHELINE_SIZE == 64, "owner-ready signal ABI needs 64-byte lines");
141+ auto* ready = reinterpret_cast<__gm__ int32_t*>(ready_addr);
142+ auto* plan = reinterpret_cast<__gm__ int32_t*>(experts_to_copy_addr);
143+ // Publish before ANY wait, even for an empty/local-only receiver. Each
144+ // owner has its own cache line so peer SET/flush cannot clobber another.
145+ for (int32_t pe = 0; pe < ranks; ++pe) {
146+ if (pe != rank) {
147+ aclshmemx_signal_op(ready + rank * stride, epoch, ACLSHMEM_SIGNAL_SET, pe);
148+ }
149+ }
150+ aclshmem_quiet();
151+ for (int32_t owner = 0; owner < ranks; ++owner) {
152+ if (owner == rank) {
153+ continue;
154+ }
155+ for (int32_t slot = 0; slot < slots; ++slot) {
156+ const int32_t expert = plan[static_cast<int64_t>(rank) * slots + slot];
157+ if (expert >= 0 && expert / local_experts == owner) {
158+ aclshmem_signal_wait_until(ready + owner * stride, ACLSHMEM_CMP_EQ, epoch);
159+ break;
160+ }
161+ }
162+ }
163+ aclshmem_quiet();
164+}
165+ 
166+extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__
167+void MoonEPLPlusBOwnerReduce(
168+ GM_ADDR target_ptrs_addr,
169+ GM_ADDR grad_slots_addr,
170+ GM_ADDR experts_to_copy_addr,
171+ int64_t row_elements,
172+ int32_t local_experts,
173+ int32_t ranks,
174+ int32_t slots,
175+ int32_t rank)
176+{
177+ if ASCEND_IS_AIC {
178+ return;
179+ }
180+ auto* target_ptrs = reinterpret_cast<__gm__ uint64_t*>(target_ptrs_addr);
181+ auto* grad_slots = reinterpret_cast<__gm__ float*>(grad_slots_addr);
182+ auto* plan = reinterpret_cast<__gm__ int32_t*>(experts_to_copy_addr);
183+ const int32_t block = LPlusBWorkerIndex();
184+ const int32_t block_count = GetBlockNum();
185+ const int32_t local_begin = rank * local_experts;
186+ const int64_t chunks = LPlusBCeilDiv(row_elements, kLPlusBFp32Tile);
187+ auto* accum = reinterpret_cast<__ubuf__ float*>(kLPlusBUbOffset);
188+ auto* remote = reinterpret_cast<__ubuf__ float*>(kLPlusBUbOffset + kLPlusBFp32TileBytes);
189+ auto* zero = reinterpret_cast<__ubuf__ float*>(kLPlusBUbOffset + 2 * kLPlusBFp32TileBytes);
190+ 
191+ for (int32_t local_expert = 0; local_expert < local_experts; ++local_expert) {
192+ const int32_t global_expert = local_begin + local_expert;
193+ auto* target = reinterpret_cast<__gm__ float*>(target_ptrs[local_expert]);
194+ for (int64_t chunk = block; chunk < chunks; chunk += block_count) {
195+ const int64_t begin = chunk * kLPlusBFp32Tile;
196+ const int32_t elements = static_cast<int32_t>(
197+ row_elements - begin < kLPlusBFp32Tile ? row_elements - begin : kLPlusBFp32Tile);
198+ LPlusBLoadLocalFp32(accum, target + begin, elements);
199+ auto accum_in = LPlusBLocalAt(accum, elements, TPosition::VECIN);
200+ auto accum_out = LPlusBLocalAt(accum, elements, TPosition::VECOUT);
201+ for (int32_t pe = 0; pe < ranks; ++pe) {
202+ for (int32_t slot = 0; slot < slots; ++slot) {
203+ if (plan[static_cast<int64_t>(pe) * slots + slot] != global_expert) {
204+ continue;
205+ }
206+ aclshmemx_mte_get_nbi(
207+ remote,
208+ grad_slots + static_cast<int64_t>(slot) * row_elements + begin,
209+ static_cast<uint32_t>(elements), pe, EVENT_ID0);
210+ SetFlag<HardEvent::MTE2_V>(EVENT_ID0);
211+ WaitFlag<HardEvent::MTE2_V>(EVENT_ID0);
212+ auto remote_in = LPlusBLocalAt(remote, elements, TPosition::VECIN);
213+ Add(accum_out, accum_in, remote_in, elements);
214+ PipeBarrier<PIPE_ALL>();
215+ }
216+ }
217+ LPlusBStoreLocalFp32(target + begin, accum, elements);
218+ }
219+ }
220+ 
221+ // All ranks finish remote reads before any rank clears its local slots.
222+ aclshmem_quiet();
223+ aclshmemx_barrier_all_vec();
224+ auto zero_out = LPlusBLocalAt(zero, kLPlusBFp32Tile, TPosition::VECOUT);
225+ Duplicate(zero_out, 0.0F, kLPlusBFp32Tile);
226+ PipeBarrier<PIPE_ALL>();
227+ const int64_t local_elements = static_cast<int64_t>(slots) * row_elements;
228+ const int64_t clear_chunks = LPlusBCeilDiv(local_elements, kLPlusBFp32Tile);
229+ for (int64_t chunk = block; chunk < clear_chunks; chunk += block_count) {
230+ const int64_t begin = chunk * kLPlusBFp32Tile;
231+ const int32_t elements = static_cast<int32_t>(
232+ local_elements - begin < kLPlusBFp32Tile ? local_elements - begin : kLPlusBFp32Tile);
233+ LPlusBStoreLocalFp32(grad_slots + begin, zero, elements);
234+ }
235+}
236+ 
237+extern "C" ASCEND_MOONEP_EXPORT int moonep_lplusb_owner_push(
238+ void* stream, const uint64_t* source_ptrs, void* weight_slots,
239+ const int32_t* experts_to_copy, int64_t row_elements, int32_t local_experts,
240+ int32_t ranks, int32_t slots, int32_t rank, int32_t blocks)
241+{
242+ if (stream == nullptr || source_ptrs == nullptr || weight_slots == nullptr ||
243+ experts_to_copy == nullptr || row_elements <= 0 || local_experts <= 0 ||
244+ ranks <= 0 || slots <= 0 || rank < 0 || rank >= ranks || blocks <= 0 ||
245+ ranks != aclshmem_n_pes()) {
246+ return ACL_ERROR_INVALID_PARAM;
247+ }
248+ (void)aclrtGetLastError(ACL_RT_THREAD_LEVEL);
249+ MoonEPLPlusBOwnerPush<<<blocks, nullptr, stream>>>(
250+ reinterpret_cast<uint8_t*>(const_cast<uint64_t*>(source_ptrs)),
251+ reinterpret_cast<uint8_t*>(weight_slots),
252+ reinterpret_cast<uint8_t*>(const_cast<int32_t*>(experts_to_copy)),
253+ row_elements, local_experts, ranks, slots, rank);
254+ return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
255+}
256+ 
257+extern "C" ASCEND_MOONEP_EXPORT int moonep_lplusb_owner_ready(
258+ void* stream, int32_t* ready, const int32_t* experts_to_copy,
259+ int32_t local_experts, int32_t ranks, int32_t slots, int32_t rank, int32_t epoch)
260+{
261+ if (stream == nullptr || ready == nullptr || experts_to_copy == nullptr ||
262+ local_experts <= 0 || ranks <= 0 || slots <= 0 || rank < 0 || rank >= ranks ||
263+ epoch <= 0 || ranks != aclshmem_n_pes()) {
264+ return ACL_ERROR_INVALID_PARAM;
265+ }
266+ (void)aclrtGetLastError(ACL_RT_THREAD_LEVEL);
267+ MoonEPLPlusBOwnerReady<<<1, nullptr, stream>>>(
268+ reinterpret_cast<uint8_t*>(ready),
269+ reinterpret_cast<uint8_t*>(const_cast<int32_t*>(experts_to_copy)),
270+ local_experts, ranks, slots, rank, epoch);
271+ return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
272+}
273+ 
274+extern "C" ASCEND_MOONEP_EXPORT int moonep_lplusb_owner_reduce(
275+ void* stream, const uint64_t* target_ptrs, void* grad_slots,
276+ const int32_t* experts_to_copy, int64_t row_elements, int32_t local_experts,
277+ int32_t ranks, int32_t slots, int32_t rank, int32_t blocks)
278+{
279+ if (stream == nullptr || target_ptrs == nullptr || grad_slots == nullptr ||
280+ experts_to_copy == nullptr || row_elements <= 0 || local_experts <= 0 ||
281+ ranks <= 0 || slots <= 0 || rank < 0 || rank >= ranks || blocks <= 0 ||
282+ ranks != aclshmem_n_pes()) {
283+ return ACL_ERROR_INVALID_PARAM;
284+ }
285+ (void)aclrtGetLastError(ACL_RT_THREAD_LEVEL);
286+ MoonEPLPlusBOwnerReduce<<<blocks, nullptr, stream>>>(
287+ reinterpret_cast<uint8_t*>(const_cast<uint64_t*>(target_ptrs)),
288+ reinterpret_cast<uint8_t*>(grad_slots),
289+ reinterpret_cast<uint8_t*>(const_cast<int32_t*>(experts_to_copy)),
290+ row_elements, local_experts, ranks, slots, rank);
291+ return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
292+}
@@ -36,7 +36,7 @@
36using namespace AscendC;36using namespace AscendC;
37using half_t = __fp16;37using half_t = __fp16;
38using bf16_t = bfloat16_t;38using bf16_t = bfloat16_t;
39-using ascend_moonep::kMoonEPAivNum;39+constexpr uint32_t kRestoredCombineAivs = 8;
40using ascend_moonep::MoonEPCombineTilingData;40using ascend_moonep::MoonEPCombineTilingData;
41 41 
42namespace {42namespace {
@@ -1044,7 +1044,7 @@ extern "C" ASCEND_MOONEP_EXPORT void moonep_combine_kernel_do(
1044 uint8_t* tiling_host)1044 uint8_t* tiling_host)
1045{1045{
1046 auto* td = reinterpret_cast<MoonEPCombineTilingData*>(tiling_host);1046 auto* td = reinterpret_cast<MoonEPCombineTilingData*>(tiling_host);
1047- moonep_combine_kernel<<<kMoonEPAivNum, nullptr, stream>>>(1047+ moonep_combine_kernel<<<kRestoredCombineAivs, nullptr, stream>>>(
1048 hidden_buf,1048 hidden_buf,
1049 weight_buf,1049 weight_buf,
1050 dst,1050 dst,
@@ -2,7 +2,7 @@
2// UBMEM implementation — uses SHMEM symmetric window and DataCopyPad + UB/MTE.2// UBMEM implementation — uses SHMEM symmetric window and DataCopyPad + UB/MTE.
3// No URMA/UDMA, no zero-fill.3// No URMA/UDMA, no zero-fill.
4//4//
5-// Architecture: A2/A5, fixed kMoonEPAivNum AIV cores.5+// Architecture: A2/A5, fixed kRestoredDispatchAivs AIV cores.
6//6//
7// Single-kernel design:7// Single-kernel design:
8// Phase 1 (Scatter): cores split routed slots N=S*K.8// Phase 1 (Scatter): cores split routed slots N=S*K.
@@ -19,7 +19,7 @@
19using namespace AscendC;19using namespace AscendC;
20 20 
21using bf16_t = bfloat16_t;21using bf16_t = bfloat16_t;
22-using ascend_moonep::kMoonEPAivNum;22+constexpr uint32_t kRestoredDispatchAivs = 8;
23 23 
24// UB buffer sizing: one bf16 hidden row, weight ping-pong, and route metadata.24// UB buffer sizing: one bf16 hidden row, weight ping-pong, and route metadata.
25// Safety margin: allocate up to 128KB for hidden row (H <= 65536).25// Safety margin: allocate up to 128KB for hidden row (H <= 65536).
@@ -635,7 +635,7 @@ extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ void moonep_dispa
635 hidden_buf_gm, route_weights_buf_gm,635 hidden_buf_gm, route_weights_buf_gm,
636 S, H, K, tiling.R, NvS,636 S, H, K, tiling.R, NvS,
637 with_weights != 0,637 with_weights != 0,
638- core_idx, kMoonEPAivNum);638+ core_idx, kRestoredDispatchAivs);
639 639 
640 aclshmem_quiet();640 aclshmem_quiet();
641 aclshmemx_barrier_all_vec();641 aclshmemx_barrier_all_vec();
@@ -644,7 +644,7 @@ extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ void moonep_dispa
644 644 
645 PlanEpiloguePhase<bf16_t>(645 PlanEpiloguePhase<bf16_t>(
646 ub_base, hbuf, dgrp, dloff, dcnt,646 ub_base, hbuf, dgrp, dloff, dcnt,
647- H, NvS, core_idx, kMoonEPAivNum);647+ H, NvS, core_idx, kRestoredDispatchAivs);
648}648}
649 649 
650 650 
@@ -667,7 +667,7 @@ void moonep_dispatch_kernel_do(
667{667{
668 auto* td = reinterpret_cast<ascend_moonep::MoonEPDispatchTilingData*>(tiling_host);668 auto* td = reinterpret_cast<ascend_moonep::MoonEPDispatchTilingData*>(tiling_host);
669 669 
670- moonep_dispatch_kernel<<<kMoonEPAivNum, nullptr, stream>>>(670+ moonep_dispatch_kernel<<<kRestoredDispatchAivs, nullptr, stream>>>(
671 hidden_sh,671 hidden_sh,
672 route_weights,672 route_weights,
673 dst,673 dst,
@@ -299,7 +299,8 @@ void MoonEPShmemGradReduceFused(
299 int32_t projection,299 int32_t projection,
300 int32_t ranks,300 int32_t ranks,
301 int32_t slots,301 int32_t slots,
302- int32_t rank)302+ int32_t rank,
303+ bool pointer_targets)
303{304{
304 util_set_ffts_config(ffts_addr);305 util_set_ffts_config(ffts_addr);
305 if ASCEND_IS_AIC {306 if ASCEND_IS_AIC {
@@ -307,6 +308,7 @@ void MoonEPShmemGradReduceFused(
307 }308 }
308 309 
309 auto* grads = reinterpret_cast<__gm__ float*>(expert_grads_addr);310 auto* grads = reinterpret_cast<__gm__ float*>(expert_grads_addr);
311+ auto* target_ptrs = reinterpret_cast<__gm__ uint64_t*>(expert_grads_addr);
310 auto* reduce = reinterpret_cast<__gm__ float*>(reduce_buffers_addr);312 auto* reduce = reinterpret_cast<__gm__ float*>(reduce_buffers_addr);
311 auto* plan = reinterpret_cast<__gm__ int32_t*>(experts_to_copy_addr);313 auto* plan = reinterpret_cast<__gm__ int32_t*>(experts_to_copy_addr);
312 const int32_t local_begin = rank * epn;314 const int32_t local_begin = rank * epn;
@@ -324,19 +326,26 @@ void MoonEPShmemGradReduceFused(
324 326 
325 for (int32_t local_expert = 0; local_expert < epn; ++local_expert) {327 for (int32_t local_expert = 0; local_expert < epn; ++local_expert) {
326 const int32_t global_expert = local_begin + local_expert;328 const int32_t global_expert = local_begin + local_expert;
329+ // Adapt pointer targets to the existing dense accumulation contract:
330+ // one expert allocation is a one-row dense view, addressed at row 0.
331+ // Keep global_expert unchanged for matching contributions in the plan.
332+ auto* accum_grads = pointer_targets ?
333+ reinterpret_cast<__gm__ float*>(target_ptrs[local_expert]) :
334+ grads;
335+ const int32_t accum_local_expert = pointer_targets ? 0 : local_expert;
327 for (int64_t tile = block; tile < tiles_per_expert; tile += block_count) {336 for (int64_t tile = block; tile < tiles_per_expert; tile += block_count) {
328 const int64_t tile_begin = tile * kTileElements;337 const int64_t tile_begin = tile * kTileElements;
329 const int32_t elements = static_cast<int32_t>(338 const int32_t elements = static_cast<int32_t>(
330 matrix - tile_begin < kTileElements ?339 matrix - tile_begin < kTileElements ?
331 matrix - tile_begin : kTileElements);340 matrix - tile_begin : kTileElements);
332 AccumulatePlanTile(341 AccumulatePlanTile(
333- grads,342+ accum_grads,
334 reduce,343 reduce,
335 plan,344 plan,
336 accum_ub,345 accum_ub,
337 reduce_ping_ub,346 reduce_ping_ub,
338 reduce_pong_ub,347 reduce_pong_ub,
339- local_expert,348+ accum_local_expert,
340 global_expert,349 global_expert,
341 matrix,350 matrix,
342 tile_begin,351 tile_begin,
@@ -347,27 +356,28 @@ void MoonEPShmemGradReduceFused(
347 }356 }
348 }357 }
349 358 
350- // Every AIV on every rank must reach this collective. Do not add an AIV
351- // early return above it, including for empty plans or blocks with no work.
352 aclshmem_quiet();359 aclshmem_quiet();
353- // This kernel is [[core_ratio(0, 1)]] and launches AIV workers only.
354- // The installed CANN-SHMEM generic barrier also includes non-vector
355- // participants and deadlocks for this launch shape; use its vector-only
356- // device collective so the participant set matches the kernel grid.
357- aclshmemx_barrier_all_vec();
358- 
359- ClearLocalSlots(
360- reduce,
361- plan,
362- accum_ub,
363- matrix,
364- slots,
365- rank,
366- block,
367- block_count);
368}360}
369 361 
370-extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce(362+// The host stream barrier separates all peer reads from local slot reuse.
363+// Keep the ordinary collective outside these vector-only compute kernels.
364+extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__
365+void MoonEPShmemGradReduceClearValidSlots(
366+ uint64_t ffts_addr, GM_ADDR reduce_buffers_addr,
367+ GM_ADDR experts_to_copy_addr, int64_t matrix, int32_t slots, int32_t rank)
368+{
369+ util_set_ffts_config(ffts_addr);
370+ if ASCEND_IS_AIC {
371+ return;
372+ }
373+ auto* reduce = reinterpret_cast<__gm__ float*>(reduce_buffers_addr);
374+ auto* plan = reinterpret_cast<__gm__ int32_t*>(experts_to_copy_addr);
375+ auto* zero_ub = reinterpret_cast<__ubuf__ float*>(kUbScratchOffset);
376+ ClearLocalSlots(reduce, plan, zero_ub, matrix, slots, rank,
377+ GetWorkerIndex(), GetBlockNum());
378+}
379+ 
380+static int LaunchGradReduce(
371 void* stream,381 void* stream,
372 void* expert_grads,382 void* expert_grads,
373 void* reduce_buffers,383 void* reduce_buffers,
@@ -378,7 +388,8 @@ extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce(
378 int32_t ranks,388 int32_t ranks,
379 int32_t slots,389 int32_t slots,
380 int32_t rank,390 int32_t rank,
381- int32_t blocks)391+ int32_t blocks,
392+ bool pointer_targets)
382{393{
383 if (stream == nullptr || expert_grads == nullptr ||394 if (stream == nullptr || expert_grads == nullptr ||
384 reduce_buffers == nullptr || experts_to_copy == nullptr ||395 reduce_buffers == nullptr || experts_to_copy == nullptr ||
@@ -404,6 +415,41 @@ extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce(
404 projection,415 projection,
405 ranks,416 ranks,
406 slots,417 slots,
407- rank);418+ rank,
419+ pointer_targets);
420+ auto status = aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
421+ if (status != ACL_SUCCESS) {
422+ return status;
423+ }
424+ aclshmemx_barrier_all_on_stream(stream);
425+ status = aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
426+ if (status != ACL_SUCCESS) {
427+ return status;
428+ }
429+ MoonEPShmemGradReduceClearValidSlots<<<blocks, nullptr, stream>>>(
430+ shmemx_get_ffts_config(),
431+ reinterpret_cast<std::uint8_t*>(reduce_buffers),
432+ reinterpret_cast<std::uint8_t*>(const_cast<int32_t*>(experts_to_copy)),
433+ static_cast<int64_t>(hidden) * projection, slots, rank);
408 return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);434 return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
409}435}
436+ 
437+extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce(
438+ void* stream, void* expert_grads, void* reduce_buffers,
439+ const int32_t* experts_to_copy, int32_t epn, int32_t hidden,
440+ int32_t projection, int32_t ranks, int32_t slots, int32_t rank,
441+ int32_t blocks)
442+{
443+ return LaunchGradReduce(stream, expert_grads, reduce_buffers, experts_to_copy,
444+ epn, hidden, projection, ranks, slots, rank, blocks, false);
445+}
446+ 
447+extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_targets(
448+ void* stream, void* target_ptrs, void* reduce_buffers,
449+ const int32_t* experts_to_copy, int32_t epn, int32_t hidden,
450+ int32_t projection, int32_t ranks, int32_t slots, int32_t rank,
451+ int32_t blocks)
452+{
453+ return LaunchGradReduce(stream, target_ptrs, reduce_buffers, experts_to_copy,
454+ epn, hidden, projection, ranks, slots, rank, blocks, true);
455+}
@@ -1,6 +1,8 @@
1// SPDX-License-Identifier: Apache-2.01// SPDX-License-Identifier: Apache-2.0
2 2 
3#include <cstdint>3#include <cstdint>
4+#include <cstdlib>
5+#include <cstring>
4 6 
5#include "acl/acl.h"7#include "acl/acl.h"
6#include "kernel_operator.h"8#include "kernel_operator.h"
@@ -53,6 +55,21 @@ __aicore__ inline void ComputeSingle(
53 55 
54using namespace moonEP::gradReduce;56using namespace moonEP::gradReduce;
55 57 
58+extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__
59+void MoonEPShmemClearValidGradSlots(
60+ GM_ADDR reduce_addr, GM_ADDR plan_addr, int64_t matrix, int32_t slots, int32_t rank)
61+{
62+ AscendC::TPipe pipe; // experimental explicit InitOutput resource lifetime
63+ auto* plan = reinterpret_cast<__gm__ int32_t*>(plan_addr);
64+ GlobalTensor<float> reduce;
65+ reduce.SetGlobalBuffer(reinterpret_cast<__gm__ float*>(reduce_addr));
66+ for (int32_t slot = 0; slot < slots; ++slot) {
67+ if (plan[static_cast<int64_t>(rank) * slots + slot] >= 0) {
68+ InitOutput(reduce[static_cast<int64_t>(slot) * matrix], matrix, 0.0f);
69+ }
70+ }
71+}
72+ 
56extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__73extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__
57void MoonEPShmemGradReduceUdmaFused(74void MoonEPShmemGradReduceUdmaFused(
58 uint64_t ffts_addr,75 uint64_t ffts_addr,
@@ -65,7 +82,8 @@ void MoonEPShmemGradReduceUdmaFused(
65 int32_t projection,82 int32_t projection,
66 int32_t ranks,83 int32_t ranks,
67 int32_t slots,84 int32_t slots,
68- int32_t rank)85+ int32_t rank,
86+ bool pointer_targets)
69{87{
70 util_set_ffts_config(ffts_addr);88 util_set_ffts_config(ffts_addr);
71 89 
@@ -74,6 +92,7 @@ void MoonEPShmemGradReduceUdmaFused(
74 const int64_t matrix = static_cast<int64_t>(hidden) * projection;92 const int64_t matrix = static_cast<int64_t>(hidden) * projection;
75 93 
76 auto* grads = reinterpret_cast<__gm__ float*>(expert_grads_addr);94 auto* grads = reinterpret_cast<__gm__ float*>(expert_grads_addr);
95+ auto* target_ptrs = reinterpret_cast<__gm__ uint64_t*>(expert_grads_addr);
77 auto* reduce = reinterpret_cast<__gm__ float*>(reduce_buffers_addr);96 auto* reduce = reinterpret_cast<__gm__ float*>(reduce_buffers_addr);
78 auto* plan = reinterpret_cast<__gm__ int32_t*>(experts_to_copy_addr);97 auto* plan = reinterpret_cast<__gm__ int32_t*>(experts_to_copy_addr);
79 auto* workspace = reinterpret_cast<__gm__ float*>(workspace_addr) + coreIdx * OUTER_LOOP_SIZE;98 auto* workspace = reinterpret_cast<__gm__ float*>(workspace_addr) + coreIdx * OUTER_LOOP_SIZE;
@@ -101,6 +120,12 @@ void MoonEPShmemGradReduceUdmaFused(
101 if (dstRankIdx != rank) {120 if (dstRankIdx != rank) {
102 continue;121 continue;
103 }122 }
123+ // Adapt each canonical allocation as a one-expert dense view,
124+ // just like the MTE kernel; leave the reduction itself unchanged.
125+ auto* accum_grads = pointer_targets ?
126+ reinterpret_cast<__gm__ float*>(target_ptrs[dstExpertIdx]) :
127+ grads;
128+ const int32_t accum_local_expert = pointer_targets ? 0 : dstExpertIdx;
104 129 
105 for (int64_t slotOffset = 0; slotOffset < matrix; slotOffset += OUTER_LOOP_SIZE)130 for (int64_t slotOffset = 0; slotOffset < matrix; slotOffset += OUTER_LOOP_SIZE)
106 {131 {
@@ -108,29 +133,41 @@ void MoonEPShmemGradReduceUdmaFused(
108 if (srcRankIdx != dstRankIdx) {133 if (srcRankIdx != dstRankIdx) {
109 aclshmemx_udma_get_nbi((__gm__ uint8_t*)(workspace), (__gm__ uint8_t*)(reduce + srcSlotIdx * matrix + slotOffset), wqe_scratch, loopSize * sizeof(float), srcRankIdx, 0);134 aclshmemx_udma_get_nbi((__gm__ uint8_t*)(workspace), (__gm__ uint8_t*)(reduce + srcSlotIdx * matrix + slotOffset), wqe_scratch, loopSize * sizeof(float), srcRankIdx, 0);
110 aclshmemx_udma_quiet(srcRankIdx);135 aclshmemx_udma_quiet(srcRankIdx);
111- ComputeSingle(grads + dstExpertIdx * matrix + slotOffset, workspace, ubLocal, loopSize);136+ ComputeSingle(accum_grads + accum_local_expert * matrix + slotOffset, workspace, ubLocal, loopSize);
112 } else {137 } else {
113- ComputeSingle(grads + dstExpertIdx * matrix + slotOffset, reduce + srcSlotIdx * matrix + slotOffset, ubLocal, loopSize);138+ ComputeSingle(accum_grads + accum_local_expert * matrix + slotOffset, reduce + srcSlotIdx * matrix + slotOffset, ubLocal, loopSize);
114 }139 }
115 }140 }
116 }141 }
117 }142 }
118 143 
144+ // Cross-rank completion and slot clearing are submitted by the host.
119 aclshmem_quiet();145 aclshmem_quiet();
120- aclshmemx_barrier_all_vec();
121- 
122- if (coreIdx == 0) {
123- GlobalTensor<float> reduceGm_;
124- reduceGm_.SetGlobalBuffer(reduce);
125- for (int32_t localIdx = 0; localIdx < slots; localIdx++) {
126- if (plan[rank * slots + localIdx] >= 0) {
127- InitOutput(reduceGm_[localIdx * matrix], matrix, 0.0f);
128- }
129- }
130- }
131}146}
132 147 
133-extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_udma(148+// Canonical UDMA GradReduce uses one AIV for its WORLD barrier in AIV mode.
149+extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__
150+void MoonEPGradReduceBarrierAiv(uint64_t ffts_config)
151+{
152+ util_set_ffts_config(ffts_config);
153+ aclshmemx_barrier_all_vec();
154+}
155+ 
156+extern "C" ASCEND_MOONEP_EXPORT int moonep_grad_reduce_native_barrier(void* stream)
157+{
158+ if (stream == nullptr) return ACL_ERROR_INVALID_PARAM;
159+ const char* mode = std::getenv("MOONEP_GRAD_REDUCE_NATIVE_BARRIER_MODE");
160+ if (mode == nullptr || std::strcmp(mode, "mixed") == 0) {
161+ aclshmemx_barrier_all_on_stream(stream);
162+ } else if (std::strcmp(mode, "aiv") == 0) {
163+ MoonEPGradReduceBarrierAiv<<<1, nullptr, stream>>>(shmemx_get_ffts_config());
164+ } else {
165+ return ACL_ERROR_INVALID_PARAM;
166+ }
167+ return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
168+}
169+ 
170+static int LaunchGradReduceUdma(
134 void* stream,171 void* stream,
135 void* expert_grads,172 void* expert_grads,
136 void* reduce_buffers,173 void* reduce_buffers,
@@ -142,7 +179,8 @@ extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_udma(
142 int32_t ranks,179 int32_t ranks,
143 int32_t slots,180 int32_t slots,
144 int32_t rank,181 int32_t rank,
145- int32_t blocks)182+ int32_t blocks,
183+ bool pointer_targets)
146{184{
147 if (stream == nullptr || expert_grads == nullptr ||185 if (stream == nullptr || expert_grads == nullptr ||
148 reduce_buffers == nullptr || experts_to_copy == nullptr ||186 reduce_buffers == nullptr || experts_to_copy == nullptr ||
@@ -152,7 +190,15 @@ extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_udma(
152 return ACL_ERROR_INVALID_PARAM;190 return ACL_ERROR_INVALID_PARAM;
153 }191 }
154 192 
155- (void)aclrtGetLastError(ACL_RT_THREAD_LEVEL);193+ if (pointer_targets) {
194+ // Preserve an existing error instead of erasing the first failure.
195+ const auto status = aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
196+ if (status != ACL_SUCCESS) {
197+ return status;
198+ }
199+ } else {
200+ (void)aclrtGetLastError(ACL_RT_THREAD_LEVEL);
201+ }
156 const int32_t shmem_ranks = aclshmem_n_pes();202 const int32_t shmem_ranks = aclshmem_n_pes();
157 if (shmem_ranks <= 0 || ranks != shmem_ranks) {203 if (shmem_ranks <= 0 || ranks != shmem_ranks) {
158 return ACL_ERROR_INVALID_PARAM;204 return ACL_ERROR_INVALID_PARAM;
@@ -160,15 +206,49 @@ extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_udma(
160 206 
161 MoonEPShmemGradReduceUdmaFused<<<blocks, nullptr, stream>>>(207 MoonEPShmemGradReduceUdmaFused<<<blocks, nullptr, stream>>>(
162 shmemx_get_ffts_config(),208 shmemx_get_ffts_config(),
163- reinterpret_cast<std::uint8_t*>(expert_grads),209+ reinterpret_cast<uint8_t*>(expert_grads),
164- reinterpret_cast<std::uint8_t*>(reduce_buffers),210+ reinterpret_cast<uint8_t*>(reduce_buffers),
165- reinterpret_cast<std::uint8_t*>(workspace),211+ reinterpret_cast<uint8_t*>(workspace),
166- reinterpret_cast<std::uint8_t*>(const_cast<int32_t*>(experts_to_copy)),212+ reinterpret_cast<uint8_t*>(const_cast<int32_t*>(experts_to_copy)),
167- epn,213+ epn, hidden, projection, ranks, slots, rank, pointer_targets);
168- hidden,214+ 
169- projection,215+ auto status = aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
170- ranks,216+ if (status != ACL_SUCCESS) {
171- slots,217+ return status;
172- rank);218+ }
219+ // Every peer must finish reading before any rank clears its source slots.
220+ if (pointer_targets) {
221+ status = moonep_grad_reduce_native_barrier(stream);
222+ } else {
223+ aclshmemx_barrier_all_on_stream(stream);
224+ status = aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
225+ }
226+ if (status != ACL_SUCCESS) {
227+ return status;
228+ }
229+ MoonEPShmemClearValidGradSlots<<<1, nullptr, stream>>>(
230+ reinterpret_cast<uint8_t*>(reduce_buffers),
231+ reinterpret_cast<uint8_t*>(const_cast<int32_t*>(experts_to_copy)),
232+ static_cast<int64_t>(hidden) * projection, slots, rank);
173 return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);233 return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
174}234}
235+ 
236+extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_udma(
237+ void* stream, void* expert_grads, void* reduce_buffers, void* workspace,
238+ const int32_t* experts_to_copy, int32_t epn, int32_t hidden,
239+ int32_t projection, int32_t ranks, int32_t slots, int32_t rank,
240+ int32_t blocks)
241+{
242+ return LaunchGradReduceUdma(stream, expert_grads, reduce_buffers, workspace,
243+ experts_to_copy, epn, hidden, projection, ranks, slots, rank, blocks, false);
244+}
245+ 
246+extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_targets_udma(
247+ void* stream, void* target_ptrs, void* reduce_buffers, void* workspace,
248+ const int32_t* experts_to_copy, int32_t epn, int32_t hidden,
249+ int32_t projection, int32_t ranks, int32_t slots, int32_t rank,
250+ int32_t blocks)
251+{
252+ return LaunchGradReduceUdma(stream, target_ptrs, reduce_buffers, workspace,
253+ experts_to_copy, epn, hidden, projection, ranks, slots, rank, blocks, true);
254+}
@@ -0,0 +1,50 @@
1+// SPDX-License-Identifier: Apache-2.0
2+#include "ascend_moonep/kernels/launch.h"
3+#include "acl/acl.h"
4+#if defined(CATLASS_ARCH) && CATLASS_ARCH == 3510
5+#include "ascend_moonep/kernels/urma_push_core.h"
6+extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__
7+void prefetch_barrier_vec(uint64_t ffts_config) {
8+ util_set_ffts_config(ffts_config);
9+ aclshmemx_barrier_all_vec();
10+}
11+extern "C" ASCEND_MOONEP_EXPORT int moonep_prefetch_barrier_vec(void* stream) {
12+ if (stream == nullptr) return ACL_ERROR_INVALID_PARAM;
13+ prefetch_barrier_vec<<<1,nullptr,stream>>>(shmemx_get_ffts_config());
14+ return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
15+}
16+// Separate name makes the async-lane domain distinguishable from prefetch
17+// completion and ordered GradReduce in the device trace. Same SDK team/state.
18+extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__
19+void async_stream_barrier_vec(uint64_t ffts_config) {
20+ util_set_ffts_config(ffts_config);
21+ aclshmemx_barrier_all_vec();
22+}
23+extern "C" ASCEND_MOONEP_EXPORT int moonep_async_stream_barrier_vec(void* stream) {
24+ if (stream == nullptr) return ACL_ERROR_INVALID_PARAM;
25+ async_stream_barrier_vec<<<1,nullptr,stream>>>(shmemx_get_ffts_config());
26+ return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
27+}
28+extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__
29+void prefetch_pointer_push_udma(GM_ADDR pointers, GM_ADDR slots, GM_ADDR plan,
30+ int64_t experts, int64_t row_elements, int64_t num_slots) {
31+ moonep_urma_push::Run<true>(pointers,slots,plan,experts,row_elements,num_slots);
32+}
33+extern "C" ASCEND_MOONEP_EXPORT int prefetch_pointer_push_udma_available() { return 1; }
34+extern "C" ASCEND_MOONEP_EXPORT int moonep_prefetch_pointer_push_udma(
35+ void* stream, uint8_t* pointers, uint8_t* slots, uint8_t* plan,
36+ int64_t experts, int64_t row_elements, int64_t num_slots) {
37+ const auto status = aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
38+ if (status != ACL_SUCCESS) {
39+ return status;
40+ }
41+ prefetch_pointer_push_udma<<<1,nullptr,stream>>>(pointers,slots,plan,experts,row_elements,num_slots);
42+ return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
43+}
44+#else
45+extern "C" ASCEND_MOONEP_EXPORT int moonep_prefetch_barrier_vec(void*) { return -1; }
46+extern "C" ASCEND_MOONEP_EXPORT int moonep_async_stream_barrier_vec(void*) { return -1; }
47+extern "C" ASCEND_MOONEP_EXPORT int prefetch_pointer_push_udma_available() { return 0; }
48+extern "C" ASCEND_MOONEP_EXPORT int moonep_prefetch_pointer_push_udma(
49+ void*,uint8_t*,uint8_t*,uint8_t*,int64_t,int64_t,int64_t) { return -1; }
50+#endif
@@ -0,0 +1,27 @@
1+// SPDX-License-Identifier: Apache-2.0
2+#include "ascend_moonep/kernels/launch.h"
3+#include "acl/acl.h"
4+#if defined(CATLASS_ARCH) && CATLASS_ARCH == 3510
5+#include "ascend_moonep/kernels/urma_push_core.h"
6+extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__
7+void prefetch_weight_push_udma(GM_ADDR source, GM_ADDR slots, GM_ADDR plan,
8+ int64_t experts, int64_t row_elements, int64_t num_slots) {
9+ moonep_urma_push::Run<false>(source, slots, plan, experts, row_elements, num_slots);
10+}
11+extern "C" ASCEND_MOONEP_EXPORT int prefetch_weight_push_udma_available() { return 1; }
12+extern "C" ASCEND_MOONEP_EXPORT int prefetch_weight_push_udma_do(
13+ void* stream, uint8_t* source, uint8_t* slots, uint8_t* plan,
14+ int64_t experts, int64_t row_elements, int64_t num_slots) {
15+ const auto status = aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
16+ if (status != ACL_SUCCESS) {
17+ return status;
18+ }
19+ prefetch_weight_push_udma<<<1, nullptr, stream>>>(
20+ source, slots, plan, experts, row_elements, num_slots);
21+ return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
22+}
23+#else
24+extern "C" ASCEND_MOONEP_EXPORT int prefetch_weight_push_udma_available() { return 0; }
25+extern "C" ASCEND_MOONEP_EXPORT int prefetch_weight_push_udma_do(
26+ void*, uint8_t*, uint8_t*, uint8_t*, int64_t, int64_t, int64_t) { return -1; }
27+#endif
@@ -8,7 +8,7 @@
8 8 
9using namespace AscendC;9using namespace AscendC;
10 10 
11-#if defined(__NPU_ARCH__) && (__NPU_ARCH__ == 3510)11+#if defined(CATLASS_ARCH) && (CATLASS_ARCH == 3510)
12 12 
13namespace {13namespace {
14 14 
@@ -123,6 +123,9 @@ extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ void prefetch_wei
123 __ubuf__ bfloat16_t* ub =123 __ubuf__ bfloat16_t* ub =
124 reinterpret_cast<__ubuf__ bfloat16_t*>(ub_local.GetPhyAddr());124 reinterpret_cast<__ubuf__ bfloat16_t*>(ub_local.GetPhyAddr());
125 Duplicate(wqe_local, static_cast<bfloat16_t>(0), kUdmaWqeElements);125 Duplicate(wqe_local, static_cast<bfloat16_t>(0), kUdmaWqeElements);
126+ // Complete the vector clear before SDK scalar stores reuse its raw UB.
127+ SetFlag<HardEvent::V_S>(EVENT_ID2);
128+ WaitFlag<HardEvent::V_S>(EVENT_ID2);
126 129 
127 int64_t active_experts = 0;130 int64_t active_experts = 0;
128 for (int64_t slot = 0; slot < B; ++slot) {131 for (int64_t slot = 0; slot < B; ++slot) {
@@ -0,0 +1,95 @@
1+"""Storage parameters for the native Buffer API, without a scheduling protocol.
2+ 
3+Allocate/register symmetric sources before SHMEM init; prepare these bindings
4+after init and before hot work. The caller still owns final-use/reuse ordering.
5+"""
6+ 
7+from dataclasses import dataclass
8+ 
9+import torch
10+ 
11+from .buffer_c import sym_tensor
12+from .shmem_runtime import ShmemRuntime
13+ 
14+ 
15+def tensor_signature(tensor):
16+ """Metadata only: detect rebinding without reading device data/versions."""
17+ storage = tensor.untyped_storage()
18+ return (tensor.data_ptr(), tuple(tensor.shape), tuple(tensor.stride()),
19+ tensor.storage_offset(), tensor.dtype, tensor.device,
20+ storage._cdata, storage.nbytes())
21+ 
22+ 
23+def symmetric_source(source):
24+ if not ShmemRuntime.is_initialized():
25+ raise RuntimeError("initialize buffer-backed SHMEM before preparing bindings")
26+ if getattr(source, '_vmm_allocation', None) is None:
27+ raise ValueError("expected a registered VMM source tensor")
28+ return sym_tensor(source)
29+ 
30+ 
31+def overlaps(left, right):
32+ if left.device != right.device:
33+ return False
34+ a, b = left.data_ptr(), right.data_ptr()
35+ return (a < b + right.numel() * right.element_size() and
36+ b < a + left.numel() * left.element_size())
37+ 
38+ 
39+@dataclass(frozen=True, eq=False, repr=False)
40+class CommBuffers:
41+ """Prepared hidden/route views. Obtain with Buffer.prepare_comm_buffers.
42+ 
43+ No allocation, lease, generation or completion state is owned by this value.
44+ Backing references keep the original source metadata/physical owners alive;
45+ callers must keep the tensors' storage and layout fixed while bound.
46+ """
47+ 
48+ hidden: torch.Tensor
49+ route: torch.Tensor
50+ sources: tuple
51+ owner: object
52+ 
53+ 
54+@dataclass(frozen=True, eq=False, repr=False)
55+class LPlusBBinding:
56+ """L ordinary canonical matrices plus one symmetric B-slot projection.
57+ 
58+ Pointer metadata is prepared once. Retain this value and the Buffer until
59+ completion, and order all slot consumers before reusing the destination.
60+ """
61+ 
62+ refs: tuple
63+ sources: tuple
64+ slot: torch.Tensor
65+ slot_source: torch.Tensor
66+ table: torch.Tensor
67+ ref_signatures: tuple
68+ owner: object
69+ 
70+ def validate_refs(self, refs):
71+ """Reject a caller that switched canonical matrices after setup."""
72+ validate_unchanged(tuple(refs), self.ref_signatures)
73+ 
74+ 
75+def validate_unchanged(refs, signatures):
76+ if tuple(tensor_signature(ref) for ref in refs) != signatures:
77+ raise ValueError("prepared storage was rebound or its layout changed")
78+ 
79+ 
80+def comm_context(ctx, buffers, owner, carrier):
81+ """Select the symmetric data banks for one call, sharing control and workspace.
82+ 
83+ Each EP rank must select the corresponding banks for the collective.
84+ The caller orders submissions that share the workspace.
85+ """
86+ if not ShmemRuntime.is_initialized() or getattr(ShmemRuntime, '_poisoned', False):
87+ raise RuntimeError('explicit communication storage requires initialized healthy SHMEM')
88+ if not isinstance(buffers, CommBuffers) or buffers.owner is not owner:
89+ raise ValueError("comm_buffers must be prepared by this Buffer")
90+ n, h = int(ctx['NvS']), int(ctx['H'])
91+ local = dict(ctx)
92+ local['_native_comm_buffers'] = True
93+ local['hidden_buf'] = local['hidden_buf_local'] = carrier(buffers.hidden, (n, h), torch.bfloat16)
94+ local['weights_buf'] = local['weights_buf_local'] = carrier(buffers.route, (n,), torch.int32)
95+ return local
@@ -18,6 +18,7 @@ from .launchers import (
18 launch_dispatch_op,18 launch_dispatch_op,
19 launch_dispatch_profile_op,19 launch_dispatch_profile_op,
20 launch_grad_reduce,20 launch_grad_reduce,
21+ launch_grad_reduce_targets,
21 launch_planning_op,22 launch_planning_op,
22 launch_prefetch,23 launch_prefetch,
23)24)
@@ -317,6 +318,17 @@ class GradReduceOp(KernelOp):
317 - shmem_instance_id: shmem runtime instance to operate on (default 0; the318 - shmem_instance_id: shmem runtime instance to operate on (default 0; the
318 shmem Python API currently supports a single instance).319 shmem Python API currently supports a single instance).
319 Cross-rank: home rank gets each peer's reduce-buffer rows (host get / RMA).320 Cross-rank: home rank gets each peer's reduce-buffer rows (host get / RMA).
321+ 
322+ compute_targets(ctx, target_ptrs, reduce_buffer, experts_to_copy, rank,
323+ num_sms, shmem_instance_id=0):
324+ - explicit alternative for setup-frozen INT64 [epn] canonical pointers;
325+ no method or launcher selects this contract by inspecting dtype.
326+ - targets are ordinary local contiguous FP32 [H,H'] matrices, disjoint,
327+ address-stable and kept alive by the caller until completion.
328+ - only the [B,H,H'] source bank must be symmetric. MTE is ordered.
329+ Canonical UDMA uses the fused atomic-add kernel with unspecified
330+ accumulation order and setup-owned ctx['_grad_reduce_target_workspace'].
331+ Canonical targets use pre/post barriers and clear only valid source slots.
320 """332 """
321 333 
322 def compute(self, ctx, full_grad_home, reduce_buffer, experts_to_copy,334 def compute(self, ctx, full_grad_home, reduce_buffer, experts_to_copy,
@@ -369,3 +381,31 @@ class GradReduceOp(KernelOp):
369 barrier_off=0,381 barrier_off=0,
370 grid_sync_bar=None,382 grid_sync_bar=None,
371 )383 )
384+ 
385+ def compute_targets(self, ctx, target_ptrs, reduce_buffer, experts_to_copy,
386+ rank, num_sms, shmem_instance_id: int = 0):
387+ """Reduce symmetric slots into explicitly supplied canonical pointers."""
388+ R = int(ctx["R"]); E = int(ctx["E"]); B = int(ctx["B"])
389+ if R <= 0 or E % R:
390+ raise RuntimeError(f"invalid expert layout for grad reduce: E={E}, R={R}")
391+ epn = E // R
392+ if reduce_buffer.ndim != 3:
393+ raise ValueError("GradReduceOp.compute_targets: reduce_buffer must be [B,H,H_prime]")
394+ H, H_prime = map(int, reduce_buffer.shape[1:])
395+ _collect_inputs(
396+ "GradReduceOp.compute_targets",
397+ tensors=(
398+ ("canonical target pointers", target_ptrs, [epn], torch.int64),
399+ ("reduce_buffer", reduce_buffer, [B, H, H_prime], torch.float32),
400+ ("experts_to_copy", experts_to_copy, [R, B], torch.int32),
401+ ),
402+ scalars=(("rank", rank), ("num_sms", num_sms),
403+ ("shmem_instance_id", shmem_instance_id)),
404+ )
405+ workspace = ctx.get('_grad_reduce_target_workspace')
406+ launch_args = {} if workspace is None else {'udma_workspace': workspace}
407+ if '_grad_reduce_use_udma' in ctx:
408+ launch_args['use_udma'] = ctx['_grad_reduce_use_udma']
409+ launch_grad_reduce_targets(
410+ target_ptrs, reduce_buffer, experts_to_copy,
411+ rank=int(rank), num_sms=int(num_sms), **launch_args)
@@ -43,7 +43,12 @@ class MoonEPCommPlan:
43 # so rebuilding a different plan does not invalidate independent snapshots.43 # so rebuilding a different plan does not invalidate independent snapshots.
44 _planning_generation: int = field(default=0, repr=False, compare=False)44 _planning_generation: int = field(default=0, repr=False, compare=False)
45 45 
46+ cu_seqlens: torch.Tensor | None = None
47+ 
46 def __post_init__(self) -> None:48 def __post_init__(self) -> None:
49+ if self.cu_seqlens is not None:
50+ assert self.cu_seqlens.dtype == torch.int32 and self.cu_seqlens.is_contiguous()
51+ assert tuple(self.cu_seqlens.shape) == (int(self.E) + int(self.B),)
47 N = int(self.N)52 N = int(self.N)
48 R = int(self.R)53 R = int(self.R)
49 E = int(self.E)54 E = int(self.E)
@@ -90,6 +95,7 @@ class MoonEPCommPlan:
90 stream.wait_event(execution.ready)95 stream.wait_event(execution.ready)
91 snapshot = type(self)(96 snapshot = type(self)(
92 dst=self.dst.clone(),97 dst=self.dst.clone(),
98+ cu_seqlens=self.cu_seqlens.clone() if self.cu_seqlens is not None else None,
93 experts_to_copy=self.experts_to_copy.clone(),99 experts_to_copy=self.experts_to_copy.clone(),
94 zero_fill_ranges=self.zero_fill_ranges.clone(),100 zero_fill_ranges=self.zero_fill_ranges.clone(),
95 remote_stats=self.remote_stats.clone(),101 remote_stats=self.remote_stats.clone(),
@@ -109,10 +115,11 @@ class MoonEPCommPlan:
109 ready = torch_npu.npu.Event()115 ready = torch_npu.npu.Event()
110 ready.record(stream)116 ready.record(stream)
111 for plan in (self, snapshot):117 for plan in (self, snapshot):
112- for tensor in (plan.dst, plan.experts_to_copy, plan.zero_fill_ranges,118+ for tensor in (plan.dst, plan.cu_seqlens, plan.experts_to_copy,
113- plan.remote_stats, plan.dup_groups, plan.dup_loffs,119+ plan.zero_fill_ranges, plan.remote_stats, plan.dup_groups,
114- plan.dup_counts):120+ plan.dup_loffs, plan.dup_counts):
115- tensor.record_stream(stream)121+ if tensor is not None:
122+ tensor.record_stream(stream)
116 execution.storage.record_stream(stream)123 execution.storage.record_stream(stream)
117 storage.record_stream(stream)124 storage.record_stream(stream)
118 copied_execution = CombineExecutionPlan(125 copied_execution = CombineExecutionPlan(
@@ -146,6 +153,10 @@ def _key(ctx):
146 return tuple(int(ctx[name]) for name in ('S', 'H', 'K', 'R', 'rank'))153 return tuple(int(ctx[name]) for name in ('S', 'H', 'K', 'R', 'rank'))
147 154 
148 155 
156+def _combine_workspace_layout(ctx):
157+ return (int(ctx['NvS']), int(ctx['H']), int(ctx['R']))
158+ 
159+ 
149def _execution_key(ctx):160def _execution_key(ctx):
150 # Keep the five native launch arguments stable. The local cached-plan key161 # Keep the five native launch arguments stable. The local cached-plan key
151 # also binds the private ring ABI and workspace geometry.162 # also binds the private ring ABI and workspace geometry.
@@ -172,12 +183,18 @@ class CombineExecutionPlan:
172 fused: bool = False183 fused: bool = False
173 184 
174 def validate(self, ctx, plan):185 def validate(self, ctx, plan):
175- if ctx is not self.owner_ctx or _execution_key(ctx) != self.key:186+ # Buffer launches use fresh logical views over the same capacity owner.
187+ # Activation banks may change between dispatch, forward and backward
188+ # combine; the immutable routing snapshot contains no bank addresses.
189+ owner = self.owner_ctx.get('_capacity_ctx', self.owner_ctx)
190+ if ctx.get('_capacity_ctx', ctx) is not owner or _execution_key(ctx) != self.key:
176 raise ValueError('execution plan belongs to a different Buffer/topology/shape')191 raise ValueError('execution plan belongs to a different Buffer/topology/shape')
177 if ctx['combine_workspace'].data_ptr() != self.workspace.data_ptr():192 if ctx['combine_workspace'].data_ptr() != self.workspace.data_ptr():
178 raise ValueError('combine workspace changed; collectively prepare a new plan')193 raise ValueError('combine workspace changed; collectively prepare a new plan')
179 if id(plan) != self.routing_id or tuple(map(_stamp, _routes(plan))) != self.route_stamps:194 if id(plan) != self.routing_id or tuple(map(_stamp, _routes(plan))) != self.route_stamps:
180 raise ValueError('routing changed; all ranks must prepare a new execution plan')195 raise ValueError('routing changed; all ranks must prepare a new execution plan')
196+ if plan.combine_execution_plan is not self:
197+ raise ValueError('execution plan was replaced; collectively prepare a new plan')
181 if plan._planning_generation != self.generation:198 if plan._planning_generation != self.generation:
182 raise ValueError('planning was rerun; all ranks must prepare a new execution plan')199 raise ValueError('planning was rerun; all ranks must prepare a new execution plan')
183 if _stamp(self.storage) != self.storage_stamp:200 if _stamp(self.storage) != self.storage_stamp:
@@ -243,6 +260,10 @@ def prepare_combine_plan(ctx, plan, *, storage=None, fused_timing=None):
243 plan._planning_generation, end, ctx, begin, end)260 plan._planning_generation, end, ctx, begin, end)
244 execution.fused = fused261 execution.fused = fused
245 object.__setattr__(plan, 'combine_execution_plan', execution)262 object.__setattr__(plan, 'combine_execution_plan', execution)
263+ # Ready flags live in the shared workspace, unlike immutable route tables.
264+ # A different logical size places payload and flags at different offsets.
265+ owner = ctx.get('_capacity_ctx', ctx)
266+ owner['_combine_workspace_layout'] = _combine_workspace_layout(ctx)
246 return execution267 return execution
247 268 
248 269 
@@ -315,6 +336,7 @@ def allocate_planning_outputs(ctx: dict):
315 336 
316 plan = MoonEPCommPlan(337 plan = MoonEPCommPlan(
317 dst=dst,338 dst=dst,
339+ cu_seqlens=cu_seqlens,
318 experts_to_copy=experts_to_copy,340 experts_to_copy=experts_to_copy,
319 zero_fill_ranges=zero_fill_ranges,341 zero_fill_ranges=zero_fill_ranges,
320 remote_stats=remote_stats,342 remote_stats=remote_stats,
@@ -0,0 +1,127 @@
1+"""Independent pointer-source PUSH; Buffer integrations own their own leases."""
2+ 
3+ 
4+class _PendingPushes:
5+ """Retain submitted storage until transfer completion, including failures.
6+ 
7+ This owner is used only by the standalone launcher. Buffer/lane callers
8+ use the stateless native operation and their existing lease instead.
9+ """
10+ def __init__(self):
11+ self.pending = []
12+ self.poisoned = False
13+ 
14+ def collect(self):
15+ if self.poisoned:
16+ raise RuntimeError("standalone PUSH is poisoned; backing remains retained")
17+ try:
18+ remaining = [row for row in self.pending if row[0] is None or not row[0].query()]
19+ except BaseException:
20+ self.poisoned = True
21+ raise
22+ self.pending = remaining
23+ 
24+ def submit(self, resources, launch, make_event):
25+ self.collect()
26+ row = [None, resources]
27+ self.pending.append(row) # before the first potentially partial submission
28+ try:
29+ result = launch()
30+ event = make_event()
31+ event.record()
32+ row[0] = event
33+ return result
34+ except BaseException:
35+ self.poisoned = True
36+ raise
37+ 
38+ def drain(self):
39+ if self.poisoned:
40+ raise RuntimeError("standalone PUSH is poisoned; cannot release or finalize")
41+ try:
42+ for event, _ in self.pending:
43+ if event is None:
44+ raise RuntimeError("PUSH has no proven completion event")
45+ event.synchronize()
46+ except BaseException:
47+ self.poisoned = True
48+ raise
49+ self.pending.clear()
50+ 
51+ 
52+_pending = _PendingPushes()
53+ 
54+ 
55+def validate_pointer_sources(refs, slots, plan, num_sms, *, bf16, int32):
56+ """Validate Tensor metadata only; expert order is the input sequence order."""
57+ refs = tuple(refs)
58+ if type(num_sms) is not int or num_sms <= 0:
59+ raise ValueError("num_sms must be a positive integer")
60+ if (slots.device.type != 'npu' or plan.device != slots.device or
61+ slots.dtype != bf16 or plan.dtype != int32):
62+ raise ValueError("expected BF16 slots and INT32 plan on one NPU")
63+ if (slots.ndim != 3 or plan.ndim != 2 or not slots.is_contiguous() or
64+ not plan.is_contiguous() or plan.shape[1] != slots.shape[0]):
65+ raise ValueError("expected contiguous slots[B,M,N] and plan[EP,B]")
66+ if (not 0 < plan.shape[0] <= 2147483647 or not refs or
67+ len(refs) > 2147483647 // plan.shape[0] or
68+ slots.shape[0] > 15736 or min(slots.shape[1:]) <= 0):
69+ raise ValueError("invalid L/EP/projection or URMA UB extent")
70+ begin = slots.data_ptr()
71+ end = begin + slots.numel() * slots.element_size()
72+ for ref in refs:
73+ if (ref.device != slots.device or ref.dtype != bf16 or ref.ndim != 2 or
74+ tuple(ref.shape) != tuple(slots.shape[1:]) or not ref.is_contiguous()):
75+ raise ValueError("each expert must be a matching contiguous BF16 [M,N] Tensor")
76+ left = ref.data_ptr()
77+ right = left + ref.numel() * ref.element_size()
78+ if left == 0 or (begin < end and left < end and begin < right):
79+ raise ValueError("PUSH source must not alias destination slots")
80+ return refs
81+ 
82+ 
83+def launch_prefetch_push_ptrs(expert_weights, prefetch_buffers, experts_to_copy, num_sms):
84+ """Push L ordinary local BF16 expert Tensors into symmetric [B,M,N] slots.
85+ 
86+ Each rank calls collectively with the same INT32 [EP,B] plan (-1=empty).
87+ E=L*EP; global expert g belongs to g//L with local index g%L. Distinct
88+ allocations and reverse expert addresses are legal; each matrix is dense.
89+ No raw addresses are accepted by this public API and no weights are copied.
90+ 
91+ Submission uses the current NPU stream, including pre/post barriers. The
92+ original destination Tensor is returned; host return is not completion.
93+ Order producer writes and previous slot users before calling; on another
94+ stream wait an event recorded after this call. Do not mutate source/plan,
95+ overwrite slots, unmap backing or finalize before the corresponding uses
96+ complete. Transfer backing is internally retained through its completion;
97+ final consumer use and manual VMM ownership remain the caller's duty.
98+ """
99+ import torch
100+ import torch_npu
101+ from . import _C
102+ from .shmem_runtime import ShmemRuntime
103+ refs = validate_pointer_sources(expert_weights, prefetch_buffers, experts_to_copy,
104+ num_sms, bf16=torch.bfloat16, int32=torch.int32)
105+ if (getattr(_C, 'PREFETCH_PUSH_POINTER_ABI', None) != 1 or
106+ not _C._prefetch_push_available()):
107+ raise RuntimeError("native pointer PUSH is unavailable; no MTE fallback")
108+ if (getattr(ShmemRuntime, '_poisoned', False) or
109+ not ShmemRuntime.is_initialized() or not ShmemRuntime._udma_enabled):
110+ raise RuntimeError("pointer PUSH requires initialized URMA SHMEM")
111+ if '950' not in torch.npu.get_device_name(prefetch_buffers.device):
112+ raise RuntimeError("URMA PUSH requires Ascend950")
113+ # Immutable Tensor metadata retains the real backing if Parameter.data moves.
114+ sources = tuple(ref.detach() for ref in refs)
115+ table = torch.tensor([ref.data_ptr() for ref in sources], dtype=torch.int64,
116+ device=prefetch_buffers.device)
117+ plan = experts_to_copy.detach()
118+ slots = prefetch_buffers.detach()
119+ _pending.submit((sources, table, slots, plan),
120+ lambda: _C._prefetch_push_pointers(table, slots, plan, len(sources)),
121+ torch_npu.npu.Event)
122+ return prefetch_buffers
123+ 
124+ 
125+def drain_prefetch_push():
126+ """Wait standalone transfers, retaining backing on failure; not consumer drain."""
127+ _pending.drain()
@@ -43,10 +43,12 @@ def audit_loaded_shmem_library(
43) -> dict[str, object]:43) -> dict[str, object]:
44 """Return identity evidence for the one loaded ``libshmem.so`` image.44 """Return identity evidence for the one loaded ``libshmem.so`` image.
45 45 
46- Mappings are deduplicated by the resolved file's ``(st_dev, st_ino)``;46+ Mappings are deduplicated by procfs ``(device, inode)`` so repeated ELF
47- repeated ELF segments are therefore one library. The procfs device/inode47+ segments are one library. The procfs inode must match ``stat(2)``. The
48- fields must also match ``stat(2)``. Any missing, deleted, inconsistent, or48+ device numbers are both reported but may differ when a container path is
49- multiple runtime images fail closed before ACLSHMEM initialization.49+ an overlay/bind-mount view of the mapped host file. Any missing, deleted,
50+ inode-inconsistent, or multiple runtime images fail closed before ACLSHMEM
51+ initialization.
50 """52 """
51 current_platform = sys.platform if platform is None else platform53 current_platform = sys.platform if platform is None else platform
52 if current_platform != "linux":54 if current_platform != "linux":
@@ -92,20 +94,30 @@ def audit_loaded_shmem_library(
92 raise RuntimeError(94 raise RuntimeError(
93 f"cannot resolve loaded libshmem mapping identity: {mapped_path}") from exc95 f"cannot resolve loaded libshmem mapping identity: {mapped_path}") from exc
94 96 
95- if maps_device_number != stat_result.st_dev or maps_inode != stat_result.st_ino:97+ # /proc/<pid>/maps can expose the backing filesystem's device number
98+ # while stat(2) of the same absolute path reports the device number of
99+ # the container's overlay/bind-mount view. In that case the pathname
100+ # and inode still identify the same file, but st_dev legitimately
101+ # differs (for example maps=fd:00 and stat=0:33). An inode mismatch is
102+ # still a replacement/identity failure and must remain fail-closed.
103+ if maps_inode != stat_result.st_ino:
96 raise RuntimeError(104 raise RuntimeError(
97 "loaded libshmem mapping metadata changed during audit: "105 "loaded libshmem mapping metadata changed during audit: "
98 f"{mapped_path} maps dev/inode={maps_device}/{maps_inode}, "106 f"{mapped_path} maps dev/inode={maps_device}/{maps_inode}, "
99 f"stat dev/inode={os.major(stat_result.st_dev):x}:"107 f"stat dev/inode={os.major(stat_result.st_dev):x}:"
100 f"{os.minor(stat_result.st_dev):x}/{stat_result.st_ino}")108 f"{os.minor(stat_result.st_dev):x}/{stat_result.st_ino}")
101 109 
102- identity = (stat_result.st_dev, stat_result.st_ino)110+ identity = (maps_device_number, maps_inode)
103 identities.setdefault(identity, {111 identities.setdefault(identity, {
104 "realpath": str(realpath),112 "realpath": str(realpath),
105 "device": int(stat_result.st_dev),113 "device": int(stat_result.st_dev),
106 "device_major": int(os.major(stat_result.st_dev)),114 "device_major": int(os.major(stat_result.st_dev)),
107 "device_minor": int(os.minor(stat_result.st_dev)),115 "device_minor": int(os.minor(stat_result.st_dev)),
108 "inode": int(stat_result.st_ino),116 "inode": int(stat_result.st_ino),
117+ "maps_device": int(maps_device_number),
118+ "maps_device_major": int(os.major(maps_device_number)),
119+ "maps_device_minor": int(os.minor(maps_device_number)),
120+ "device_alias": bool(maps_device_number != stat_result.st_dev),
109 })121 })
110 122 
111 if len(identities) != 1:123 if len(identities) != 1:
@@ -115,9 +127,10 @@ def audit_loaded_shmem_library(
115 f"{len(identities)}: {paths}")127 f"{len(identities)}: {paths}")
116 128 
117 info = next(iter(identities.values()))129 info = next(iter(identities.values()))
118- identity = (int(info["device"]), int(info["inode"]))130+ path_identity = (int(info["device"]), int(info["inode"]))
119 try:131 try:
120- info["sha256"] = _sha256_file(Path(str(info["realpath"])), identity)132+ info["sha256"] = _sha256_file(
133+ Path(str(info["realpath"])), path_identity)
121 except OSError as exc:134 except OSError as exc:
122 raise RuntimeError(135 raise RuntimeError(
123 f"cannot hash loaded libshmem runtime: {info['realpath']}") from exc136 f"cannot hash loaded libshmem runtime: {info['realpath']}") from exc
@@ -148,6 +148,7 @@ def _npu_extension():
148 os.path.join("native", "csrc", "acl_shared_buffer.cpp"),148 os.path.join("native", "csrc", "acl_shared_buffer.cpp"),
149 os.path.join("native", "csrc", "torch_classes.cpp"),149 os.path.join("native", "csrc", "torch_classes.cpp"),
150 os.path.join("native", "csrc", "launcher.cpp"),150 os.path.join("native", "csrc", "launcher.cpp"),
151+ os.path.join("native", "csrc", "lplusb_runtime.cpp"),
151 os.path.join("native", "csrc", "ops", "moonep_combine.cpp"),152 os.path.join("native", "csrc", "ops", "moonep_combine.cpp"),
152 os.path.join("native", "csrc", "ops", "moonep_combine_udma.cpp"),153 os.path.join("native", "csrc", "ops", "moonep_combine_udma.cpp"),
153 os.path.join("native", "csrc", "ops", "moonep_dispatch.cpp"),154 os.path.join("native", "csrc", "ops", "moonep_dispatch.cpp"),
@@ -239,7 +240,7 @@ def _package_data():
239 if BACKEND != "npu":240 if BACKEND != "npu":
240 return {}241 return {}
241 # Globs are relative to the `npu_patch` package directory.242 # Globs are relative to the `npu_patch` package directory.
242- libs = ["lib/*.so", "lib/*.so.*"]243+ libs = ["lib/*.so", "lib/*.so.*", "_integration_capabilities.json"]
243 return {"npu_patch": libs}244 return {"npu_patch": libs}
244 245 
245 246 
@@ -197,6 +197,7 @@ class ShmemRuntime:
197 """Thin facade over the shmem symmetric-memory runtime lifecycle."""197 """Thin facade over the shmem symmetric-memory runtime lifecycle."""
198 198 
199 _initialized = False199 _initialized = False
200+ _udma_enabled = False
200 _poisoned = False201 _poisoned = False
201 _runtime_library_record = None202 _runtime_library_record = None
202 203 
@@ -286,7 +287,7 @@ class ShmemRuntime:
286 # Fail closed before any SHMEM-native call (including UID generation).287 # Fail closed before any SHMEM-native call (including UID generation).
287 # Loading two libshmem images creates independent process-global288 # Loading two libshmem images creates independent process-global
288 # PE/heap state.289 # PE/heap state.
289- # cls._runtime_library_record = audit_loaded_shmem_library()290+ cls._runtime_library_record = audit_loaded_shmem_library()
290 rank = dist.get_rank(group=group)291 rank = dist.get_rank(group=group)
291 world_size = dist.get_world_size(group=group)292 world_size = dist.get_world_size(group=group)
292 if uid_bytes is None:293 if uid_bytes is None:
@@ -327,6 +328,7 @@ class ShmemRuntime:
327 else ACLSHMEM_DATA_OP_MTE),328 else ACLSHMEM_DATA_OP_MTE),
328 device_id=int(torch.npu.current_device()),329 device_id=int(torch.npu.current_device()),
329 enable_udma=enable_udma, qp_count=qp_count)330 enable_udma=enable_udma, qp_count=qp_count)
331+ cls._udma_enabled = bool(enable_udma)
330 cls._initialized = True332 cls._initialized = True
331 333 
332 @classmethod334 @classmethod
@@ -367,7 +369,7 @@ class ShmemRuntime:
367 return369 return
368 # The IP/port path owns the same process-global runtime and backing as370 # The IP/port path owns the same process-global runtime and backing as
369 # the UID path, so it must pass the identical pre-native audit.371 # the UID path, so it must pass the identical pre-native audit.
370- # cls._runtime_library_record = audit_loaded_shmem_library()372+ cls._runtime_library_record = audit_loaded_shmem_library()
371 if ip_port is None:373 if ip_port is None:
372 ip_port = _env_shmem_ip_port()374 ip_port = _env_shmem_ip_port()
373 if ip_port is None:375 if ip_port is None:
@@ -400,6 +402,7 @@ class ShmemRuntime:
400 else ACLSHMEM_DATA_OP_MTE),402 else ACLSHMEM_DATA_OP_MTE),
401 device_id=int(torch.npu.current_device()),403 device_id=int(torch.npu.current_device()),
402 enable_udma=enable_udma, qp_count=qp_count)404 enable_udma=enable_udma, qp_count=qp_count)
405+ cls._udma_enabled = bool(enable_udma)
403 cls._initialized = True406 cls._initialized = True
404 407 
405 @classmethod408 @classmethod
@@ -412,6 +415,13 @@ class ShmemRuntime:
412 only after diagnostics are captured.415 only after diagnostics are captured.
413 """416 """
414 if cls._initialized:417 if cls._initialized:
418+ # Standalone PUSH owns only transfer backing, never Buffer leases.
419+ from .prefetch_pointer import drain_prefetch_push
420+ try:
421+ drain_prefetch_push()
422+ except BaseException:
423+ cls._poisoned = True
424+ raise
415 # Plan B: reuse the buffer_c wrapper.425 # Plan B: reuse the buffer_c wrapper.
416 rc = int(shmem_finalize())426 rc = int(shmem_finalize())
417 if rc != 0:427 if rc != 0:
@@ -422,6 +432,7 @@ class ShmemRuntime:
422 # --- Original implementation (plan A) ---432 # --- Original implementation (plan A) ---
423 # core.finalize()433 # core.finalize()
424 cls._initialized = False434 cls._initialized = False
435+ cls._udma_enabled = False
425 cls._poisoned = False436 cls._poisoned = False
426 return rc437 return rc
427 return 0438 return 0
@@ -0,0 +1,118 @@
1+"""Device acceptance for the additive native APIs; run with fresh workers.
2+ 
3+MOONEP_NATIVE_TEST_UDMA=0 torchrun --nproc-per-node=2 -m pytest -s -x \
4+ test_npu/buffer_test/test_buffer_native_async_extensions.py
5+ 
6+Repeat with world=8, then UDMA=1 on Ascend950 with matching native ABIs.
7+No profiling/performance claim is made by this correctness test.
8+"""
9+import os
10+ 
11+import pytest
12+import torch
13+import torch.distributed as dist
14+import torch_npu
15+ 
16+from npu_patch import Buffer, ShmemRuntime
17+from npu_patch.buffer_c import create_vmm_physical, reset_symmetric_descriptors
18+ 
19+ 
20+def test_native_async_storage_and_lplusb(dist_env):
21+ rank, world = dist_env
22+ if world not in (2, 8):
23+ pytest.skip('acceptance recipe is EP2 or EP8')
24+ raw = os.environ.get('MOONEP_NATIVE_TEST_UDMA', '0')
25+ if raw not in ('0', '1'):
26+ raise ValueError('MOONEP_NATIVE_TEST_UDMA must be 0 or 1')
27+ udma = raw == '1'
28+ if ShmemRuntime.is_initialized():
29+ raise RuntimeError('run this acceptance test alone in fresh workers')
30+ s, h, k, local, b = 16, 128, 1, 2, 2
31+ device = torch.device('npu', torch.npu.current_device())
32+ buffer = Buffer(S=s, H=h, K=k, E=world * local, B=b, num_ep_ranks=world,
33+ group=dist.group.WORLD, explicitly_destroy=True,
34+ prefetch_use_udma=udma, grad_reduce_use_udma=udma)
35+ sources = []
36+ def allocate(shape, dtype):
37+ value, _, _ = create_vmm_physical(shape, dtype, device.index)
38+ sources.append(value)
39+ return value
40+ # Every rank registers the same inventory/order before one-shot SHMEM init.
41+ activation_sources = [(allocate((s * k, h), torch.bfloat16),
42+ allocate((s * k,), torch.int32)) for _ in range(3)]
43+ weight_slots = allocate((b, h, h), torch.bfloat16)
44+ grad_slots = allocate((b, h, h), torch.float32)
45+ weights = tuple(torch.full((h, h), rank * local + i + 1,
46+ dtype=torch.bfloat16, device=device) for i in range(local))
47+ targets = tuple(torch.full((h, h), 10 + rank * local + i,
48+ dtype=torch.float32, device=device) for i in range(local))
49+ ShmemRuntime.init_with_buffer(group=dist.group.WORLD, enable_udma=udma,
50+ qp_count=2 if udma else 0)
51+ banks = [buffer.prepare_comm_buffers(*pair) for pair in activation_sources]
52+ wbind = buffer.prepare_lplusb(weights, weight_slots)
53+ gbind = buffer.prepare_lplusb(targets, grad_slots)
54+ q1 = torch_npu.npu.current_stream()
55+ routes = torch.zeros(s, k, dtype=torch.int32, device=device)
56+ counts = torch.bincount(routes.flatten().long(), minlength=world * local).int()
57+ probabilities = torch.ones(s, k, dtype=torch.float32, device=device)
58+ saved = []
59+ # Three live Z3/R1/Z1-like outputs must survive later communication calls.
60+ for value, bank in zip((1, 2, 3), banks):
61+ hidden = torch.full((s, h), rank * 4 + value, dtype=torch.bfloat16, device=device)
62+ out, probs, cu, plan, done = buffer.dispatch(hidden, probabilities, routes, counts,
63+ async_finish=True, zero_copy=True, router_weights_zero_copy=True, comm_buffers=bank)
64+ saved.append((hidden, out, probs, plan, done, bank))
65+ for hidden, out, probs, plan, done, bank in saved:
66+ q1.wait_event(done)
67+ combined, _, event = buffer.combine(plan, out, async_finish=True,
68+ zero_copy=True, comm_buffers=bank)
69+ q1.wait_event(event)
70+ torch.npu.synchronize()
71+ torch.testing.assert_close(combined, hidden, atol=0, rtol=0)
72+ # Default copying path uses no bank argument and preserves each result.
73+ copied = []
74+ for value in (5, 6):
75+ hidden = torch.full((s, h), value, dtype=torch.bfloat16, device=device)
76+ out, _, _, plan, event = buffer.dispatch(hidden, probabilities, routes, counts,
77+ async_finish=True)
78+ copied.append((hidden, out, plan, event))
79+ for hidden, out, plan, event in copied:
80+ q1.wait_event(event)
81+ result, _, event = buffer.combine(plan, out, async_finish=True)
82+ q1.wait_event(event)
83+ torch.npu.synchronize()
84+ torch.testing.assert_close(result, hidden, atol=0, rtol=0)
85+ 
86+ # Use an explicit replicated ring plan to exercise nonempty and empty slots
87+ # on all ranks, independently of the token planner's load distribution.
88+ plan = saved[-1][3].clone()
89+ ring = torch.full((world, b), -1, dtype=torch.int32)
90+ for peer in range(world):
91+ ring[peer, 0] = ((peer + 1) % world) * local
92+ plan.experts_to_copy.copy_(ring.to(device))
93+ done = buffer.prefetch_lplusb(plan, wbind, async_finish=True)
94+ q1.wait_event(done)
95+ torch.npu.synchronize()
96+ torch.testing.assert_close(wbind.slot[0], torch.full_like(wbind.slot[0],
97+ int(ring[rank, 0]) + 1), atol=0, rtol=0)
98+ for round_id in range(2):
99+ gbind.slot.fill_(99)
100+ gbind.slot[0].fill_(rank + 1)
101+ done = buffer.reduce_grad(plan, async_finish=True, lplusb=gbind)
102+ q1.wait_event(done)
103+ torch.npu.synchronize()
104+ for i, target in enumerate(targets):
105+ contribution = sum(peer + 1 for peer in range(world)
106+ if int(ring[peer, 0]) == rank * local + i)
107+ expected = 10 + rank * local + i + (round_id + 1) * contribution
108+ torch.testing.assert_close(target, torch.full_like(target, expected), atol=0, rtol=0)
109+ assert torch.count_nonzero(gbind.slot[0]).item() == 0
110+ assert torch.all(gbind.slot[1] == 99).item()
111+ # Only successful, globally drained execution may reach teardown.
112+ torch.npu.synchronize()
113+ dist.barrier()
114+ ShmemRuntime.finalize()
115+ buffer.destroy()
116+ for source in sources:
117+ source._vmm_allocation.destroy()
118+ reset_symmetric_descriptors()
@@ -0,0 +1,539 @@
1+# SPDX-License-Identifier: Apache-2.0
2+"""Eight-card DSV4 public Buffer e2e test (MTE).
3+ 
4+Derived from the adjacent original e2e test, with eight EP ranks and
5+S=4096, H=7168, K=6, E=48, B=6, Hp=3072, and 32 blocks. Inputs use a
6+rank-seeded random top-k: repeated calls reproduce the same routing.
7+The public sync/async dispatch, separate prefetch, plan reuse, zero-copy,
8+combine, and gradient-reduction checks are retained on the MTE path.
9+All gate/up/down projections use [H, Hp]; this is an operator-chain test,
10+without expert GEMM or a training loop. VMM pages are pinned to 2 MiB
11+during the test and the previous page setting is restored afterwards.
12+ 
13+Run from the MoonEP root:
14+ torchrun --standalone --nproc_per_node=8 -m pytest -s -x test_npu/mte/test_e2e_dsv4.py
15+"""
16+ 
17+import os
18+import sys
19+ 
20+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
21+import torch
22+import torch.distributed as dist
23+ 
24+import torch_npu
25+ 
26+from npu_patch import Buffer, MoonEPCommPlan
27+from kernel_test_utils import (
28+ clone_dedup_plan_fields,
29+ dedup_plan_fields_equal,
30+ dedup_plan_semantic_errors,
31+ init_shmem,
32+ local_device_index,
33+)
34+from moonep.buffer import (
35+ create_full_grad_and_reduce_buffer,
36+ create_full_weight,
37+ projection_home_slice,
38+ projection_slot_slice,
39+ release_owned,
40+)
41+ 
42+ 
43+def make_inputs(rank, S, H, K, E, seed=0):
44+ dev = "npu"
45+ # Reproducible random routing; each rank uses its own fixed seed.
46+ g = torch.Generator(device=dev).manual_seed(seed + rank)
47+ hidden = torch.randn(S, H, dtype=torch.bfloat16, device=dev, generator=g)
48+ weights = torch.rand(S, K, dtype=torch.float32, device=dev, generator=g)
49+ topk = torch.randint(0, E, (S, K), dtype=torch.int32, device=dev, generator=g)
50+ tpe = torch.bincount(topk.flatten(), minlength=E).to(torch.int32)
51+ return hidden, weights, topk, tpe
52+ 
53+ 
54+def _expert_value(expert, H, Hp, dev):
55+ e = torch.full((H, Hp), float(expert), dtype=torch.bfloat16, device=dev)
56+ e += (torch.arange(Hp, dtype=torch.bfloat16, device=dev) * 0.01).view(1, Hp)
57+ e += (torch.arange(H, dtype=torch.bfloat16, device=dev) * 0.0001).view(H, 1)
58+ return e
59+ 
60+ 
61+def make_full_weight(rank, R, E, B, H, Hp, device, source_offset):
62+ """Return ``(full_weight, offset)``.
63+ 
64+ full_weight is built by ``create_full_weight``: it creates this rank's home/slot
65+ VMM chunk and ``[E+B]`` projection, copies ``expert_table[rank*epn:(rank+1)*epn]``
66+ into the home rows plus offset, zeroes the slot rows, and attaches the home/slot
67+ source VAs (the Buffer prefetch_weight VMM path translates through them). expert_table
68+ is generated in full by a deterministic formula and is identical on all ranks (rank-invariant).
69+ """
70+ dev = f"npu:{device}"
71+ expert_table = torch.stack(
72+ [_expert_value(e, H, Hp, dev) for e in range(E)])
73+ full = create_full_weight(
74+ E, B, H, Hp, rank, R, expert_table, source_offset, device=device)
75+ return full, source_offset
76+ 
77+ 
78+def make_prefetch_args(rank, R, E, B, H, Hp, device):
79+ """Return ``(args_dict, meta)``.
80+ 
81+ ``args_dict`` values are the full_weight **tensors** (spread into ``buffer.prefetch_weight(**args)``);
82+ ``meta[name] = (full_weight, offset)`` is for the assertions (slot rows read via
83+ ``projection_slot_slice``).
84+ """
85+ args = {}
86+ meta = {}
87+ for name, offset in (("full_gate_weight", 0.0),
88+ ("full_up_weight", 1.0),
89+ ("full_down_weight", 2.0)):
90+ full, off = make_full_weight(rank, R, E, B, H, Hp, device, offset)
91+ args[name] = full
92+ meta[name] = (full, off)
93+ return args, meta
94+ 
95+ 
96+def assert_prefetched(prefetch_arge, prefetch_meta, experts_to_copy, R):
97+ """``R`` is the *domain* EP size (== group world size), not the global one.
98+ 
99+ The prefetch projection lays ``[E+B]`` global expert rows where ``E =
100+ epn * R``; taking ``R`` from the caller keeps this correct inside an EP
@@ -19,6 +19,7 @@ import torch.distributed as dist
19import torch_npu19import torch_npu
20 20 
21from npu_patch._device import local_device_index21from npu_patch._device import local_device_index
22+from npu_patch._grad_reduce_contract import workspace_elements
22from npu_patch import ShmemRuntime23from npu_patch import ShmemRuntime
23from npu_patch.buffer_c import (24from npu_patch.buffer_c import (
24 create_vmm_physical,25 create_vmm_physical,
@@ -27,6 +28,7 @@ from npu_patch.buffer_c import (
27 symmetric_descriptors,28 symmetric_descriptors,
28)29)
29from npu_patch.launchers import launch_grad_reduce30from npu_patch.launchers import launch_grad_reduce
31+from npu_patch.ops import GradReduceOp
30 32 
31# --- Original implementation (option A: the shmem Python package) ---33# --- Original implementation (option A: the shmem Python package) ---
32# import importlib34# import importlib
@@ -408,6 +410,102 @@ def test_grad_reduce(dist_env, case):
408 run_case(rank, local_rank, R, case)410 run_case(rank, local_rank, R, case)
409 411 
410 412 
413+@pytest.mark.parametrize('shape', [(129, 101), (6144, 7168), (7168, 3072)],
414+ ids=['tail_tile', 'fc1', 'fc2'])
415+@pytest.mark.parametrize('use_udma', [False, True], ids=['mte', 'udma'])
416+def test_grad_reduce_canonical_targets(dist_env, shape, use_udma, monkeypatch):
417+ """Plain independent home allocations, changing plans and valid-only clear.
418+ 
419+ Run in fresh torchrun workers after rebuilding extension + kernel library.
420+ No legacy owner-reduce fallback is allowed. This is correctness, not timing.
421+ """
422+ from npu_patch import _C
423+ import time
424+ rank, local_rank, R = dist_env
425+ device = f'npu:{local_device_index(local_rank)}'
426+ epn, B, blocks = 6, 6, 32
427+ H, Hp = shape
428+ source = None
429+ monkeypatch.setenv('ASCEND_MOONEP_GRAD_REDUCE_USE_UDMA', str(int(use_udma)))
430+ monkeypatch.setattr(_C, '_lplusb_owner_reduce',
431+ lambda *a: pytest.fail('canonical Op used legacy binding'))
432+ try:
433+ source, _, _ = create_vmm_physical((B, H, Hp), torch.float32,
434+ local_device_index(local_rank))
435+ ShmemRuntime.init_with_buffer(group=None, descriptors=symmetric_descriptors(),
436+ enable_udma=use_udma, qp_count=2 if use_udma else 0)
437+ slots = sym_tensor(source)
438+ slots.zero_()
439+ targets = tuple(torch.full((H, Hp), float(100 + e), dtype=torch.float32, device=device)
440+ for e in range(epn))
441+ # Reverse allocation order so a dense base+expert*matrix assumption
442+ # cannot accidentally satisfy the canonical pointer contract.
443+ targets = targets[::-1]
444+ table = torch.tensor([t.data_ptr() for t in targets], dtype=torch.int64, device=device)
445+ addresses = tuple(t.data_ptr() for t in targets)
446+ wanted = [float(100 + epn - 1 - e) for e in range(epn)]
447+ op = GradReduceOp(ws_bytes=0, num_sms=blocks)
448+ ctx = dict(E=R*epn, R=R, B=B)
449+ if use_udma:
450+ ctx['_grad_reduce_target_workspace'] = torch.empty(
451+ workspace_elements(R, B, min(blocks, 64)), dtype=torch.float32, device=device)
452+ plan_cases = ('random', 'empty', 'asymmetric', 'hotspot', 'ring')
453+ for iteration, plan_name in enumerate(plan_cases):
454+ final_round = iteration == len(plan_cases) - 1
455+ plan = (torch.zeros((R, B), dtype=torch.int32, device=device)
456+ if plan_name == 'hotspot' else
457+ PLAN_BUILDERS[plan_name](R, B, epn, device, 7 + iteration))
458+ rows = plan.cpu().tolist()
459+ # Delay one producer before its writes: pointer mode's native pre
460+ # barrier must stop early owners reading an unpublished slot.
461+ if rank == R-1 and iteration == 2:
462+ time.sleep(.05)
463+ was_clean = []
464+ for slot, expert in enumerate(rows[rank]):
465+ if expert >= 0:
466+ was_clean.append(torch.all(slots[slot] == 0))
467+ slots[slot].add_(1 + rank*B + slot + iteration*100)
468+ elif final_round:
469+ # Intentional sentinel only in the final diagnostic round;
470+ # the preceding rounds never write inactive slots.
471+ slots[slot].fill_(-1234)
472+ for pe, row in enumerate(rows):
473+ for slot, expert in enumerate(row):
474+ local = expert - rank*epn
475+ if expert >= 0 and 0 <= local < epn:
476+ wanted[local] += 1 + pe*B + slot + iteration*100
477+ if not use_udma and iteration == 0:
478+ # Torch custom-class defaults preserve the old MTE call.
479+ torch.classes.AscendMoonEP.GradReduce().compute_targets(
480+ table, slots, plan, epn, H, Hp, R, B, rank, blocks)
481+ elif not use_udma and iteration == 1:
482+ # The explicit flag selects MTE even when scratch is supplied.
483+ torch.classes.AscendMoonEP.GradReduce().compute_targets(
484+ table, slots, plan, epn, H, Hp, R, B, rank, blocks,
485+ False, torch.empty(1, dtype=torch.float32, device=device))
486+ else:
487+ op.compute_targets(ctx, table, slots, plan, rank, blocks)
488+ torch.npu.synchronize()
489+ checks = was_clean + [torch.all(t == value) for t, value in zip(targets, wanted)]
490+ checks += [torch.all(slots[s] == (0 if expert >= 0 or not final_round else -1234))
491+ for s, expert in enumerate(rows[rank])]
492+ ok = torch.stack(checks).all().to(torch.int32)
493+ dist.all_reduce(ok, op=dist.ReduceOp.MIN)
494+ assert bool(ok), f'canonical {shape} round={iteration} failed'
495+ assert tuple(t.data_ptr() for t in targets) == addresses
496+ if rank == 0:
497+ print(f'canonical targets shape={shape} actual_blocks={min(blocks,64)} '
498+ f'backend={"UDMA" if use_udma else "MTE"} '
499+ f'changed_plans={len(plan_cases)} valid_slot_clear=True')
500+ finally:
501+ dist.barrier()
502+ if ShmemRuntime.is_initialized():
503+ ShmemRuntime.finalize()
504+ if source is not None:
505+ source._vmm_allocation.destroy()
506+ reset_symmetric_descriptors()
507+ 
508+ 
411def test_grad_reduce_repeated_launch(dist_env):509def test_grad_reduce_repeated_launch(dist_env):
412 rank, local_rank, R = dist_env510 rank, local_rank, R = dist_env
413 dev = f"npu:{local_device_index(local_rank)}"511 dev = f"npu:{local_device_index(local_rank)}"