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
Mnpu_patch/__init__.py+12-2File content is under review, please try again later
Anpu_patch/_grad_reduce_contract.py+13-0File content is under review, please try again later
Anpu_patch/_integration_capabilities.json+57-0File content is under review, please try again later
@@ -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")
Mnpu_patch/api.py+617-56File content is under review, please try again later
@@ -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)",
Mnpu_patch/launchers.py+104-1File content is under review, please try again later
Mnpu_patch/native/CMakeLists.txt+3-0File content is under review, please try again later
@@ -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}
Anpu_patch/native/csrc/lplusb_runtime.cpp+192-0File content is under review, please try again later
@@ -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
Mnpu_patch/native/csrc/ops/grad_reduce.cpp+95-3File content is under review, please try again later
@@ -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
Mnpu_patch/native/csrc/pybind.cpp+47-0File content is under review, please try again later
Mnpu_patch/native/csrc/torch_classes.cpp+32-1File content is under review, please try again later
Mnpu_patch/native/include/ascend_moonep/kernels/launch.h+57-0File content is under review, please try again later
Mnpu_patch/native/include/ascend_moonep/kernels/types.h+3-0File content is under review, please try again later
@@ -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+}
Mnpu_patch/native/kernels/moonep_combine.cpp+2-2File content is under review, please try again later
Mnpu_patch/native/kernels/moonep_dispatch.cpp+5-5File content is under review, please try again later
Mnpu_patch/native/kernels/moonep_grad_reduce.cpp+69-23File content is under review, please try again later
Mnpu_patch/native/kernels/moonep_grad_reduce_udma.cpp+107-27File content is under review, please try again later
@@ -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
Mnpu_patch/ops.py+40-0File content is under review, please try again later
@@ -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 
Mnpu_patch/shmem_runtime.py+13-2File content is under review, please try again later
@@ -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)}"