Draft
[WIP]Draft: feat(npu): provide shared slots and counted URMA runtime integration #18
[WIP]Draft: feat(npu): provide shared slots and counted URMA runtime integration #18
Draft
Jia_AustinAdd on 24 days ago
Total: 16 files changed+1999-76
@@ -44,6 +44,7 @@ from .ops import (
44)44)
45from .launchers import planning_workspace_sizes45from .launchers import planning_workspace_sizes
46from .shmem_runtime import ShmemRuntime46from .shmem_runtime import ShmemRuntime
47+from .shared_slots import SharedSlotsMixin
47 48 
48logger = logging.getLogger(__name__)49logger = logging.getLogger(__name__)
49 50 
@@ -352,7 +353,7 @@ def _create_context(
352 return ctx353 return ctx
353 354 
354 355 
355-class Buffer:356+class Buffer(SharedSlotsMixin):
356 """Ascend MoonEP communication buffer owner (buffer-backed path only).357 """Ascend MoonEP communication buffer owner (buffer-backed path only).
357 358 
358 A Buffer owns the communication chunks, local scratch tensors, the kernel359 A Buffer owns the communication chunks, local scratch tensors, the kernel
@@ -438,6 +439,7 @@ class Buffer:
438 use_udma=use_udma,439 use_udma=use_udma,
439 udma_flags=udma_flags,440 udma_flags=udma_flags,
440 )441 )
442+ self._init_shared_slots()
441 # Buffer-backed: set True by _ensure_shmem_views after init_with_buffer.443 # Buffer-backed: set True by _ensure_shmem_views after init_with_buffer.
442 self._shmem_ready = False444 self._shmem_ready = False
443 self._comm_stream = torch_npu.npu.Stream(445 self._comm_stream = torch_npu.npu.Stream(
@@ -454,13 +456,15 @@ class Buffer:
454 """Total CANN VMM bytes of this Buffer's comm chunks + RMA op workspaces456 """Total CANN VMM bytes of this Buffer's comm chunks + RMA op workspaces
455 (i.e. the descriptor size registered with buffer-backed shmem init).457 (i.e. the descriptor size registered with buffer-backed shmem init).
456 458 
457- The framework-side local physical segments of full weight/grad/reduce459+ Includes registered shared weight/FP32-gradient slots with physical
458- buffers are not counted; per §6 the framework collects460+ allocation padding. Canonical weights/main_grad, ordinary wgrad scratch
459- ``buffer_c.symmetric_descriptors()`` and calls init_with_buffer once.461+ and the native GR temporary workspace are separate budgets.
460 """462 """
461 ctx = self._ctx463 ctx = self._ctx
462 assert ctx is not None, "Buffer is destroyed"464 assert ctx is not None, "Buffer is destroyed"
463- return int(ctx['shmem_footprint_bytes'])465+ slots = sum(tensor._vmm_allocation.size for record in self._shared_sources
466+ for tensor in record[1:])
467+ return int(ctx['shmem_footprint_bytes']) + slots
464 468 
465 def _require_ctx(self) -> dict:469 def _require_ctx(self) -> dict:
466 assert not self._destroyed, "MoonEP-Ascend Buffer has been destroyed"470 assert not self._destroyed, "MoonEP-Ascend Buffer has been destroyed"
@@ -518,6 +522,10 @@ class Buffer:
518 """522 """
519 if self._destroyed:523 if self._destroyed:
520 return524 return
525+ self.assert_quiescent()
526+ self.assert_no_bindings()
527+ if ShmemRuntime.is_initialized():
528+ raise RuntimeError("finalize SHMEM successfully before Buffer.destroy")
521 ctx = self._ctx529 ctx = self._ctx
522 if ctx is None:530 if ctx is None:
523 self._destroyed = True531 self._destroyed = True
@@ -536,6 +544,12 @@ class Buffer:
536 # trailing barrier so no rank frees memory another rank is still using.544 # trailing barrier so no rank frees memory another rank is still using.
537 # Global shmem init/finalize belongs to the framework/caller (the545 # Global shmem init/finalize belongs to the framework/caller (the
538 # Buffer does not shmem_finalize itself).546 # Buffer does not shmem_finalize itself).
547+ allocations = [tensor._vmm_allocation for record in self._shared_sources
548+ for tensor in record[1:]]
549+ self._shared_views.clear()
550+ self._shared_sources.clear()
551+ for allocation in allocations:
552+ allocation.destroy()
539 for op in ctx['kernels'].values():553 for op in ctx['kernels'].values():
540 op.destroy()554 op.destroy()
541 for name in (555 for name in (
@@ -617,6 +631,14 @@ class Buffer:
617 router_weights_zero_copy: bool = False,631 router_weights_zero_copy: bool = False,
618 ) -> None:632 ) -> None:
619 stream = torch_npu.npu.current_stream().npu_stream633 stream = torch_npu.npu.current_stream().npu_stream
634+ if self._operation is not None:
635+ self._checked_stream()
636+ if not inter_rank_sync:
637+ raise RuntimeError('strict dispatch requires peer-ready barrier')
638+ self._peer_fence(complete=True) # previous peer readers finished before clear.
639+ ctx['hidden_buf_local'].zero_()
640+ if route_weights_sk is not None:
641+ ctx['weights_buf_local'].zero_()
620 if inter_rank_sync:642 if inter_rank_sync:
621 cross_rank_barrier(ctx, stream)643 cross_rank_barrier(ctx, stream)
622 644 
@@ -626,6 +648,10 @@ class Buffer:
626 ctx, topk_flat, tokens_per_expert, cu_seqlens, plan,648 ctx, topk_flat, tokens_per_expert, cu_seqlens, plan,
627 shmem_instance_id=0)649 shmem_instance_id=0)
628 650 
651+ if self._operation is not None:
652+ prefix = planning_args[2] if planning_args is not None else plan.carrier_cu_seqlens
653+ self._check_dispatch_capacity(prefix)
654+ 
629 ctx['kernels']['dispatch'].compute(655 ctx['kernels']['dispatch'].compute(
630 ctx,656 ctx,
631 hidden_sh,657 hidden_sh,
@@ -827,6 +853,7 @@ class Buffer:
827 inter_rank_sync: bool = True,853 inter_rank_sync: bool = True,
828 zero_copy: bool = False,854 zero_copy: bool = False,
829 router_weights_zero_copy: bool = False,855 router_weights_zero_copy: bool = False,
856+ native_counts: bool = False,
830 ):857 ):
831 """dispatch fwd: run planning (unless reusing a plan) and scatter tokens858 """dispatch fwd: run planning (unless reusing a plan) and scatter tokens
832 to their expert-grouped positions on remote ranks.859 to their expert-grouped positions on remote ranks.
@@ -836,16 +863,30 @@ class Buffer:
836 into via the peer address), and ``router_weights_zero_copy`` independently863 into via the peer address), and ``router_weights_zero_copy`` independently
837 returns the ``route_weights_nvs`` fp32 view of ``weights_buf_local``864 returns the ``route_weights_nvs`` fp32 view of ``weights_buf_local``
838 instead of a fresh copy (default False, matching the CUDA API).865 instead of a fresh copy (default False, matching the CUDA API).
866+ ``native_counts=True`` is strict/fresh-plan only: no compatibility
867+ histogram is supplied; the existing native planner counts topk IDs.
839 """868 """
840 ctx = self._require_ctx()869 ctx = self._require_ctx()
841 self._ensure_shmem_views()870 self._ensure_shmem_views()
871+ if self._operation is not None:
872+ self._require_operation()
873+ if async_finish or (not self._operation['activation_copy'] and (
874+ not zero_copy or (route_weights_sk is not None and not router_weights_zero_copy))):
875+ raise RuntimeError('strict dispatch requires synchronous C/P zero-copy')
876+ if plan is not None:
877+ self._check_shared_plan(plan)
842 878 
879+ if type(native_counts) is not bool:
880+ raise TypeError('native_counts must be bool')
881+ if native_counts and (self._operation is None or plan is not None or tokens_per_expert is not None):
882+ raise ValueError('native_counts requires a fresh strict plan and tokens_per_expert=None')
843 if plan is None:883 if plan is None:
844- assert topk_experts_sk is not None and tokens_per_expert is not None884+ assert topk_experts_sk is not None
845 topk_flat = topk_experts_sk.reshape(-1)885 topk_flat = topk_experts_sk.reshape(-1)
846 assert topk_flat.dtype == torch.int32 and topk_flat.numel() == int(ctx['N'])886 assert topk_flat.dtype == torch.int32 and topk_flat.numel() == int(ctx['N'])
847- assert tokens_per_expert.dtype == torch.int32887+ if not native_counts:
848- assert tokens_per_expert.numel() == int(ctx['E']) and tokens_per_expert.is_contiguous()888+ assert tokens_per_expert is not None and tokens_per_expert.dtype == torch.int32
889+ assert tokens_per_expert.numel() == int(ctx['E']) and tokens_per_expert.is_contiguous()
849 plan, cu_seqlens = allocate_planning_outputs(ctx)890 plan, cu_seqlens = allocate_planning_outputs(ctx)
850 planning_args = (topk_flat, tokens_per_expert, cu_seqlens)891 planning_args = (topk_flat, tokens_per_expert, cu_seqlens)
851 else:892 else:
@@ -865,8 +906,12 @@ class Buffer:
865 route_weights_nvs = torch.empty(906 route_weights_nvs = torch.empty(
866 ctx['NvS'], dtype=torch.float32, device=ctx['weights_buf'].device)907 ctx['NvS'], dtype=torch.float32, device=ctx['weights_buf'].device)
867 908 
909+ if self._operation is not None:
910+ self._operation['refs'].extend((hidden_sh, route_weights_sk,
911+ topk_experts_sk, tokens_per_expert, plan, cu_seqlens,
912+ hidden_nvsh, route_weights_nvs, planning_args))
868 if not async_finish:913 if not async_finish:
869- self._run_dispatch_on_current_stream(914+ self._shared_invoke(self._run_dispatch_on_current_stream,
870 ctx,915 ctx,
871 hidden_sh,916 hidden_sh,
872 route_weights_sk,917 route_weights_sk,
@@ -1003,6 +1048,11 @@ class Buffer:
1003 """combine fwd: gather expert outputs from the symmetric shard and1048 """combine fwd: gather expert outputs from the symmetric shard and
1004 K-sum back to token-major [S, H]. Also serves as dispatch bwd."""1049 K-sum back to token-major [S, H]. Also serves as dispatch bwd."""
1005 ctx = self._require_ctx()1050 ctx = self._require_ctx()
1051+ if self._operation is not None:
1052+ self._check_shared_plan(plan)
1053+ if async_finish or (not self._operation['activation_copy'] and (
1054+ not zero_copy or (route_weights_nvs is not None and not router_weights_zero_copy))):
1055+ raise RuntimeError('strict combine requires synchronous C/P zero-copy')
1006 self._ensure_shmem_views()1056 self._ensure_shmem_views()
1007 1057 
1008 assert isinstance(plan, MoonEPCommPlan), "Buffer.combine: plan is required"1058 assert isinstance(plan, MoonEPCommPlan), "Buffer.combine: plan is required"
@@ -1044,8 +1094,11 @@ class Buffer:
1044 if route_weights_nvs is not None else None1094 if route_weights_nvs is not None else None
1045 )1095 )
1046 1096 
1097+ if self._operation is not None:
1098+ self._operation['refs'].extend((plan, hidden_nvsh, route_weights_nvs,
1099+ hidden_sh, route_weights_sk))
1047 if not async_finish:1100 if not async_finish:
1048- self._run_combine_on_current_stream(1101+ self._shared_invoke(self._run_combine_on_current_stream,
1049 ctx,1102 ctx,
1050 hidden_sh,1103 hidden_sh,
1051 plan,1104 plan,
@@ -1132,6 +1185,7 @@ class Buffer:
1132 ),1185 ),
1133 reduce_buffers: Sequence[torch.Tensor] | None = None,1186 reduce_buffers: Sequence[torch.Tensor] | None = None,
1134 async_finish: bool = False,1187 async_finish: bool = False,
1188+ *, local_dense: bool = False, transport: str | None = None,
1135 ):1189 ):
1136 """Reduce an arbitrary non-empty sequence of projection gradients.1190 """Reduce an arbitrary non-empty sequence of projection gradients.
1137 1191 
@@ -1147,6 +1201,12 @@ class Buffer:
1147 For source compatibility, callers may alternatively pass separate1201 For source compatibility, callers may alternatively pass separate
1148 ``projection_grads`` and ``reduce_buffers`` sequences.1202 ``projection_grads`` and ``reduce_buffers`` sequences.
1149 """1203 """
1204+ if local_dense:
1205+ if reduce_buffers is not None:
1206+ raise ValueError('local_dense uses explicit (head,slot) pairs')
1207+ return self._reduce_local_dense(plan, projection_grads, transport, async_finish)
1208+ if transport is not None:
1209+ raise ValueError('transport override requires local_dense=True')
1150 ctx = self._require_ctx()1210 ctx = self._require_ctx()
1151 assert isinstance(plan, MoonEPCommPlan), \1211 assert isinstance(plan, MoonEPCommPlan), \
1152 "Buffer.reduce_projection_grads: plan is required"1212 "Buffer.reduce_projection_grads: plan is required"
@@ -361,6 +361,7 @@ def launch_grad_reduce(
361 meta_stride: int,361 meta_stride: int,
362 barrier_off: int,362 barrier_off: int,
363 grid_sync_bar: torch.Tensor,363 grid_sync_bar: torch.Tensor,
364+ use_udma: bool | None = None,
364) -> None:365) -> None:
365 """Accumulate symmetric reduce slots into owner gradients.366 """Accumulate symmetric reduce slots into owner gradients.
366 367 
@@ -414,5 +415,5 @@ def launch_grad_reduce(
414 B,415 B,
415 rank,416 rank,
416 min(num_sms, 64),417 min(num_sms, 64),
417- _env_use_udma('grad_reduce'),418+ _env_use_udma('grad_reduce') if use_udma is None else bool(use_udma),
418 )419 )
@@ -80,7 +80,8 @@ if(ASCEND_MOONEP_UDMA)
80 kernels/moonep_combine_udma.cpp80 kernels/moonep_combine_udma.cpp
81 kernels/moonep_dispatch_udma.cpp81 kernels/moonep_dispatch_udma.cpp
82 kernels/moonep_grad_reduce_udma.cpp82 kernels/moonep_grad_reduce_udma.cpp
83- kernels/prefetch_udma.cpp)83+ kernels/prefetch_udma.cpp
84+ kernels/prefetch_pointer_push_udma.cpp)
84else()85else()
85 set(ASCEND_MOONEP_UDMA_KERNEL_SOURCES "")86 set(ASCEND_MOONEP_UDMA_KERNEL_SOURCES "")
86endif()87endif()
@@ -76,7 +76,8 @@ bool acquire_init_path(InitPath requested) {
76 static_cast<int>(requested), ", current path ",76 static_cast<int>(requested), ", current path ",
77 static_cast<int>(g_init_path),77 static_cast<int>(g_init_path),
78 "); two shmem init paths must not mix");78 "); two shmem init paths must not mix");
79- return false; // same-path idempotent79+ TORCH_CHECK(false, "native SHMEM init cannot repeat; Python must verify the frozen signature");
80+ return false;
80}81}
81 82 
82int64_t elem_size(at::ScalarType dtype) {83int64_t elem_size(at::ScalarType dtype) {
@@ -602,6 +603,7 @@ static int init_with_buffers_impl(
602 attr.ip_port[ip_port.size()] = '\0';603 attr.ip_port[ip_port.size()] = '\0';
603 attr.comm_args = nullptr;604 attr.comm_args = nullptr;
604 }605 }
606+ attr.runtime_config.udma_shared_jetty = ACLSHMEM_CONFIG_DISABLED;
605 attr.option_attr.data_op_engine_type =607 attr.option_attr.data_op_engine_type =
606 static_cast<data_op_engine_type_t>(data_op_engine_type);608 static_cast<data_op_engine_type_t>(data_op_engine_type);
607 609 
@@ -3,6 +3,8 @@
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>
7+#include "shmem.h"
6 8 
7#include <torch_npu/csrc/core/npu/NPUStream.h>9#include <torch_npu/csrc/core/npu/NPUStream.h>
8 10 
@@ -118,4 +120,60 @@ torch::Tensor LaunchPrefetch(
118 return prefetch_buffers;120 return prefetch_buffers;
119}121}
120 122 
123+bool PrefetchPushPointersAvailable() {
124+ #if defined(ASCEND_MOONEP_UDMA)
125+ return prefetch_pointer_push_udma_available() == 1;
126+#else
127+ return false;
128+#endif
129+}
130+ 
131+namespace {
132+int64_t CheckPushProjection(const torch::Tensor& source, const torch::Tensor& slots,
133+ const torch::Tensor& plan, int64_t local_experts) {
134+ CheckNpuContiguous(source, "source");
135+ CheckNpuContiguous(slots, "slots");
136+ CheckNpuContiguous(plan, "plan");
137+ TORCH_CHECK(source.device() == slots.device() && slots.device() == plan.device(),
138+ "source, slots and plan must share one NPU");
139+ TORCH_CHECK(slots.scalar_type() == torch::kBFloat16 &&
140+ plan.scalar_type() == torch::kInt32 && slots.dim() == 3 && plan.dim() == 2,
141+ "expected BF16 slots[B,M,N] and INT32 plan[EP,B]");
142+ const int64_t ep = plan.size(0);
143+ TORCH_CHECK(ep > 0 && ep == aclshmem_n_pes() && local_experts > 0 &&
144+ local_experts <= INT32_MAX / ep,
145+ "local expert count or SHMEM topology differs");
146+ TORCH_CHECK(plan.size(1) == slots.size(0) && slots.size(0) <= 15736 &&
147+ slots.size(1) > 0 && slots.size(2) > 0 &&
148+ slots.size(1) <= std::numeric_limits<int64_t>::max() / slots.size(2),
149+ "invalid projection, slots or URMA UB extent");
150+ return slots.size(1) * slots.size(2);
151+}
152+}
153+ 
154+torch::Tensor LaunchPrefetchPushPointers(torch::Tensor pointers, torch::Tensor slots,
155+ torch::Tensor plan, int64_t local_experts) {
156+ TORCH_CHECK(PrefetchPushPointersAvailable(), "URMA pointer PUSH unavailable; no MTE fallback");
157+ const int64_t elements = CheckPushProjection(pointers, slots, plan, local_experts);
158+ TORCH_CHECK(pointers.scalar_type() == torch::kInt64 && pointers.dim() == 1 &&
159+ pointers.numel() == local_experts, "expected INT64 pointer table[L]");
160+ aclrtStream stream = c10_npu::getCurrentNPUStream().stream();
161+ TORCH_CHECK(stream != nullptr, "Q1 drain failed; stream is null");
162+ aclshmemx_barrier_all_on_stream(stream);
163+ #if defined(ASCEND_MOONEP_UDMA)
164+ TORCH_CHECK(moonep_prefetch_pointer_push_udma(stream,
165+ reinterpret_cast<uint8_t*>(pointers.data_ptr()),
166+ reinterpret_cast<uint8_t*>(slots.data_ptr()),
167+ reinterpret_cast<uint8_t*>(plan.data_ptr()),
168+ local_experts * plan.size(0), elements, slots.size(0)) == 0,
169+ "URMA pointer PUSH launch unavailable");
170+ #else
171+ TORCH_CHECK(false, "URMA unavailable in this build");
172+ #endif
173+ TORCH_CHECK(stream != nullptr, "Q1 drain failed; stream is null");
174+ aclshmemx_barrier_all_on_stream(stream);
175+ return slots;
176+}
177+ 
178+ 
121} // namespace ascend_moonep::ops179} // namespace ascend_moonep::ops
@@ -12,4 +12,8 @@ torch::Tensor LaunchPrefetch(
12 int64_t instance_id,12 int64_t instance_id,
13 bool use_udma);13 bool use_udma);
14 14 
15+bool PrefetchPushPointersAvailable();
16+torch::Tensor LaunchPrefetchPushPointers(torch::Tensor pointers, torch::Tensor slots,
17+ torch::Tensor plan, int64_t local_experts);
18+ 
15} // namespace ascend_moonep::ops19} // namespace ascend_moonep::ops
@@ -1,8 +1,12 @@
1#include <torch/extension.h>1#include <torch/extension.h>
2+#include <acl/acl.h>
2 3 
3#include "acl_shared_buffer.h"4#include "acl_shared_buffer.h"
4#include "launcher.h"5#include "launcher.h"
5#include "shmem.h"6#include "shmem.h"
7+#include "csrc/ops/prefetch.h"
8+#include <torch_npu/csrc/core/npu/NPUStream.h>
9+#include <torch_npu/csrc/core/npu/NPUGraphsUtils.h>
6 10 
7PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {11PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
8 m.doc() = "MoonEP NPU symmetric-memory extension (shmem C++ backend)";12 m.doc() = "MoonEP NPU symmetric-memory extension (shmem C++ backend)";
@@ -12,6 +16,36 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
12 py::int_(sizeof(aclshmemx_buffer_optional_attr_t));16 py::int_(sizeof(aclshmemx_buffer_optional_attr_t));
13 17 
14 using py::arg;18 using py::arg;
19+ m.attr("SHARED_SLOTS_ABI") = 1;
20+ m.def("shared_slots_stream", [](int device, uint64_t expected, bool complete) {
21+ int actual = -1;
22+ TORCH_CHECK(aclrtGetDevice(&actual) == ACL_SUCCESS && actual == device,
23+ "shared slots device changed");
24+ TORCH_CHECK(c10_npu::currentStreamCaptureStatusMayInitCtx() ==
25+ c10_npu::CaptureStatus::None, "graph capture is unsupported");
26+ auto current = c10_npu::getCurrentNPUStream(device);
27+ auto raw = current.stream();
28+ TORCH_CHECK(raw != nullptr, "Q1 queue drain failed");
29+ TORCH_CHECK(expected == 0 || expected == reinterpret_cast<uint64_t>(raw),
30+ "operation current stream changed");
31+ // Public synchronize rejects external streams. Begin also completes
32+ // once to establish this admission check; subsequent raw checks do not.
33+ if (complete) {
34+ current.synchronize(); // also rejects external streams.
35+ TORCH_CHECK(current.stream() == raw, "Q1 stream changed after completion");
36+ TORCH_CHECK(aclrtSynchronizeStream(raw) == ACL_SUCCESS,
37+ "captured stream completion failed");
38+ }
39+ return reinterpret_cast<uint64_t>(raw);
40+ });
41+ m.def("shared_slots_qp0", [](int peer) {
42+ aclshmemx_net_layer_t layer = ACLSHMEM_NET_LAYER_DEFAULT;
43+ int rc = aclshmemx_get_qp_net_layer(ACLSHMEM_DATA_OP_UDMA, peer, 0, &layer);
44+ return py::make_tuple(rc, static_cast<uint32_t>(layer));
45+ });
46+ m.def("prefetch_push_pointers_available", &ascend_moonep::ops::PrefetchPushPointersAvailable);
47+ m.def("prefetch_push_pointers", &ascend_moonep::ops::LaunchPrefetchPushPointers);
48+ 
15 49 
16 m.def("launch_device_barrier_bench", &LaunchDeviceBarrierBench,50 m.def("launch_device_barrier_bench", &LaunchDeviceBarrierBench,
17 arg("iterations"), arg("block_dim") = 32,51 arg("iterations"), arg("block_dim") = 32,
@@ -156,4 +156,8 @@ ASCEND_MOONEP_EXPORT void prefetch_weight_kernel_udma_do(
156 int64_t num_slots,156 int64_t num_slots,
157 int64_t block_dim);157 int64_t block_dim);
158 158 
159+ASCEND_MOONEP_EXPORT int prefetch_pointer_push_udma_available();
160+ASCEND_MOONEP_EXPORT int moonep_prefetch_pointer_push_udma(
161+ void*, uint8_t*, uint8_t*, uint8_t*, int64_t, int64_t, int64_t);
162+ 
159} // extern "C"163} // extern "C"
@@ -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,33 @@
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+extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__
17+void prefetch_pointer_push_udma(GM_ADDR pointers, GM_ADDR slots, GM_ADDR plan,
18+ int64_t experts, int64_t row_elements, int64_t num_slots) {
19+ moonep_urma_push::Run<true>(pointers,slots,plan,experts,row_elements,num_slots);
20+}
21+extern "C" ASCEND_MOONEP_EXPORT int prefetch_pointer_push_udma_available() { return 1; }
22+extern "C" ASCEND_MOONEP_EXPORT int moonep_prefetch_pointer_push_udma(
23+ void* stream, uint8_t* pointers, uint8_t* slots, uint8_t* plan,
24+ int64_t experts, int64_t row_elements, int64_t num_slots) {
25+ prefetch_pointer_push_udma<<<1,nullptr,stream>>>(pointers,slots,plan,experts,row_elements,num_slots);
26+ return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL);
27+}
28+#else
29+extern "C" ASCEND_MOONEP_EXPORT int moonep_prefetch_barrier_vec(void*) { return -1; }
30+extern "C" ASCEND_MOONEP_EXPORT int prefetch_pointer_push_udma_available() { return 0; }
31+extern "C" ASCEND_MOONEP_EXPORT int moonep_prefetch_pointer_push_udma(
32+ void*,uint8_t*,uint8_t*,uint8_t*,int64_t,int64_t,int64_t) { return -1; }
33+#endif
@@ -273,7 +273,7 @@ class GradReduceOp(KernelOp):
273 """273 """
274 274 
275 def compute(self, ctx, full_grad_home, reduce_buffer, experts_to_copy,275 def compute(self, ctx, full_grad_home, reduce_buffer, experts_to_copy,
276- rank, num_sms, shmem_instance_id: int = 0):276+ rank, num_sms, shmem_instance_id: int = 0, use_udma=None):
277 # full_grad_home is this rank's physical epn-row owner chunk;277 # full_grad_home is this rank's physical epn-row owner chunk;
278 # reduce_buffer is this rank's B-row symmetric contribution chunk.278 # reduce_buffer is this rank's B-row symmetric contribution chunk.
279 R = int(ctx["R"]); E = int(ctx["E"]); B = int(ctx["B"])279 R = int(ctx["R"]); E = int(ctx["E"]); B = int(ctx["B"])
@@ -321,4 +321,5 @@ class GradReduceOp(KernelOp):
321 meta_stride=0,321 meta_stride=0,
322 barrier_off=0,322 barrier_off=0,
323 grid_sync_bar=None,323 grid_sync_bar=None,
324+ use_udma=use_udma,
324 )325 )
@@ -32,6 +32,9 @@ class MoonEPCommPlan:
32 dup_loffs: torch.Tensor32 dup_loffs: torch.Tensor
33 dup_counts: torch.Tensor33 dup_counts: torch.Tensor
34 34 
35+ carrier_cu_seqlens: object = None
36+ origin: object = None
37+ 
35 def __post_init__(self) -> None:38 def __post_init__(self) -> None:
36 N = int(self.N)39 N = int(self.N)
37 R = int(self.R)40 R = int(self.R)
@@ -70,6 +73,9 @@ class MoonEPCommPlan:
70 B=self.B,73 B=self.B,
71 NvS=self.NvS,74 NvS=self.NvS,
72 K=self.K,75 K=self.K,
76+ carrier_cu_seqlens=(self.carrier_cu_seqlens.clone()
77+ if self.carrier_cu_seqlens is not None else None),
78+ origin=self.origin,
73 )79 )
74 80 
75 81 
@@ -122,5 +128,7 @@ def allocate_planning_outputs(ctx: dict):
122 B=B,128 B=B,
123 NvS=NvS,129 NvS=NvS,
124 K=K,130 K=K,
131+ carrier_cu_seqlens=cu_seqlens,
132+ origin=ctx.get("_shared_plan_origin"),
125 )133 )
126 return plan, cu_seqlens134 return plan, cu_seqlens
@@ -0,0 +1,417 @@
1+"""Default-off synchronous shared-slot extensions on the existing Buffer owner.
2+ 
3+No home registration, home mirror, transport fallback or native math operator.
4+All ranks must invoke operations/projections in the same order. A failed
5+submission poisons this owner; process termination is the recovery policy.
6+"""
7+import os
8+import hashlib
9+import weakref
10+ 
11+_POISONED_BUFFERS = [] # Failure quarantine intentionally survives Python GC.
12+ 
13+ 
14+def _dependencies():
15+ import torch
16+ from . import _C
17+ from . import buffer_c
18+ from .shmem_runtime import ShmemRuntime
19+ return torch, _C, buffer_c, ShmemRuntime
20+ 
21+ 
22+class SharedSlotsMixin:
23+ def _init_shared_slots(self):
24+ self._shared_sources = []
25+ self._shared_views = {}
26+ self._native_keepalive = []
27+ self._operation = None
28+ self._live_calls = {}
29+ self._capacity = None
30+ self._binding_refs = []
31+ self._control_keepalive = []
32+ self._shared_poisoned = False
33+ self._plan_origin = object()
34+ self._ctx['_shared_plan_origin'] = self._plan_origin
35+ runtime = _dependencies()[3]
36+ if not hasattr(runtime, '_buffer_refs'):
37+ runtime._buffer_refs = []
38+ runtime._buffer_refs.append(weakref.ref(self))
39+ 
40+ def register_binding(self, binding):
41+ """Register a caller-owned binding; it must support weak references.
42+ 
43+ Returned slot tensors are borrowed. Before finalize/destroy the caller
44+ must drop every binding AND every derived/external slot tensor alias.
45+ Weak binding checks cover registered holders, not arbitrary Tensor views.
46+ """
47+ self._binding_refs[:] = [ref for ref in self._binding_refs if ref() is not None]
48+ if not any(ref() is binding for ref in self._binding_refs):
49+ self._binding_refs.append(weakref.ref(binding))
50+ 
51+ def assert_no_bindings(self):
52+ if any(ref() is not None for ref in self._binding_refs):
53+ raise RuntimeError('detach/release every shared-slot binding before shutdown')
54+ 
55+ def configure_capacity(self, max_live_contexts, live_context_bytes):
56+ """Freeze this existing owner's context count and retained-byte limits."""
57+ runtime = _dependencies()[3]
58+ if (self._capacity is not None or self._operation or self._live_calls
59+ or runtime.is_initialized() or getattr(runtime, '_init_signature', None) is not None):
60+ raise RuntimeError('capacity must be configured once before SHMEM initialization')
61+ if any(type(v) is not int or not 0 < v < 2**63
62+ for v in (max_live_contexts, live_context_bytes)):
63+ raise ValueError('positive int64 context and retained-byte limits are required')
64+ self._capacity = (max_live_contexts, live_context_bytes)
65+ 
66+ def register_shared_projection(self, shape):
67+ """Register [B,O,I] W/G source backing before the one SHMEM init."""
68+ torch, _, memory, runtime = _dependencies()
69+ if (runtime.is_initialized() or runtime._poisoned
70+ or getattr(runtime, "_init_signature", None) is not None
71+ or self._operation or self._shared_poisoned):
72+ raise RuntimeError('shared projection registration must precede init')
73+ shape = tuple(shape)
74+ if len(shape) != 2 or any(type(n) is not int or n <= 0 for n in shape):
75+ raise ValueError('projection shape must contain two positive integers')
76+ ctx = self._require_ctx()
77+ if ctx['B'] != ctx['E'] // ctx['R'] or ctx['E'] % ctx['R']:
78+ raise RuntimeError('strict slots requires B=L and E divisible by EP')
79+ for index, record in enumerate(self._shared_sources):
80+ if record[0] == shape:
81+ return index
82+ allocated = []
83+ try:
84+ for dtype in (torch.bfloat16, torch.float32):
85+ tensor, _, _ = memory.create_vmm_physical(
86+ (ctx['B'], *shape), dtype, ctx['device'])
87+ allocated.append(tensor) # Registration submits no device work.
88+ except BaseException:
89+ self._native_keepalive.extend(allocated)
90+ try:
91+ for tensor in allocated:
92+ tensor._vmm_allocation.destroy()
93+ except BaseException:
94+ self.poison_and_retain()
95+ raise
96+ self._native_keepalive[:] = [value for value in self._native_keepalive
97+ if not any(value is tensor for tensor in allocated)]
98+ raise
99+ self._shared_sources.append((shape, *allocated))
100+ return len(self._shared_sources) - 1
101+ 
102+ def shared_slots(self, projection_index):
103+ _, _, memory, runtime = _dependencies()
104+ if not runtime.is_initialized() or runtime._poisoned or self._shared_poisoned:
105+ raise RuntimeError('healthy initialized runtime is required')
106+ if type(projection_index) is not int or not 0 <= projection_index < len(self._shared_sources):
107+ raise ValueError('unknown projection index')
108+ if projection_index not in self._shared_views:
109+ _, weight, grad = self._shared_sources[projection_index]
110+ self._shared_views[projection_index] = (memory.sym_tensor(weight), memory.sym_tensor(grad))
111+ return self._shared_views[projection_index]
112+ 
113+ def _checked_stream(self, complete=False):
114+ _, native, _, _ = _dependencies()
115+ ctx = self._require_ctx()
116+ expected = self._operation['stream'] if self._operation else 0
117+ try:
118+ return native.shared_slots_stream(int(ctx['device']), expected, complete)
119+ except BaseException:
120+ self.poison_and_retain()
121+ raise
122+ 
123+ def begin_operation(self, call_id, *, admission_error=False, context_bytes=0, activation_copy=False):
124+ """Collectively admit one operation before any peer-native barrier.
125+ 
126+ identity=(layer, virtual_pipeline, microbatch, sequence), all int64.
127+ A broken device/control collective cannot promise coordinated recovery:
128+ poison and external process-group/job timeout are mandatory then.
129+ """
130+ torch, native, _, runtime = _dependencies()
131+ ctx = self._require_ctx() # Destroyed owners have no usable control group.
132+ frozen = getattr(runtime, '_init_signature', None)
133+ control_group = runtime._init_group if frozen is not None else ctx.get('group')
134+ control_size = frozen[3] if frozen is not None else int(ctx['R'])
135+ stream, failure = 0, None
136+ header = [0] * 16
137+ try:
138+ if type(activation_copy) is not bool:
139+ raise ValueError('activation_copy must be an explicit bool')
140+ if type(admission_error) is not bool or admission_error:
141+ raise RuntimeError('caller preflight rejected this operation')
142+ if self._shared_poisoned or runtime._poisoned:
143+ raise RuntimeError('poisoned shared-slot owner')
144+ if self._operation is not None or runtime._active_operations:
145+ raise RuntimeError('shared-slot operation is already active')
146+ if (not isinstance(call_id, tuple) or len(call_id) != 2
147+ or call_id[1] not in ('forward', 'backward')):
148+ raise ValueError('call_id must be (identity, forward/backward)')
149+ identity, phase = call_id
150+ if self._capacity is None or type(context_bytes) is not int or not 0 <= context_bytes < 2**63:
151+ raise ValueError('frozen capacity and a nonnegative int64 charge are required')
152+ if phase == 'forward' and (len(self._live_calls) >= self._capacity[0]
153+ or sum(self._live_calls.values()) + context_bytes > self._capacity[1]):
154+ raise RuntimeError('live context count or retained-byte capacity exceeded')
155+ if phase == 'backward' and context_bytes:
156+ raise ValueError('backward must not charge a second context')
157+ if (not isinstance(identity, tuple) or len(identity) != 4
158+ or any(type(v) is not int or not 0 <= v < 2**63 for v in identity)):
159+ raise ValueError('identity must be four nonnegative int64 values')
160+ layout = tuple(record[0] for record in self._shared_sources)
161+ digest = hashlib.sha256(repr(layout).encode('ascii')).digest()
162+ header = [*identity, int(phase == 'backward') + 2 * activation_copy,
163+ *[int(ctx[key]) for key in ('R', 'E', 'B', 'S', 'K', 'H')],
164+ len(layout), *[int.from_bytes(digest[i:i+8], 'little') & (2**63-1)
165+ for i in (0, 8)], *self._capacity]
166+ if any(not 0 <= value < 2**63 for value in header):
167+ raise ValueError('operation header exceeds int64 range')
168+ if ((phase == 'forward' and identity in self._live_calls)
169+ or (phase == 'backward' and identity not in self._live_calls)):
170+ raise RuntimeError('duplicate forward or backward without live forward')
171+ if not runtime.is_initialized() or not runtime._udma_enabled:
172+ raise RuntimeError('shared slots needs one MTE|UDMA buffer init')
173+ if frozen is not None and frozen[6] != 2:
174+ raise RuntimeError('strict slots requires frozen qp_count=2')
175+ if not runtime.matches_group(ctx.get('group'), ctx['device'], ctx['rank'], ctx['R']):
176+ raise RuntimeError('Buffer topology/device differs from frozen SHMEM session')
177+ if getattr(native, 'SHARED_SLOTS_ABI', None) != 1 or not native.prefetch_push_pointers_available():
178+ raise RuntimeError('shared slots native ABI/URMA PUSH unavailable')
179+ if ctx['_dispatch_use_udma'] or ctx['_combine_use_udma'] or ctx['_planning_use_udma']:
180+ raise RuntimeError('strict profile requires MTE activation and planning')
181+ if int(ctx['num_sms']) != 32 or ctx['E'] % ctx['R'] or ctx['B'] != ctx['E'] // ctx['R']:
182+ raise RuntimeError('strict profile requires num_sms=32 and B=L')
183+ if os.environ.get('ASCEND_MOONEP_ASYNC_BARRIER', '1').lower() in ('0', 'false', 'off'):
184+ raise RuntimeError('strict profile requires on-stream peer barriers')
185+ if torch.npu.memory.get_allocator_backend() != 'native':
186+ raise RuntimeError('strict profile requires native caching allocator')
187+ # Public synchronize rejects external streams. No peer-native call
188+ # may happen before the control collective below accepts all PEs.
189+ stream = self._checked_stream(complete=True)
190+ self._ensure_shmem_views()
191+ for index in range(len(self._shared_sources)):
192+ self.shared_slots(index) # All local aliases must map before collective admission.
193+ routes = [native.shared_slots_qp0(peer)
194+ for peer in range(ctx['R']) if peer != ctx['rank']]
195+ if not all(rc == 0 and layer in (0, 1) for rc, layer in routes):
196+ raise RuntimeError('all-peer QP0 route admission failed')
197+ except BaseException as error:
198+ failure = error
199+ try:
200+ low = torch.tensor([int(failure is None), *header], dtype=torch.int64,
201+ device=ctx['hidden_buf'].device)
202+ high = low.clone()
203+ self._control_keepalive[:] = [low, high]
204+ if control_size > 1:
205+ import torch.distributed as dist
206+ dist.all_reduce(low, op=dist.ReduceOp.MIN, group=control_group)
207+ dist.all_reduce(high, op=dist.ReduceOp.MAX, group=control_group)
208+ accepted = bool(low[0].item()) and bool(torch.equal(low, high))
209+ except BaseException:
210+ self.poison_and_retain()
211+ raise
212+ self._control_keepalive.clear()
213+ if not accepted:
214+ raise RuntimeError('all-rank operation admission/header agreement rejected') from failure
215+ self._operation = dict(id=call_id, stream=stream, refs=[], calls=[], grad_ready=set(),
216+ activation_copy=activation_copy,
217+ context_bytes=context_bytes)
218+ runtime._active_operations += 1
219+ try:
220+ self._peer_fence(complete=True)
221+ except BaseException:
222+ self.poison_and_retain()
223+ raise
224+ return self
225+ 
226+ def _peer_fence(self, complete=False):
227+ _, native, _, _ = _dependencies()
228+ stream = self._checked_stream()
229+ native.acl_shmem_barrier_all_on_stream(stream)
230+ if complete:
231+ self._checked_stream(complete=True)
232+ 
233+ def _check_dispatch_capacity(self, prefix):
234+ """Validate the device prefix before any token payload dispatch.
235+ 
236+ Only the reduced error flag is read by the host, never token counts.
237+ A device/control failure poisons the owner and needs job termination.
238+ """
239+ torch, _, _, runtime = _dependencies()
240+ ctx = self._require_ctx()
241+ try:
242+ valid = (prefix is not None and prefix.dtype == torch.int32
243+ and prefix.device == ctx['hidden_buf'].device
244+ and tuple(prefix.shape) == (ctx['E'] + ctx['B'],)
245+ and prefix.is_contiguous())
246+ if valid:
247+ bad = ((prefix < 0).any() | (prefix[1:] < prefix[:-1]).any()
248+ | (prefix[-1] > int(ctx['NvS'])))
249+ error = bad.to(dtype=torch.int32).reshape(1)
250+ else:
251+ error = torch.tensor([1], dtype=torch.int32, device=ctx['hidden_buf'].device)
252+ self._control_keepalive[:] = [prefix, error]
253+ frozen = getattr(runtime, '_init_signature', None)
254+ size = frozen[3] if frozen is not None else int(ctx['R'])
255+ group = runtime._init_group if frozen is not None else ctx.get('group')
256+ if size > 1:
257+ import torch.distributed as dist
258+ dist.all_reduce(error, op=dist.ReduceOp.MAX, group=group)
259+ rejected = bool(error.item())
260+ except BaseException:
261+ self.poison_and_retain()
262+ raise
263+ self._control_keepalive.clear()
264+ if rejected:
265+ raise RuntimeError('all-rank native plan prefix/capacity check rejected before dispatch')
266+ 
267+ def _shared_invoke(self, function, *args, **kwargs):
268+ try:
269+ return function(*args, **kwargs)
270+ except BaseException:
271+ if self._operation is not None:
272+ self.poison_and_retain()
273+ raise
274+ 
275+ def _require_operation(self):
276+ if self._shared_poisoned or self._operation is None:
277+ raise RuntimeError('healthy begin_operation is required')
278+ self._checked_stream()
279+ return self._operation
280+ 
281+ def retain_native(self, call):
282+ op = self._require_operation()
283+ if not any(value is call for value in self._native_keepalive):
284+ self._native_keepalive.append(call)
285+ op['calls'].append(call)
286+ 
287+ def release_native_after_local_complete(self, call):
288+ self._require_operation()
289+ try:
290+ self._checked_stream(complete=True)
291+ except BaseException:
292+ self.poison_and_retain()
293+ raise
294+ self._native_keepalive[:] = [value for value in self._native_keepalive if value is not call]
295+ self._operation['calls'][:] = [value for value in self._operation['calls'] if value is not call]
296+ 
297+ def poison_and_retain(self):
298+ self._shared_poisoned = True
299+ _dependencies()[3]._poisoned = True
300+ if not any(owner is self for owner in _POISONED_BUFFERS):
301+ _POISONED_BUFFERS.append(self)
302+ # Keep operation, Calls, plan, refs, pointer tables and all VMM owners.
303+ # No finalization, source unmap, native destructor or retry is safe here.
304+ 
305+ def end_operation(self):
306+ self._require_operation()
307+ try:
308+ self._checked_stream(complete=True)
309+ self._peer_fence(complete=True)
310+ except BaseException:
311+ self.poison_and_retain()
312+ raise
313+ identity, phase = self._operation['id']
314+ if phase == 'forward':
315+ self._live_calls[identity] = self._operation['context_bytes']
316+ _dependencies()[3]._live_contexts += 1
317+ else:
318+ del self._live_calls[identity]
319+ _dependencies()[3]._live_contexts -= 1
320+ self._native_keepalive.clear()
321+ _dependencies()[3]._active_operations -= 1
322+ self._operation = None
323+ 
324+ def assert_quiescent(self):
325+ if (self._shared_poisoned or _dependencies()[3]._poisoned
326+ or self._operation is not None or self._live_calls):
327+ raise RuntimeError('live/active/poisoned calls forbid update or destroy')
328+ 
329+ def _check_shared_plan(self, plan):
330+ self._require_operation()
331+ if getattr(plan, 'origin', None) is not self._plan_origin:
332+ raise RuntimeError('plan belongs to another Buffer/session')
333+ ctx = self._require_ctx()
334+ if (plan.R, plan.E, plan.B, plan.NvS) != (ctx['R'], ctx['E'], ctx['B'], ctx['NvS']):
335+ raise RuntimeError('plan shape differs from Buffer')
336+ 
337+ def _shared_slot_index(self, slot, gradient=False):
338+ for index in range(len(self._shared_sources)):
339+ expected = self.shared_slots(index)[int(gradient)]
340+ if (slot.data_ptr() == expected.data_ptr() and slot.device == expected.device
341+ and tuple(slot.shape) == tuple(expected.shape) and slot.dtype == expected.dtype
342+ and slot.is_contiguous() and not slot.is_neg() and not slot.is_conj()):
343+ return index
344+ raise RuntimeError('slot must be an exact registered symmetric view')
345+ 
346+ def zero_shared_grad(self, slot):
347+ """Before B target.add_; previous operation/final-use fence is required."""
348+ self._require_operation()
349+ index = self._shared_slot_index(slot, gradient=True)
350+ try:
351+ self._peer_fence(complete=True)
352+ slot.zero_()
353+ self._operation['grad_ready'].add(index)
354+ except BaseException:
355+ self.poison_and_retain()
356+ raise
357+ 
358+ def prefetch_projection_refs(self, plan, refs, slot, transport='urma'):
359+ torch, native, _, _ = _dependencies()
360+ self._check_shared_plan(plan)
361+ if transport != 'urma':
362+ raise ValueError('only explicit URMA PUSH is supported')
363+ self._shared_slot_index(slot)
364+ ctx = self._require_ctx()
365+ refs = tuple(refs)
366+ if len(refs) != ctx['E'] // ctx['R']:
367+ raise ValueError('one canonical pointer per local expert is required')
368+ if any(ref.dtype != torch.bfloat16 or not ref.is_contiguous() or ref.is_neg() or ref.is_conj() or
369+ tuple(ref.shape) != tuple(slot.shape[1:]) or ref.device != slot.device for ref in refs):
370+ raise ValueError('canonical refs must be contiguous BF16 [O,I] on slot device')
371+ op = self._operation
372+ op['refs'].extend((plan, refs, slot)) # BEFORE any uncertain submission.
373+ try:
374+ pointers = torch.tensor([ref.data_ptr() for ref in refs], dtype=torch.int64, device=slot.device)
375+ op['refs'].append(pointers)
376+ self._peer_fence(complete=True) # previous readers have finished.
377+ slot.zero_() # inactive slots cannot retain old weights/NaNs.
378+ self._peer_fence() # every PE's destination is ready before PUSH.
379+ self._checked_stream()
380+ native.prefetch_push_pointers(pointers, slot, plan.experts_to_copy, len(refs))
381+ self._checked_stream(complete=True)
382+ except BaseException:
383+ self.poison_and_retain()
384+ raise
385+ return slot
386+ 
387+ def _reduce_local_dense(self, plan, pairs, transport, async_finish):
388+ torch, _, _, _ = _dependencies()
389+ self._check_shared_plan(plan)
390+ if transport != 'urma' or async_finish:
391+ raise ValueError('local_dense supports synchronous explicit URMA only')
392+ ctx = self._require_ctx()
393+ pairs = tuple(pairs)
394+ if not pairs:
395+ raise ValueError('at least one gradient pair is required')
396+ for head, slot in pairs:
397+ index = self._shared_slot_index(slot, gradient=True)
398+ if index not in self._operation['grad_ready']:
399+ raise RuntimeError('zero_shared_grad must precede this projection producer')
400+ if (head.dtype != torch.float32 or not head.is_contiguous() or head.is_neg() or head.is_conj() or head.device != slot.device
401+ or tuple(head.shape) != (ctx['E'] // ctx['R'], *slot.shape[1:])):
402+ raise ValueError('GR head must be ordinary contiguous FP32 [L,O,I]')
403+ self._operation['refs'].extend((plan, pairs))
404+ try:
405+ self._peer_fence() # all rank wgrad/add producers precede native GR reads.
406+ for head, slot in pairs:
407+ self._checked_stream()
408+ ctx['kernels']['grad_reduce'].compute(
409+ ctx, head, slot, plan.experts_to_copy, rank=ctx['rank'],
410+ num_sms=ctx['num_sms'], shmem_instance_id=0, use_udma=True)
411+ self._checked_stream(complete=True) # includes native active-slot clear.
412+ self._peer_fence(complete=True) # final-use fence before any bank reuse.
413+ for _, slot in pairs:
414+ self._operation['grad_ready'].discard(self._shared_slot_index(slot, gradient=True))
415+ except BaseException:
416+ self.poison_and_retain()
417+ raise
@@ -24,6 +24,7 @@ mixed (do not mix).
24from __future__ import annotations24from __future__ import annotations
25 25 
26import os26import os
27+import hashlib
27 28 
28import torch29import torch
29import torch.distributed as dist30import torch.distributed as dist
@@ -39,7 +40,7 @@ from .buffer_c import (
39 shmem_init_with_buffer,40 shmem_init_with_buffer,
40 symmetric_descriptors,41 symmetric_descriptors,
41)42)
42-from ._C import acl_shmem_barrier_all, acl_shmem_get_unique_id43+from ._C import acl_shmem_barrier_all, acl_shmem_get_unique_id, shared_slots_stream
43from .runtime_audit import audit_loaded_shmem_library44from .runtime_audit import audit_loaded_shmem_library
44 45 
45 46 
@@ -94,6 +95,103 @@ class ShmemRuntime:
94 _initialized = False95 _initialized = False
95 _poisoned = False96 _poisoned = False
96 _runtime_library_record = None97 _runtime_library_record = None
98+ _init_signature = None
99+ _init_group = None
100+ _udma_enabled = False
101+ _active_operations = 0
102+ _live_contexts = 0
103+ _buffer_refs = []
104+ _control_keepalive = []
105+ 
106+ @classmethod
107+ def matches_group(cls, group, device, rank, size):
108+ sig = cls._init_signature
109+ return sig is not None and sig[:4] == (id(group), int(device), int(rank), int(size))
110+ 
111+ @classmethod
112+ def _prove_cached_allocator(cls, device):
113+ if torch.npu.memory.get_allocator_backend() != 'native':
114+ raise RuntimeError('strict SHMEM requires the native cached allocator')
115+ stream = shared_slots_stream(device, 0, False) # Reject capture before ordinary allocation.
116+ probe = torch.empty(1, dtype=torch.uint8, device=f'npu:{device}')
117+ cls._control_keepalive.append(probe)
118+ if probe.storage_offset() != 0 or probe.numel() != 1:
119+ raise RuntimeError('ordinary allocator probe layout changed')
120+ matches = []
121+ for segment in torch.npu.memory_snapshot():
122+ if type(segment.get('device')) is not int or segment['device'] != device:
123+ continue
124+ for block in segment.get('blocks', []):
125+ if type(block.get('address')) is int and block['address'] == probe.data_ptr():
126+ matches.append((segment, block))
127+ if len(matches) != 1:
128+ raise RuntimeError('ordinary probe lacks a unique exact cached block')
129+ segment, block = matches[0]
130+ if (block.get('state') != 'active_allocated'
131+ or any(type(block.get(k)) is not int for k in ('size', 'requested_size'))
132+ or not block['size'] >= block['requested_size'] >= probe.numel() * probe.element_size()
133+ or type(segment.get('total_size')) is not int or segment['total_size'] < block['size']):
134+ raise RuntimeError('cached block schema/state/extent is unsupported')
135+ shared_slots_stream(device, stream, False)
136+ return dict(probe_bytes=probe.numel() * probe.element_size(),
137+ segment_total_size=segment['total_size'])
138+ 
139+ @classmethod
140+ def _admit_init(cls, group, rank, size, descriptors, udma, qp, mode, tail):
141+ signature = (id(group), int(torch.npu.current_device()), int(rank), int(size),
142+ tuple(descriptors), bool(udma), int(qp), mode, int(tail))
143+ record, error, header = None, None, [0] * 5
144+ try:
145+ if cls._poisoned:
146+ raise RuntimeError('poisoned SHMEM admission cannot retry')
147+ if cls._initialized and signature != cls._init_signature:
148+ raise RuntimeError("SHMEM one-init topology/backing/engine signature changed")
149+ if not cls._initialized and cls._init_signature is not None:
150+ raise RuntimeError("SHMEM session is one-shot; use a new process")
151+ strict = any(ref() is not None and ref()._shared_sources for ref in cls._buffer_refs)
152+ probe_record = None
153+ if strict:
154+ if size > 1 and not dist.is_initialized():
155+ raise RuntimeError('strict multi-rank SHMEM requires its actual control group')
156+ probe_record = cls._prove_cached_allocator(signature[1])
157+ record = audit_loaded_shmem_library()
158+ if strict:
159+ record['allocator_probe'] = probe_record
160+ layout = (tuple(int(d[1]) for d in descriptors), bool(udma), int(qp), str(mode), int(tail), bool(strict))
161+ digest = hashlib.sha256(repr(layout).encode('ascii')).digest()
162+ header = [1, int(cls._initialized), int(size), len(descriptors),
163+ int.from_bytes(digest[:8], 'little') & (2**63-1)]
164+ except BaseException as caught:
165+ error = caught
166+ # Ordinary training supplies the actual EP process group. Explicit
167+ # no-PG IP bootstrap retains its legacy local-only admission semantics;
168+ # it is not a supported strict shared-slots training bootstrap.
169+ if size > 1 and dist.is_initialized():
170+ try:
171+ low = torch.tensor(header, dtype=torch.int64,
172+ device=f'npu:{torch.npu.current_device()}')
173+ high = low.clone()
174+ cls._control_keepalive.extend((low, high))
175+ dist.all_reduce(low, op=dist.ReduceOp.MIN, group=group)
176+ dist.all_reduce(high, op=dist.ReduceOp.MAX, group=group)
177+ accepted = bool(low[0].item()) and bool(torch.equal(low, high))
178+ except BaseException:
179+ cls._poisoned = True
180+ raise
181+ if not accepted:
182+ cls._poisoned = True
183+ raise RuntimeError('all-rank SHMEM audit/layout admission rejected') from error
184+ elif error is not None:
185+ cls._poisoned = True
186+ raise error
187+ cls._control_keepalive.clear()
188+ if cls._initialized:
189+ return False
190+ cls._runtime_library_record = record
191+ cls._init_signature = signature
192+ cls._init_group = group
193+ cls._udma_enabled = bool(udma)
194+ return True
97 195 
98 @staticmethod196 @staticmethod
99 def compute_mem_size(197 def compute_mem_size(
@@ -156,14 +254,8 @@ class ShmemRuntime:
156 ``create_vmm_physical`` at construction). Must run AFTER every Buffer is254 ``create_vmm_physical`` at construction). Must run AFTER every Buffer is
157 constructed and BEFORE the first dispatch/combine/prefetch/reduce_grad.255 constructed and BEFORE the first dispatch/combine/prefetch/reduce_grad.
158 """256 """
159- if cls._poisoned:
160- raise RuntimeError(
161- "shmem runtime is poisoned by a prior finalize failure; "
162- "reinitialization is forbidden")
163 if enable_udma is None:257 if enable_udma is None:
164 enable_udma = _env_udma_enabled()258 enable_udma = _env_udma_enabled()
165- if cls._initialized:
166- return
167 if enable_udma and not qp_count:259 if enable_udma and not qp_count:
168 qp_count = 2260 qp_count = 2
169 if ip_port is not None:261 if ip_port is not None:
@@ -171,51 +263,58 @@ class ShmemRuntime:
171 tail_bytes=tail_bytes, ip_port=ip_port,263 tail_bytes=tail_bytes, ip_port=ip_port,
172 enable_udma=enable_udma, qp_count=qp_count)264 enable_udma=enable_udma, qp_count=qp_count)
173 return265 return
174- # Fail closed before any SHMEM-native call (including UID generation).
175- # Loading two libshmem images creates independent process-global
176- # PE/heap state.
177- # cls._runtime_library_record = audit_loaded_shmem_library()
178 rank = dist.get_rank(group=group)266 rank = dist.get_rank(group=group)
179 world_size = dist.get_world_size(group=group)267 world_size = dist.get_world_size(group=group)
180- if uid_bytes is None:
181- uid = acl_shmem_get_unique_id() if rank == 0 else None
182- # ``src`` is always a global rank even when ``group`` is an EP
183- # subgroup. EP rank 0 is not necessarily global rank 0.
184- uid_root = 0 if group is None else dist.get_global_rank(group, 0)
185- # HCCL process groups do not provide a CPU/object transport. Send
186- # the binary UID as NPU tensors, including its ABI-derived length,
187- # so embedded NUL bytes are preserved without pickle or Gloo.
188- device = torch.device("npu", torch.npu.current_device())
189- uid_length = torch.tensor(
190- [len(uid) if uid is not None else 0],
191- dtype=torch.int64,
192- device=device,
193- )
194- dist.broadcast(uid_length, src=uid_root, group=group)
195- length = int(uid_length.item())
196- if length <= 0:
197- raise RuntimeError("aclshmem UID broadcast produced an invalid byte length")
198- uid_tensor = (
199- torch.tensor(list(uid), dtype=torch.uint8, device=device)
200- if uid is not None
201- else torch.empty(length, dtype=torch.uint8, device=device)
202- )
203- if int(uid_tensor.numel()) != length:
204- raise RuntimeError(
205- "aclshmem UID length changed while preparing subgroup broadcast"
206- )
207- dist.broadcast(uid_tensor, src=uid_root, group=group)
208- uid_bytes = bytes(uid_tensor.cpu().tolist())
209 if descriptors is None:268 if descriptors is None:
210 descriptors = symmetric_descriptors()269 descriptors = symmetric_descriptors()
211- shmem_init_with_buffer(270+ descriptors = tuple(tuple(descriptor) for descriptor in descriptors)
212- descriptors, int(rank), int(world_size), uid_bytes,271+ if not cls._admit_init(group, rank, world_size, descriptors, enable_udma,
213- tail_bytes=int(tail_bytes),272+ qp_count, ('uid', bytes(uid_bytes) if uid_bytes is not None else None), tail_bytes):
214- data_op_engine_type=(ACLSHMEM_DATA_OP_UDMA | ACLSHMEM_DATA_OP_MTE if enable_udma273+ return
215- else ACLSHMEM_DATA_OP_MTE),274+ try:
216- device_id=int(torch.npu.current_device()),275+ if uid_bytes is None:
217- enable_udma=enable_udma, qp_count=qp_count)276+ uid = acl_shmem_get_unique_id() if rank == 0 else None
218- cls._initialized = True277+ # ``src`` is always a global rank even when ``group`` is an EP
278+ # subgroup. EP rank 0 is not necessarily global rank 0.
279+ uid_root = 0 if group is None else dist.get_global_rank(group, 0)
280+ # HCCL process groups do not provide a CPU/object transport. Send
281+ # the binary UID as NPU tensors, including its ABI-derived length,
282+ # so embedded NUL bytes are preserved without pickle or Gloo.
283+ device = torch.device("npu", torch.npu.current_device())
284+ uid_length = torch.tensor(
285+ [len(uid) if uid is not None else 0],
286+ dtype=torch.int64,
287+ device=device,
288+ )
289+ cls._control_keepalive.append(uid_length)
290+ dist.broadcast(uid_length, src=uid_root, group=group)
291+ length = int(uid_length.item())
292+ if length <= 0:
293+ raise RuntimeError("aclshmem UID broadcast produced an invalid byte length")
294+ uid_tensor = (
295+ torch.tensor(list(uid), dtype=torch.uint8, device=device)
296+ if uid is not None
297+ else torch.empty(length, dtype=torch.uint8, device=device)
298+ )
299+ if int(uid_tensor.numel()) != length:
300+ raise RuntimeError(
301+ "aclshmem UID length changed while preparing subgroup broadcast"
302+ )
303+ cls._control_keepalive.append(uid_tensor)
304+ dist.broadcast(uid_tensor, src=uid_root, group=group)
305+ uid_bytes = bytes(uid_tensor.cpu().tolist())
306+ shmem_init_with_buffer(
307+ descriptors, int(rank), int(world_size), uid_bytes,
308+ tail_bytes=int(tail_bytes),
309+ data_op_engine_type=(ACLSHMEM_DATA_OP_UDMA | ACLSHMEM_DATA_OP_MTE if enable_udma
310+ else ACLSHMEM_DATA_OP_MTE),
311+ device_id=int(torch.npu.current_device()),
312+ enable_udma=enable_udma, qp_count=qp_count)
313+ cls._initialized = True
314+ cls._control_keepalive.clear()
315+ except BaseException:
316+ cls._poisoned = True
317+ raise
219 318 
220 @classmethod319 @classmethod
221 def init_with_ip_port(cls, group=None, ip_port=None, descriptors=None,320 def init_with_ip_port(cls, group=None, ip_port=None, descriptors=None,
@@ -241,17 +340,10 @@ class ShmemRuntime:
241 allocations (``buffer_c.symmetric_descriptors()``). Timing is the340 allocations (``buffer_c.symmetric_descriptors()``). Timing is the
242 same as ``init_with_buffer``.341 same as ``init_with_buffer``.
243 """342 """
244- if cls._poisoned:
245- raise RuntimeError(
246- "shmem runtime is poisoned by a prior finalize failure; "
247- "reinitialization is forbidden")
248 if enable_udma is None:343 if enable_udma is None:
249 enable_udma = _env_udma_enabled()344 enable_udma = _env_udma_enabled()
250- if cls._initialized:
251- return
252 # The IP/port path owns the same process-global runtime and backing as345 # The IP/port path owns the same process-global runtime and backing as
253 # the UID path, so it must pass the identical pre-native audit.346 # the UID path, so it must pass the identical pre-native audit.
254- # cls._runtime_library_record = audit_loaded_shmem_library()
255 if ip_port is None:347 if ip_port is None:
256 ip_port = _env_shmem_ip_port()348 ip_port = _env_shmem_ip_port()
257 if ip_port is None:349 if ip_port is None:
@@ -278,13 +370,21 @@ class ShmemRuntime:
278 descriptors = symmetric_descriptors()370 descriptors = symmetric_descriptors()
279 if enable_udma and not qp_count:371 if enable_udma and not qp_count:
280 qp_count = 2372 qp_count = 2
281- shmem_init_with_ip_port(373+ descriptors = tuple(tuple(descriptor) for descriptor in descriptors)
282- int(rank), int(world_size), ip_port, descriptors,374+ if not cls._admit_init(group, rank, world_size, descriptors, enable_udma,
283- tail_bytes=int(tail_bytes),375+ qp_count, str(ip_port), tail_bytes):
284- data_op_engine_type=(ACLSHMEM_DATA_OP_UDMA | ACLSHMEM_DATA_OP_MTE if enable_udma376+ return
285- else ACLSHMEM_DATA_OP_MTE),377+ try:
286- device_id=int(torch.npu.current_device()),378+ shmem_init_with_ip_port(
287- enable_udma=enable_udma, qp_count=qp_count)379+ int(rank), int(world_size), ip_port, descriptors,
380+ tail_bytes=int(tail_bytes),
381+ data_op_engine_type=(ACLSHMEM_DATA_OP_UDMA | ACLSHMEM_DATA_OP_MTE if enable_udma
382+ else ACLSHMEM_DATA_OP_MTE),
383+ device_id=int(torch.npu.current_device()),
384+ enable_udma=enable_udma, qp_count=qp_count)
385+ except BaseException:
386+ cls._poisoned = True
387+ raise
288 cls._initialized = True388 cls._initialized = True
289 389 
290 @classmethod390 @classmethod
@@ -296,6 +396,13 @@ class ShmemRuntime:
296 releasable. The process should be considered poisoned and terminated396 releasable. The process should be considered poisoned and terminated
297 only after diagnostics are captured.397 only after diagnostics are captured.
298 """398 """
399+ if cls._poisoned or cls._active_operations or cls._live_contexts:
400+ raise RuntimeError('active/poisoned operations forbid SHMEM finalization')
401+ for reference in cls._buffer_refs:
402+ buffer = reference()
403+ if buffer is not None:
404+ buffer.assert_quiescent()
405+ buffer.assert_no_bindings()
299 if cls._initialized:406 if cls._initialized:
300 # Plan B: reuse the buffer_c wrapper.407 # Plan B: reuse the buffer_c wrapper.
301 rc = int(shmem_finalize())408 rc = int(shmem_finalize())
@@ -0,0 +1,214 @@
1+"""Two-rank S2 component-only probe; no promotion, training or strict-copy PASS.
2+ 
3+torchrun --standalone --nproc-per-node=2 FILE --source-lock LOCK --out DIRECTORY
4+LOCK is the independently reviewed actual source/build installation identity.
5+CPU snapshots and synthetic plans are test instrumentation, never production.
6+"""
7+import argparse
8+from datetime import timedelta
9+import hashlib
10+import json
11+import os
12+from pathlib import Path
13+import subprocess
14+ 
15+_QUARANTINE = []
16+ 
17+ 
18+def digest(path):
19+ path = Path(path).resolve(strict=True)
20+ return dict(realpath=str(path), sha256=hashlib.sha256(path.read_bytes()).hexdigest())
21+ 
22+ 
23+def installation_identity(torch, torch_npu, native, device):
24+ from npu_patch.runtime_audit import audit_loaded_shmem_library, _decode_maps_path
25+ root = Path(__file__).resolve().parents[2]
26+ git = lambda *args: subprocess.check_output(['git', '-C', str(root), *args])
27+ if Path(git('rev-parse', '--show-toplevel').decode().strip()).resolve() != root:
28+ raise RuntimeError('a private source-prebuilt Git checkout is required')
29+ names = git('ls-files', '--cached', '--others', '--exclude-standard', '--', 'npu_patch', 'setup.py').decode().splitlines()
30+ source = {name: digest(root / name)['sha256'] for name in names if (root / name).is_file()
31+ and Path(name).suffix in ('.py', '.cpp', '.h', '.json', '.cmake', '.txt', '.sh')}
32+ candidate = dict(head=git('rev-parse', 'HEAD').decode().strip(), source_files=source,
33+ patch_sha256=hashlib.sha256(git('diff', '--binary', 'HEAD')).hexdigest())
34+ mapped = [str(Path(_decode_maps_path(line.split(None, 5)[5])).resolve())
35+ for line in Path('/proc/self/maps').read_text().splitlines()
36+ if len(line.split(None, 5)) == 6 and line.split(None, 5)[5].startswith('/')]
37+ kernels = set(p for p in mapped if Path(p).name == 'libascend_moonep_kernels.so')
38+ torch_native = set(p for p in mapped if Path(p).name == 'libtorch_npu.so')
39+ if len(kernels) != 1 or len(torch_native) != 1 or str(Path(native.__file__).resolve()) not in mapped:
40+ raise RuntimeError('actual loaded provider extension/kernel identity is ambiguous')
41+ return dict(candidate=candidate, extension=digest(native.__file__),
42+ kernel=digest(next(iter(kernels))), shmem=digest(audit_loaded_shmem_library()['realpath']),
43+ torch_npu_native=digest(next(iter(torch_native))),
44+ torch_npu=digest(torch_npu.__file__), soc=torch.npu.get_device_name(device), driver=digest(__file__))
45+ 
46+ 
47+def inspect_cached(device, expect_uncached):
48+ import torch
49+ import torch_npu
50+ from npu_patch import _C
51+ from npu_patch.shmem_runtime import ShmemRuntime
52+ 
53+ torch.npu.set_device(device)
54+ if ShmemRuntime.is_initialized() or ShmemRuntime._init_signature is not None:
55+ raise RuntimeError('allocator inspection requires a fresh uninitialized SHMEM process')
56+ identity = installation_identity(torch, torch_npu, _C, device)
57+ before = torch.npu.memory_reserved(device)
58+ proof, rejection = None, None
59+ try:
60+ proof = ShmemRuntime._prove_cached_allocator(device)
61+ except RuntimeError as error:
62+ if not expect_uncached or str(error) != 'ordinary probe lacks a unique exact cached block':
63+ raise
64+ rejection = str(error)
65+ if bool(rejection) != expect_uncached or not ShmemRuntime._control_keepalive:
66+ raise AssertionError('expected allocator outcome/probe retention was not observed')
67+ if ShmemRuntime.is_initialized() or ShmemRuntime._init_signature is not None:
68+ raise AssertionError('allocator inspection unexpectedly initialized SHMEM')
69+ after = torch.npu.memory_reserved(device)
70+ return dict(stage='S0_ALLOCATOR_ONLY', status='PASS', observations_only=True, identity=identity,
71+ expected_uncached=expect_uncached, rejection=rejection, proof=proof,
72+ reserved_before=before, reserved_after=after, reserved_delta=after - before,
73+ retained_probes=len(ShmemRuntime._control_keepalive), shmem_initialized=ShmemRuntime.is_initialized())
74+ 
75+ 
76+def run(lock_path, output):
77+ import torch
78+ import torch_npu
79+ import torch.distributed as dist
80+ 
81+ device = int(os.environ['LOCAL_RANK'])
82+ torch.npu.set_device(device)
83+ dist.init_process_group('hccl', timeout=timedelta(seconds=180))
84+ rank, buffer = dist.get_rank(), None
85+ 
86+ def check(condition, name):
87+ flag = torch.tensor([int(bool(condition))], dtype=torch.int32, device=f'npu:{device}')
88+ dist.all_reduce(flag, op=dist.ReduceOp.MIN)
89+ if not flag.item():
90+ raise AssertionError(name)
91+ 
92+ try:
93+ error, identity = None, None
94+ try:
95+ from npu_patch import _C
96+ from npu_patch.api import Buffer
97+ from npu_patch.planning import allocate_planning_outputs
98+ from npu_patch.shmem_runtime import ShmemRuntime
99+ identity = installation_identity(torch, torch_npu, _C, device)
100+ if json.loads(Path(lock_path).read_text()) != identity:
101+ raise RuntimeError('actual installation differs from independently frozen build lock')
102+ if (dist.get_world_size() != 2 or torch.npu.current_device() != device
103+ or torch.npu.memory.get_allocator_backend() != 'native'
104+ or _C.SHARED_SLOTS_ABI != 1 or not _C.prefetch_push_pointers_available()
105+ or ShmemRuntime.is_initialized() or ShmemRuntime._init_signature is not None):
106+ raise RuntimeError('unsupported device/allocator/ABI or preexisting SHMEM session')
107+ except Exception as caught:
108+ error = caught
109+ check(error is None, 'collective source-prebuilt admission: ' + str(error))
110+ error = None
111+ try:
112+ buffer = Buffer(S=128, H=128, K=1, E=4, num_ep_ranks=2, B=2,
113+ num_sms=32, group=dist.group.WORLD, use_udma=False,
114+ grad_reduce_use_udma=True, prefetch_use_udma=True, explicitly_destroy=True)
115+ buffer.configure_capacity(1, 1 << 30)
116+ projection = buffer.register_shared_projection((128, 128))
117+ except Exception as caught:
118+ error = caught
119+ check(error is None, 'collective Buffer/projection preparation: ' + str(error))
120+ ShmemRuntime.init_with_buffer(group=dist.group.WORLD, enable_udma=True, qp_count=2)
121+ signature = ShmemRuntime._init_signature
122+ 
123+ def transport_case(generation, matrix):
124+ plan, _ = allocate_planning_outputs(buffer._ctx)
125+ plan.experts_to_copy.copy_(torch.tensor(matrix, dtype=torch.int32, device=f'npu:{device}'))
126+ weights, gradients = buffer.shared_slots(projection)
127+ refs = tuple(torch.full((128, 128), rank * 2 + i + 1 + 8 * generation,
128+ dtype=torch.bfloat16, device=weights.device) for i in range(2))
129+ call = (0, 0, generation, generation)
130+ buffer.begin_operation((call, 'forward'), context_bytes=1 << 20)
131+ buffer.prefetch_projection_refs(plan, refs, weights, transport='urma')
132+ for slot, expert in enumerate(matrix[rank]):
133+ expected = 0 if expert == -1 else expert + 1 + 8 * generation
134+ check(torch.equal(weights[slot].cpu(), torch.full((128, 128), expected, dtype=torch.bfloat16)), 'PUSH')
135+ buffer.end_operation()
136+ buffer.begin_operation((call, 'backward'))
137+ buffer.zero_shared_grad(gradients)
138+ gradients.fill_(rank + 1) # Explicit test producer, not a grouped-wgrad implementation.
139+ head = torch.full((2, 128, 128), 10., dtype=torch.float32, device=weights.device)
140+ buffer.reduce_projection_grads(plan, ((head, gradients),), local_dense=True, transport='urma')
141+ for expert in range(2):
142+ expected = 10 + sum(src + 1 for src in range(2) for value in matrix[src] if value == rank * 2 + expert)
143+ check(torch.equal(head[expert].cpu(), torch.full((128, 128), float(expected))), 'ordinary nonzero head GR')
144+ for slot, expert in enumerate(matrix[rank]):
145+ expected = 0 if expert >= 0 else rank + 1
146+ check(torch.equal(gradients[slot].cpu(), torch.full((128, 128), float(expected))), 'active-only clear')
147+ buffer.end_operation()
148+ 
149+ for generation, matrix in enumerate(([[0, 2], [0, -1]], [[-1, -1], [-1, -1]], [[-1, 3], [1, 2]])):
150+ transport_case(generation, matrix)
151+ check(ShmemRuntime._init_signature == signature, 'one frozen session')
152+ 
153+ def redispatch_case():
154+ call = (0, 0, 3, 3)
155+ x = torch.full((128, 128), rank + 1, dtype=torch.bfloat16, device=f'npu:{device}')
156+ probabilities = torch.ones((128, 1), dtype=torch.float32, device=x.device)
157+ ids = torch.zeros((128, 1), dtype=torch.int32, device=x.device)
158+ check(x.untyped_storage().nbytes() + probabilities.untyped_storage().nbytes() < 1 << 20,
159+ 'fixed source backing capacity')
160+ buffer.begin_operation((call, 'forward'), context_bytes=1 << 20)
161+ carrier, p, cu, plan = buffer.dispatch(x, probabilities, ids, None,
162+ zero_copy=True, router_weights_zero_copy=True, native_counts=True)
163+ buffer._peer_fence(complete=True)
164+ valid = torch.arange(carrier.shape[0], device=x.device) < cu[-1]
165+ check(0 < int(cu[-1].item()) <= 128, 'nonempty bounded R1 oracle')
166+ oracle = carrier[valid].cpu() # CPU oracle snapshot; never retained by production.
167+ buffer.end_operation()
168+ buffer.begin_operation((call, 'backward'))
169+ p.fill_(17)
170+ carrier.zero_()
171+ restored, _, _, returned = buffer.dispatch(x, None, plan=plan, zero_copy=True)
172+ check(returned is plan and restored.data_ptr() == carrier.data_ptr(), 'exact-plan carrier R1')
173+ check(torch.equal(restored[valid].cpu(), oracle), 'R1 restored X')
174+ check(torch.equal(p.cpu(), torch.full((128,), 17.)), 'R1 preserves dP')
175+ buffer.end_operation()
176+ 
177+ redispatch_case()
178+ buffer.assert_quiescent()
179+ dist.barrier()
180+ ShmemRuntime.finalize()
181+ buffer.destroy()
182+ result = dict(stage='S2_COMPONENT_ONLY', status='PASS', identity=identity, rank=rank,
183+ assertions=['synthetic PUSH', 'ordinary nonzero head GR', 'self/multiple contribution',
184+ 'empty/inactive-active', 'active clear', 'real-plan R1/dP', 'normal finalize'],
185+ strict_zero_copy='NOT_RUN', peer_delay_failure_injection='NOT_RUN', training='NOT_RUN')
186+ path = Path(output) / f'rank-{rank}.json'
187+ path.parent.mkdir(parents=True, exist_ok=True)
188+ path.write_text(json.dumps(result, indent=2) + '\n')
189+ dist.destroy_process_group()
190+ except BaseException:
191+ if buffer is not None:
192+ buffer.poison_and_retain()
193+ _QUARANTINE.append(buffer)
194+ raise
195+ 
196+ 
197+if __name__ == '__main__':
198+ parser = argparse.ArgumentParser(description=__doc__)
199+ parser.add_argument('--source-lock')
200+ parser.add_argument('--out', required=True)
201+ parser.add_argument('--inspect-cached', action='store_true')
202+ parser.add_argument('--expect-uncached', action='store_true')
203+ parser.add_argument('--device', type=int, default=0)
204+ args = parser.parse_args()
205+ if (args.device < 0 or (args.expect_uncached and not args.inspect_cached)
206+ or (args.inspect_cached and args.source_lock) or (not args.inspect_cached and not args.source_lock)
207+ or (not args.inspect_cached and args.device != 0)):
208+ parser.error('--source-lock is required only for S2; --expect-uncached/--device require --inspect-cached')
209+ if args.inspect_cached:
210+ result = inspect_cached(args.device, args.expect_uncached)
211+ Path(args.out).parent.mkdir(parents=True, exist_ok=True)
212+ Path(args.out).write_text(json.dumps(result, indent=2) + '\n')
213+ else:
214+ run(args.source_lock, args.out)