Draft
[WIP][SUPERSEDED] [WIP]Draft: feat(npu): add shared-slot bindings and pointer-source URMA PUSH #17
[WIP][SUPERSEDED] [WIP]Draft: feat(npu): add shared-slot bindings and pointer-source URMA PUSH #17
Draft
Jia_AustinAdd on 24 days ago
Total: 15 files changed+1613-67
@@ -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,29 @@ 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 zero_copy or (route_weights_sk is not None and not router_weights_zero_copy):
874+ raise RuntimeError('strict dispatch requires synchronous C/P zero-copy')
875+ if plan is not None:
876+ self._check_shared_plan(plan)
842 877 
878+ if type(native_counts) is not bool:
879+ raise TypeError('native_counts must be bool')
880+ if native_counts and (self._operation is None or plan is not None or tokens_per_expert is not None):
881+ raise ValueError('native_counts requires a fresh strict plan and tokens_per_expert=None')
843 if plan is None:882 if plan is None:
844- assert topk_experts_sk is not None and tokens_per_expert is not None883+ assert topk_experts_sk is not None
845 topk_flat = topk_experts_sk.reshape(-1)884 topk_flat = topk_experts_sk.reshape(-1)
846 assert topk_flat.dtype == torch.int32 and topk_flat.numel() == int(ctx['N'])885 assert topk_flat.dtype == torch.int32 and topk_flat.numel() == int(ctx['N'])
847- assert tokens_per_expert.dtype == torch.int32886+ if not native_counts:
848- assert tokens_per_expert.numel() == int(ctx['E']) and tokens_per_expert.is_contiguous()887+ assert tokens_per_expert is not None and tokens_per_expert.dtype == torch.int32
888+ assert tokens_per_expert.numel() == int(ctx['E']) and tokens_per_expert.is_contiguous()
849 plan, cu_seqlens = allocate_planning_outputs(ctx)889 plan, cu_seqlens = allocate_planning_outputs(ctx)
850 planning_args = (topk_flat, tokens_per_expert, cu_seqlens)890 planning_args = (topk_flat, tokens_per_expert, cu_seqlens)
851 else:891 else:
@@ -865,8 +905,12 @@ class Buffer:
865 route_weights_nvs = torch.empty(905 route_weights_nvs = torch.empty(
866 ctx['NvS'], dtype=torch.float32, device=ctx['weights_buf'].device)906 ctx['NvS'], dtype=torch.float32, device=ctx['weights_buf'].device)
867 907 
908+ if self._operation is not None:
909+ self._operation['refs'].extend((hidden_sh, route_weights_sk,
910+ topk_experts_sk, tokens_per_expert, plan, cu_seqlens,
911+ hidden_nvsh, route_weights_nvs, planning_args))
868 if not async_finish:912 if not async_finish:
869- self._run_dispatch_on_current_stream(913+ self._shared_invoke(self._run_dispatch_on_current_stream,
870 ctx,914 ctx,
871 hidden_sh,915 hidden_sh,
872 route_weights_sk,916 route_weights_sk,
@@ -1003,6 +1047,10 @@ class Buffer:
1003 """combine fwd: gather expert outputs from the symmetric shard and1047 """combine fwd: gather expert outputs from the symmetric shard and
1004 K-sum back to token-major [S, H]. Also serves as dispatch bwd."""1048 K-sum back to token-major [S, H]. Also serves as dispatch bwd."""
1005 ctx = self._require_ctx()1049 ctx = self._require_ctx()
1050+ if self._operation is not None:
1051+ self._check_shared_plan(plan)
1052+ if async_finish or not zero_copy or (route_weights_nvs is not None and not router_weights_zero_copy):
1053+ raise RuntimeError('strict combine requires synchronous C/P zero-copy')
1006 self._ensure_shmem_views()1054 self._ensure_shmem_views()
1007 1055 
1008 assert isinstance(plan, MoonEPCommPlan), "Buffer.combine: plan is required"1056 assert isinstance(plan, MoonEPCommPlan), "Buffer.combine: plan is required"
@@ -1044,8 +1092,11 @@ class Buffer:
1044 if route_weights_nvs is not None else None1092 if route_weights_nvs is not None else None
1045 )1093 )
1046 1094 
1095+ if self._operation is not None:
1096+ self._operation['refs'].extend((plan, hidden_nvsh, route_weights_nvs,
1097+ hidden_sh, route_weights_sk))
1047 if not async_finish:1098 if not async_finish:
1048- self._run_combine_on_current_stream(1099+ self._shared_invoke(self._run_combine_on_current_stream,
1049 ctx,1100 ctx,
1050 hidden_sh,1101 hidden_sh,
1051 plan,1102 plan,
@@ -1132,6 +1183,7 @@ class Buffer:
1132 ),1183 ),
1133 reduce_buffers: Sequence[torch.Tensor] | None = None,1184 reduce_buffers: Sequence[torch.Tensor] | None = None,
1134 async_finish: bool = False,1185 async_finish: bool = False,
1186+ *, local_dense: bool = False, transport: str | None = None,
1135 ):1187 ):
1136 """Reduce an arbitrary non-empty sequence of projection gradients.1188 """Reduce an arbitrary non-empty sequence of projection gradients.
1137 1189 
@@ -1147,6 +1199,12 @@ class Buffer:
1147 For source compatibility, callers may alternatively pass separate1199 For source compatibility, callers may alternatively pass separate
1148 ``projection_grads`` and ``reduce_buffers`` sequences.1200 ``projection_grads`` and ``reduce_buffers`` sequences.
1149 """1201 """
1202+ if local_dense:
1203+ if reduce_buffers is not None:
1204+ raise ValueError('local_dense uses explicit (head,slot) pairs')
1205+ return self._reduce_local_dense(plan, projection_grads, transport, async_finish)
1206+ if transport is not None:
1207+ raise ValueError('transport override requires local_dense=True')
1150 ctx = self._require_ctx()1208 ctx = self._require_ctx()
1151 assert isinstance(plan, MoonEPCommPlan), \1209 assert isinstance(plan, MoonEPCommPlan), \
1152 "Buffer.reduce_projection_grads: plan is required"1210 "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,13 @@
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>
10+#include <torch_npu/csrc/core/npu/register/OptionsManager.h>
6 11 
7PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {12PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
8 m.doc() = "MoonEP NPU symmetric-memory extension (shmem C++ backend)";13 m.doc() = "MoonEP NPU symmetric-memory extension (shmem C++ backend)";
@@ -12,6 +17,38 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
12 py::int_(sizeof(aclshmemx_buffer_optional_attr_t));17 py::int_(sizeof(aclshmemx_buffer_optional_attr_t));
13 18 
14 using py::arg;19 using py::arg;
20+ m.attr("SHARED_SLOTS_ABI") = 1;
21+ m.def("shared_slots_stream", [](int device, uint64_t expected, bool complete) {
22+ int actual = -1;
23+ TORCH_CHECK(aclrtGetDevice(&actual) == ACL_SUCCESS && actual == device,
24+ "shared slots device changed");
25+ TORCH_CHECK(!c10_npu::option::OptionsManager::CheckForceUncached(),
26+ "shared slots requires cached native allocator");
27+ TORCH_CHECK(c10_npu::currentStreamCaptureStatusMayInitCtx() ==
28+ c10_npu::CaptureStatus::None, "graph capture is unsupported");
29+ auto current = c10_npu::getCurrentNPUStream(device);
30+ auto raw = current.stream();
31+ TORCH_CHECK(raw != nullptr, "Q1 queue drain failed");
32+ TORCH_CHECK(expected == 0 || expected == reinterpret_cast<uint64_t>(raw),
33+ "operation current stream changed");
34+ // Public synchronize rejects external streams. Begin also completes
35+ // once to establish this admission check; subsequent raw checks do not.
36+ if (complete) {
37+ current.synchronize(); // also rejects external streams.
38+ TORCH_CHECK(current.stream() == raw, "Q1 stream changed after completion");
39+ TORCH_CHECK(aclrtSynchronizeStream(raw) == ACL_SUCCESS,
40+ "captured stream completion failed");
41+ }
42+ return reinterpret_cast<uint64_t>(raw);
43+ });
44+ m.def("shared_slots_qp0", [](int peer) {
45+ aclshmemx_net_layer_t layer = ACLSHMEM_NET_LAYER_DEFAULT;
46+ int rc = aclshmemx_get_qp_net_layer(ACLSHMEM_DATA_OP_UDMA, peer, 0, &layer);
47+ return py::make_tuple(rc, static_cast<uint32_t>(layer));
48+ });
49+ m.def("prefetch_push_pointers_available", &ascend_moonep::ops::PrefetchPushPointersAvailable);
50+ m.def("prefetch_push_pointers", &ascend_moonep::ops::LaunchPrefetchPushPointers);
51+ 
15 52 
16 m.def("launch_device_barrier_bench", &LaunchDeviceBarrierBench,53 m.def("launch_device_barrier_bench", &LaunchDeviceBarrierBench,
17 arg("iterations"), arg("block_dim") = 32,54 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,394 @@
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 = set()
29+ self._binding_refs = []
30+ self._control_keepalive = []
31+ self._shared_poisoned = False
32+ self._plan_origin = object()
33+ self._ctx['_shared_plan_origin'] = self._plan_origin
34+ runtime = _dependencies()[3]
35+ if not hasattr(runtime, '_buffer_refs'):
36+ runtime._buffer_refs = []
37+ runtime._buffer_refs.append(weakref.ref(self))
38+ 
39+ def register_binding(self, binding):
40+ """Register a caller-owned binding; it must support weak references.
41+ 
42+ Returned slot tensors are borrowed. Before finalize/destroy the caller
43+ must drop every binding AND every derived/external slot tensor alias.
44+ Weak binding checks cover registered holders, not arbitrary Tensor views.
45+ """
46+ self._binding_refs[:] = [ref for ref in self._binding_refs if ref() is not None]
47+ if not any(ref() is binding for ref in self._binding_refs):
48+ self._binding_refs.append(weakref.ref(binding))
49+ 
50+ def assert_no_bindings(self):
51+ if any(ref() is not None for ref in self._binding_refs):
52+ raise RuntimeError('detach/release every shared-slot binding before shutdown')
53+ 
54+ def register_shared_projection(self, shape):
55+ """Register [B,O,I] W/G source backing before the one SHMEM init."""
56+ torch, _, memory, runtime = _dependencies()
57+ if (runtime.is_initialized() or runtime._poisoned
58+ or getattr(runtime, "_init_signature", None) is not None
59+ or self._operation or self._shared_poisoned):
60+ raise RuntimeError('shared projection registration must precede init')
61+ shape = tuple(shape)
62+ if len(shape) != 2 or any(type(n) is not int or n <= 0 for n in shape):
63+ raise ValueError('projection shape must contain two positive integers')
64+ ctx = self._require_ctx()
65+ if ctx['B'] != ctx['E'] // ctx['R'] or ctx['E'] % ctx['R']:
66+ raise RuntimeError('strict slots requires B=L and E divisible by EP')
67+ for index, record in enumerate(self._shared_sources):
68+ if record[0] == shape:
69+ return index
70+ allocated = []
71+ try:
72+ for dtype in (torch.bfloat16, torch.float32):
73+ tensor, _, _ = memory.create_vmm_physical(
74+ (ctx['B'], *shape), dtype, ctx['device'])
75+ allocated.append(tensor) # Registration submits no device work.
76+ except BaseException:
77+ self._native_keepalive.extend(allocated)
78+ try:
79+ for tensor in allocated:
80+ tensor._vmm_allocation.destroy()
81+ except BaseException:
82+ self.poison_and_retain()
83+ raise
84+ self._native_keepalive[:] = [value for value in self._native_keepalive
85+ if not any(value is tensor for tensor in allocated)]
86+ raise
87+ self._shared_sources.append((shape, *allocated))
88+ return len(self._shared_sources) - 1
89+ 
90+ def shared_slots(self, projection_index):
91+ _, _, memory, runtime = _dependencies()
92+ if not runtime.is_initialized() or runtime._poisoned or self._shared_poisoned:
93+ raise RuntimeError('healthy initialized runtime is required')
94+ if type(projection_index) is not int or not 0 <= projection_index < len(self._shared_sources):
95+ raise ValueError('unknown projection index')
96+ if projection_index not in self._shared_views:
97+ _, weight, grad = self._shared_sources[projection_index]
98+ self._shared_views[projection_index] = (memory.sym_tensor(weight), memory.sym_tensor(grad))
99+ return self._shared_views[projection_index]
100+ 
101+ def _checked_stream(self, complete=False):
102+ _, native, _, _ = _dependencies()
103+ ctx = self._require_ctx()
104+ expected = self._operation['stream'] if self._operation else 0
105+ try:
106+ return native.shared_slots_stream(int(ctx['device']), expected, complete)
107+ except BaseException:
108+ self.poison_and_retain()
109+ raise
110+ 
111+ def begin_operation(self, call_id, *, admission_error=False):
112+ """Collectively admit one operation before any peer-native barrier.
113+ 
114+ identity=(layer, virtual_pipeline, microbatch, sequence), all int64.
115+ A broken device/control collective cannot promise coordinated recovery:
116+ poison and external process-group/job timeout are mandatory then.
117+ """
118+ torch, native, _, runtime = _dependencies()
119+ ctx = self._require_ctx() # Destroyed owners have no usable control group.
120+ frozen = getattr(runtime, '_init_signature', None)
121+ control_group = runtime._init_group if frozen is not None else ctx.get('group')
122+ control_size = frozen[3] if frozen is not None else int(ctx['R'])
123+ stream, failure = 0, None
124+ header = [0] * 14
125+ try:
126+ if type(admission_error) is not bool or admission_error:
127+ raise RuntimeError('caller preflight rejected this operation')
128+ if self._shared_poisoned or runtime._poisoned:
129+ raise RuntimeError('poisoned shared-slot owner')
130+ if self._operation is not None or runtime._active_operations:
131+ raise RuntimeError('shared-slot operation is already active')
132+ if (not isinstance(call_id, tuple) or len(call_id) != 2
133+ or call_id[1] not in ('forward', 'backward')):
134+ raise ValueError('call_id must be (identity, forward/backward)')
135+ identity, phase = call_id
136+ if (not isinstance(identity, tuple) or len(identity) != 4
137+ or any(type(v) is not int or not 0 <= v < 2**63 for v in identity)):
138+ raise ValueError('identity must be four nonnegative int64 values')
139+ layout = tuple(record[0] for record in self._shared_sources)
140+ digest = hashlib.sha256(repr(layout).encode('ascii')).digest()
141+ header = [*identity, int(phase == 'backward'),
142+ *[int(ctx[key]) for key in ('R', 'E', 'B', 'S', 'K', 'H')],
143+ len(layout), *[int.from_bytes(digest[i:i+8], 'little') & (2**63-1)
144+ for i in (0, 8)]]
145+ if any(not 0 <= value < 2**63 for value in header):
146+ raise ValueError('operation header exceeds int64 range')
147+ if ((phase == 'forward' and identity in self._live_calls)
148+ or (phase == 'backward' and identity not in self._live_calls)):
149+ raise RuntimeError('duplicate forward or backward without live forward')
150+ if not runtime.is_initialized() or not runtime._udma_enabled:
151+ raise RuntimeError('shared slots needs one MTE|UDMA buffer init')
152+ if frozen is not None and frozen[6] != 2:
153+ raise RuntimeError('strict slots requires frozen qp_count=2')
154+ if not runtime.matches_group(ctx.get('group'), ctx['device'], ctx['rank'], ctx['R']):
155+ raise RuntimeError('Buffer topology/device differs from frozen SHMEM session')
156+ if getattr(native, 'SHARED_SLOTS_ABI', None) != 1 or not native.prefetch_push_pointers_available():
157+ raise RuntimeError('shared slots native ABI/URMA PUSH unavailable')
158+ if ctx['_dispatch_use_udma'] or ctx['_combine_use_udma'] or ctx['_planning_use_udma']:
159+ raise RuntimeError('strict profile requires MTE activation and planning')
160+ if int(ctx['num_sms']) != 32 or ctx['E'] % ctx['R'] or ctx['B'] != ctx['E'] // ctx['R']:
161+ raise RuntimeError('strict profile requires num_sms=32 and B=L')
162+ if os.environ.get('ASCEND_MOONEP_ASYNC_BARRIER', '1').lower() in ('0', 'false', 'off'):
163+ raise RuntimeError('strict profile requires on-stream peer barriers')
164+ if torch.npu.memory.get_allocator_backend() != 'native':
165+ raise RuntimeError('strict profile requires native caching allocator')
166+ # Public synchronize rejects external streams. No peer-native call
167+ # may happen before the control collective below accepts all PEs.
168+ stream = self._checked_stream(complete=True)
169+ self._ensure_shmem_views()
170+ for index in range(len(self._shared_sources)):
171+ self.shared_slots(index) # All local aliases must map before collective admission.
172+ routes = [native.shared_slots_qp0(peer)
173+ for peer in range(ctx['R']) if peer != ctx['rank']]
174+ if not all(rc == 0 and layer in (0, 1) for rc, layer in routes):
175+ raise RuntimeError('all-peer QP0 route admission failed')
176+ except BaseException as error:
177+ failure = error
178+ try:
179+ low = torch.tensor([int(failure is None), *header], dtype=torch.int64,
180+ device=ctx['hidden_buf'].device)
181+ high = low.clone()
182+ self._control_keepalive[:] = [low, high]
183+ if control_size > 1:
184+ import torch.distributed as dist
185+ dist.all_reduce(low, op=dist.ReduceOp.MIN, group=control_group)
186+ dist.all_reduce(high, op=dist.ReduceOp.MAX, group=control_group)
187+ accepted = bool(low[0].item()) and bool(torch.equal(low, high))
188+ except BaseException:
189+ self.poison_and_retain()
190+ raise
191+ self._control_keepalive.clear()
192+ if not accepted:
193+ raise RuntimeError('all-rank operation admission/header agreement rejected') from failure
194+ self._operation = dict(id=call_id, stream=stream, refs=[], calls=[], grad_ready=set())
195+ runtime._active_operations += 1
196+ try:
197+ self._peer_fence(complete=True)
198+ except BaseException:
199+ self.poison_and_retain()
200+ raise
201+ return self
202+ 
203+ def _peer_fence(self, complete=False):
204+ _, native, _, _ = _dependencies()
205+ stream = self._checked_stream()
206+ native.acl_shmem_barrier_all_on_stream(stream)
207+ if complete:
208+ self._checked_stream(complete=True)
209+ 
210+ def _check_dispatch_capacity(self, prefix):
211+ """Validate the device prefix before any token payload dispatch.
212+ 
213+ Only the reduced error flag is read by the host, never token counts.
214+ A device/control failure poisons the owner and needs job termination.
215+ """
216+ torch, _, _, runtime = _dependencies()
217+ ctx = self._require_ctx()
218+ try:
219+ valid = (prefix is not None and prefix.dtype == torch.int32
220+ and prefix.device == ctx['hidden_buf'].device
221+ and tuple(prefix.shape) == (ctx['E'] + ctx['B'],)
222+ and prefix.is_contiguous())
223+ if valid:
224+ bad = ((prefix < 0).any() | (prefix[1:] < prefix[:-1]).any()
225+ | (prefix[-1] > int(ctx['NvS'])))
226+ error = bad.to(dtype=torch.int32).reshape(1)
227+ else:
228+ error = torch.tensor([1], dtype=torch.int32, device=ctx['hidden_buf'].device)
229+ self._control_keepalive[:] = [prefix, error]
230+ frozen = getattr(runtime, '_init_signature', None)
231+ size = frozen[3] if frozen is not None else int(ctx['R'])
232+ group = runtime._init_group if frozen is not None else ctx.get('group')
233+ if size > 1:
234+ import torch.distributed as dist
235+ dist.all_reduce(error, op=dist.ReduceOp.MAX, group=group)
236+ rejected = bool(error.item())
237+ except BaseException:
238+ self.poison_and_retain()
239+ raise
240+ self._control_keepalive.clear()
241+ if rejected:
242+ raise RuntimeError('all-rank native plan prefix/capacity check rejected before dispatch')
243+ 
244+ def _shared_invoke(self, function, *args, **kwargs):
245+ try:
246+ return function(*args, **kwargs)
247+ except BaseException:
248+ if self._operation is not None:
249+ self.poison_and_retain()
250+ raise
251+ 
252+ def _require_operation(self):
253+ if self._shared_poisoned or self._operation is None:
254+ raise RuntimeError('healthy begin_operation is required')
255+ self._checked_stream()
256+ return self._operation
257+ 
258+ def retain_native(self, call):
259+ op = self._require_operation()
260+ if not any(value is call for value in self._native_keepalive):
261+ self._native_keepalive.append(call)
262+ op['calls'].append(call)
263+ 
264+ def release_native_after_local_complete(self, call):
265+ self._require_operation()
266+ try:
267+ self._checked_stream(complete=True)
268+ except BaseException:
269+ self.poison_and_retain()
270+ raise
271+ self._native_keepalive[:] = [value for value in self._native_keepalive if value is not call]
272+ self._operation['calls'][:] = [value for value in self._operation['calls'] if value is not call]
273+ 
274+ def poison_and_retain(self):
275+ self._shared_poisoned = True
276+ _dependencies()[3]._poisoned = True
277+ if not any(owner is self for owner in _POISONED_BUFFERS):
278+ _POISONED_BUFFERS.append(self)
279+ # Keep operation, Calls, plan, refs, pointer tables and all VMM owners.
280+ # No finalization, source unmap, native destructor or retry is safe here.
281+ 
282+ def end_operation(self):
283+ self._require_operation()
284+ try:
285+ self._checked_stream(complete=True)
286+ self._peer_fence(complete=True)
287+ except BaseException:
288+ self.poison_and_retain()
289+ raise
290+ identity, phase = self._operation['id']
291+ if phase == 'forward':
292+ self._live_calls.add(identity)
293+ _dependencies()[3]._live_contexts += 1
294+ else:
295+ self._live_calls.remove(identity)
296+ _dependencies()[3]._live_contexts -= 1
297+ self._native_keepalive.clear()
298+ _dependencies()[3]._active_operations -= 1
299+ self._operation = None
300+ 
301+ def assert_quiescent(self):
302+ if (self._shared_poisoned or _dependencies()[3]._poisoned
303+ or self._operation is not None or self._live_calls):
304+ raise RuntimeError('live/active/poisoned calls forbid update or destroy')
305+ 
306+ def _check_shared_plan(self, plan):
307+ self._require_operation()
308+ if getattr(plan, 'origin', None) is not self._plan_origin:
309+ raise RuntimeError('plan belongs to another Buffer/session')
310+ ctx = self._require_ctx()
311+ if (plan.R, plan.E, plan.B, plan.NvS) != (ctx['R'], ctx['E'], ctx['B'], ctx['NvS']):
312+ raise RuntimeError('plan shape differs from Buffer')
313+ 
314+ def _shared_slot_index(self, slot, gradient=False):
315+ for index in range(len(self._shared_sources)):
316+ expected = self.shared_slots(index)[int(gradient)]
317+ if (slot.data_ptr() == expected.data_ptr() and slot.device == expected.device
318+ and tuple(slot.shape) == tuple(expected.shape) and slot.dtype == expected.dtype
319+ and slot.is_contiguous() and not slot.is_neg() and not slot.is_conj()):
320+ return index
321+ raise RuntimeError('slot must be an exact registered symmetric view')
322+ 
323+ def zero_shared_grad(self, slot):
324+ """Before B target.add_; previous operation/final-use fence is required."""
325+ self._require_operation()
326+ index = self._shared_slot_index(slot, gradient=True)
327+ try:
328+ self._peer_fence(complete=True)
329+ slot.zero_()
330+ self._operation['grad_ready'].add(index)
331+ except BaseException:
332+ self.poison_and_retain()
333+ raise
334+ 
335+ def prefetch_projection_refs(self, plan, refs, slot, transport='urma'):
336+ torch, native, _, _ = _dependencies()
337+ self._check_shared_plan(plan)
338+ if transport != 'urma':
339+ raise ValueError('only explicit URMA PUSH is supported')
340+ self._shared_slot_index(slot)
341+ ctx = self._require_ctx()
342+ refs = tuple(refs)
343+ if len(refs) != ctx['E'] // ctx['R']:
344+ raise ValueError('one canonical pointer per local expert is required')
345+ if any(ref.dtype != torch.bfloat16 or not ref.is_contiguous() or ref.is_neg() or ref.is_conj() or
346+ tuple(ref.shape) != tuple(slot.shape[1:]) or ref.device != slot.device for ref in refs):
347+ raise ValueError('canonical refs must be contiguous BF16 [O,I] on slot device')
348+ op = self._operation
349+ op['refs'].extend((plan, refs, slot)) # BEFORE any uncertain submission.
350+ try:
351+ pointers = torch.tensor([ref.data_ptr() for ref in refs], dtype=torch.int64, device=slot.device)
352+ op['refs'].append(pointers)
353+ self._peer_fence(complete=True) # previous readers have finished.
354+ slot.zero_() # inactive slots cannot retain old weights/NaNs.
355+ self._peer_fence() # every PE's destination is ready before PUSH.
356+ self._checked_stream()
357+ native.prefetch_push_pointers(pointers, slot, plan.experts_to_copy, len(refs))
358+ self._checked_stream(complete=True)
359+ except BaseException:
360+ self.poison_and_retain()
361+ raise
362+ return slot
363+ 
364+ def _reduce_local_dense(self, plan, pairs, transport, async_finish):
365+ torch, _, _, _ = _dependencies()
366+ self._check_shared_plan(plan)
367+ if transport != 'urma' or async_finish:
368+ raise ValueError('local_dense supports synchronous explicit URMA only')
369+ ctx = self._require_ctx()
370+ pairs = tuple(pairs)
371+ if not pairs:
372+ raise ValueError('at least one gradient pair is required')
373+ for head, slot in pairs:
374+ index = self._shared_slot_index(slot, gradient=True)
375+ if index not in self._operation['grad_ready']:
376+ raise RuntimeError('zero_shared_grad must precede this projection producer')
377+ if (head.dtype != torch.float32 or not head.is_contiguous() or head.is_neg() or head.is_conj() or head.device != slot.device
378+ or tuple(head.shape) != (ctx['E'] // ctx['R'], *slot.shape[1:])):
379+ raise ValueError('GR head must be ordinary contiguous FP32 [L,O,I]')
380+ self._operation['refs'].extend((plan, pairs))
381+ try:
382+ self._peer_fence() # all rank wgrad/add producers precede native GR reads.
383+ for head, slot in pairs:
384+ self._checked_stream()
385+ ctx['kernels']['grad_reduce'].compute(
386+ ctx, head, slot, plan.experts_to_copy, rank=ctx['rank'],
387+ num_sms=ctx['num_sms'], shmem_instance_id=0, use_udma=True)
388+ self._checked_stream(complete=True) # includes native active-slot clear.
389+ self._peer_fence(complete=True) # final-use fence before any bank reuse.
390+ for _, slot in pairs:
391+ self._operation['grad_ready'].discard(self._shared_slot_index(slot, gradient=True))
392+ except BaseException:
393+ self.poison_and_retain()
394+ 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
@@ -94,6 +95,63 @@ 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 _admit_init(cls, group, rank, size, descriptors, udma, qp, mode, tail):
113+ signature = (id(group), int(torch.npu.current_device()), int(rank), int(size),
114+ tuple(descriptors), bool(udma), int(qp), mode, int(tail))
115+ if cls._initialized:
116+ if signature != cls._init_signature:
117+ raise RuntimeError("SHMEM one-init topology/backing/engine signature changed")
118+ return False
119+ if cls._init_signature is not None:
120+ raise RuntimeError("SHMEM session is one-shot; use a new process")
121+ record, error, header = None, None, [0] * 4
122+ try:
123+ record = audit_loaded_shmem_library()
124+ layout = (tuple(int(d[1]) for d in descriptors), bool(udma), int(qp), str(mode), int(tail))
125+ digest = hashlib.sha256(repr(layout).encode('ascii')).digest()
126+ header = [1, int(size), len(descriptors),
127+ int.from_bytes(digest[:8], 'little') & (2**63-1)]
128+ except BaseException as caught:
129+ error = caught
130+ # Ordinary training supplies the actual EP process group. Explicit
131+ # no-PG IP bootstrap retains its legacy local-only admission semantics;
132+ # it is not a supported strict shared-slots training bootstrap.
133+ if size > 1 and dist.is_initialized():
134+ try:
135+ low = torch.tensor(header, dtype=torch.int64,
136+ device=f'npu:{torch.npu.current_device()}')
137+ high = low.clone()
138+ cls._control_keepalive[:] = [low, high]
139+ dist.all_reduce(low, op=dist.ReduceOp.MIN, group=group)
140+ dist.all_reduce(high, op=dist.ReduceOp.MAX, group=group)
141+ accepted = bool(low[0].item()) and bool(torch.equal(low, high))
142+ except BaseException:
143+ cls._poisoned = True
144+ raise
145+ cls._control_keepalive.clear()
146+ if not accepted:
147+ raise RuntimeError('all-rank SHMEM audit/layout admission rejected') from error
148+ elif error is not None:
149+ raise error
150+ cls._runtime_library_record = record
151+ cls._init_signature = signature
152+ cls._init_group = group
153+ cls._udma_enabled = bool(udma)
154+ return True
97 155 
98 @staticmethod156 @staticmethod
99 def compute_mem_size(157 def compute_mem_size(
@@ -162,8 +220,6 @@ class ShmemRuntime:
162 "reinitialization is forbidden")220 "reinitialization is forbidden")
163 if enable_udma is None:221 if enable_udma is None:
164 enable_udma = _env_udma_enabled()222 enable_udma = _env_udma_enabled()
165- if cls._initialized:
166- return
167 if enable_udma and not qp_count:223 if enable_udma and not qp_count:
168 qp_count = 2224 qp_count = 2
169 if ip_port is not None:225 if ip_port is not None:
@@ -171,51 +227,58 @@ class ShmemRuntime:
171 tail_bytes=tail_bytes, ip_port=ip_port,227 tail_bytes=tail_bytes, ip_port=ip_port,
172 enable_udma=enable_udma, qp_count=qp_count)228 enable_udma=enable_udma, qp_count=qp_count)
173 return229 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)230 rank = dist.get_rank(group=group)
179 world_size = dist.get_world_size(group=group)231 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:232 if descriptors is None:
210 descriptors = symmetric_descriptors()233 descriptors = symmetric_descriptors()
211- shmem_init_with_buffer(234+ descriptors = tuple(tuple(descriptor) for descriptor in descriptors)
212- descriptors, int(rank), int(world_size), uid_bytes,235+ if not cls._admit_init(group, rank, world_size, descriptors, enable_udma,
213- tail_bytes=int(tail_bytes),236+ 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_udma237+ return
215- else ACLSHMEM_DATA_OP_MTE),238+ try:
216- device_id=int(torch.npu.current_device()),239+ if uid_bytes is None:
217- enable_udma=enable_udma, qp_count=qp_count)240+ uid = acl_shmem_get_unique_id() if rank == 0 else None
218- cls._initialized = True241+ # ``src`` is always a global rank even when ``group`` is an EP
242+ # subgroup. EP rank 0 is not necessarily global rank 0.
243+ uid_root = 0 if group is None else dist.get_global_rank(group, 0)
244+ # HCCL process groups do not provide a CPU/object transport. Send
245+ # the binary UID as NPU tensors, including its ABI-derived length,
246+ # so embedded NUL bytes are preserved without pickle or Gloo.
247+ device = torch.device("npu", torch.npu.current_device())
248+ uid_length = torch.tensor(
249+ [len(uid) if uid is not None else 0],
250+ dtype=torch.int64,
251+ device=device,
252+ )
253+ cls._control_keepalive.append(uid_length)
254+ dist.broadcast(uid_length, src=uid_root, group=group)
255+ length = int(uid_length.item())
256+ if length <= 0:
257+ raise RuntimeError("aclshmem UID broadcast produced an invalid byte length")
258+ uid_tensor = (
259+ torch.tensor(list(uid), dtype=torch.uint8, device=device)
260+ if uid is not None
261+ else torch.empty(length, dtype=torch.uint8, device=device)
262+ )
263+ if int(uid_tensor.numel()) != length:
264+ raise RuntimeError(
265+ "aclshmem UID length changed while preparing subgroup broadcast"
266+ )
267+ cls._control_keepalive.append(uid_tensor)
268+ dist.broadcast(uid_tensor, src=uid_root, group=group)
269+ uid_bytes = bytes(uid_tensor.cpu().tolist())
270+ shmem_init_with_buffer(
271+ descriptors, int(rank), int(world_size), uid_bytes,
272+ tail_bytes=int(tail_bytes),
273+ data_op_engine_type=(ACLSHMEM_DATA_OP_UDMA | ACLSHMEM_DATA_OP_MTE if enable_udma
274+ else ACLSHMEM_DATA_OP_MTE),
275+ device_id=int(torch.npu.current_device()),
276+ enable_udma=enable_udma, qp_count=qp_count)
277+ cls._initialized = True
278+ cls._control_keepalive.clear()
279+ except BaseException:
280+ cls._poisoned = True
281+ raise
219 282 
220 @classmethod283 @classmethod
221 def init_with_ip_port(cls, group=None, ip_port=None, descriptors=None,284 def init_with_ip_port(cls, group=None, ip_port=None, descriptors=None,
@@ -247,11 +310,8 @@ class ShmemRuntime:
247 "reinitialization is forbidden")310 "reinitialization is forbidden")
248 if enable_udma is None:311 if enable_udma is None:
249 enable_udma = _env_udma_enabled()312 enable_udma = _env_udma_enabled()
250- if cls._initialized:
251- return
252 # The IP/port path owns the same process-global runtime and backing as313 # 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.314 # 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:315 if ip_port is None:
256 ip_port = _env_shmem_ip_port()316 ip_port = _env_shmem_ip_port()
257 if ip_port is None:317 if ip_port is None:
@@ -278,13 +338,21 @@ class ShmemRuntime:
278 descriptors = symmetric_descriptors()338 descriptors = symmetric_descriptors()
279 if enable_udma and not qp_count:339 if enable_udma and not qp_count:
280 qp_count = 2340 qp_count = 2
281- shmem_init_with_ip_port(341+ descriptors = tuple(tuple(descriptor) for descriptor in descriptors)
282- int(rank), int(world_size), ip_port, descriptors,342+ if not cls._admit_init(group, rank, world_size, descriptors, enable_udma,
283- tail_bytes=int(tail_bytes),343+ qp_count, str(ip_port), tail_bytes):
284- data_op_engine_type=(ACLSHMEM_DATA_OP_UDMA | ACLSHMEM_DATA_OP_MTE if enable_udma344+ return
285- else ACLSHMEM_DATA_OP_MTE),345+ try:
286- device_id=int(torch.npu.current_device()),346+ shmem_init_with_ip_port(
287- enable_udma=enable_udma, qp_count=qp_count)347+ int(rank), int(world_size), ip_port, descriptors,
348+ tail_bytes=int(tail_bytes),
349+ data_op_engine_type=(ACLSHMEM_DATA_OP_UDMA | ACLSHMEM_DATA_OP_MTE if enable_udma
350+ else ACLSHMEM_DATA_OP_MTE),
351+ device_id=int(torch.npu.current_device()),
352+ enable_udma=enable_udma, qp_count=qp_count)
353+ except BaseException:
354+ cls._poisoned = True
355+ raise
288 cls._initialized = True356 cls._initialized = True
289 357 
290 @classmethod358 @classmethod
@@ -296,6 +364,13 @@ class ShmemRuntime:
296 releasable. The process should be considered poisoned and terminated364 releasable. The process should be considered poisoned and terminated
297 only after diagnostics are captured.365 only after diagnostics are captured.
298 """366 """
367+ if cls._poisoned or cls._active_operations or cls._live_contexts:
368+ raise RuntimeError('active/poisoned operations forbid SHMEM finalization')
369+ for reference in cls._buffer_refs:
370+ buffer = reference()
371+ if buffer is not None:
372+ buffer.assert_quiescent()
373+ buffer.assert_no_bindings()
299 if cls._initialized:374 if cls._initialized:
300 # Plan B: reuse the buffer_c wrapper.375 # Plan B: reuse the buffer_c wrapper.
301 rc = int(shmem_finalize())376 rc = int(shmem_finalize())