Draft
[WIP]Draft: feat(npu): provide shared slots and counted URMA runtime integration #18
Jia_AustinAdd on 24 days ago
[WIP]Draft: feat(npu): provide shared slots and counted URMA runtime integration #18
Draft
Total: 16 files changed+1999-76
| @@ -44,6 +44,7 @@ from .ops import ( | |||
| 44 | ) | 44 | ) |
| 45 | from .launchers import planning_workspace_sizes | 45 | from .launchers import planning_workspace_sizes |
| 46 | from .shmem_runtime import ShmemRuntime | 46 | from .shmem_runtime import ShmemRuntime |
| 47 | +from .shared_slots import SharedSlotsMixin | ||
| 47 | 48 | ||
| 48 | logger = logging.getLogger(__name__) | 49 | logger = logging.getLogger(__name__) |
| 49 | 50 | ||
| @@ -352,7 +353,7 @@ def _create_context( | |||
| 352 | return ctx | 353 | 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 kernel | 359 | 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 = False | 444 | 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 workspaces | 456 | """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/reduce | 459 | + Includes registered shared weight/FP32-gradient slots with physical |
| 458 | - buffers are not counted; per §6 the framework collects | 460 | + 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._ctx | 463 | 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 | return | 524 | 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._ctx | 529 | ctx = self._ctx |
| 522 | if ctx is None: | 530 | if ctx is None: |
| 523 | self._destroyed = True | 531 | 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 (the | 545 | # 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_stream | 633 | 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 tokens | 858 | """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`` independently | 863 | 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 None | 884 | + 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.int32 | 887 | + 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 and | 1048 | """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 None | 1094 | 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 separate | 1201 | 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.cpp | 80 | kernels/moonep_combine_udma.cpp |
| 81 | kernels/moonep_dispatch_udma.cpp | 81 | kernels/moonep_dispatch_udma.cpp |
| 82 | kernels/moonep_grad_reduce_udma.cpp | 82 | kernels/moonep_grad_reduce_udma.cpp |
| 83 | - kernels/prefetch_udma.cpp) | 83 | + kernels/prefetch_udma.cpp |
| 84 | + kernels/prefetch_pointer_push_udma.cpp) | ||
| 84 | else() | 85 | else() |
| 85 | set(ASCEND_MOONEP_UDMA_KERNEL_SOURCES "") | 86 | set(ASCEND_MOONEP_UDMA_KERNEL_SOURCES "") |
| 86 | endif() | 87 | endif() |
| @@ -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::ops | 179 | } // 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::ops | 19 | } // 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 | ||
| 7 | PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { | 11 | PYBIND11_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.Tensor | 32 | dup_loffs: torch.Tensor |
| 33 | dup_counts: torch.Tensor | 33 | 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_seqlens | 134 | return plan, cu_seqlens |
| @@ -24,6 +24,7 @@ mixed (do not mix). | |||
| 24 | from __future__ import annotations | 24 | from __future__ import annotations |
| 25 | 25 | ||
| 26 | import os | 26 | import os |
| 27 | +import hashlib | ||
| 27 | 28 | ||
| 28 | import torch | 29 | import torch |
| 29 | import torch.distributed as dist | 30 | import 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_id | 43 | +from ._C import acl_shmem_barrier_all, acl_shmem_get_unique_id, shared_slots_stream |
| 43 | from .runtime_audit import audit_loaded_shmem_library | 44 | from .runtime_audit import audit_loaded_shmem_library |
| 44 | 45 | ||
| 45 | 46 | ||
| @@ -94,6 +95,103 @@ class ShmemRuntime: | |||
| 94 | _initialized = False | 95 | _initialized = False |
| 95 | _poisoned = False | 96 | _poisoned = False |
| 96 | _runtime_library_record = None | 97 | _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 | @staticmethod | 196 | @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 is | 254 | ``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 = 2 | 260 | 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 | return | 265 | 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_udma | 273 | + 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 = True | 277 | + # ``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 | @classmethod | 319 | @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 the | 340 | 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 as | 345 | # 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 = 2 | 372 | 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_udma | 376 | + 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 = True | 388 | cls._initialized = True |
| 289 | 389 | ||
| 290 | @classmethod | 390 | @classmethod |
| @@ -296,6 +396,13 @@ class ShmemRuntime: | |||
| 296 | releasable. The process should be considered poisoned and terminated | 396 | 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()) |