Draft
[WIP]experiment/contiguous-grad-lplusb #5
&NewgateAdd on 25 days ago
[WIP]experiment/contiguous-grad-lplusb #5
Draft
&NewgateAdd on 25 days ago
Total: 50 files changed+4273-164
Anpu_patch/CONTIGUOUS_GRAD.md+57-0File content is under review, please try again later
Mnpu_patch/README.md+12-0File content is under review, please try again later
Mnpu_patch/__init__.py+11-2File content is under review, please try again later
Anpu_patch/_integration_capabilities.json+54-0File content is under review, please try again later
Mnpu_patch/api.py+617-59File 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+82-6File content is under review, please try again later
@@ -85,6 +85,8 @@ 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
89+ kernels/barrier.cpp
88 kernels/barrier_bench.cpp90 kernels/barrier_bench.cpp
89 kernels/moonep_combine.cpp91 kernels/moonep_combine.cpp
90 kernels/moonep_combine_udma.cpp92 kernels/moonep_combine_udma.cpp
@@ -95,6 +97,8 @@ ascend_moonep_add_kernel_library(
95 kernels/planning.cpp97 kernels/planning.cpp
96 kernels/prefetch.cpp98 kernels/prefetch.cpp
97 kernels/prefetch_udma.cpp99 kernels/prefetch_udma.cpp
100+ kernels/prefetch_push_udma.cpp
101+ kernels/prefetch_pointer_push_udma.cpp
98 INCLUDES102 INCLUDES
99 include103 include
100 kernels104 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}
Anpu_patch/native/csrc/lplusb_runtime.cpp+165-0File content is under review, please try again later
Anpu_patch/native/csrc/lplusb_runtime.h+28-0File content is under review, please try again later
Mnpu_patch/native/csrc/ops/grad_reduce.cpp+34-6File content is under review, please try again later
Mnpu_patch/native/csrc/ops/grad_reduce.h+2-1File content is under review, please try again later
@@ -44,8 +44,12 @@ void MoonEPCombine(
44 int64_t K,44 int64_t K,
45 int64_t R,45 int64_t R,
46 int64_t rank,46 int64_t rank,
47- bool use_udma) {47+ bool use_udma,
48+ int64_t num_sms) {
48 (void)use_udma;49 (void)use_udma;
50+ TORCH_CHECK(num_sms > 0 &&
51+ static_cast<uint64_t>(num_sms) <= std::numeric_limits<uint32_t>::max(),
52+ "num_sms must be a positive uint32 launch width");
49 CheckNpuContiguous(hidden_buf, "hidden_buf");53 CheckNpuContiguous(hidden_buf, "hidden_buf");
50 CheckNpuContiguous(dst, "dst");54 CheckNpuContiguous(dst, "dst");
51 CheckNpuContiguous(dup_groups, "dup_groups");55 CheckNpuContiguous(dup_groups, "dup_groups");
@@ -137,7 +141,7 @@ void MoonEPCombine(
137 tiling.num_tokens = static_cast<uint32_t>(S);141 tiling.num_tokens = static_cast<uint32_t>(S);
138 tiling.hidden = static_cast<uint32_t>(H);142 tiling.hidden = static_cast<uint32_t>(H);
139 tiling.num_topk = static_cast<uint32_t>(K);143 tiling.num_topk = static_cast<uint32_t>(K);
140- tiling.block_dim = 32u;144+ tiling.block_dim = static_cast<uint32_t>(num_sms);
141 tiling.with_weight = with_weight ? 1u : 0u;145 tiling.with_weight = with_weight ? 1u : 0u;
142 tiling.reserved = 0u;146 tiling.reserved = 0u;
143 147 
@@ -7,7 +7,7 @@ namespace ascend_moonep::ops {
7// Plan-driven moonEP_combine on already-symmetric SHMEM shards.7// Plan-driven moonEP_combine on already-symmetric SHMEM shards.
8// Outputs are caller-allocated. Host ABI mirrors MoonEPDispatch.8// Outputs are caller-allocated. Host ABI mirrors MoonEPDispatch.
9// Provide weight_buf and route_weights_sk_out together, or omit both.9// Provide weight_buf and route_weights_sk_out together, or omit both.
10-// Launch width is fixed at 32 AIV.10+// MTE launch width is controlled by num_sms.
11//11//
12// route_weights_sk_out must be fp32 [S, AlignUp(K, 8)] when present12// route_weights_sk_out must be fp32 [S, AlignUp(K, 8)] when present
13// (kernel DataCopy width).13// (kernel DataCopy width).
@@ -25,6 +25,7 @@ void MoonEPCombine(
25 int64_t K,25 int64_t K,
26 int64_t R,26 int64_t R,
27 int64_t rank,27 int64_t rank,
28- bool use_udma);28+ bool use_udma,
29+ int64_t num_sms = 32);
29 30 
30} // namespace ascend_moonep::ops31} // namespace ascend_moonep::ops
@@ -185,13 +185,18 @@ MoonEPDispatch(
185 int64_t R,185 int64_t R,
186 int64_t rank,186 int64_t rank,
187 bool use_udma,187 bool use_udma,
188- bool server_dedup) {188+ bool server_dedup,
189+ int64_t num_sms) {
189 190 
190 auto args = CheckDispatchArgs(191 auto args = CheckDispatchArgs(
191 hidden_sh, route_weights, dst, dup_groups, dup_loffs, dup_counts,192 hidden_sh, route_weights, dst, dup_groups, dup_loffs, dup_counts,
192 hidden_buf, route_weights_buf, S, H, K, R, rank, use_udma, server_dedup);193 hidden_buf, route_weights_buf, S, H, K, R, rank, use_udma, server_dedup);
193 194 
194 if (!use_udma) {195 if (!use_udma) {
196+ TORCH_CHECK(num_sms > 0 &&
197+ static_cast<uint64_t>(num_sms) <= std::numeric_limits<uint32_t>::max(),
198+ "num_sms must be a positive uint32 launch width");
199+ args.tiling.block_dim = static_cast<uint32_t>(num_sms);
195 // Peer-to-peer MTE path: rank-level dedup only, no UDMA messaging.200 // Peer-to-peer MTE path: rank-level dedup only, no UDMA messaging.
196 LaunchMoonEPDispatchKernel(201 LaunchMoonEPDispatchKernel(
197 hidden_sh, args.route_weights, dst,202 hidden_sh, args.route_weights, dst,
@@ -23,7 +23,8 @@ MoonEPDispatch(
23 int64_t R,23 int64_t R,
24 int64_t rank,24 int64_t rank,
25 bool use_udma,25 bool use_udma,
26- bool server_dedup);26+ bool server_dedup,
27+ int64_t num_sms = 32);
27 28 
28void29void
29MoonEPDispatchProfile(30MoonEPDispatchProfile(
@@ -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+43-0File content is under review, please try again later
Mnpu_patch/native/csrc/torch_classes.cpp+45-9File content is under review, please try again later
Mnpu_patch/native/include/ascend_moonep/kernels/launch.h+33-0File content is under review, please try again later
@@ -66,7 +66,7 @@ struct alignas(8) MoonEPCombineTilingData {
66 uint32_t num_tokens; // S66 uint32_t num_tokens; // S
67 uint32_t hidden; // H67 uint32_t hidden; // H
68 uint32_t num_topk; // K68 uint32_t num_topk; // K
69- uint32_t block_dim; // fixed 32 AIV (host always writes 32)69+ uint32_t block_dim; // MTE AIV launch width from num_sms
70 uint32_t with_weight; // 1: gather weights → [S,K]; 0: skip70 uint32_t with_weight; // 1: gather weights → [S,K]; 0: skip
71 uint32_t reserved;71 uint32_t reserved;
72};72};
@@ -90,8 +90,12 @@ struct alignas(8) MoonEPDispatchTilingData {
90 uint32_t rank;90 uint32_t rank;
91 uint32_t with_weights;91 uint32_t with_weights;
92 uint32_t server_dedup;92 uint32_t server_dedup;
93+ uint32_t block_dim; // MTE only; occupies the former tail padding
93};94};
94 95 
96+static_assert(sizeof(MoonEPDispatchTilingData) == 32, "dispatch tiling ABI must remain 32 bytes");
97+static_assert(sizeof(MoonEPCombineTilingData) == 32, "combine tiling ABI must remain 32 bytes");
98+ 
95// Udma dispatch profile ABI (mirrors the UBMEM template-<bool Profile> pattern99// Udma dispatch profile ABI (mirrors the UBMEM template-<bool Profile> pattern
96// from the timing branch): moonep_dispatch_udma_profile_kernel writes each AIV's100// from the timing branch): moonep_dispatch_udma_profile_kernel writes each AIV's
97// metrics as an int64 row into a [kMoonEPAivNum, kMoonEPDispatchUdmaProfileFields]101// 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,35 @@
1+// SPDX-License-Identifier: Apache-2.0
2+ 
3+#include <cstdint>
4+#include <cstdlib>
5+#include <cstring>
6+ 
7+#include "acl/acl.h"
8+#include "kernel_operator.h"
9+#include "shmem.h"
10+ 
11+#include "ascend_moonep/kernels/launch.h"
12+ 
13+using namespace AscendC;
14+ 
15+// Canonical MTE and UDMA GradReduce use one AIV for their WORLD barriers in AIV mode.
16+extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__
17+void MoonEPGradReduceBarrierAiv(uint64_t ffts_config)
18+{
19+ util_set_ffts_config(ffts_config);
20+ aclshmemx_barrier_all_vec();
21+}
22+ 
23+extern "C" ASCEND_MOONEP_EXPORT int moonep_grad_reduce_native_barrier(void* stream)
24+{
25+ if (stream == nullptr) return ACL_ERROR_INVALID_PARAM;
26+ const char* mode = std::getenv("MOONEP_GRAD_REDUCE_NATIVE_BARRIER_MODE");
27+ if (mode == nullptr || std::strcmp(mode, "mixed") == 0) {
28+ aclshmemx_barrier_all_on_stream(stream);
29+ } else if (std::strcmp(mode, "aiv") == 0) {
30+ MoonEPGradReduceBarrierAiv<<<1, nullptr, stream>>>(shmemx_get_ffts_config());
31+ } else {
32+ return ACL_ERROR_INVALID_PARAM;
33+ }
34+ return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
35+}
Anpu_patch/native/kernels/lplusb_runtime.cpp+167-0File content is under review, please try again later
@@ -36,7 +36,6 @@
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;
40using ascend_moonep::MoonEPCombineTilingData;39using ascend_moonep::MoonEPCombineTilingData;
41 40 
42namespace {41namespace {
@@ -1044,7 +1043,7 @@ extern "C" ASCEND_MOONEP_EXPORT void moonep_combine_kernel_do(
1044 uint8_t* tiling_host)1043 uint8_t* tiling_host)
1045{1044{
1046 auto* td = reinterpret_cast<MoonEPCombineTilingData*>(tiling_host);1045 auto* td = reinterpret_cast<MoonEPCombineTilingData*>(tiling_host);
1047- moonep_combine_kernel<<<kMoonEPAivNum, nullptr, stream>>>(1046+ moonep_combine_kernel<<<td->block_dim, nullptr, stream>>>(
1048 hidden_buf,1047 hidden_buf,
1049 weight_buf,1048 weight_buf,
1050 dst,1049 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, AIV launch width controlled by num_sms.
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,6 @@
19using namespace AscendC;19using namespace AscendC;
20 20 
21using bf16_t = bfloat16_t;21using bf16_t = bfloat16_t;
22-using ascend_moonep::kMoonEPAivNum;
23 22 
24// UB buffer sizing: one bf16 hidden row, weight ping-pong, and route metadata.23// 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).24// Safety margin: allocate up to 128KB for hidden row (H <= 65536).
@@ -618,6 +617,7 @@ extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ void moonep_dispa
618 uint32_t with_weights = tiling.with_weights;617 uint32_t with_weights = tiling.with_weights;
619 618 
620 uint32_t core_idx = get_block_idx();619 uint32_t core_idx = get_block_idx();
620+ uint32_t core_count = get_block_num();
621 621 
622 LocalTensor<uint8_t> ub_base;622 LocalTensor<uint8_t> ub_base;
623 ub_base.address_.logicPos = static_cast<uint8_t>(TPosition::VECIN);623 ub_base.address_.logicPos = static_cast<uint8_t>(TPosition::VECIN);
@@ -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, core_count);
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, core_count);
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<<<td->block_dim, nullptr, stream>>>(
671 hidden_sh,671 hidden_sh,
672 route_weights,672 route_weights,
673 dst,673 dst,
Mnpu_patch/native/kernels/moonep_grad_reduce.cpp+42-18File content is under review, please try again later
Mnpu_patch/native/kernels/moonep_grad_reduce_udma.cpp+50-24File 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) {
Anpu_patch/native_async.py+116-0File content is under review, please try again later
Mnpu_patch/ops.py+7-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 
@@ -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
Atest_host/conftest.py+214-0File content is under review, please try again later
Atest_host/test_contiguous_grad.py+174-0File content is under review, please try again later
Atest_host/test_dense_grad_native.py+133-0File content is under review, please try again later
Atest_host/test_grad_reduce_launch.py+207-0File content is under review, please try again later
Atest_npu/buffer_test/test_buffer_native_async_extensions.py+121-0File content is under review, please try again later
Mtest_npu/mte/test_grad_reduce.py+92-0File content is under review, please try again later