Merged
feat(npu): add prepared L+B bindings and async communication APIs #20
&NewgateAdd on 23 days ago
feat(npu): add prepared L+B bindings and async communication APIs #20
Merged
Total: 38 files changed+2845-100
| @@ -132,9 +132,12 @@ def _load_buffer_api(): | |||
| 132 | from .shmem_runtime import ShmemRuntime, runtime_library_info | 132 | from .shmem_runtime import ShmemRuntime, runtime_library_info |
| 133 | from .planning import MoonEPCommPlan | 133 | from .planning import MoonEPCommPlan |
| 134 | from .api import Buffer | 134 | from .api import Buffer |
| 135 | + from .buffer_bindings import CommBuffers, ExpertPointerBinding | ||
| 135 | 136 | ||
| 136 | return { | 137 | return { |
| 137 | "Buffer": Buffer, | 138 | "Buffer": Buffer, |
| 139 | + "CommBuffers": CommBuffers, | ||
| 140 | + "ExpertPointerBinding": ExpertPointerBinding, | ||
| 138 | "MoonEPCommPlan": MoonEPCommPlan, | 141 | "MoonEPCommPlan": MoonEPCommPlan, |
| 139 | "ShmemRuntime": ShmemRuntime, | 142 | "ShmemRuntime": ShmemRuntime, |
| 140 | "runtime_library_info": runtime_library_info, | 143 | "runtime_library_info": runtime_library_info, |
| @@ -142,7 +145,7 @@ def _load_buffer_api(): | |||
| 142 | 145 | ||
| 143 | 146 | ||
| 144 | _BUFFER_API_NAMES = frozenset({ | 147 | _BUFFER_API_NAMES = frozenset({ |
| 145 | - "Buffer", "MoonEPCommPlan", "ShmemRuntime", "runtime_library_info" | 148 | + "Buffer", "CommBuffers", "ExpertPointerBinding", "MoonEPCommPlan", "ShmemRuntime", "runtime_library_info" |
| 146 | }) | 149 | }) |
| 147 | _BUF_API_CACHE = None | 150 | _BUF_API_CACHE = None |
| 148 | 151 | ||
| @@ -156,16 +159,20 @@ def __getattr__(name): | |||
| 156 | raise AttributeError(f"module 'npu_patch' has no attribute {name!r}") | 159 | raise AttributeError(f"module 'npu_patch' has no attribute {name!r}") |
| 157 | 160 | ||
| 158 | 161 | ||
| 159 | -from .launchers import launch_grad_reduce, launch_prefetch | 162 | +from .launchers import launch_grad_reduce, launch_grad_reduce_targets, launch_prefetch, launch_prefetch_from_ptrs |
| 160 | 163 | ||
| 161 | __all__ = [ | 164 | __all__ = [ |
| 162 | "ShmemInstance", | 165 | "ShmemInstance", |
| 163 | "GradReduce", | 166 | "GradReduce", |
| 164 | "launch_grad_reduce", | 167 | "launch_grad_reduce", |
| 168 | + "launch_grad_reduce_targets", | ||
| 165 | "Buffer", | 169 | "Buffer", |
| 170 | + "CommBuffers", | ||
| 171 | + "ExpertPointerBinding", | ||
| 166 | "MoonEPCommPlan", | 172 | "MoonEPCommPlan", |
| 167 | "ShmemRuntime", | 173 | "ShmemRuntime", |
| 168 | "runtime_library_info", | 174 | "runtime_library_info", |
| 169 | "PrefetchWeight", | 175 | "PrefetchWeight", |
| 170 | "launch_prefetch", | 176 | "launch_prefetch", |
| 177 | + "launch_prefetch_from_ptrs", | ||
| 171 | ] | 178 | ] |
| @@ -16,10 +16,11 @@ from collections.abc import Sequence | |||
| 16 | import torch | 16 | import torch |
| 17 | import torch_npu | 17 | import torch_npu |
| 18 | import torch.distributed as dist | 18 | import torch.distributed as dist |
| 19 | - | ||
| 20 | # Plan B: the C-interface path no longer depends on the shmem Python package. | 19 | # Plan B: the C-interface path no longer depends on the shmem Python package. |
| 21 | # import shmem.core as core | 20 | # import shmem.core as core |
| 22 | 21 | ||
| 22 | +from . import _C | ||
| 23 | + | ||
| 23 | from ._common import ( | 24 | from ._common import ( |
| 24 | BARRIER_SLOTS, | 25 | BARRIER_SLOTS, |
| 25 | OP_WS_BYTES_DEFAULT, | 26 | OP_WS_BYTES_DEFAULT, |
| @@ -44,6 +45,10 @@ from .ops import ( | |||
| 44 | ) | 45 | ) |
| 45 | from .launchers import planning_workspace_sizes | 46 | from .launchers import planning_workspace_sizes |
| 46 | from .shmem_runtime import ShmemRuntime | 47 | from .shmem_runtime import ShmemRuntime |
| 48 | +from .buffer_bindings import ( | ||
| 49 | + CommBuffers, ExpertPointerBinding, comm_context, overlaps, symmetric_source, | ||
| 50 | + tensor_signature, validate_unchanged, | ||
| 51 | +) | ||
| 47 | 52 | ||
| 48 | logger = logging.getLogger(__name__) | 53 | logger = logging.getLogger(__name__) |
| 49 | 54 | ||
| @@ -97,6 +102,16 @@ def _op_ws_bytes_from_env(default: int = OP_WS_BYTES_DEFAULT) -> int: | |||
| 97 | return int(raw) | 102 | return int(raw) |
| 98 | 103 | ||
| 99 | 104 | ||
| 105 | +def _validate_plan_layout(ctx: dict, plan: MoonEPCommPlan) -> None: | ||
| 106 | + """Require a saved plan to match the Buffer's fixed token layout.""" | ||
| 107 | + if not isinstance(plan, MoonEPCommPlan): | ||
| 108 | + raise TypeError("expected a MoonEPCommPlan") | ||
| 109 | + identity = (plan.N, plan.R, plan.E, plan.B, plan.NvS, plan.K) | ||
| 110 | + expected = tuple(int(ctx[name]) for name in ('N', 'R', 'E', 'B', 'NvS', 'K')) | ||
| 111 | + if tuple(int(value) for value in identity) != expected: | ||
| 112 | + raise RuntimeError("plan belongs to another Buffer layout") | ||
| 113 | + | ||
| 114 | + | ||
| 100 | def _log_context_buffer_size(ctx: dict) -> None: | 115 | def _log_context_buffer_size(ctx: dict) -> None: |
| 101 | def tensor_nbytes(tensor: torch.Tensor) -> int: | 116 | def tensor_nbytes(tensor: torch.Tensor) -> int: |
| 102 | return int(tensor.numel()) * int(tensor.element_size()) | 117 | return int(tensor.numel()) * int(tensor.element_size()) |
| @@ -352,6 +367,33 @@ def _create_context( | |||
| 352 | return ctx | 367 | return ctx |
| 353 | 368 | ||
| 354 | 369 | ||
| 370 | +_BARRIER_MODE = None | ||
| 371 | + | ||
| 372 | + | ||
| 373 | +def _extend_context(ctx: dict, *, barrier_mode: str | None = None) -> dict: | ||
| 374 | + """Configure one process-wide barrier policy before SHMEM initialization. | ||
| 375 | + | ||
| 376 | + Layouts and workspaces remain owned by the original _create_context. | ||
| 377 | + All Buffers/ranks must use the same mode; never change the environment | ||
| 378 | + while operations are in flight. The policy is independent of use_udma. | ||
| 379 | + """ | ||
| 380 | + from . import buffer_c | ||
| 381 | + global _BARRIER_MODE | ||
| 382 | + if (ShmemRuntime.is_initialized() or getattr(ShmemRuntime, '_poisoned', False) | ||
| 383 | + or buffer_c._SHMEM_BACKING_LOCKED): | ||
| 384 | + raise RuntimeError('extend context before SHMEM initialization and backing lock') | ||
| 385 | + mode = (os.environ.get('ASCEND_MOONEP_BARRIER_MODE', 'mixed') | ||
| 386 | + if barrier_mode is None else barrier_mode) | ||
| 387 | + if mode not in ('mixed', 'aiv'): | ||
| 388 | + raise ValueError('barrier_mode must be mixed or aiv') | ||
| 389 | + if _BARRIER_MODE is not None and mode != _BARRIER_MODE: | ||
| 390 | + raise RuntimeError('all Buffers in a process must use the same barrier_mode') | ||
| 391 | + os.environ['ASCEND_MOONEP_BARRIER_MODE'] = mode | ||
| 392 | + _BARRIER_MODE = mode | ||
| 393 | + ctx['barrier_mode'] = mode | ||
| 394 | + return ctx | ||
| 395 | + | ||
| 396 | + | ||
| 355 | class Buffer: | 397 | class Buffer: |
| 356 | """Ascend MoonEP communication buffer owner (buffer-backed path only). | 398 | """Ascend MoonEP communication buffer owner (buffer-backed path only). |
| 357 | 399 | ||
| @@ -402,6 +444,7 @@ class Buffer: | |||
| 402 | # _ensure_shmem_views. | 444 | # _ensure_shmem_views. |
| 403 | allowed_udma = {'planning', 'dispatch', 'combine', 'prefetch', 'grad_reduce'} | 445 | allowed_udma = {'planning', 'dispatch', 'combine', 'prefetch', 'grad_reduce'} |
| 404 | use_udma = kwargs.pop('use_udma', False) | 446 | use_udma = kwargs.pop('use_udma', False) |
| 447 | + barrier_mode = kwargs.pop('barrier_mode', None) | ||
| 405 | if not isinstance(use_udma, bool): | 448 | if not isinstance(use_udma, bool): |
| 406 | raise TypeError('use_udma must be a bool') | 449 | raise TypeError('use_udma must be a bool') |
| 407 | udma_flags = {} | 450 | udma_flags = {} |
| @@ -426,6 +469,7 @@ class Buffer: | |||
| 426 | self.explicitly_destroy = explicitly_destroy | 469 | self.explicitly_destroy = explicitly_destroy |
| 427 | self.comm_stream_priority = comm_stream_priority | 470 | self.comm_stream_priority = comm_stream_priority |
| 428 | self.enable_pdl = enable_pdl | 471 | self.enable_pdl = enable_pdl |
| 472 | + self._comm_buffers: CommBuffers | None = None | ||
| 429 | self._comm_stream: torch_npu.npu.Stream | None = None | 473 | self._comm_stream: torch_npu.npu.Stream | None = None |
| 430 | self._destroyed = False | 474 | self._destroyed = False |
| 431 | self._ctx = _create_context( | 475 | self._ctx = _create_context( |
| @@ -440,6 +484,10 @@ class Buffer: | |||
| 440 | ) | 484 | ) |
| 441 | # Buffer-backed: set True by _ensure_shmem_views after init_with_buffer. | 485 | # Buffer-backed: set True by _ensure_shmem_views after init_with_buffer. |
| 442 | self._shmem_ready = False | 486 | self._shmem_ready = False |
| 487 | + _extend_context( | ||
| 488 | + self._ctx, | ||
| 489 | + barrier_mode=barrier_mode, | ||
| 490 | + ) | ||
| 443 | self._comm_stream = torch_npu.npu.Stream( | 491 | self._comm_stream = torch_npu.npu.Stream( |
| 444 | device=int(self._ctx['device']), | 492 | device=int(self._ctx['device']), |
| 445 | priority=self.comm_stream_priority, | 493 | priority=self.comm_stream_priority, |
| @@ -523,6 +571,14 @@ class Buffer: | |||
| 523 | self._destroyed = True | 571 | self._destroyed = True |
| 524 | return | 572 | return |
| 525 | 573 | ||
| 574 | + # Reject before touching any op while SHMEM still owns VMM backing, | ||
| 575 | + # including when collective finalize failed. | ||
| 576 | + from . import buffer_c | ||
| 577 | + if buffer_c._SHMEM_BACKING_LOCKED: | ||
| 578 | + raise RuntimeError( | ||
| 579 | + 'cannot release VMM descriptor backing before a successful ' | ||
| 580 | + 'collective shmem finalize') | ||
| 581 | + | ||
| 526 | # torch_npu.npu.synchronize() below already drains every stream on the | 582 | # torch_npu.npu.synchronize() below already drains every stream on the |
| 527 | # device, including the comm stream, so no separate comm-stream sync. | 583 | # device, including the comm stream, so no separate comm-stream sync. |
| 528 | torch_npu.npu.synchronize() | 584 | torch_npu.npu.synchronize() |
| @@ -568,6 +624,8 @@ class Buffer: | |||
| 568 | self._ctx = None | 624 | self._ctx = None |
| 569 | self._comm_stream = None | 625 | self._comm_stream = None |
| 570 | self._destroyed = True | 626 | self._destroyed = True |
| 627 | + self._comm_buffers = None | ||
| 628 | + self.__dict__.get('_native_storage_bindings', []).clear() | ||
| 571 | 629 | ||
| 572 | def __del__(self): | 630 | def __del__(self): |
| 573 | if getattr(self, "_destroyed", True): | 631 | if getattr(self, "_destroyed", True): |
| @@ -602,6 +660,156 @@ class Buffer: | |||
| 602 | plan.dup_counts, | 660 | plan.dup_counts, |
| 603 | ) | 661 | ) |
| 604 | 662 | ||
| 663 | + @property | ||
| 664 | + def comm_stream(self): | ||
| 665 | + """The single ordered native communication stream (read-only binding).""" | ||
| 666 | + self._require_ctx() | ||
| 667 | + return self._comm_stream | ||
| 668 | + | ||
| 669 | + def barrier_on_stream(self, stream): | ||
| 670 | + """Enqueue the configured collective fence; caller owns its ordering.""" | ||
| 671 | + self._require_ctx() | ||
| 672 | + if stream.device != self._comm_stream.device: | ||
| 673 | + raise ValueError('barrier stream must share the Buffer device') | ||
| 674 | + _C.acl_shmem_barrier_all_on_stream(stream.npu_stream) | ||
| 675 | + | ||
| 676 | + def prepare_comm_buffers(self, hidden_source, route_source): | ||
| 677 | + """Prepare caller-owned banks after SHMEM init, before hot calls. | ||
| 678 | + | ||
| 679 | + Register the VMM backing for both sources before init_with_buffer. | ||
| 680 | + This method only maps views; it does not allocate memory or choose capacity. | ||
| 681 | + """ | ||
| 682 | + ctx = self._require_ctx() | ||
| 683 | + nvs, hidden_size = int(ctx['NvS']), int(ctx['H']) | ||
| 684 | + if (hidden_source.dtype != torch.bfloat16 or route_source.dtype != torch.int32 or | ||
| 685 | + tuple(hidden_source.shape) != (nvs, hidden_size) or | ||
| 686 | + tuple(route_source.shape) != (nvs,) or | ||
| 687 | + hidden_source.device != ctx['hidden_buf_local'].device or | ||
| 688 | + route_source.device != hidden_source.device or overlaps(hidden_source, route_source)): | ||
| 689 | + raise ValueError('expected distinct capacity-sized BF16 hidden and INT32 route VMM sources') | ||
| 690 | + hidden, route = symmetric_source(hidden_source), symmetric_source(route_source) | ||
| 691 | + result = CommBuffers(hidden, route, (hidden_source, route_source)) | ||
| 692 | + self.__dict__.setdefault('_native_storage_bindings', []).append(result) | ||
| 693 | + return result | ||
| 694 | + | ||
| 695 | + def set_comm_buffers(self, comm_buffers: CommBuffers | None) -> None: | ||
| 696 | + """Select prepared storage for subsequent Dispatch and Combine calls. | ||
| 697 | + | ||
| 698 | + Selection does not wait for outstanding work or release the old bank. | ||
| 699 | + Use one host submission thread; callers own cross-rank and reuse order. | ||
| 700 | + None selects the Buffer's default storage. | ||
| 701 | + """ | ||
| 702 | + self._require_ctx() | ||
| 703 | + if comm_buffers is not None and not isinstance(comm_buffers, CommBuffers): | ||
| 704 | + raise TypeError('comm_buffers must be CommBuffers or None') | ||
| 705 | + self._comm_buffers = comm_buffers | ||
| 706 | + | ||
| 707 | + def prepare_expert_binding(self, expert_tensors, comm_buffer_source) -> ExpertPointerBinding: | ||
| 708 | + """Prepare expert addresses and one registered local communication buffer. | ||
| 709 | + | ||
| 710 | + The communication buffer dtype selects BF16 expert weight sources or | ||
| 711 | + FP32 canonical gradient destinations; expert tensors must match it. | ||
| 712 | + All device pointer metadata/scratch is prepared | ||
| 713 | + here, never on an execution-path cache miss. Addresses must stay fixed. | ||
| 714 | + Prepare and submit from the same caller stream. Async submission makes | ||
| 715 | + the communication stream wait for that caller stream. | ||
| 716 | + """ | ||
| 717 | + ctx = self._require_ctx() | ||
| 718 | + expert_tensors = tuple(expert_tensors) | ||
| 719 | + ranks, slots = int(ctx['R']), int(ctx['B']) | ||
| 720 | + local_experts = int(ctx['E']) // ranks | ||
| 721 | + dtype = comm_buffer_source.dtype | ||
| 722 | + if dtype not in (torch.bfloat16, torch.float32): | ||
| 723 | + raise TypeError('expert communication buffer must be BF16 or FP32') | ||
| 724 | + if (comm_buffer_source.ndim != 3 or comm_buffer_source.shape[0] != slots or | ||
| 725 | + min(comm_buffer_source.shape[1:]) <= 0 or | ||
| 726 | + comm_buffer_source.device != ctx['hidden_buf_local'].device): | ||
| 727 | + raise ValueError('expert communication buffer must be local [B,M,N] on the Buffer device') | ||
| 728 | + comm_buffer = symmetric_source(comm_buffer_source) | ||
| 729 | + addresses, ranges = self._validate_expert_tensors( | ||
| 730 | + expert_tensors, comm_buffer, dtype=dtype, operation='prepare expert pointers', expected_experts=local_experts) | ||
| 731 | + slot_bytes = comm_buffer_source.numel() * comm_buffer_source.element_size() | ||
| 732 | + if any(start < base + slot_bytes and base < end | ||
| 733 | + for base in (comm_buffer_source.data_ptr(), comm_buffer.data_ptr()) for start, end in ranges): | ||
| 734 | + raise ValueError('expert tensors must not alias their communication buffer') | ||
| 735 | + if dtype == torch.float32: | ||
| 736 | + ordered = sorted(ranges) | ||
| 737 | + if any(a[1] > b[0] for a, b in zip(ordered, ordered[1:])): | ||
| 738 | + raise ValueError('canonical gradient destinations must not overlap') | ||
| 739 | + if slots != local_experts: | ||
| 740 | + raise ValueError('gradient reduction requires one gradient slot per local expert') | ||
| 741 | + use_udma = ctx.get('_grad_reduce_use_udma', False) | ||
| 742 | + if use_udma and ctx.get('_grad_reduce_target_workspace') is None: | ||
| 743 | + blocks = int(min(ctx['num_sms'], 64)) | ||
| 744 | + elements = 512 * 1024 * max(2 * blocks, ranks * slots) | ||
| 745 | + ctx['_grad_reduce_target_workspace'] = torch.empty( | ||
| 746 | + elements, dtype=torch.float32, device=comm_buffer.device) | ||
| 747 | + expert_views = tuple(ref.detach() for ref in expert_tensors) | ||
| 748 | + expert_ptrs = torch.tensor(addresses, dtype=torch.int64, device=comm_buffer.device) | ||
| 749 | + result = ExpertPointerBinding(expert_tensors, expert_views, comm_buffer, comm_buffer_source, expert_ptrs, | ||
| 750 | + tuple(tensor_signature(ref) for ref in expert_tensors)) | ||
| 751 | + self.__dict__.setdefault('_native_storage_bindings', []).append(result) | ||
| 752 | + return result | ||
| 753 | + | ||
| 754 | + def _validate_pointer_binding(self, binding, plan, *, dtype): | ||
| 755 | + ctx = self._require_ctx() | ||
| 756 | + if not isinstance(binding, ExpertPointerBinding): | ||
| 757 | + raise TypeError('expert pointer binding must be ExpertPointerBinding') | ||
| 758 | + if not ShmemRuntime.is_initialized() or getattr(ShmemRuntime, '_poisoned', False): | ||
| 759 | + raise RuntimeError('expert pointer execution requires initialized healthy SHMEM') | ||
| 760 | + validate_unchanged(binding.expert_tensors, binding.tensor_signatures) | ||
| 761 | + if binding.comm_buffer.dtype != dtype: | ||
| 762 | + raise TypeError('expert pointer binding has the wrong projection dtype') | ||
| 763 | + self._validate_expert_plan(plan, binding.comm_buffer, 'expert pointer communication') | ||
| 764 | + return ctx | ||
| 765 | + | ||
| 766 | + def prefetch_weight_from_ptrs(self, plan, weight_binding, async_finish: bool = False): | ||
| 767 | + """Prefetch BF16 expert weights through their prepared address table.""" | ||
| 768 | + binding = weight_binding | ||
| 769 | + ctx = self._validate_pointer_binding(binding, plan, dtype=torch.bfloat16) | ||
| 770 | + operation = ctx['kernels']['prefetch'].compute_from_ptrs | ||
| 771 | + args = (ctx, binding.expert_ptrs, binding.comm_buffer, plan.experts_to_copy) | ||
| 772 | + | ||
| 773 | + if not async_finish: | ||
| 774 | + operation(*args) | ||
| 775 | + return None | ||
| 776 | + | ||
| 777 | + prev_stream = torch_npu.npu.current_stream() | ||
| 778 | + with torch_npu.npu.stream(self._comm_stream): | ||
| 779 | + self._comm_stream.wait_stream(prev_stream) | ||
| 780 | + operation(*args) | ||
| 781 | + self._record_streams( | ||
| 782 | + (*binding.expert_views, binding.comm_buffer, binding.comm_buffer_source, binding.expert_ptrs, | ||
| 783 | + plan.experts_to_copy), self._comm_stream) | ||
| 784 | + done = self._comm_stream.record_event() | ||
| 785 | + return done | ||
| 786 | + | ||
| 787 | + def reduce_grad_to_ptrs(self, plan, grad_binding, async_finish: bool = False): | ||
| 788 | + """Accumulate FP32 slot gradients into prepared expert destinations.""" | ||
| 789 | + binding = grad_binding | ||
| 790 | + ctx = self._validate_pointer_binding(binding, plan, dtype=torch.float32) | ||
| 791 | + if not async_finish: | ||
| 792 | + ctx['kernels']['grad_reduce'].compute_targets( | ||
| 793 | + ctx, binding.expert_ptrs, binding.comm_buffer, plan.experts_to_copy, | ||
| 794 | + rank=int(ctx['rank']), | ||
| 795 | + num_sms=int(ctx['num_sms'])) | ||
| 796 | + return None | ||
| 797 | + | ||
| 798 | + prev_stream = torch_npu.npu.current_stream() | ||
| 799 | + with torch_npu.npu.stream(self._comm_stream): | ||
| 800 | + self._comm_stream.wait_stream(prev_stream) | ||
| 801 | + ctx['kernels']['grad_reduce'].compute_targets( | ||
| 802 | + ctx, binding.expert_ptrs, binding.comm_buffer, plan.experts_to_copy, | ||
| 803 | + rank=int(ctx['rank']), | ||
| 804 | + num_sms=int(ctx['num_sms'])) | ||
| 805 | + self._record_streams( | ||
| 806 | + (*binding.expert_views, binding.comm_buffer, binding.comm_buffer_source, binding.expert_ptrs, | ||
| 807 | + plan.experts_to_copy, ctx.get('_grad_reduce_target_workspace')), | ||
| 808 | + self._comm_stream) | ||
| 809 | + done = self._comm_stream.record_event() | ||
| 810 | + return done | ||
| 811 | + | ||
| 812 | + | ||
| 605 | def _run_dispatch_on_current_stream( | 813 | def _run_dispatch_on_current_stream( |
| 606 | self, | 814 | self, |
| 607 | ctx: dict, | 815 | ctx: dict, |
| @@ -655,7 +863,6 @@ class Buffer: | |||
| 655 | zero_copy: bool, | 863 | zero_copy: bool, |
| 656 | router_weights_zero_copy: bool = False, | 864 | router_weights_zero_copy: bool = False, |
| 657 | ) -> None: | 865 | ) -> None: |
| 658 | - stream = torch_npu.npu.current_stream().npu_stream | ||
| 659 | if not zero_copy: | 866 | if not zero_copy: |
| 660 | # master-style boundary copy of the hidden shard (same stream). | 867 | # master-style boundary copy of the hidden shard (same stream). |
| 661 | ctx['hidden_buf_local'].copy_(hidden_nvsh) | 868 | ctx['hidden_buf_local'].copy_(hidden_nvsh) |
| @@ -667,6 +874,9 @@ class Buffer: | |||
| 667 | # peer shards. Keeping this boundary common lets CombineOp own the | 874 | # peer shards. Keeping this boundary common lets CombineOp own the |
| 668 | # implementation selection without duplicating Buffer call paths. | 875 | # implementation selection without duplicating Buffer call paths. |
| 669 | if inter_rank_sync: | 876 | if inter_rank_sync: |
| 877 | + # Fetch the raw stream after the copies to flush torch_npu's CPU | ||
| 878 | + # task queue before enqueueing the SHMEM barrier (upstream PR #14). | ||
| 879 | + stream = torch_npu.npu.current_stream().npu_stream | ||
| 670 | cross_rank_barrier(ctx, stream) | 880 | cross_rank_barrier(ctx, stream) |
| 671 | # Prologue is folded into moonEP_combine (cf. dispatch_epilogue). | 881 | # Prologue is folded into moonEP_combine (cf. dispatch_epilogue). |
| 672 | ctx['kernels']['combine'].compute( | 882 | ctx['kernels']['combine'].compute( |
| @@ -677,6 +887,59 @@ class Buffer: | |||
| 677 | shmem_instance_id=0, | 887 | shmem_instance_id=0, |
| 678 | ) | 888 | ) |
| 679 | 889 | ||
| 890 | + @staticmethod | ||
| 891 | + def _validate_expert_tensors(expert_tensors, comm_buffer, *, dtype, operation, expected_experts): | ||
| 892 | + """Host metadata validation only; never materialize a device tensor.""" | ||
| 893 | + expert_tensors = tuple(expert_tensors) | ||
| 894 | + if _C is None: | ||
| 895 | + raise RuntimeError(f"{operation} requires the npu_patch native extension") | ||
| 896 | + if not isinstance(comm_buffer, torch.Tensor) or comm_buffer.ndim < 2: | ||
| 897 | + raise TypeError(f"{operation} comm_buffer must be a [B,...] Tensor") | ||
| 898 | + if not comm_buffer.is_contiguous() or comm_buffer.dtype != dtype: | ||
| 899 | + raise TypeError(f"{operation} comm_buffer must be contiguous {dtype}") | ||
| 900 | + count = expected_experts | ||
| 901 | + if type(count) is not int or count <= 0 or len(expert_tensors) != count: | ||
| 902 | + raise ValueError(f"{operation} requires exactly {count} local expert references") | ||
| 903 | + row_shape = tuple(int(value) for value in comm_buffer.shape[1:]) | ||
| 904 | + addresses = [] | ||
| 905 | + ranges = [] | ||
| 906 | + for index, ref in enumerate(expert_tensors): | ||
| 907 | + if not isinstance(ref, torch.Tensor): | ||
| 908 | + raise TypeError(f"{operation} reference {index} is not a Tensor") | ||
| 909 | + if ref.device != comm_buffer.device: | ||
| 910 | + raise RuntimeError(f"{operation} references and slots must share one NPU") | ||
| 911 | + if ref.dtype != dtype or not ref.is_contiguous(): | ||
| 912 | + raise TypeError(f"{operation} references must be contiguous {dtype}") | ||
| 913 | + if tuple(int(value) for value in ref.shape) != row_shape: | ||
| 914 | + raise ValueError( | ||
| 915 | + f"{operation} reference {index} shape {tuple(ref.shape)} " | ||
| 916 | + f"does not match slot row {row_shape}" | ||
| 917 | + ) | ||
| 918 | + begin = int(ref.data_ptr()) | ||
| 919 | + end = begin + int(ref.numel()) * int(ref.element_size()) | ||
| 920 | + addresses.append(begin) | ||
| 921 | + ranges.append((begin, end)) | ||
| 922 | + return addresses, ranges | ||
| 923 | + | ||
| 924 | + | ||
| 925 | + def _validate_expert_plan(self, plan, comm_buffer, operation): | ||
| 926 | + if not isinstance(plan, MoonEPCommPlan): | ||
| 927 | + raise TypeError(f"{operation} requires a MoonEPCommPlan") | ||
| 928 | + ctx = self._require_ctx() | ||
| 929 | + _validate_plan_layout(ctx, plan) | ||
| 930 | + experts_to_copy = plan.experts_to_copy | ||
| 931 | + if ( | ||
| 932 | + experts_to_copy.dtype != torch.int32 | ||
| 933 | + or experts_to_copy.ndim != 2 | ||
| 934 | + or not experts_to_copy.is_contiguous() | ||
| 935 | + ): | ||
| 936 | + raise TypeError(f"{operation} plan must contain contiguous INT32 [R,B] experts") | ||
| 937 | + if experts_to_copy.device != comm_buffer.device: | ||
| 938 | + raise RuntimeError(f"{operation} plan and comm_buffer must share one NPU") | ||
| 939 | + if int(experts_to_copy.shape[1]) != int(comm_buffer.shape[0]): | ||
| 940 | + raise ValueError(f"{operation} plan B does not match comm_buffer") | ||
| 941 | + | ||
| 942 | + | ||
| 680 | def _run_prefetch_weight_on_current_stream( | 943 | def _run_prefetch_weight_on_current_stream( |
| 681 | self, | 944 | self, |
| 682 | ctx: dict, | 945 | ctx: dict, |
| @@ -836,8 +1099,14 @@ class Buffer: | |||
| 836 | into via the peer address), and ``router_weights_zero_copy`` independently | 1099 | into via the peer address), and ``router_weights_zero_copy`` independently |
| 837 | returns the ``route_weights_nvs`` fp32 view of ``weights_buf_local`` | 1100 | returns the ``route_weights_nvs`` fp32 view of ``weights_buf_local`` |
| 838 | instead of a fresh copy (default False, matching the CUDA API). | 1101 | instead of a fresh copy (default False, matching the CUDA API). |
| 1102 | + Autograd integrations must manage their own Tensor wrappers and saved | ||
| 1103 | + values before returning these aliases through a custom Function. | ||
| 1104 | + Input shapes must match S, H and K fixed at Buffer construction. | ||
| 1105 | + Only plan-defined rows are valid; callers own initialization of unused | ||
| 1106 | + carrier capacity before including it in downstream computation. | ||
| 839 | """ | 1107 | """ |
| 840 | ctx = self._require_ctx() | 1108 | ctx = self._require_ctx() |
| 1109 | + comm_buffers = getattr(self, '_comm_buffers', None) | ||
| 841 | self._ensure_shmem_views() | 1110 | self._ensure_shmem_views() |
| 842 | 1111 | ||
| 843 | if plan is None: | 1112 | if plan is None: |
| @@ -851,7 +1120,10 @@ class Buffer: | |||
| 851 | else: | 1120 | else: |
| 852 | cu_seqlens = None | 1121 | cu_seqlens = None |
| 853 | planning_args = None | 1122 | planning_args = None |
| 854 | - assert isinstance(plan, MoonEPCommPlan) | 1123 | + _validate_plan_layout(ctx, plan) |
| 1124 | + | ||
| 1125 | + if comm_buffers is not None: | ||
| 1126 | + ctx = comm_context(ctx, comm_buffers) | ||
| 855 | 1127 | ||
| 856 | if zero_copy: | 1128 | if zero_copy: |
| 857 | hidden_nvsh = ctx['hidden_buf_local'] | 1129 | hidden_nvsh = ctx['hidden_buf_local'] |
| @@ -893,6 +1165,8 @@ class Buffer: | |||
| 893 | plan.dup_counts, | 1165 | plan.dup_counts, |
| 894 | *(planning_args or ()), | 1166 | *(planning_args or ()), |
| 895 | ) | 1167 | ) |
| 1168 | + if comm_buffers is not None: | ||
| 1169 | + tensors += (*comm_buffers.sources, comm_buffers.hidden, comm_buffers.route) | ||
| 896 | # First make comm_stream wait for sync work already queued on the | 1170 | # First make comm_stream wait for sync work already queued on the |
| 897 | # current stream (e.g. a preceding dispatch) to drain, then launch | 1171 | # current stream (e.g. a preceding dispatch) to drain, then launch |
| 898 | # async on comm_stream; otherwise the two streams race over the same | 1172 | # async on comm_stream; otherwise the two streams race over the same |
| @@ -1001,12 +1275,21 @@ class Buffer: | |||
| 1001 | router_weights_zero_copy: bool = False, | 1275 | router_weights_zero_copy: bool = False, |
| 1002 | ): | 1276 | ): |
| 1003 | """combine fwd: gather expert outputs from the symmetric shard and | 1277 | """combine fwd: gather expert outputs from the symmetric shard and |
| 1004 | - K-sum back to token-major [S, H]. Also serves as dispatch bwd.""" | 1278 | + K-sum back to token-major [S, H]. Also serves as dispatch bwd. |
| 1279 | + | ||
| 1280 | + Prepared communication storage is selected with set_comm_buffers(). | ||
| 1281 | + """ | ||
| 1005 | ctx = self._require_ctx() | 1282 | ctx = self._require_ctx() |
| 1283 | + comm_buffers = getattr(self, '_comm_buffers', None) | ||
| 1006 | self._ensure_shmem_views() | 1284 | self._ensure_shmem_views() |
| 1007 | 1285 | ||
| 1008 | assert isinstance(plan, MoonEPCommPlan), "Buffer.combine: plan is required" | 1286 | assert isinstance(plan, MoonEPCommPlan), "Buffer.combine: plan is required" |
| 1009 | 1287 | ||
| 1288 | + _validate_plan_layout(ctx, plan) | ||
| 1289 | + | ||
| 1290 | + if comm_buffers is not None: | ||
| 1291 | + ctx = comm_context(ctx, comm_buffers) | ||
| 1292 | + | ||
| 1010 | assert hidden_nvsh is not None | 1293 | assert hidden_nvsh is not None |
| 1011 | assert hidden_nvsh.dtype == torch.bfloat16 | 1294 | assert hidden_nvsh.dtype == torch.bfloat16 |
| 1012 | assert hidden_nvsh.is_contiguous() | 1295 | assert hidden_nvsh.is_contiguous() |
| @@ -1066,6 +1349,8 @@ class Buffer: | |||
| 1066 | plan.remote_stats, plan.dup_groups, plan.dup_loffs, | 1349 | plan.remote_stats, plan.dup_groups, plan.dup_loffs, |
| 1067 | plan.dup_counts, | 1350 | plan.dup_counts, |
| 1068 | ) | 1351 | ) |
| 1352 | + if comm_buffers is not None: | ||
| 1353 | + tensors += (*comm_buffers.sources, comm_buffers.hidden, comm_buffers.route) | ||
| 1069 | prev_stream = torch_npu.npu.current_stream() | 1354 | prev_stream = torch_npu.npu.current_stream() |
| 1070 | with torch_npu.npu.stream(self._comm_stream): | 1355 | with torch_npu.npu.stream(self._comm_stream): |
| 1071 | self._comm_stream.wait_stream(prev_stream) | 1356 | self._comm_stream.wait_stream(prev_stream) |
| @@ -1104,6 +1389,7 @@ class Buffer: | |||
| 1104 | rank's home grads, rows ``[E, E+B)`` are backed by the reduce buffer — | 1389 | rank's home grads, rows ``[E, E+B)`` are backed by the reduce buffer — |
| 1105 | and each ``*_reduce_buffer`` is the full ``[R, B, H, H']`` fp32 view | 1390 | and each ``*_reduce_buffer`` is the full ``[R, B, H, H']`` fp32 view |
| 1106 | (all R ranks' reduce buffers mapped as one). | 1391 | (all R ranks' reduce buffers mapped as one). |
| 1392 | + | ||
| 1107 | """ | 1393 | """ |
| 1108 | projection_grads = (full_gate_grad, full_up_grad, full_down_grad) | 1394 | projection_grads = (full_gate_grad, full_up_grad, full_down_grad) |
| 1109 | reduce_buffers = ( | 1395 | reduce_buffers = ( |
| @@ -0,0 +1,324 @@ | |||
| 1 | +""" | ||
| 2 | +MoonEP-Ascend remote expert weight-grad reduce benchmark (canonical targets). | ||
| 3 | + | ||
| 4 | +Matches ``bench_grad_reduce.py``'s cases and timing, driven through the | ||
| 5 | +low-level ``launch_grad_reduce_targets`` instead of ``launch_grad_reduce``. | ||
| 6 | +On Ascend each rank owns local fp32 ``[H, H']`` target tensors (ordinary memory, | ||
| 7 | +handed to the op as a pointer table) and a ``[B, H, H']`` fp32 reduce-slot chunk | ||
| 8 | +(symmetric memory); duplicated experts' grads are reduced into those targets and | ||
| 9 | +the consumed slots are cleared. This variant passes ``epn`` local target | ||
| 10 | +addresses. The unchanged dense reference currently allocates ``E = R * epn`` | ||
| 11 | +home rows; matching case fields does not remove that workload difference. | ||
| 12 | +``epn`` counts local targets; ``B`` is independent slot capacity. Both the | ||
| 13 | +default suite's B values and the ``--B`` default (14) match the dense benchmark. | ||
| 14 | + | ||
| 15 | +The reported latency is the worst rank's (``agg=max``), matching the CUDA | ||
| 16 | +reference's owner-rank timing. ``DEFAULT_CASES`` (labels + settings) are kept | ||
| 17 | +identical to ``bench_grad_reduce.py``, including slot capacity and contribution | ||
| 18 | +counts; the production 8-card shape (H=7168, Hp=3072, E=896, B=112) is run via | ||
| 19 | +``--single``. | ||
| 20 | + | ||
| 21 | +Run: | ||
| 22 | + bash npu_patch/benchmarks/run_bench.sh bench_grad_reduce_targets.py # default suite | ||
| 23 | + bash npu_patch/benchmarks/run_bench.sh bench_grad_reduce_targets.py "--single --epn 112 --H 7168 --Hp 3072 --B 112 --nremote 2" | ||
| 24 | +""" | ||
| 25 | + | ||
| 26 | +import argparse | ||
| 27 | +import csv | ||
| 28 | +import os | ||
| 29 | +import sys | ||
| 30 | + | ||
| 31 | +import torch | ||
| 32 | +import torch_npu | ||
| 33 | +import torch.distributed as dist | ||
| 34 | + | ||
| 35 | +if __package__: | ||
| 36 | + from ._bench_common import ( | ||
| 37 | + add_common_args, | ||
| 38 | + apply_engine, | ||
| 39 | + setup, | ||
| 40 | + time_kernel, | ||
| 41 | + time_text, | ||
| 42 | + ) | ||
| 43 | +else: | ||
| 44 | + from _bench_common import ( | ||
| 45 | + add_common_args, | ||
| 46 | + apply_engine, | ||
| 47 | + setup, | ||
| 48 | + time_kernel, | ||
| 49 | + time_text, | ||
| 50 | + ) | ||
| 51 | +from npu_patch._device import local_device_index | ||
| 52 | +from npu_patch.buffer_c import ( | ||
| 53 | + create_vmm_physical, | ||
| 54 | + reset_symmetric_descriptors, | ||
| 55 | + sym_tensor, | ||
| 56 | +) | ||
| 57 | +from npu_patch.launchers import launch_grad_reduce_targets | ||
| 58 | +from npu_patch.shmem_runtime import ShmemRuntime | ||
| 59 | + | ||
| 60 | +NUM_SMS = 32 | ||
| 61 | +EXP_H = 3584 | ||
| 62 | +EXP_HP = 3072 | ||
| 63 | + | ||
| 64 | +# Match every dense case field, including B: pointer targets do not require | ||
| 65 | +# one slot per local expert. The two scripts use the same contribution grid. | ||
| 66 | +DEFAULT_CASES = [ | ||
| 67 | + {"label": "slots_1", "epn": 8, "H": EXP_H, "Hp": EXP_HP, "base_B": 14, | ||
| 68 | + "counts": [1, 0, 0, 0, 0, 0, 0, 0]}, | ||
| 69 | + {"label": "slots_2", "epn": 8, "H": EXP_H, "Hp": EXP_HP, "base_B": 14, | ||
| 70 | + "counts": [1, 1, 0, 0, 0, 0, 0, 0]}, | ||
| 71 | + {"label": "slots_3", "epn": 8, "H": EXP_H, "Hp": EXP_HP, "base_B": 14, | ||
| 72 | + "counts": [2, 1, 0, 0, 0, 0, 0, 0]}, | ||
| 73 | + {"label": "slots_5", "epn": 8, "H": EXP_H, "Hp": EXP_HP, "base_B": 14, | ||
| 74 | + "counts": [3, 2, 0, 0, 0, 0, 0, 0]}, | ||
| 75 | + {"label": "ramp_0_3", "epn": 8, "H": EXP_H, "Hp": EXP_HP, "base_B": 14, | ||
| 76 | + "counts": [0, 1, 2, 3, 0, 1, 2, 3]}, | ||
| 77 | + {"label": "mixed", "epn": 8, "H": EXP_H, "Hp": EXP_HP, "base_B": 14, | ||
| 78 | + "counts": [3, 0, 2, 1, 3, 0, 2, 1]}, | ||
| 79 | + {"label": "heavy", "epn": 8, "H": EXP_H, "Hp": EXP_HP, "base_B": 14, | ||
| 80 | + "counts": [3, 3, 2, 3, 1, 0, 2, 3]}, | ||
| 81 | + {"label": "full_3x8", "epn": 8, "H": EXP_H, "Hp": EXP_HP, "base_B": 14, | ||
| 82 | + "counts": [3, 3, 3, 3, 3, 3, 3, 3]}, | ||
| 83 | + {"label": "dense_B8", "epn": 8, "H": EXP_H, "Hp": EXP_HP, "base_B": 8, | ||
| 84 | + "counts": [2, 1, 3, 1, 2, 3, 1, 2]}, | ||
| 85 | + {"label": "epn4_full", "epn": 4, "H": EXP_H, "Hp": EXP_HP, "base_B": 14, | ||
| 86 | + "counts": [3, 3, 3, 3]}, | ||
| 87 | + {"label": "epn16_mixed", "epn": 16, "H": EXP_H, "Hp": EXP_HP, "base_B": 16, | ||
| 88 | + "counts": [3, 2, 1, 0, 3, 2, 1, 0, 3, 2, 1, 0, 3, 2, 1, 0]}, | ||
| 89 | + {"label": "thin_7168x128", "epn": 8, "H": 7168, "Hp": 128, "base_B": 14, | ||
| 90 | + "counts": [3, 0, 2, 1, 3, 0, 2, 1]}, | ||
| 91 | + {"label": "tall_1024x3072", "epn": 8, "H": 1024, "Hp": 3072, "base_B": 14, | ||
| 92 | + "counts": [3, 0, 2, 1, 3, 0, 2, 1]}, | ||
| 93 | + {"label": "tiny_512x512", "epn": 8, "H": 512, "Hp": 512, "base_B": 14, | ||
| 94 | + "counts": [3, 3, 2, 3, 1, 0, 2, 3]}, | ||
| 95 | +] | ||
| 96 | + | ||
| 97 | + | ||
| 98 | +def grad_reduce_plan(R, B, epn, counts, dev): | ||
| 99 | + """Expert e (owned by rank 0's ``epn`` share) is reduced ``counts[e]`` times. | ||
| 100 | + | ||
| 101 | + The contributing remote ranks are ``1..counts[e]``, each placing its grad in | ||
| 102 | + slot column e; all other slots stay idle (-1). Mirrors the CUDA reference. | ||
| 103 | + """ | ||
| 104 | + plan = torch.full((R, B), -1, dtype=torch.int32, device=dev) | ||
| 105 | + for e in range(epn): | ||
| 106 | + for src_rank in range(1, counts[e] + 1): | ||
| 107 | + plan[src_rank, e] = e | ||
| 108 | + return plan | ||
| 109 | + | ||
| 110 | + | ||
| 111 | +def check_payload(checks, group): | ||
| 112 | + passed = torch.stack(checks).all().to(torch.int32) | ||
| 113 | + dist.all_reduce(passed, op=dist.ReduceOp.MIN, group=group) | ||
| 114 | + if not bool(passed.item()): | ||
| 115 | + raise RuntimeError("collective payload/reference or slot-clear check failed") | ||
| 116 | + | ||
| 117 | + | ||
| 118 | +def explicit_single_config_requested(argv): | ||
| 119 | + flags = ("--epn", "--H", "--Hp", "--B", "--nremote") | ||
| 120 | + return any(arg == f or arg.startswith(f + "=") for arg in argv for f in flags) | ||
| 121 | + | ||
| 122 | + | ||
| 123 | +def parse_args(argv=None): | ||
| 124 | + ap = argparse.ArgumentParser(description=__doc__) | ||
| 125 | + add_common_args(ap) | ||
| 126 | + ap.add_argument("--suite", action="store_true", help="Run the default case suite.") | ||
| 127 | + ap.add_argument("--single", action="store_true", | ||
| 128 | + help="Run exactly the config given by --epn/--H/--Hp/--B/--nremote.") | ||
| 129 | + ap.add_argument("--epn", type=int, default=8) | ||
| 130 | + ap.add_argument("--H", type=int, default=EXP_H) | ||
| 131 | + ap.add_argument("--Hp", type=int, default=EXP_HP) | ||
| 132 | + ap.add_argument("--B", type=int, default=14, | ||
| 133 | + help="Reduction slot capacity, independent of epn (default: 14).") | ||
| 134 | + ap.add_argument("--nremote", type=int, default=2) | ||
| 135 | + ap.add_argument("--ip-port", help="SHMEM bootstrap URL for multi-node runs") | ||
| 136 | + args = ap.parse_args(argv) | ||
| 137 | + # This benchmark places expert e in column e, matching the dense plan | ||
| 138 | + # builder. Extra B columns remain idle; the operator itself accepts plans | ||
| 139 | + # with arbitrary mappings between slots and local experts. | ||
| 140 | + if min(args.epn, args.B, args.H, args.Hp, args.iters) <= 0 or args.warmup < 0 or args.nremote < 0: | ||
| 141 | + ap.error("dimensions/iters must be positive; warmup/nremote must be nonnegative") | ||
| 142 | + if args.num_sms is not None and not 8 <= args.num_sms <= 56: | ||
| 143 | + ap.error("num-sms must be in 8..56") | ||
| 144 | + return args | ||
| 145 | + | ||
| 146 | + | ||
| 147 | +def bench_case(case, args, rank, group, R, local_rank): | ||
| 148 | + dev = f"npu:{local_rank}" | ||
| 149 | + epn = int(case["epn"]) | ||
| 150 | + E = R * epn | ||
| 151 | + H = int(case["H"]) | ||
| 152 | + Hp = int(case["Hp"]) | ||
| 153 | + B = int(case["base_B"]) | ||
| 154 | + counts = case.get("counts") or [int(case.get("nremote", 1))] * epn | ||
| 155 | + num_sms = args.num_sms or NUM_SMS | ||
| 156 | + | ||
| 157 | + assert H % 128 == 0 and Hp % 128 == 0, \ | ||
| 158 | + f"{case['label']}: H and Hp must be multiples of 128" | ||
| 159 | + | ||
| 160 | + assert len(counts) == epn, f"{case['label']}: counts must have epn={epn} entries" | ||
| 161 | + assert all(0 <= c < R for c in counts), \ | ||
| 162 | + f"{case['label']}: each count must be in [0, R)" | ||
| 163 | + | ||
| 164 | + plan = grad_reduce_plan(R, B, epn, counts, dev) | ||
| 165 | + # Canonical targets: this rank's ``epn`` local fp32 ``[H, H']`` tensors, | ||
| 166 | + # handed to the op as a pointer table (ordinary memory, not symmetric). | ||
| 167 | + targets = tuple(torch.empty((H, Hp), dtype=torch.float32, device=dev) | ||
| 168 | + for _ in range(epn)) | ||
| 169 | + target_ptrs = torch.tensor([t.data_ptr() for t in targets], | ||
| 170 | + dtype=torch.int64, device=dev) | ||
| 171 | + # Buffer-backed only: allocate/register the VMM slot chunk; after | ||
| 172 | + # init_with_buffer it becomes the local symmetric tensor the kernel expects | ||
| 173 | + # (symmetric base). | ||
| 174 | + slots_src, _, _ = create_vmm_physical([B, H, Hp], torch.float32, local_rank) | ||
| 175 | + slots_src.zero_() | ||
| 176 | + workspace = (torch.empty(512 * 1024 * max(2 * min(num_sms, 64), R * B), | ||
| 177 | + dtype=torch.float32, device=dev) | ||
| 178 | + if args.use_udma else None) | ||
| 179 | + torch.npu.synchronize() | ||
| 180 | + dist.barrier(group=group) | ||
| 181 | + if not ShmemRuntime.is_initialized(): | ||
| 182 | + # This script calls `launch_grad_reduce_targets` directly (no Buffer): | ||
| 183 | + # the engine policy comes from env set by apply_engine, and enable_udma | ||
| 184 | + # is passed explicitly to keep the symmetric heap and op choice aligned. | ||
| 185 | + ShmemRuntime.init_with_buffer(group=group, tail_bytes=64 * 1024 * 1024, | ||
| 186 | + enable_udma=args.use_udma, | ||
| 187 | + ip_port=args.ip_port) | ||
| 188 | + slots = sym_tensor(slots_src) | ||
| 189 | + row = plan[rank].tolist() | ||
| 190 | + | ||
| 191 | + def fill_inputs(): | ||
| 192 | + for expert, target in enumerate(targets): | ||
| 193 | + target.fill_(3 + expert) | ||
| 194 | + slots.fill_(-17) | ||
| 195 | + for slot, expert in enumerate(row): | ||
| 196 | + if expert >= 0: | ||
| 197 | + slots[slot].fill_((rank + 1) * (slot + 1)) | ||
| 198 | + | ||
| 199 | + def submit(): | ||
| 200 | + launch_grad_reduce_targets(target_ptrs, slots, plan, rank=rank, | ||
| 201 | + num_sms=num_sms, udma_workspace=workspace) | ||
| 202 | + | ||
| 203 | + try: | ||
| 204 | + # Verify the payload / slot-clear contract once, on a single application. | ||
| 205 | + fill_inputs() | ||
| 206 | + torch.npu.synchronize() | ||
| 207 | + dist.barrier(group=group) | ||
| 208 | + submit() | ||
| 209 | + torch.npu.synchronize() | ||
| 210 | + checks = [] | ||
| 211 | + for expert, target in enumerate(targets): | ||
| 212 | + contribution = (sum((peer + 1) * (expert + 1) | ||
| 213 | + for peer in range(1, counts[expert] + 1)) | ||
| 214 | + if rank == 0 else 0) | ||
| 215 | + checks.append(torch.all(target == 3 + expert + contribution)) | ||
| 216 | + for slot, expert in enumerate(row): | ||
| 217 | + checks.append(torch.all(slots[slot] == (0 if expert >= 0 else -17))) | ||
| 218 | + check_payload(checks, group) | ||
| 219 | + | ||
| 220 | + # The nonzero preflight above is outside timing. Reset both operands | ||
| 221 | + # to match the dense benchmark's zero-input timed loop. | ||
| 222 | + for target in targets: | ||
| 223 | + target.zero_() | ||
| 224 | + slots_src.zero_() | ||
| 225 | + torch.npu.synchronize() | ||
| 226 | + dist.barrier(group=group) | ||
| 227 | + res = time_kernel( | ||
| 228 | + submit, group, rank, warmup=args.warmup, iters=args.iters, | ||
| 229 | + agg="max", cudagraph=args.cudagraph) | ||
| 230 | + finally: | ||
| 231 | + # Re-init per case: finalize (tear down symmetric mappings) first, then | ||
| 232 | + # reverse the VMM allocations, then clear the descriptor registry. | ||
| 233 | + dist.barrier(group=group) | ||
| 234 | + if ShmemRuntime.is_initialized(): | ||
| 235 | + ShmemRuntime.finalize() | ||
| 236 | + alloc = getattr(slots_src, "_vmm_allocation", None) | ||
| 237 | + if alloc is not None: | ||
| 238 | + alloc.destroy() | ||
| 239 | + reset_symmetric_descriptors() | ||
| 240 | + return res, E, B | ||
| 241 | + | ||
| 242 | + | ||
| 243 | +def main(): | ||
| 244 | + args = parse_args() | ||
| 245 | + if args.out and os.path.exists(args.out): | ||
| 246 | + raise FileExistsError("use a new --out CSV path") | ||
| 247 | + rank, world_size, local_rank = setup() | ||
| 248 | + local_rank = local_device_index(local_rank) | ||
| 249 | + args.use_udma = apply_engine(args.engine) | ||
| 250 | + R = args.ep_size if args.ep_size is not None else world_size | ||
| 251 | + assert R >= 2, "grad-reduce benchmark requires at least 2 ranks" | ||
| 252 | + assert R <= world_size, f"--ep-size {R} exceeds world size {world_size}" | ||
| 253 | + in_group = rank < R | ||
| 254 | + group = dist.new_group(ranks=list(range(R))) | ||
| 255 | + | ||
| 256 | + run_single = args.single or (not args.suite and explicit_single_config_requested(sys.argv[1:])) | ||
| 257 | + if run_single: | ||
| 258 | + cases = [{"label": "custom", "epn": args.epn, "H": args.H, "Hp": args.Hp, | ||
| 259 | + "base_B": args.B, "nremote": args.nremote}] | ||
| 260 | + else: | ||
| 261 | + cases = DEFAULT_CASES | ||
| 262 | + # Suite cases need R > max(counts) (a count c needs contributing ranks 1..c). | ||
| 263 | + skipped = [c["label"] for c in cases | ||
| 264 | + if max(c.get("counts") or [c.get("nremote", 1)] * c["epn"]) >= R] | ||
| 265 | + cases = [c for c in cases | ||
| 266 | + if max(c.get("counts") or [c.get("nremote", 1)] * c["epn"]) < R] | ||
| 267 | + if rank == 0 and skipped: | ||
| 268 | + print(f"NOTE: skipping {len(skipped)} cases needing >{R} ranks: " | ||
| 269 | + f"{', '.join(skipped)}", flush=True) | ||
| 270 | + | ||
| 271 | + if rank == 0: | ||
| 272 | + print(f"=== bench_grad_reduce_targets: world={world_size} R={R} " | ||
| 273 | + f"cases={len(cases)} === ", flush=True) | ||
| 274 | + | ||
| 275 | + dist.barrier() | ||
| 276 | + | ||
| 277 | + if rank == 0: | ||
| 278 | + print(f"{'Config':<20} {'E':>5} {'B':>4} {'H':>7} {'Hp':>6} {'Slots':>6} " | ||
| 279 | + f"{'Worst(us)':>10} {'Status':>8}") | ||
| 280 | + print("-" * 78) | ||
| 281 | + | ||
| 282 | + failures = 0 | ||
| 283 | + results = [] | ||
| 284 | + for case in cases: | ||
| 285 | + res = None | ||
| 286 | + if in_group: | ||
| 287 | + try: | ||
| 288 | + res, E, B = bench_case(case, args, rank, group, R, local_rank) | ||
| 289 | + except Exception: | ||
| 290 | + import traceback | ||
| 291 | + traceback.print_exc() | ||
| 292 | + res = None | ||
| 293 | + dist.barrier() | ||
| 294 | + | ||
| 295 | + if rank == 0: | ||
| 296 | + if res is None: | ||
| 297 | + failures += 1 | ||
| 298 | + print(f"{case['label']:<20} FAILED", flush=True) | ||
| 299 | + continue | ||
| 300 | + slots = sum(case.get("counts") or [case.get("nremote", 1)] * case["epn"]) | ||
| 301 | + st = "ok" if res["status"] == "ok" else "stub" | ||
| 302 | + print(f"{case['label']:<20} {E:>5} {B:>4} {case['H']:>7} {case['Hp']:>6} " | ||
| 303 | + f"{slots:>6} {time_text(res):>10} {st:>8}", flush=True) | ||
| 304 | + results.append(dict(Config=case["label"], E=E, B=B, H=case["H"], | ||
| 305 | + Hp=case["Hp"], Slots=slots, | ||
| 306 | + **{"Worst(us)": res["us"], "Status": res["status"]})) | ||
| 307 | + | ||
| 308 | + if rank == 0 and args.out: | ||
| 309 | + with open(args.out, "x", newline="", encoding="utf-8") as output: | ||
| 310 | + writer = csv.DictWriter(output, fieldnames=["Config", "E", "B", "H", "Hp", | ||
| 311 | + "Slots", "Worst(us)", "Status"]) | ||
| 312 | + writer.writeheader() | ||
| 313 | + writer.writerows(results) | ||
| 314 | + | ||
| 315 | + if in_group: | ||
| 316 | + ShmemRuntime.finalize() | ||
| 317 | + dist.destroy_process_group() | ||
| 318 | + if rank == 0 and failures: | ||
| 319 | + print(f"{failures}/{len(cases)} cases FAILED", flush=True) | ||
| 320 | + raise SystemExit(1) | ||
| 321 | + | ||
| 322 | + | ||
| 323 | +if __name__ == "__main__": | ||
| 324 | + main() | ||
| @@ -0,0 +1,309 @@ | |||
| 1 | +""" | ||
| 2 | +MoonEP-Ascend remote expert weight prefetch benchmark (pointer PUSH). | ||
| 3 | + | ||
| 4 | +Ascend port of ``MoonEP/benchmarks/bench_prefetch.py``, driven through the | ||
| 5 | +low-level ``launch_prefetch_from_ptrs`` exactly like ``test/test_prefetch.py``. | ||
| 6 | +Each rank owns a per-rank symmetric chunk ``[epn + B, H, H']`` bf16; the first | ||
| 7 | +``epn`` rows are this rank's local expert weights (the ``source_ptrs`` table) and | ||
| 8 | +the local ``[B, H, H']`` slice is the prefetch-slot buffer. Unlike the GET path | ||
| 9 | +the sources are passed as BF16 pointers and the whole ``[R, B]`` plan is passed | ||
| 10 | +instead of this rank's ``experts_to_copy`` row; ``--barrier-mode {mixed,aiv}`` | ||
| 11 | +selects the native pre/post barrier variant (this path does not take | ||
| 12 | +``--num-sms``). | ||
| 13 | + | ||
| 14 | +The reported latency is the worst rank's (``agg=max``). ``DEFAULT_CASES`` | ||
| 15 | +(labels + settings) are kept byte-for-byte identical to the origin so results | ||
| 16 | +compare directly; the production 8-card shape (H=7168, Hp=3072, E=896, B=112) | ||
| 17 | +is run via ``--single``. | ||
| 18 | + | ||
| 19 | +Run: | ||
| 20 | + bash npu_patch/benchmarks/run_bench.sh bench_prefetch_push.py # default suite | ||
| 21 | + bash npu_patch/benchmarks/run_bench.sh bench_prefetch_push.py "--single --epn 112 --H 7168 --Hp 3072 --B 112 --nremote 2" | ||
| 22 | +""" | ||
| 23 | + | ||
| 24 | +import argparse | ||
| 25 | +import csv | ||
| 26 | +import os | ||
| 27 | +import sys | ||
| 28 | + | ||
| 29 | +import torch | ||
| 30 | +import torch_npu | ||
| 31 | +import torch.distributed as dist | ||
| 32 | + | ||
| 33 | +from _bench_common import ( | ||
| 34 | + add_common_args, | ||
| 35 | + apply_engine, | ||
| 36 | + setup, | ||
| 37 | + time_kernel, | ||
| 38 | + time_text, | ||
| 39 | +) | ||
| 40 | +from npu_patch import ShmemRuntime, launch_prefetch_from_ptrs | ||
| 41 | +from npu_patch.buffer_c import ( | ||
| 42 | + create_sym_tensor_from_ptr, | ||
| 43 | + create_vmm_physical, | ||
| 44 | + map_to_sym_ptr, | ||
| 45 | + reset_symmetric_descriptors, | ||
| 46 | +) | ||
| 47 | + | ||
| 48 | +EXP_H = 3584 | ||
| 49 | +EXP_HP = 3072 | ||
| 50 | + | ||
| 51 | +# Byte-for-byte the origin's suite: the PUSH and GET variants run the same | ||
| 52 | +# workload. | ||
| 53 | +DEFAULT_CASES = [ | ||
| 54 | + {"label": "slots_1", "epn": 8, "H": EXP_H, "Hp": EXP_HP, "base_B": 14, | ||
| 55 | + "counts": [1, 0, 0, 0, 0, 0, 0, 0]}, | ||
| 56 | + {"label": "slots_2", "epn": 8, "H": EXP_H, "Hp": EXP_HP, "base_B": 14, | ||
| 57 | + "counts": [1, 1, 0, 0, 0, 0, 0, 0]}, | ||
| 58 | + {"label": "slots_3", "epn": 8, "H": EXP_H, "Hp": EXP_HP, "base_B": 14, | ||
| 59 | + "counts": [2, 1, 0, 0, 0, 0, 0, 0]}, | ||
| 60 | + {"label": "slots_5", "epn": 8, "H": EXP_H, "Hp": EXP_HP, "base_B": 14, | ||
| 61 | + "counts": [3, 2, 0, 0, 0, 0, 0, 0]}, | ||
| 62 | + {"label": "ramp_0_3", "epn": 8, "H": EXP_H, "Hp": EXP_HP, "base_B": 14, | ||
| 63 | + "counts": [0, 1, 2, 3, 0, 1, 2, 3]}, | ||
| 64 | + {"label": "mixed", "epn": 8, "H": EXP_H, "Hp": EXP_HP, "base_B": 14, | ||
| 65 | + "counts": [3, 0, 2, 1, 3, 0, 2, 1]}, | ||
| 66 | + {"label": "heavy", "epn": 8, "H": EXP_H, "Hp": EXP_HP, "base_B": 14, | ||
| 67 | + "counts": [3, 3, 2, 3, 1, 0, 2, 3]}, | ||
| 68 | + {"label": "full_3x8", "epn": 8, "H": EXP_H, "Hp": EXP_HP, "base_B": 14, | ||
| 69 | + "counts": [3, 3, 3, 3, 3, 3, 3, 3]}, | ||
| 70 | + {"label": "dense_B8", "epn": 8, "H": EXP_H, "Hp": EXP_HP, "base_B": 8, | ||
| 71 | + "counts": [2, 1, 3, 1, 2, 3, 1, 2]}, | ||
| 72 | + {"label": "epn4_full", "epn": 4, "H": EXP_H, "Hp": EXP_HP, "base_B": 14, | ||
| 73 | + "counts": [3, 3, 3, 3]}, | ||
| 74 | + {"label": "epn16_mixed", "epn": 16, "H": EXP_H, "Hp": EXP_HP, "base_B": 16, | ||
| 75 | + "counts": [3, 2, 1, 0, 3, 2, 1, 0, 3, 2, 1, 0, 3, 2, 1, 0]}, | ||
| 76 | + {"label": "thin_7168x128", "epn": 8, "H": 7168, "Hp": 128, "base_B": 14, | ||
| 77 | + "counts": [3, 0, 2, 1, 3, 0, 2, 1]}, | ||
| 78 | + {"label": "tall_1024x3072", "epn": 8, "H": 1024, "Hp": 3072, "base_B": 14, | ||
| 79 | + "counts": [3, 0, 2, 1, 3, 0, 2, 1]}, | ||
| 80 | + {"label": "tiny_512x512", "epn": 8, "H": 512, "Hp": 512, "base_B": 14, | ||
| 81 | + "counts": [3, 3, 2, 3, 1, 0, 2, 3]}, | ||
| 82 | +] | ||
| 83 | + | ||
| 84 | + | ||
| 85 | +def make_symmetric_experts(rank, R, E, H, Hp, B): | ||
| 86 | + """Allocate the per-rank [epn + B, H, Hp] VMM chunk registered with the | ||
| 87 | + buffer-backed init. Returns the source tensor (``data_ptr`` = source VA); | ||
| 88 | + kernel args are mapped to local symmetric tensors via ``map_to_sym_ptr`` | ||
| 89 | + in ``bench_case``. ``rank`` is only used for shape math: the VMM physical | ||
| 90 | + allocation must land on the physical card of the current logical device | ||
| 91 | + (in multi-node the global rank is not a local card id), hence | ||
| 92 | + ``torch.npu.current_device()``. | ||
| 93 | + """ | ||
| 94 | + epn = (E + R - 1) // R | ||
| 95 | + return create_vmm_physical( | ||
| 96 | + [epn + B, H, Hp], torch.bfloat16, | ||
| 97 | + torch.npu.current_device())[0] | ||
| 98 | + | ||
| 99 | + | ||
| 100 | +def prefetch_plan(R, B, epn, counts, dev): | ||
| 101 | + """Rank r pulls remote expert ``(r-1)*epn + e`` for column e when r <= counts[e]. | ||
| 102 | + | ||
| 103 | + Mirrors the CUDA reference's slot grid: idle slots stay -1. ``counts[e]`` | ||
| 104 | + must be < R so every id fits in the remote table; ``epn <= B`` so column e | ||
| 105 | + exists. The PUSH variant inverts the same grid: the owner of expert | ||
| 106 | + ``(r-1)*epn + e`` pushes it into rank r's slot e. | ||
| 107 | + """ | ||
| 108 | + plan = torch.full((R, B), -1, dtype=torch.int32, device=dev) | ||
| 109 | + for e in range(epn): | ||
| 110 | + for src_rank in range(1, counts[e] + 1): | ||
| 111 | + plan[src_rank, e] = (src_rank - 1) * epn + e | ||
| 112 | + return plan | ||
| 113 | + | ||
| 114 | + | ||
| 115 | +def check_payload(checks, group): | ||
| 116 | + passed = torch.stack(checks).all().to(torch.int32) | ||
| 117 | + dist.all_reduce(passed, op=dist.ReduceOp.MIN, group=group) | ||
| 118 | + if not bool(passed.item()): | ||
| 119 | + raise RuntimeError("PUSH slot payload check failed") | ||
| 120 | + | ||
| 121 | + | ||
| 122 | +def explicit_single_config_requested(argv): | ||
| 123 | + flags = ("--epn", "--H", "--Hp", "--B", "--nremote") | ||
| 124 | + return any(arg == f or arg.startswith(f + "=") for arg in argv for f in flags) | ||
| 125 | + | ||
| 126 | + | ||
| 127 | +def parse_args(argv=None): | ||
| 128 | + ap = argparse.ArgumentParser(description=__doc__) | ||
| 129 | + add_common_args(ap) | ||
| 130 | + ap.add_argument("--suite", action="store_true", help="Run the default case suite.") | ||
| 131 | + ap.add_argument("--single", action="store_true", | ||
| 132 | + help="Run exactly the config given by --epn/--H/--Hp/--B/--nremote.") | ||
| 133 | + ap.add_argument("--epn", type=int, default=8) | ||
| 134 | + ap.add_argument("--H", type=int, default=EXP_H) | ||
| 135 | + ap.add_argument("--Hp", type=int, default=EXP_HP) | ||
| 136 | + ap.add_argument("--B", type=int, default=14) | ||
| 137 | + ap.add_argument("--nremote", type=int, default=2) | ||
| 138 | + ap.add_argument("--barrier-mode", choices=("mixed", "aiv"), default="mixed", | ||
| 139 | + help="Native pre/post barrier variant for the PUSH path.") | ||
| 140 | + ap.add_argument("--ip-port", help="SHMEM bootstrap URL for multi-node runs") | ||
| 141 | + return ap.parse_args(argv) | ||
| 142 | + | ||
| 143 | + | ||
| 144 | +def bench_case(case, args, rank, group, R): | ||
| 145 | + dev = f"npu:{torch.npu.current_device()}" | ||
| 146 | + epn = int(case["epn"]) | ||
| 147 | + E = R * epn | ||
| 148 | + H = int(case["H"]) | ||
| 149 | + Hp = int(case["Hp"]) | ||
| 150 | + B = int(case["base_B"]) | ||
| 151 | + counts = case.get("counts") or [int(case.get("nremote", 1))] * epn | ||
| 152 | + | ||
| 153 | + assert H % 128 == 0 and Hp % 128 == 0, \ | ||
| 154 | + f"{case['label']}: H and Hp must be multiples of 128" | ||
| 155 | + assert len(counts) == epn, f"{case['label']}: counts must have epn={epn} entries" | ||
| 156 | + assert all(0 <= c < R for c in counts), \ | ||
| 157 | + f"{case['label']}: each count must be in [0, R)" | ||
| 158 | + | ||
| 159 | + os.environ["ASCEND_MOONEP_BARRIER_MODE"] = args.barrier_mode | ||
| 160 | + keepalive = make_symmetric_experts(rank, R, E, H, Hp, B) | ||
| 161 | + local_expert = keepalive[:epn] | ||
| 162 | + prefetch_src = keepalive[epn:] | ||
| 163 | + row_bytes = H * Hp * 2 | ||
| 164 | + | ||
| 165 | + # Deterministic per-expert payload: every row carries its own expert id so | ||
| 166 | + # the receiving rank can check the pushed slot without a reference copy. | ||
| 167 | + local_expert.zero_() | ||
| 168 | + prefetch_src.fill_(-17) | ||
| 169 | + for index in range(epn): | ||
| 170 | + expert = rank * epn + index | ||
| 171 | + local_expert[index].fill_(1 + expert % 127) | ||
| 172 | + local_expert[index].view(-1)[0] = -(1 + expert // 127) | ||
| 173 | + source_ptrs = torch.tensor( | ||
| 174 | + [local_expert.data_ptr() + index * row_bytes for index in range(epn)], | ||
| 175 | + dtype=torch.int64, device=dev) | ||
| 176 | + plan = prefetch_plan(R, B, epn, counts, dev) | ||
| 177 | + torch.npu.synchronize() | ||
| 178 | + dist.barrier(group=group) | ||
| 179 | + | ||
| 180 | + # Buffer-backed only: map to symmetric tensors after init_with_buffer (EP | ||
| 181 | + # group). This script calls launch_prefetch_from_ptrs directly (not via | ||
| 182 | + # Buffer); apply_engine writes the engine policy into env and enable_udma is | ||
| 183 | + # passed through explicitly, so the symmetric heap and the op select the | ||
| 184 | + # same engine. | ||
| 185 | + if not ShmemRuntime.is_initialized(): | ||
| 186 | + ShmemRuntime.init_with_buffer(group=group, enable_udma=args.use_udma, | ||
| 187 | + ip_port=args.ip_port) | ||
| 188 | + sym_base = map_to_sym_ptr(keepalive.data_ptr(), 'prefetch_chunk') | ||
| 189 | + push_slots = create_sym_tensor_from_ptr( | ||
| 190 | + sym_base + epn * row_bytes, [B, H, Hp], torch.bfloat16, dev) | ||
| 191 | + | ||
| 192 | + def submit(): | ||
| 193 | + launch_prefetch_from_ptrs(source_ptrs, push_slots, plan, local_experts=epn) | ||
| 194 | + | ||
| 195 | + def check(): | ||
| 196 | + checks = [] | ||
| 197 | + for slot, expert in enumerate(plan[rank].tolist()): | ||
| 198 | + flat = push_slots[slot].view(-1) | ||
| 199 | + checks.extend(( | ||
| 200 | + torch.all(flat[1:] == (-17 if expert < 0 else 1 + expert % 127)), | ||
| 201 | + flat[0] == (-17 if expert < 0 else -(1 + expert // 127)), | ||
| 202 | + )) | ||
| 203 | + check_payload(checks, group) | ||
| 204 | + | ||
| 205 | + try: | ||
| 206 | + submit() # Initialize the launcher custom class and verify before timing. | ||
| 207 | + torch.npu.synchronize() | ||
| 208 | + check() | ||
| 209 | + res = time_kernel( | ||
| 210 | + submit, group, rank, warmup=args.warmup, iters=args.iters, agg="max", | ||
| 211 | + cudagraph=args.cudagraph) | ||
| 212 | + # PUSH overwrites the slots, so the payload check still holds after the | ||
| 213 | + # timed iterations (no per-iteration refill is needed). | ||
| 214 | + check() | ||
| 215 | + finally: | ||
| 216 | + # Re-init per case: finalize first (drop symmetric mappings so shmem no | ||
| 217 | + # longer references the chunk VA), then the inverse VMM ops | ||
| 218 | + # (unmap/release/free), then clear the registry. Reversing the order | ||
| 219 | + # makes the re-init's get_buffer_ptr miss the newly registered chunk. | ||
| 220 | + dist.barrier(group=group) | ||
| 221 | + if ShmemRuntime.is_initialized(): | ||
| 222 | + ShmemRuntime.finalize() | ||
| 223 | + alloc = getattr(keepalive, '_vmm_allocation', None) | ||
| 224 | + if alloc is not None: | ||
| 225 | + alloc.destroy() | ||
| 226 | + reset_symmetric_descriptors() | ||
| 227 | + return res, E, B | ||
| 228 | + | ||
| 229 | + | ||
| 230 | +def main(): | ||
| 231 | + args = parse_args() | ||
| 232 | + if args.out and os.path.exists(args.out): | ||
| 233 | + raise FileExistsError("use a new --out CSV path") | ||
| 234 | + rank, world_size, _ = setup() | ||
| 235 | + args.use_udma = apply_engine(args.engine) | ||
| 236 | + R = args.ep_size if args.ep_size is not None else world_size | ||
| 237 | + assert R >= 2, "prefetch benchmark requires at least 2 ranks (a source and a sink)" | ||
| 238 | + assert R <= world_size, f"--ep-size {R} exceeds world size {world_size}" | ||
| 239 | + in_group = rank < R | ||
| 240 | + group = dist.new_group(ranks=list(range(R))) | ||
| 241 | + | ||
| 242 | + run_single = args.single or (not args.suite and explicit_single_config_requested(sys.argv[1:])) | ||
| 243 | + if run_single: | ||
| 244 | + cases = [{"label": "custom", "epn": args.epn, "H": args.H, "Hp": args.Hp, | ||
| 245 | + "base_B": args.B, "nremote": args.nremote}] | ||
| 246 | + else: | ||
| 247 | + cases = DEFAULT_CASES | ||
| 248 | + skipped = [c["label"] for c in cases | ||
| 249 | + if max(c.get("counts") or [c.get("nremote", 1)] * c["epn"]) >= R] | ||
| 250 | + cases = [c for c in cases | ||
| 251 | + if max(c.get("counts") or [c.get("nremote", 1)] * c["epn"]) < R] | ||
| 252 | + if rank == 0 and skipped: | ||
| 253 | + print(f"NOTE: skipping {len(skipped)} cases needing >{R} ranks: " | ||
| 254 | + f"{', '.join(skipped)}", flush=True) | ||
| 255 | + | ||
| 256 | + engine = "urma" if args.use_udma else "ubmem" | ||
| 257 | + if rank == 0: | ||
| 258 | + print(f"=== bench_prefetch_push: world={world_size} R={R} engine={engine} " | ||
| 259 | + f"barrier-mode={args.barrier_mode} cases={len(cases)} === ", flush=True) | ||
| 260 | + | ||
| 261 | + # shmem init lives inside each case's bench_case (buffer-backed only). | ||
| 262 | + dist.barrier() | ||
| 263 | + | ||
| 264 | + if rank == 0: | ||
| 265 | + print(f"{'Config':<20} {'E':>5} {'B':>4} {'H':>7} {'Hp':>6} {'Slots':>6} " | ||
| 266 | + f"{'Worst(us)':>10} {'Status':>8}") | ||
| 267 | + print("-" * 78) | ||
| 268 | + | ||
| 269 | + failures = 0 | ||
| 270 | + results = [] | ||
| 271 | + for case in cases: | ||
| 272 | + res = None | ||
| 273 | + if in_group: | ||
| 274 | + try: | ||
| 275 | + res, E, B = bench_case(case, args, rank, group, R) | ||
| 276 | + except Exception: | ||
| 277 | + import traceback | ||
| 278 | + traceback.print_exc() | ||
| 279 | + res = None | ||
| 280 | + dist.barrier() | ||
| 281 | + | ||
| 282 | + if rank == 0: | ||
| 283 | + if res is None: | ||
| 284 | + failures += 1 | ||
| 285 | + print(f"{case['label']:<20} FAILED", flush=True) | ||
| 286 | + continue | ||
| 287 | + slots = sum(case.get("counts") or [case.get("nremote", 1)] * case["epn"]) | ||
| 288 | + st = "ok" if res["status"] == "ok" else "stub" | ||
| 289 | + print(f"{case['label']:<20} {E:>5} {B:>4} {case['H']:>7} {case['Hp']:>6} " | ||
| 290 | + f"{slots:>6} {time_text(res):>10} {st:>8}", flush=True) | ||
| 291 | + results.append(dict(Config=case["label"], E=E, B=B, H=case["H"], | ||
| 292 | + Hp=case["Hp"], Slots=slots, | ||
| 293 | + **{"Worst(us)": res["us"], "Status": res["status"]})) | ||
| 294 | + | ||
| 295 | + if rank == 0 and args.out: | ||
| 296 | + with open(args.out, "x", newline="", encoding="utf-8") as output: | ||
| 297 | + writer = csv.DictWriter(output, fieldnames=["Config", "E", "B", "H", "Hp", | ||
| 298 | + "Slots", "Worst(us)", "Status"]) | ||
| 299 | + writer.writeheader() | ||
| 300 | + writer.writerows(results) | ||
| 301 | + | ||
| 302 | + dist.destroy_process_group() | ||
| 303 | + if rank == 0 and failures: | ||
| 304 | + print(f"{failures}/{len(cases)} cases FAILED", flush=True) | ||
| 305 | + raise SystemExit(1) | ||
| 306 | + | ||
| 307 | + | ||
| 308 | +if __name__ == "__main__": | ||
| 309 | + main() | ||
| @@ -0,0 +1,95 @@ | |||
| 1 | +"""Storage parameters for the native Buffer API, without a scheduling protocol. | ||
| 2 | + | ||
| 3 | +Allocate/register symmetric sources before SHMEM init; prepare these bindings | ||
| 4 | +after init and before hot work. The caller still owns final-use/reuse ordering. | ||
| 5 | +Bindings carry no Buffer identity; callers must select storage compatible with | ||
| 6 | +the Buffer's layout and device. | ||
| 7 | +""" | ||
| 8 | + | ||
| 9 | +from dataclasses import dataclass | ||
| 10 | + | ||
| 11 | +import torch | ||
| 12 | + | ||
| 13 | +from .buffer_c import sym_tensor | ||
| 14 | +from .shmem_runtime import ShmemRuntime | ||
| 15 | + | ||
| 16 | + | ||
| 17 | +def tensor_signature(tensor): | ||
| 18 | + """Metadata only: detect rebinding without reading device data/versions.""" | ||
| 19 | + storage = tensor.untyped_storage() | ||
| 20 | + return (tensor.data_ptr(), tuple(tensor.shape), tuple(tensor.stride()), | ||
| 21 | + tensor.storage_offset(), tensor.dtype, tensor.device, | ||
| 22 | + storage._cdata, storage.nbytes()) | ||
| 23 | + | ||
| 24 | + | ||
| 25 | +def symmetric_source(source): | ||
| 26 | + if not ShmemRuntime.is_initialized(): | ||
| 27 | + raise RuntimeError("initialize buffer-backed SHMEM before preparing bindings") | ||
| 28 | + if getattr(ShmemRuntime, '_poisoned', False): | ||
| 29 | + raise RuntimeError("binding preparation requires healthy SHMEM") | ||
| 30 | + if getattr(source, '_vmm_allocation', None) is None: | ||
| 31 | + raise ValueError("expected a registered VMM source tensor") | ||
| 32 | + return sym_tensor(source) | ||
| 33 | + | ||
| 34 | + | ||
| 35 | +def overlaps(left, right): | ||
| 36 | + if left.device != right.device: | ||
| 37 | + return False | ||
| 38 | + a, b = left.data_ptr(), right.data_ptr() | ||
| 39 | + return (a < b + right.numel() * right.element_size() and | ||
| 40 | + b < a + left.numel() * left.element_size()) | ||
| 41 | + | ||
| 42 | + | ||
| 43 | +@dataclass(frozen=True, eq=False, repr=False) | ||
| 44 | +class CommBuffers: | ||
| 45 | + """Prepared hidden/route views. Obtain with Buffer.prepare_comm_buffers. | ||
| 46 | + | ||
| 47 | + No allocation, lease, generation or completion state is owned by this value. | ||
| 48 | + Backing references keep the original source metadata/physical owners alive; | ||
| 49 | + callers must keep the tensors' storage and layout fixed while bound. | ||
| 50 | + """ | ||
| 51 | + | ||
| 52 | + hidden: torch.Tensor | ||
| 53 | + route: torch.Tensor | ||
| 54 | + sources: tuple | ||
| 55 | + | ||
| 56 | + | ||
| 57 | +@dataclass(frozen=True, eq=False, repr=False) | ||
| 58 | +class ExpertPointerBinding: | ||
| 59 | + """Prepared expert addresses and one symmetric communication buffer. | ||
| 60 | + | ||
| 61 | + Weight prefetch reads expert_tensors; gradient reduction writes them. | ||
| 62 | + The caller keeps addresses fixed and orders final consumers before reuse. | ||
| 63 | + """ | ||
| 64 | + | ||
| 65 | + expert_tensors: tuple | ||
| 66 | + expert_views: tuple | ||
| 67 | + comm_buffer: torch.Tensor | ||
| 68 | + comm_buffer_source: torch.Tensor | ||
| 69 | + expert_ptrs: torch.Tensor | ||
| 70 | + tensor_signatures: tuple | ||
| 71 | + | ||
| 72 | + def validate_expert_tensors(self, expert_tensors): | ||
| 73 | + """Reject replaced expert tensors or changed storage/layout.""" | ||
| 74 | + validate_unchanged(tuple(expert_tensors), self.tensor_signatures) | ||
| 75 | + | ||
| 76 | + | ||
| 77 | +def validate_unchanged(refs, signatures): | ||
| 78 | + if tuple(tensor_signature(ref) for ref in refs) != signatures: | ||
| 79 | + raise ValueError("prepared storage was rebound or its layout changed") | ||
| 80 | + | ||
| 81 | + | ||
| 82 | +def comm_context(ctx, buffers): | ||
| 83 | + """Select the symmetric data banks for one call, sharing control and workspace. | ||
| 84 | + | ||
| 85 | + Each EP rank must select the corresponding banks for the collective. | ||
| 86 | + The caller orders submissions that share the workspace. | ||
| 87 | + """ | ||
| 88 | + if not ShmemRuntime.is_initialized() or getattr(ShmemRuntime, '_poisoned', False): | ||
| 89 | + raise RuntimeError('explicit communication storage requires initialized healthy SHMEM') | ||
| 90 | + if not isinstance(buffers, CommBuffers): | ||
| 91 | + raise TypeError("buffers must be CommBuffers") | ||
| 92 | + local = dict(ctx) | ||
| 93 | + local['hidden_buf'] = local['hidden_buf_local'] = buffers.hidden | ||
| 94 | + local['weights_buf'] = local['weights_buf_local'] = buffers.route | ||
| 95 | + return local | ||
| @@ -9,10 +9,12 @@ keep the ported Ascend tests minimal: they resolve the op object from | |||
| 9 | ``launch_dispatch_epilogue`` / ``launch_combine_prologue`` steps are folded into | 9 | ``launch_dispatch_epilogue`` / ``launch_combine_prologue`` steps are folded into |
| 10 | ``launch_dispatch`` / ``launch_combine`` and no longer have their own shims. | 10 | ``launch_dispatch`` / ``launch_combine`` and no longer have their own shims. |
| 11 | 11 | ||
| 12 | -Two launchers are intentionally *not* shimmed through a Buffer ctx because the | 12 | +These launchers are intentionally *not* shimmed through a Buffer ctx because the |
| 13 | standalone stage tests call them without one: | 13 | standalone stage tests call them without one: |
| 14 | - ``launch_prefetch(remote_expert, prefetch_buffers, experts_to_copy, num_sms)`` | 14 | - ``launch_prefetch(remote_expert, prefetch_buffers, experts_to_copy, num_sms)`` |
| 15 | + - ``launch_prefetch_from_ptrs(source_ptrs, prefetch_buffers, plan, local_experts, ...)`` | ||
| 15 | - ``launch_grad_reduce(remote_expert_grads, reduce_buffers, plan, rank, ...)`` | 16 | - ``launch_grad_reduce(remote_expert_grads, reduce_buffers, plan, rank, ...)`` |
| 17 | + - ``launch_grad_reduce_targets(target_ptrs, reduce_buffers, plan, rank, num_sms)`` | ||
| 16 | Their Ascend contracts are described in ``ops.py``. | 18 | Their Ascend contracts are described in ``ops.py``. |
| 17 | """ | 19 | """ |
| 18 | 20 | ||
| @@ -126,11 +128,14 @@ def launch_dispatch_op( | |||
| 126 | num_topk: int, | 128 | num_topk: int, |
| 127 | world_size: int, | 129 | world_size: int, |
| 128 | rank: int, | 130 | rank: int, |
| 131 | + num_sms: int = 32, | ||
| 129 | ) -> None: | 132 | ) -> None: |
| 133 | + """Launch dispatch; num_sms controls only the MTE AIV launch width.""" | ||
| 130 | global _DISPATCH | 134 | global _DISPATCH |
| 131 | if _DISPATCH is None: | 135 | if _DISPATCH is None: |
| 132 | _DISPATCH = torch.classes.AscendMoonEP.Dispatch() | 136 | _DISPATCH = torch.classes.AscendMoonEP.Dispatch() |
| 133 | - _DISPATCH.compute( | 137 | + use_udma = _env_use_udma('dispatch') |
| 138 | + args = ( | ||
| 134 | hidden_sh, | 139 | hidden_sh, |
| 135 | route_weights, | 140 | route_weights, |
| 136 | dst, | 141 | dst, |
| @@ -145,8 +150,11 @@ def launch_dispatch_op( | |||
| 145 | num_topk, | 150 | num_topk, |
| 146 | world_size, | 151 | world_size, |
| 147 | rank, | 152 | rank, |
| 148 | - _env_use_udma('dispatch'), | 153 | + use_udma, |
| 149 | ) | 154 | ) |
| 155 | + if not use_udma: | ||
| 156 | + args += (num_sms,) | ||
use_udma 下不会加 num_sms 参数 ![]() ![]() | |||
| 157 | + _DISPATCH.compute(*args) | ||
| 150 | 158 | ||
| 151 | 159 | ||
| 152 | def launch_dispatch_profile_op( | 160 | def launch_dispatch_profile_op( |
| @@ -204,8 +212,9 @@ def launch_combine_op( | |||
| 204 | num_topk: int, | 212 | num_topk: int, |
| 205 | world_size: int, | 213 | world_size: int, |
| 206 | rank: int, | 214 | rank: int, |
| 215 | + num_sms: int = 32, | ||
| 207 | ) -> None: | 216 | ) -> None: |
| 208 | - """Select native/UDMA combine from the process environment.""" | 217 | + """Select native/UDMA combine; num_sms controls the MTE launch width.""" |
| 209 | global _COMBINE, _COMBINE_UDMA | 218 | global _COMBINE, _COMBINE_UDMA |
| 210 | if _env_use_udma("combine"): | 219 | if _env_use_udma("combine"): |
| 211 | if _COMBINE_UDMA is None: | 220 | if _COMBINE_UDMA is None: |
| @@ -254,6 +263,7 @@ def launch_combine_op( | |||
| 254 | world_size, | 263 | world_size, |
| 255 | rank, | 264 | rank, |
| 256 | False, | 265 | False, |
| 266 | + num_sms, | ||
| 257 | ) | 267 | ) |
| 258 | 268 | ||
| 259 | if route_weights_sk_out is not None and sk_stride != num_topk: | 269 | if route_weights_sk_out is not None and sk_stride != num_topk: |
| @@ -351,6 +361,18 @@ def launch_prefetch( | |||
| 351 | num_experts, num_sms, 0, _env_use_udma('prefetch')) | 361 | num_experts, num_sms, 0, _env_use_udma('prefetch')) |
| 352 | 362 | ||
| 353 | 363 | ||
| 364 | +def launch_prefetch_from_ptrs(source_ptrs, prefetch_buffers, experts_to_copy, | ||
| 365 | + local_experts): | ||
| 366 | + """Submit prepared weight pointers through the PrefetchWeight custom class.""" | ||
| 367 | + use_udma = _env_use_udma('prefetch') | ||
| 368 | + global _PREFETCH_WEIGHT | ||
| 369 | + if _PREFETCH_WEIGHT is None: | ||
| 370 | + _PREFETCH_WEIGHT = torch.classes.AscendMoonEP.PrefetchWeight(0) | ||
| 371 | + return _PREFETCH_WEIGHT.compute_from_ptrs( | ||
| 372 | + source_ptrs, prefetch_buffers, experts_to_copy, | ||
| 373 | + local_experts, use_udma) | ||
| 374 | + | ||
| 375 | + | ||
| 354 | def launch_grad_reduce( | 376 | def launch_grad_reduce( |
| 355 | remote_expert_grads: torch.Tensor, | 377 | remote_expert_grads: torch.Tensor, |
| 356 | remote_reduce_buffers: torch.Tensor, | 378 | remote_reduce_buffers: torch.Tensor, |
| @@ -416,3 +438,59 @@ def launch_grad_reduce( | |||
| 416 | min(num_sms, 64), | 438 | min(num_sms, 64), |
| 417 | _env_use_udma('grad_reduce'), | 439 | _env_use_udma('grad_reduce'), |
| 418 | ) | 440 | ) |
| 441 | + | ||
| 442 | + | ||
| 443 | +def launch_grad_reduce_targets( | ||
| 444 | + target_ptrs: torch.Tensor, | ||
| 445 | + reduce_buffers: torch.Tensor, | ||
| 446 | + experts_to_copy: torch.Tensor, | ||
| 447 | + rank: int, | ||
| 448 | + num_sms: int, | ||
| 449 | + udma_workspace: torch.Tensor | None = None, | ||
| 450 | +) -> None: | ||
| 451 | + """Explicit canonical-pointer contract, distinct from the dense entry. | ||
| 452 | + | ||
| 453 | + ``target_ptrs`` is a setup-frozen contiguous INT64 [epn] table of local | ||
| 454 | + FP32 matrix addresses. Each target is contiguous [H, H']; targets remain | ||
| 455 | + alive, disjoint and address-stable until completion. They need not be | ||
| 456 | + symmetric or adjacent. Only ``reduce_buffers[B,H,H']`` is a symmetric | ||
| 457 | + source bank. The launcher reads the grad_reduce environment flag for | ||
| 458 | + both Buffer and standalone calls. UDMA needs | ||
| 459 | + setup-owned local FP32 scratch of at least | ||
| 460 | + 512*1024*max(2*min(num_sms,64),R*B) elements through completion. | ||
| 461 | + The native entry validates the scratch metadata and capacity. | ||
| 462 | + MTE uses ordered addition; UDMA retains dense UDMA's atomic-add ordering. | ||
| 463 | + Both fuse reduction, an AIV WORLD barrier and valid-slot clearing. | ||
| 464 | + Callers must establish cross-rank input readiness before submission. | ||
| 465 | + Completion covers local targets and local slot clearing, as in dense. | ||
| 466 | + """ | ||
| 467 | + if reduce_buffers.numel() == 0 or experts_to_copy.numel() == 0: | ||
| 468 | + return | ||
| 469 | + | ||
| 470 | + assert target_ptrs.dtype == torch.int64 | ||
| 471 | + assert target_ptrs.is_contiguous() and target_ptrs.ndim == 1 | ||
| 472 | + assert reduce_buffers.dtype == torch.float32 | ||
| 473 | + assert reduce_buffers.is_contiguous() and reduce_buffers.ndim == 3 | ||
| 474 | + assert experts_to_copy.dtype == torch.int32 | ||
| 475 | + assert experts_to_copy.is_contiguous() and experts_to_copy.ndim == 2 | ||
| 476 | + assert isinstance(rank, int) | ||
| 477 | + assert isinstance(num_sms, int) and num_sms > 0 | ||
| 478 | + epn = int(target_ptrs.numel()) | ||
| 479 | + B, H, Hp = (int(value) for value in reduce_buffers.shape) | ||
| 480 | + R, plan_B = (int(value) for value in experts_to_copy.shape) | ||
| 481 | + assert plan_B == B | ||
| 482 | + assert 0 <= rank < R | ||
| 483 | + device = target_ptrs.device | ||
| 484 | + assert device.type == "npu" | ||
| 485 | + assert reduce_buffers.device == device | ||
| 486 | + assert experts_to_copy.device == device | ||
| 487 | + | ||
| 488 | + use_udma = _env_use_udma('grad_reduce') | ||
| 489 | + blocks = min(num_sms, 64) | ||
| 490 | + global _GRAD_REDUCE | ||
| 491 | + if _GRAD_REDUCE is None: | ||
| 492 | + _GRAD_REDUCE = torch.classes.AscendMoonEP.GradReduce() | ||
| 493 | + _GRAD_REDUCE.compute_targets( | ||
| 494 | + target_ptrs, reduce_buffers, experts_to_copy, | ||
| 495 | + epn, H, Hp, R, B, rank, blocks, use_udma, | ||
| 496 | + udma_workspace if use_udma else None) | ||
| @@ -139,12 +139,16 @@ include("${CMAKE_SOURCE_DIR}/cmake/AscendMoonEPKernel.cmake") | |||
| 139 | ascend_moonep_add_kernel_library( | 139 | ascend_moonep_add_kernel_library( |
| 140 | ascend_moonep_kernels | 140 | ascend_moonep_kernels |
| 141 | SOURCES | 141 | SOURCES |
| 142 | + kernels/prefetch_pointer_push_mte.cpp | ||
| 143 | + kernels/barrier_all.cpp | ||
| 142 | kernels/barrier_bench.cpp | 144 | kernels/barrier_bench.cpp |
| 143 | kernels/moonep_combine.cpp | 145 | kernels/moonep_combine.cpp |
| 144 | kernels/moonep_dispatch.cpp | 146 | kernels/moonep_dispatch.cpp |
| 145 | kernels/moonep_grad_reduce.cpp | 147 | kernels/moonep_grad_reduce.cpp |
| 146 | ${ASCEND_MOONEP_PLANNING_KERNEL_SOURCE} | 148 | ${ASCEND_MOONEP_PLANNING_KERNEL_SOURCE} |
| 147 | kernels/prefetch.cpp | 149 | kernels/prefetch.cpp |
| 150 | + # These translation units provide unavailable stubs on A2/A3. | ||
| 151 | + kernels/prefetch_pointer_push_udma.cpp | ||
| 148 | ${ASCEND_MOONEP_UDMA_KERNEL_SOURCES} | 152 | ${ASCEND_MOONEP_UDMA_KERNEL_SOURCES} |
| 149 | INCLUDES | 153 | INCLUDES |
| 150 | include | 154 | include |
| @@ -0,0 +1,30 @@ | |||
| 1 | +#include "barrier.h" | ||
| 2 | + | ||
| 3 | +#include <cstdlib> | ||
| 4 | +#include <string> | ||
| 5 | +#include <torch/extension.h> | ||
| 6 | +#include "shmem.h" | ||
| 7 | +#include "host_device/shmem_common_types.h" | ||
| 8 | +#include "ascend_moonep/kernels/launch.h" | ||
| 9 | + | ||
| 10 | +// Same active-instance state used by the pinned SHMEM host barrier. Use its | ||
| 11 | +// actual default stream, including after an instance context switch. | ||
| 12 | +extern aclshmem_host_state_t g_state_host; | ||
| 13 | + | ||
| 14 | +namespace ascend_moonep { | ||
| 15 | +void BarrierAllOnStream(aclrtStream stream) { | ||
| 16 | + const char* setting = std::getenv("ASCEND_MOONEP_BARRIER_MODE"); | ||
| 17 | + const std::string mode = setting == nullptr ? "mixed" : setting; | ||
| 18 | + TORCH_CHECK(mode == "mixed" || mode == "aiv", | ||
| 19 | + "ASCEND_MOONEP_BARRIER_MODE must be mixed or aiv"); | ||
| 20 | + if (mode == "mixed") { | ||
| 21 | + aclshmemx_barrier_all_on_stream(stream); | ||
| 22 | + return; | ||
| 23 | + } | ||
| 24 | + TORCH_CHECK(aclshmemx_init_status() == ACLSHMEM_STATUS_IS_INITIALIZED, | ||
| 25 | + "shmem is not initialized, please initialize first"); | ||
| 26 | + if (stream == nullptr) stream = g_state_host.default_stream; | ||
| 27 | + TORCH_CHECK(aclshmemx_barrier_all_on_stream_aiv(stream) == ACL_SUCCESS, | ||
| 28 | + "single AIV barrier launch failed"); | ||
| 29 | +} | ||
| 30 | +} | ||
| @@ -0,0 +1,7 @@ | |||
| 1 | +#pragma once | ||
| 2 | +#include <acl/acl.h> | ||
| 3 | + | ||
| 4 | +namespace ascend_moonep { | ||
| 5 | +// Process-wide on-stream policy, independent of the payload transport. | ||
| 6 | +void BarrierAllOnStream(aclrtStream stream); | ||
| 7 | +} | ||
| @@ -1,11 +1,13 @@ | |||
| 1 | #include "csrc/ops/grad_reduce.h" | 1 | #include "csrc/ops/grad_reduce.h" |
| 2 | 2 | ||
| 3 | +#include <algorithm> | ||
| 3 | #include <limits> | 4 | #include <limits> |
| 4 | 5 | ||
| 5 | #include <torch/extension.h> | 6 | #include <torch/extension.h> |
| 6 | #include <torch_npu/csrc/core/npu/NPUStream.h> | 7 | #include <torch_npu/csrc/core/npu/NPUStream.h> |
| 7 | 8 | ||
| 8 | #include "ascend_moonep/kernels/launch.h" | 9 | #include "ascend_moonep/kernels/launch.h" |
| 10 | +#include "shmem.h" | ||
| 9 | 11 | ||
| 10 | namespace ascend_moonep::ops { | 12 | namespace ascend_moonep::ops { |
| 11 | 13 | ||
| @@ -82,9 +84,6 @@ void GradReduce( | |||
| 82 | int64_t rank, | 84 | int64_t rank, |
| 83 | int64_t blocks, | 85 | int64_t blocks, |
| 84 | bool use_udma) { | 86 | bool use_udma) { |
| 85 | - // The current grad-reduce implementation has no separate UDMA kernel. | ||
| 86 | - // Keep the unified ABI and deliberately use the existing SHMEM path. | ||
| 87 | - (void)use_udma; | ||
| 88 | aclrtStream stream = c10_npu::getCurrentNPUStream().stream(); | 87 | aclrtStream stream = c10_npu::getCurrentNPUStream().stream(); |
| 89 | 88 | ||
| 90 | CheckNpuContiguous(expert_grads, "expert_grads"); | 89 | CheckNpuContiguous(expert_grads, "expert_grads"); |
| @@ -151,4 +150,88 @@ void GradReduce( | |||
| 151 | } | 150 | } |
| 152 | } | 151 | } |
| 153 | 152 | ||
| 153 | +void GradReduceTargets( | ||
| 154 | + torch::Tensor target_ptrs, | ||
| 155 | + torch::Tensor reduce_buffers, | ||
| 156 | + torch::Tensor experts_to_copy, | ||
| 157 | + int64_t epn, | ||
| 158 | + int64_t hidden, | ||
| 159 | + int64_t projection, | ||
| 160 | + int64_t ranks, | ||
| 161 | + int64_t slots, | ||
| 162 | + int64_t rank, | ||
| 163 | + int64_t blocks, | ||
| 164 | + bool use_udma, | ||
| 165 | + torch::Tensor udma_workspace) { | ||
| 166 | +#if !defined(ASCEND_MOONEP_UDMA) | ||
| 167 | + TORCH_CHECK(!use_udma, | ||
| 168 | + "canonical grad_reduce UDMA kernel support is not enabled in this build"); | ||
| 169 | +#endif | ||
| 170 | + aclrtStream stream = c10_npu::getCurrentNPUStream().stream(); | ||
| 171 | + CheckNpuContiguous(target_ptrs, "target_ptrs"); | ||
| 172 | + TORCH_CHECK( | ||
| 173 | + target_ptrs.scalar_type() == torch::kInt64 && | ||
| 174 | + target_ptrs.dim() == 1 && target_ptrs.numel() == epn, | ||
| 175 | + "canonical target pointers must be contiguous INT64 [epn]"); | ||
| 176 | + TORCH_CHECK( | ||
| 177 | + target_ptrs.device() == reduce_buffers.device(), | ||
| 178 | + "target_ptrs and reduce_buffers must be on the same device"); | ||
| 179 | + CheckCommon(reduce_buffers, experts_to_copy, hidden, projection, | ||
| 180 | + ranks, slots, rank, blocks); | ||
| 181 | + TORCH_CHECK(epn > 0, "epn must be positive"); | ||
| 182 | + CheckInt32(epn, "epn"); | ||
| 183 | + | ||
| 184 | + if (use_udma) { | ||
| 185 | + TORCH_CHECK(udma_workspace.defined(), "UDMA grad_reduce requires setup-owned workspace"); | ||
| 186 | + CheckNpuContiguous(udma_workspace, "udma_workspace"); | ||
| 187 | + TORCH_CHECK(udma_workspace.scalar_type() == torch::kFloat32 && | ||
| 188 | + udma_workspace.device() == reduce_buffers.device() && | ||
| 189 | + ranks <= std::numeric_limits<int64_t>::max() / std::max<int64_t>(slots, 1), | ||
| 190 | + "udma_workspace device/dtype or rank-slot product is invalid"); | ||
| 191 | + const int64_t regions = std::max<int64_t>(blocks * 2, ranks * slots); | ||
| 192 | + constexpr int64_t tile = 512 * 1024; | ||
| 193 | + TORCH_CHECK(regions <= std::numeric_limits<int64_t>::max() / (tile * sizeof(float)), | ||
| 194 | + "ordered UDMA workspace byte count exceeds int64"); | ||
| 195 | + TORCH_CHECK(udma_workspace.numel() >= tile * regions, | ||
| 196 | + "udma_workspace must be local FP32 scratch with at least " | ||
| 197 | + "512*1024*max(blocks*2,ranks*slots) elements on the source device"); | ||
| 198 | + } | ||
| 199 | + | ||
| 200 | + // The caller publishes all ranks' input slots before this launch. | ||
| 201 | + // Completion, the AIV WORLD barrier and slot clear are fused, as in dense. | ||
| 202 | + // UDMA scratch remains caller-owned and is allocated during setup. | ||
| 203 | + if (use_udma) { | ||
| 204 | +#if defined(ASCEND_MOONEP_UDMA) | ||
| 205 | + const int ret = moonep_shmem_grad_reduce_targets_udma( | ||
| 206 | + stream, | ||
| 207 | + target_ptrs.data_ptr(), | ||
| 208 | + reduce_buffers.data_ptr(), | ||
| 209 | + udma_workspace.data_ptr(), | ||
| 210 | + experts_to_copy.data_ptr<int32_t>(), | ||
| 211 | + static_cast<int32_t>(epn), | ||
| 212 | + static_cast<int32_t>(hidden), | ||
| 213 | + static_cast<int32_t>(projection), | ||
| 214 | + static_cast<int32_t>(ranks), | ||
| 215 | + static_cast<int32_t>(slots), | ||
| 216 | + static_cast<int32_t>(rank), | ||
| 217 | + static_cast<int32_t>(blocks)); | ||
| 218 | + TORCH_CHECK(ret == 0, "canonical grad_reduce kernel failed with ACL error: ", ret); | ||
| 219 | +#endif | ||
| 220 | + } else { | ||
| 221 | + const int ret = moonep_shmem_grad_reduce_targets( | ||
| 222 | + stream, | ||
| 223 | + target_ptrs.data_ptr(), | ||
| 224 | + reduce_buffers.data_ptr(), | ||
| 225 | + experts_to_copy.data_ptr<int32_t>(), | ||
| 226 | + static_cast<int32_t>(epn), | ||
| 227 | + static_cast<int32_t>(hidden), | ||
| 228 | + static_cast<int32_t>(projection), | ||
| 229 | + static_cast<int32_t>(ranks), | ||
| 230 | + static_cast<int32_t>(slots), | ||
| 231 | + static_cast<int32_t>(rank), | ||
| 232 | + static_cast<int32_t>(blocks)); | ||
| 233 | + TORCH_CHECK(ret == 0, "canonical grad_reduce kernel failed with ACL error: ", ret); | ||
| 234 | + } | ||
| 235 | +} | ||
| 236 | + | ||
| 154 | } // namespace ascend_moonep::ops | 237 | } // namespace ascend_moonep::ops |
| @@ -19,4 +19,21 @@ void GradReduce( | |||
| 19 | int64_t blocks, | 19 | int64_t blocks, |
| 20 | bool use_udma); | 20 | bool use_udma); |
| 21 | 21 | ||
| 22 | +// Extension for canonical targets; the dense entry and its backend contract | ||
| 23 | +// remain unchanged. use_udma selects MTE or UDMA; UDMA requires caller-owned | ||
| 24 | +// local workspace. Both use pre/post barriers. | ||
| 25 | +void GradReduceTargets( | ||
| 26 | + torch::Tensor target_ptrs, | ||
| 27 | + torch::Tensor reduce_buffers, | ||
| 28 | + torch::Tensor experts_to_copy, | ||
| 29 | + int64_t epn, | ||
| 30 | + int64_t hidden, | ||
| 31 | + int64_t projection, | ||
| 32 | + int64_t ranks, | ||
| 33 | + int64_t slots, | ||
| 34 | + int64_t rank, | ||
| 35 | + int64_t blocks, | ||
| 36 | + bool use_udma = false, | ||
| 37 | + torch::Tensor udma_workspace = {}); | ||
| 38 | + | ||
| 22 | } // namespace ascend_moonep::ops | 39 | } // namespace ascend_moonep::ops |
| @@ -44,8 +44,12 @@ void MoonEPCombine( | |||
| 44 | int64_t K, | 44 | int64_t K, |
| 45 | int64_t R, | 45 | int64_t R, |
| 46 | int64_t rank, | 46 | int64_t rank, |
| 47 | - bool use_udma) { | 47 | + bool use_udma, |
| 48 | + int64_t num_sms) { | ||
| 48 | (void)use_udma; | 49 | (void)use_udma; |
| 50 | + TORCH_CHECK(num_sms > 0 && | ||
| 51 | + static_cast<uint64_t>(num_sms) <= std::numeric_limits<uint32_t>::max(), | ||
| 52 | + "num_sms must be a positive uint32 launch width"); | ||
| 49 | CheckNpuContiguous(hidden_buf, "hidden_buf"); | 53 | CheckNpuContiguous(hidden_buf, "hidden_buf"); |
| 50 | CheckNpuContiguous(dst, "dst"); | 54 | CheckNpuContiguous(dst, "dst"); |
| 51 | CheckNpuContiguous(dup_groups, "dup_groups"); | 55 | CheckNpuContiguous(dup_groups, "dup_groups"); |
| @@ -137,7 +141,7 @@ void MoonEPCombine( | |||
| 137 | tiling.num_tokens = static_cast<uint32_t>(S); | 141 | tiling.num_tokens = static_cast<uint32_t>(S); |
| 138 | tiling.hidden = static_cast<uint32_t>(H); | 142 | tiling.hidden = static_cast<uint32_t>(H); |
| 139 | tiling.num_topk = static_cast<uint32_t>(K); | 143 | tiling.num_topk = static_cast<uint32_t>(K); |
| 140 | - tiling.block_dim = 32u; | 144 | + tiling.block_dim = static_cast<uint32_t>(num_sms); |
Outdated urma上限核 ![]() ![]() | |||
| 141 | tiling.with_weight = with_weight ? 1u : 0u; | 145 | tiling.with_weight = with_weight ? 1u : 0u; |
| 142 | tiling.reserved = 0u; | 146 | tiling.reserved = 0u; |
| 143 | 147 | ||
| @@ -7,7 +7,7 @@ namespace ascend_moonep::ops { | |||
| 7 | // Plan-driven moonEP_combine on already-symmetric SHMEM shards. | 7 | // Plan-driven moonEP_combine on already-symmetric SHMEM shards. |
| 8 | // Outputs are caller-allocated. Host ABI mirrors MoonEPDispatch. | 8 | // Outputs are caller-allocated. Host ABI mirrors MoonEPDispatch. |
| 9 | // Provide weight_buf and route_weights_sk_out together, or omit both. | 9 | // Provide weight_buf and route_weights_sk_out together, or omit both. |
| 10 | -// Launch width is fixed at 32 AIV. | 10 | +// MTE launch width is controlled by num_sms. |
| 11 | // | 11 | // |
| 12 | // route_weights_sk_out must be fp32 [S, AlignUp(K, 8)] when present | 12 | // route_weights_sk_out must be fp32 [S, AlignUp(K, 8)] when present |
| 13 | // (kernel DataCopy width). | 13 | // (kernel DataCopy width). |
| @@ -25,6 +25,7 @@ void MoonEPCombine( | |||
| 25 | int64_t K, | 25 | int64_t K, |
| 26 | int64_t R, | 26 | int64_t R, |
| 27 | int64_t rank, | 27 | int64_t rank, |
| 28 | - bool use_udma); | 28 | + bool use_udma, |
| 29 | + int64_t num_sms = 32); | ||
| 29 | 30 | ||
| 30 | } // namespace ascend_moonep::ops | 31 | } // namespace ascend_moonep::ops |
| @@ -170,7 +170,8 @@ MoonEPDispatch( | |||
| 170 | int64_t K, | 170 | int64_t K, |
| 171 | int64_t R, | 171 | int64_t R, |
| 172 | int64_t rank, | 172 | int64_t rank, |
| 173 | - bool use_udma) { | 173 | + bool use_udma, |
| 174 | + int64_t num_sms) { | ||
| 174 | 175 | ||
| 175 | auto args = CheckDispatchArgs( | 176 | auto args = CheckDispatchArgs( |
| 176 | hidden_sh, route_weights, dst, dup_groups, dup_loffs, dup_counts, | 177 | hidden_sh, route_weights, dst, dup_groups, dup_loffs, dup_counts, |
| @@ -183,6 +184,10 @@ MoonEPDispatch( | |||
| 183 | hidden_buf, args.route_weights_buf, sync_buffer, | 184 | hidden_buf, args.route_weights_buf, sync_buffer, |
| 184 | args.tiling, NextDispatchMagic()); | 185 | args.tiling, NextDispatchMagic()); |
| 185 | } else { | 186 | } else { |
| 187 | + TORCH_CHECK(num_sms > 0 && | ||
| 188 | + static_cast<uint64_t>(num_sms) <= std::numeric_limits<uint32_t>::max(), | ||
| 189 | + "num_sms must be a positive uint32 launch width"); | ||
| 190 | + args.tiling.block_dim = static_cast<uint32_t>(num_sms); | ||
| 186 | LaunchMoonEPDispatchKernel( | 191 | LaunchMoonEPDispatchKernel( |
| 187 | hidden_sh, args.route_weights, dst, | 192 | hidden_sh, args.route_weights, dst, |
| 188 | dup_groups, dup_loffs, dup_counts, | 193 | dup_groups, dup_loffs, dup_counts, |
| @@ -22,7 +22,8 @@ MoonEPDispatch( | |||
| 22 | int64_t K, | 22 | int64_t K, |
| 23 | int64_t R, | 23 | int64_t R, |
| 24 | int64_t rank, | 24 | int64_t rank, |
| 25 | - bool use_udma); | 25 | + bool use_udma, |
| 26 | + int64_t num_sms = 32); | ||
| 26 | 27 | ||
| 27 | void | 28 | void |
| 28 | MoonEPDispatchProfile( | 29 | MoonEPDispatchProfile( |
| @@ -3,12 +3,15 @@ | |||
| 3 | #include <acl/acl.h> | 3 | #include <acl/acl.h> |
| 4 | #include <algorithm> | 4 | #include <algorithm> |
| 5 | #include <cstdint> | 5 | #include <cstdint> |
| 6 | +#include <limits> | ||
| 6 | 7 | ||
| 7 | #include <torch_npu/csrc/core/npu/NPUStream.h> | 8 | #include <torch_npu/csrc/core/npu/NPUStream.h> |
| 8 | 9 | ||
| 9 | #include "ascend_moonep/kernels/launch.h" | 10 | #include "ascend_moonep/kernels/launch.h" |
| 10 | #include "csrc/common/check.h" | 11 | #include "csrc/common/check.h" |
| 12 | +#include "csrc/barrier.h" | ||
| 11 | #include "csrc/shmem_instance.h" | 13 | #include "csrc/shmem_instance.h" |
| 14 | +#include "shmem.h" | ||
| 12 | 15 | ||
| 13 | namespace { | 16 | namespace { |
| 14 | 17 | ||
| @@ -39,6 +42,7 @@ torch::Tensor LaunchPrefetch( | |||
| 39 | int64_t instance_id, | 42 | int64_t instance_id, |
| 40 | bool use_udma) { | 43 | bool use_udma) { |
| 41 | // The current SHMEM runtime is a single global instance. | 44 | // The current SHMEM runtime is a single global instance. |
| 45 | + | ||
| 42 | (void)instance_id; | 46 | (void)instance_id; |
| 43 | (void)num_sms; | 47 | (void)num_sms; |
| 44 | // remote_expert is a logical cross-PE view. Its data pointer is the local | 48 | // remote_expert is a logical cross-PE view. Its data pointer is the local |
| @@ -118,4 +122,69 @@ torch::Tensor LaunchPrefetch( | |||
| 118 | return prefetch_buffers; | 122 | return prefetch_buffers; |
| 119 | } | 123 | } |
| 120 | 124 | ||
| 125 | + | ||
| 126 | +namespace { | ||
| 127 | +int32_t PrefetchMteBlocks() { | ||
| 128 | + int32_t device_id = 0; | ||
| 129 | + int64_t cores = 0; | ||
| 130 | + ASCEND_MOONEP_CHECK_ACL(aclrtGetDevice(&device_id)); | ||
| 131 | + ASCEND_MOONEP_CHECK_ACL( | ||
| 132 | + aclrtGetDeviceInfo(device_id, ACL_DEV_ATTR_AICORE_CORE_NUM, &cores)); | ||
| 133 | + TORCH_CHECK(cores > 0 && cores <= std::numeric_limits<int32_t>::max(), | ||
| 134 | + "current NPU reports an invalid AICore count"); | ||
| 135 | + return static_cast<int32_t>(cores); | ||
| 136 | +} | ||
| 137 | + | ||
| 138 | +int64_t CheckPushProjection(const torch::Tensor& source, const torch::Tensor& slots, | ||
| 139 | + const torch::Tensor& plan, int64_t local_experts, bool use_udma) { | ||
| 140 | + CheckNpuContiguous(source, "source"); | ||
| 141 | + CheckNpuContiguous(slots, "slots"); | ||
| 142 | + CheckNpuContiguous(plan, "plan"); | ||
| 143 | + TORCH_CHECK(source.device() == slots.device() && slots.device() == plan.device(), | ||
| 144 | + "source, slots and plan must share one NPU"); | ||
| 145 | + TORCH_CHECK(slots.scalar_type() == torch::kBFloat16 && | ||
| 146 | + plan.scalar_type() == torch::kInt32 && slots.dim() == 3 && plan.dim() == 2, | ||
| 147 | + "expected BF16 slots[B,M,N] and INT32 plan[EP,B]"); | ||
| 148 | + const int64_t ep = plan.size(0); | ||
| 149 | + TORCH_CHECK(ep > 0 && ep == aclshmem_n_pes() && local_experts > 0 && | ||
| 150 | + local_experts <= INT32_MAX / ep, | ||
| 151 | + "local expert count or SHMEM topology differs"); | ||
| 152 | + TORCH_CHECK(plan.size(1) == slots.size(0) && slots.size(0) > 0 && | ||
| 153 | + (!use_udma || slots.size(0) <= 15736) && | ||
| 154 | + slots.size(1) > 0 && slots.size(2) > 0 && | ||
| 155 | + slots.size(1) <= std::numeric_limits<int64_t>::max() / slots.size(2), | ||
| 156 | + "invalid projection, slots or backend UB extent"); | ||
| 157 | + return slots.size(1) * slots.size(2); | ||
| 158 | +} | ||
| 159 | +} | ||
| 160 | + | ||
| 161 | +torch::Tensor LaunchPrefetchPushPointers(torch::Tensor pointers, torch::Tensor slots, | ||
| 162 | + torch::Tensor plan, int64_t local_experts, bool use_udma) { | ||
| 163 | + if (use_udma) { | ||
| 164 | + TORCH_CHECK(prefetch_pointer_push_udma_available() == 1, | ||
| 165 | + "URMA pointer PUSH unavailable; no MTE fallback"); | ||
| 166 | + } | ||
| 167 | + const int64_t elements = CheckPushProjection(pointers, slots, plan, local_experts, use_udma); | ||
| 168 | + TORCH_CHECK(pointers.scalar_type() == torch::kInt64 && pointers.dim() == 1 && | ||
| 169 | + pointers.numel() == local_experts, "expected INT64 pointer table[L]"); | ||
| 170 | + aclrtStream stream = c10_npu::getCurrentNPUStream().stream(); | ||
| 171 | + BarrierAllOnStream(stream); | ||
| 172 | + if (use_udma) { | ||
| 173 | + ASCEND_MOONEP_CHECK_ACL(moonep_prefetch_pointer_push_udma(stream, | ||
| 174 | + reinterpret_cast<uint8_t*>(pointers.data_ptr()), | ||
| 175 | + reinterpret_cast<uint8_t*>(slots.data_ptr()), | ||
| 176 | + reinterpret_cast<uint8_t*>(plan.data_ptr()), | ||
| 177 | + local_experts * plan.size(0), elements, slots.size(0))); | ||
| 178 | + } else { | ||
| 179 | + ASCEND_MOONEP_CHECK_ACL(moonep_prefetch_pointer_push_mte(stream, | ||
| 180 | + reinterpret_cast<const uint64_t*>(pointers.data_ptr<int64_t>()), | ||
| 181 | + slots.data_ptr(), plan.data_ptr<int32_t>(), elements, | ||
| 182 | + static_cast<int32_t>(local_experts), static_cast<int32_t>(plan.size(0)), | ||
| 183 | + static_cast<int32_t>(slots.size(0)), static_cast<int32_t>(aclshmem_my_pe()), | ||
| 184 | + PrefetchMteBlocks())); | ||
| 185 | + } | ||
| 186 | + BarrierAllOnStream(stream); | ||
| 187 | + return slots; | ||
| 188 | +} | ||
| 189 | + | ||
| 121 | } // namespace ascend_moonep::ops | 190 | } // 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 | + | ||
| 16 | +// Stateless submissions: caller owns Tensor/table lifetime and consumer final use. | ||
| 17 | +torch::Tensor LaunchPrefetchPushPointers(torch::Tensor pointers, torch::Tensor slots, | ||
| 18 | + torch::Tensor plan, int64_t local_experts, bool use_udma); | ||
| 15 | } // namespace ascend_moonep::ops | 19 | } // namespace ascend_moonep::ops |
| @@ -12,7 +12,6 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { | |||
| 12 | py::int_(sizeof(aclshmemx_buffer_optional_attr_t)); | 12 | py::int_(sizeof(aclshmemx_buffer_optional_attr_t)); |
| 13 | 13 | ||
| 14 | using py::arg; | 14 | using py::arg; |
| 15 | - | ||
| 16 | m.def("launch_device_barrier_bench", &LaunchDeviceBarrierBench, | 15 | m.def("launch_device_barrier_bench", &LaunchDeviceBarrierBench, |
| 17 | arg("iterations"), arg("block_dim") = 32, | 16 | arg("iterations"), arg("block_dim") = 32, |
| 18 | "Launch a device kernel containing only repeated " | 17 | "Launch a device kernel containing only repeated " |
| @@ -12,6 +12,7 @@ | |||
| 12 | #include <torch/script.h> | 12 | #include <torch/script.h> |
| 13 | 13 | ||
| 14 | #include "shmem.h" | 14 | #include "shmem.h" |
| 15 | +#include "ascend_moonep/kernels/launch.h" | ||
| 15 | 16 | ||
| 16 | #include "csrc/common/check.h" | 17 | #include "csrc/common/check.h" |
| 17 | #include "csrc/launcher.h" | 18 | #include "csrc/launcher.h" |
| @@ -147,7 +148,13 @@ private: | |||
| 147 | 148 | ||
| 148 | class PrefetchWeight : public torch::jit::CustomClassHolder { | 149 | class PrefetchWeight : public torch::jit::CustomClassHolder { |
| 149 | public: | 150 | public: |
| 151 | + | ||
| 150 | explicit PrefetchWeight(int64_t /*local_mem_size*/) {} | 152 | explicit PrefetchWeight(int64_t /*local_mem_size*/) {} |
| 153 | + torch::Tensor compute_from_ptrs(torch::Tensor pointers, torch::Tensor slots, | ||
| 154 | + torch::Tensor plan, int64_t local_experts, bool use_udma) { | ||
| 155 | + return ascend_moonep::ops::LaunchPrefetchPushPointers( | ||
| 156 | + pointers, slots, plan, local_experts, use_udma); | ||
| 157 | + } | ||
| 151 | 158 | ||
| 152 | void destroy() {} | 159 | void destroy() {} |
| 153 | 160 | ||
| @@ -202,6 +209,19 @@ public: | |||
| 202 | blocks, | 209 | blocks, |
| 203 | use_udma); | 210 | use_udma); |
| 204 | } | 211 | } |
| 212 | + | ||
| 213 | + void compute_targets( | ||
| 214 | + torch::Tensor target_ptrs, torch::Tensor reduce_buffers, | ||
| 215 | + torch::Tensor experts_to_copy, int64_t epn, int64_t hidden, | ||
| 216 | + int64_t projection, int64_t ranks, int64_t slots, int64_t rank, | ||
| 217 | + int64_t blocks, bool use_udma = false, | ||
| 218 | + c10::optional<torch::Tensor> workspace = c10::nullopt) { | ||
| 219 | + TORCH_CHECK(rank == aclshmem_my_pe(), | ||
| 220 | + "rank does not match the active CANN-SHMEM PE"); | ||
| 221 | + ascend_moonep::ops::GradReduceTargets(target_ptrs, reduce_buffers, experts_to_copy, | ||
| 222 | + epn, hidden, projection, ranks, slots, rank, blocks, use_udma, | ||
| 223 | + workspace.value_or(torch::Tensor())); | ||
| 224 | + } | ||
| 205 | }; | 225 | }; |
| 206 | 226 | ||
| 207 | class Planning : public torch::jit::CustomClassHolder { | 227 | class Planning : public torch::jit::CustomClassHolder { |
| @@ -297,7 +317,8 @@ public: | |||
| 297 | int64_t num_topk, | 317 | int64_t num_topk, |
| 298 | int64_t world_size, | 318 | int64_t world_size, |
| 299 | int64_t rank, | 319 | int64_t rank, |
| 300 | - bool use_udma) { | 320 | + bool use_udma, |
| 321 | + int64_t num_sms = 32) { | ||
| 301 | TORCH_CHECK( | 322 | TORCH_CHECK( |
| 302 | rank == aclshmem_my_pe(), | 323 | rank == aclshmem_my_pe(), |
| 303 | "rank does not match the active CANN-SHMEM PE"); | 324 | "rank does not match the active CANN-SHMEM PE"); |
| @@ -316,7 +337,8 @@ public: | |||
| 316 | num_topk, | 337 | num_topk, |
| 317 | world_size, | 338 | world_size, |
| 318 | rank, | 339 | rank, |
| 319 | - use_udma); | 340 | + use_udma, |
| 341 | + num_sms); | ||
| 320 | } | 342 | } |
| 321 | 343 | ||
| 322 | void compute_profile( | 344 | void compute_profile( |
| @@ -377,7 +399,8 @@ public: | |||
| 377 | int64_t num_topk, | 399 | int64_t num_topk, |
| 378 | int64_t world_size, | 400 | int64_t world_size, |
| 379 | int64_t rank, | 401 | int64_t rank, |
| 380 | - bool use_udma) { | 402 | + bool use_udma, |
| 403 | + int64_t num_sms = 32) { | ||
| 381 | TORCH_CHECK( | 404 | TORCH_CHECK( |
| 382 | rank == aclshmem_my_pe(), | 405 | rank == aclshmem_my_pe(), |
| 383 | "rank does not match the active CANN-SHMEM PE"); | 406 | "rank does not match the active CANN-SHMEM PE"); |
| @@ -395,7 +418,8 @@ public: | |||
| 395 | num_topk, | 418 | num_topk, |
| 396 | world_size, | 419 | world_size, |
| 397 | rank, | 420 | rank, |
| 398 | - use_udma); | 421 | + use_udma, |
| 422 | + num_sms); | ||
| 399 | } | 423 | } |
| 400 | }; | 424 | }; |
| 401 | 425 | ||
| @@ -495,12 +519,20 @@ static auto prefetch_weight_registry = | |||
| 495 | torch::jit::class_<ascend_moonep::torch_classes::PrefetchWeight>("AscendMoonEP", "PrefetchWeight") | 519 | torch::jit::class_<ascend_moonep::torch_classes::PrefetchWeight>("AscendMoonEP", "PrefetchWeight") |
| 496 | .def(torch::jit::init<int64_t>()) | 520 | .def(torch::jit::init<int64_t>()) |
| 497 | .def("compute", &ascend_moonep::torch_classes::PrefetchWeight::compute) | 521 | .def("compute", &ascend_moonep::torch_classes::PrefetchWeight::compute) |
| 522 | + .def("compute_from_ptrs", &ascend_moonep::torch_classes::PrefetchWeight::compute_from_ptrs) | ||
| 498 | .def("destroy", &ascend_moonep::torch_classes::PrefetchWeight::destroy); | 523 | .def("destroy", &ascend_moonep::torch_classes::PrefetchWeight::destroy); |
| 499 | 524 | ||
| 500 | static auto grad_reduce_registry = | 525 | static auto grad_reduce_registry = |
| 501 | torch::jit::class_<ascend_moonep::torch_classes::GradReduce>("AscendMoonEP", "GradReduce") | 526 | torch::jit::class_<ascend_moonep::torch_classes::GradReduce>("AscendMoonEP", "GradReduce") |
| 502 | .def(torch::jit::init<>()) | 527 | .def(torch::jit::init<>()) |
| 503 | - .def("compute", &ascend_moonep::torch_classes::GradReduce::compute); | 528 | + .def("compute", &ascend_moonep::torch_classes::GradReduce::compute) |
| 529 | + .def("compute_targets", &ascend_moonep::torch_classes::GradReduce::compute_targets, | ||
| 530 | + "", {torch::arg("target_ptrs"), torch::arg("reduce_buffers"), | ||
| 531 | + torch::arg("experts_to_copy"), torch::arg("epn"), | ||
| 532 | + torch::arg("hidden"), torch::arg("projection"), | ||
| 533 | + torch::arg("ranks"), torch::arg("slots"), torch::arg("rank"), | ||
| 534 | + torch::arg("blocks"), torch::arg("use_udma") = false, | ||
| 535 | + torch::arg("workspace") = c10::IValue()}); | ||
| 504 | 536 | ||
| 505 | static auto planning_registry = | 537 | static auto planning_registry = |
| 506 | torch::jit::class_<ascend_moonep::torch_classes::Planning>("AscendMoonEP", "Planning") | 538 | torch::jit::class_<ascend_moonep::torch_classes::Planning>("AscendMoonEP", "Planning") |
| @@ -516,13 +548,26 @@ static auto planning_registry = | |||
| 516 | static auto dispatch_registry = | 548 | static auto dispatch_registry = |
| 517 | torch::jit::class_<ascend_moonep::torch_classes::Dispatch>("AscendMoonEP", "Dispatch") | 549 | torch::jit::class_<ascend_moonep::torch_classes::Dispatch>("AscendMoonEP", "Dispatch") |
| 518 | .def(torch::jit::init<>()) | 550 | .def(torch::jit::init<>()) |
| 519 | - .def("compute", &ascend_moonep::torch_classes::Dispatch::compute) | 551 | + .def("compute", &ascend_moonep::torch_classes::Dispatch::compute, |
| 552 | + "", {torch::arg("hidden_sh"), torch::arg("route_weights"), | ||
| 553 | + torch::arg("dst"), torch::arg("dup_groups"), torch::arg("dup_loffs"), | ||
| 554 | + torch::arg("dup_counts"), torch::arg("hidden_buf"), | ||
| 555 | + torch::arg("route_weights_buf"), torch::arg("sync_buffer"), | ||
| 556 | + torch::arg("num_tokens"), torch::arg("hidden_size"), torch::arg("num_topk"), | ||
| 557 | + torch::arg("world_size"), torch::arg("rank"), torch::arg("use_udma"), | ||
| 558 | + torch::arg("num_sms") = 32}) | ||
| 520 | .def("compute_profile", &ascend_moonep::torch_classes::Dispatch::compute_profile); | 559 | .def("compute_profile", &ascend_moonep::torch_classes::Dispatch::compute_profile); |
| 521 | 560 | ||
| 522 | static auto combine_registry = | 561 | static auto combine_registry = |
| 523 | torch::jit::class_<ascend_moonep::torch_classes::Combine>("AscendMoonEP", "Combine") | 562 | torch::jit::class_<ascend_moonep::torch_classes::Combine>("AscendMoonEP", "Combine") |
| 524 | .def(torch::jit::init<>()) | 563 | .def(torch::jit::init<>()) |
| 525 | - .def("compute", &ascend_moonep::torch_classes::Combine::compute); | 564 | + .def("compute", &ascend_moonep::torch_classes::Combine::compute, |
| 565 | + "", {torch::arg("hidden_buf"), torch::arg("weight_buf"), | ||
| 566 | + torch::arg("dst"), torch::arg("dup_groups"), torch::arg("dup_loffs"), | ||
| 567 | + torch::arg("dup_counts"), torch::arg("hidden_sk_out"), | ||
| 568 | + torch::arg("route_weights_sk_out"), torch::arg("num_tokens"), | ||
| 569 | + torch::arg("hidden_size"), torch::arg("num_topk"), torch::arg("world_size"), | ||
| 570 | + torch::arg("rank"), torch::arg("use_udma"), torch::arg("num_sms") = 32}); | ||
| 526 | 571 | ||
| 527 | static auto combine_urma_registry = | 572 | static auto combine_urma_registry = |
| 528 | torch::jit::class_<ascend_moonep::torch_classes::CombineUrma>("AscendMoonEP", "CombineUrma") | 573 | torch::jit::class_<ascend_moonep::torch_classes::CombineUrma>("AscendMoonEP", "CombineUrma") |
| @@ -10,6 +10,8 @@ | |||
| 10 | 10 | ||
| 11 | extern "C" { | 11 | extern "C" { |
| 12 | 12 | ||
| 13 | +// Experimental native GR barrier; public tensor/SPI ABI remains unchanged. | ||
| 14 | + | ||
| 13 | ASCEND_MOONEP_EXPORT void device_barrier_bench_kernel_do( | 15 | ASCEND_MOONEP_EXPORT void device_barrier_bench_kernel_do( |
| 14 | void* stream, | 16 | void* stream, |
| 15 | int32_t iterations, | 17 | int32_t iterations, |
| @@ -120,6 +122,19 @@ ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce( | |||
| 120 | int32_t rank, | 122 | int32_t rank, |
| 121 | int32_t blocks); | 123 | int32_t blocks); |
| 122 | 124 | ||
| 125 | +// Local canonical target pointer table; source slots remain symmetric. | ||
| 126 | +ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_targets( | ||
| 127 | + void* stream, void* target_ptrs, void* reduce_buffers, | ||
| 128 | + const int32_t* experts_to_copy, int32_t epn, int32_t hidden, | ||
| 129 | + int32_t projection, int32_t ranks, int32_t slots, int32_t rank, | ||
| 130 | + int32_t blocks); | ||
| 131 | + | ||
| 132 | +ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_targets_udma( | ||
| 133 | + void* stream, void* target_ptrs, void* reduce_buffers, void* workspace, | ||
| 134 | + const int32_t* experts_to_copy, int32_t epn, int32_t hidden, | ||
| 135 | + int32_t projection, int32_t ranks, int32_t slots, int32_t rank, | ||
| 136 | + int32_t blocks); | ||
| 137 | + | ||
| 123 | ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_udma( | 138 | ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_udma( |
| 124 | void* stream, | 139 | void* stream, |
| 125 | void* expert_grads, | 140 | void* expert_grads, |
| @@ -156,4 +171,24 @@ ASCEND_MOONEP_EXPORT void prefetch_weight_kernel_udma_do( | |||
| 156 | int64_t num_slots, | 171 | int64_t num_slots, |
| 157 | int64_t block_dim); | 172 | int64_t block_dim); |
| 158 | 173 | ||
| 174 | +ASCEND_MOONEP_EXPORT int moonep_prefetch_pointer_push_mte( | ||
| 175 | + void* stream, | ||
| 176 | + const uint64_t* source_ptrs, | ||
| 177 | + void* weight_slots, | ||
| 178 | + const int32_t* experts_to_copy, | ||
| 179 | + int64_t row_elements, | ||
| 180 | + int32_t local_experts, | ||
| 181 | + int32_t ranks, | ||
| 182 | + int32_t slots, | ||
| 183 | + int32_t rank, | ||
| 184 | + int32_t blocks); | ||
| 185 | + | ||
| 186 | + | ||
| 187 | + | ||
| 188 | +ASCEND_MOONEP_EXPORT int prefetch_pointer_push_udma_available(); | ||
| 189 | +ASCEND_MOONEP_EXPORT int aclshmemx_barrier_all_on_stream_aiv(void* stream); | ||
| 190 | +ASCEND_MOONEP_EXPORT int moonep_prefetch_pointer_push_udma( | ||
| 191 | + void* stream, uint8_t* pointers, uint8_t* slots, uint8_t* plan, | ||
| 192 | + int64_t experts, int64_t row_elements, int64_t num_slots); | ||
| 193 | + | ||
| 159 | } // extern "C" | 194 | } // extern "C" |
| @@ -21,7 +21,7 @@ struct alignas(8) MoonEPCombineTilingData { | |||
| 21 | uint32_t num_tokens; // S | 21 | uint32_t num_tokens; // S |
| 22 | uint32_t hidden; // H | 22 | uint32_t hidden; // H |
| 23 | uint32_t num_topk; // K | 23 | uint32_t num_topk; // K |
| 24 | - uint32_t block_dim; // fixed 32 AIV (host always writes 32) | 24 | + uint32_t block_dim; // MTE AIV launch width from num_sms |
| 25 | uint32_t with_weight; // 1: gather weights → [S,K]; 0: skip | 25 | uint32_t with_weight; // 1: gather weights → [S,K]; 0: skip |
| 26 | uint32_t reserved; | 26 | uint32_t reserved; |
| 27 | }; | 27 | }; |
| @@ -44,8 +44,12 @@ struct alignas(8) MoonEPDispatchTilingData { | |||
| 44 | uint32_t rank; | 44 | uint32_t rank; |
| 45 | uint32_t with_weights; | 45 | uint32_t with_weights; |
| 46 | uint32_t reserved; | 46 | uint32_t reserved; |
| 47 | + uint32_t block_dim; // MTE only; occupies the former tail padding | ||
| 47 | }; | 48 | }; |
| 48 | 49 | ||
| 50 | +static_assert(sizeof(MoonEPDispatchTilingData) == 32, "dispatch tiling ABI must remain 32 bytes"); | ||
| 51 | +static_assert(sizeof(MoonEPCombineTilingData) == 32, "combine tiling ABI must remain 32 bytes"); | ||
| 52 | + | ||
| 49 | // Udma dispatch profile ABI (mirrors the UBMEM template-<bool Profile> pattern | 53 | // Udma dispatch profile ABI (mirrors the UBMEM template-<bool Profile> pattern |
| 50 | // from the timing branch): moonep_dispatch_udma_profile_kernel writes each AIV's | 54 | // from the timing branch): moonep_dispatch_udma_profile_kernel writes each AIV's |
| 51 | // metrics as an int64 row into a [kMoonEPAivNum, kMoonEPDispatchUdmaProfileFields] | 55 | // metrics as an int64 row into a [kMoonEPAivNum, kMoonEPDispatchUdmaProfileFields] |
| @@ -0,0 +1,19 @@ | |||
| 1 | +// SPDX-License-Identifier: Apache-2.0 | ||
| 2 | +#include "ascend_moonep/kernels/launch.h" | ||
| 3 | +#include "acl/acl.h" | ||
| 4 | +#include "kernel_operator.h" | ||
| 5 | +#include "shmem.h" | ||
| 6 | + | ||
| 7 | +// Match the SDK mixed barrier algorithm, using one AIV and no AIC. | ||
| 8 | +// This is a barrier (quiet + team sync), not the vector sync-only wrapper. | ||
| 9 | +extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ | ||
| 10 | +void aclshmemi_barrier_all_on_stream_aiv_kernel(uint64_t ffts_config) { | ||
| 11 | + util_set_ffts_config(ffts_config); | ||
| 12 | + aclshmemi_barrier_algo<true>(ACLSHMEM_TEAM_WORLD); | ||
| 13 | +} | ||
| 14 | + | ||
| 15 | +extern "C" ASCEND_MOONEP_EXPORT int aclshmemx_barrier_all_on_stream_aiv(void* stream) { | ||
| 16 | + (void)aclrtGetLastError(ACL_RT_THREAD_LEVEL); | ||
| 17 | + aclshmemi_barrier_all_on_stream_aiv_kernel<<<1, nullptr, stream>>>(shmemx_get_ffts_config()); | ||
| 18 | + return aclrtGetLastError(ACL_RT_THREAD_LEVEL); | ||
| 19 | +} | ||
| @@ -36,7 +36,6 @@ | |||
| 36 | using namespace AscendC; | 36 | using namespace AscendC; |
| 37 | using half_t = __fp16; | 37 | using half_t = __fp16; |
| 38 | using bf16_t = bfloat16_t; | 38 | using bf16_t = bfloat16_t; |
| 39 | -using ascend_moonep::kMoonEPAivNum; | ||
| 40 | using ascend_moonep::MoonEPCombineTilingData; | 39 | using ascend_moonep::MoonEPCombineTilingData; |
| 41 | 40 | ||
| 42 | namespace { | 41 | namespace { |
| @@ -1044,7 +1043,7 @@ extern "C" ASCEND_MOONEP_EXPORT void moonep_combine_kernel_do( | |||
| 1044 | uint8_t* tiling_host) | 1043 | uint8_t* tiling_host) |
| 1045 | { | 1044 | { |
| 1046 | auto* td = reinterpret_cast<MoonEPCombineTilingData*>(tiling_host); | 1045 | auto* td = reinterpret_cast<MoonEPCombineTilingData*>(tiling_host); |
| 1047 | - moonep_combine_kernel<<<kMoonEPAivNum, nullptr, stream>>>( | 1046 | + moonep_combine_kernel<<<td->block_dim, nullptr, stream>>>( |
| 1048 | hidden_buf, | 1047 | hidden_buf, |
| 1049 | weight_buf, | 1048 | weight_buf, |
| 1050 | dst, | 1049 | dst, |
| @@ -2,7 +2,7 @@ | |||
| 2 | // UBMEM implementation — uses SHMEM symmetric window and DataCopyPad + UB/MTE. | 2 | // UBMEM implementation — uses SHMEM symmetric window and DataCopyPad + UB/MTE. |
| 3 | // No URMA/UDMA, no zero-fill. | 3 | // No URMA/UDMA, no zero-fill. |
| 4 | // | 4 | // |
| 5 | -// Architecture: A2/A5, fixed kMoonEPAivNum AIV cores. | 5 | +// Architecture: A2/A5, AIV launch width controlled by num_sms. |
| 6 | // | 6 | // |
| 7 | // Single-kernel design: | 7 | // Single-kernel design: |
| 8 | // Phase 1 (Scatter): cores split routed slots N=S*K. | 8 | // Phase 1 (Scatter): cores split routed slots N=S*K. |
| @@ -19,7 +19,6 @@ | |||
| 19 | using namespace AscendC; | 19 | using namespace AscendC; |
| 20 | 20 | ||
| 21 | using bf16_t = bfloat16_t; | 21 | using bf16_t = bfloat16_t; |
| 22 | -using ascend_moonep::kMoonEPAivNum; | ||
| 23 | 22 | ||
| 24 | // UB buffer sizing: one bf16 hidden row, weight ping-pong, and route metadata. | 23 | // UB buffer sizing: one bf16 hidden row, weight ping-pong, and route metadata. |
| 25 | // Safety margin: allocate up to 128KB for hidden row (H <= 65536). | 24 | // Safety margin: allocate up to 128KB for hidden row (H <= 65536). |
| @@ -614,6 +613,7 @@ extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ void moonep_dispa | |||
| 614 | uint32_t with_weights = tiling.with_weights; | 613 | uint32_t with_weights = tiling.with_weights; |
| 615 | 614 | ||
| 616 | uint32_t core_idx = get_block_idx(); | 615 | uint32_t core_idx = get_block_idx(); |
| 616 | + uint32_t core_count = get_block_num(); | ||
| 617 | 617 | ||
| 618 | LocalTensor<uint8_t> ub_base; | 618 | LocalTensor<uint8_t> ub_base; |
| 619 | ub_base.address_.logicPos = static_cast<uint8_t>(TPosition::VECIN); | 619 | ub_base.address_.logicPos = static_cast<uint8_t>(TPosition::VECIN); |
| @@ -631,7 +631,7 @@ extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ void moonep_dispa | |||
| 631 | hidden_buf_gm, route_weights_buf_gm, | 631 | hidden_buf_gm, route_weights_buf_gm, |
| 632 | S, H, K, tiling.R, NvS, | 632 | S, H, K, tiling.R, NvS, |
| 633 | with_weights != 0, | 633 | with_weights != 0, |
| 634 | - core_idx, kMoonEPAivNum); | 634 | + core_idx, core_count); |
| 635 | 635 | ||
| 636 | // The scatter above issues aclshmemx_mte_put_nbi, and sync_vec (behind | 636 | // The scatter above issues aclshmemx_mte_put_nbi, and sync_vec (behind |
| 637 | // aclshmemx_barrier_all_vec) does not complete outstanding NBI communication. | 637 | // aclshmemx_barrier_all_vec) does not complete outstanding NBI communication. |
| @@ -644,7 +644,7 @@ extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ void moonep_dispa | |||
| 644 | 644 | ||
| 645 | PlanEpiloguePhase<bf16_t>( | 645 | PlanEpiloguePhase<bf16_t>( |
| 646 | ub_base, hbuf, dgrp, dloff, dcnt, | 646 | ub_base, hbuf, dgrp, dloff, dcnt, |
| 647 | - H, NvS, core_idx, kMoonEPAivNum); | 647 | + H, NvS, core_idx, core_count); |
| 648 | } | 648 | } |
| 649 | 649 | ||
| 650 | 650 | ||
| @@ -667,7 +667,7 @@ void moonep_dispatch_kernel_do( | |||
| 667 | { | 667 | { |
| 668 | auto* td = reinterpret_cast<ascend_moonep::MoonEPDispatchTilingData*>(tiling_host); | 668 | auto* td = reinterpret_cast<ascend_moonep::MoonEPDispatchTilingData*>(tiling_host); |
| 669 | 669 | ||
| 670 | - moonep_dispatch_kernel<<<kMoonEPAivNum, nullptr, stream>>>( | 670 | + moonep_dispatch_kernel<<<td->block_dim, nullptr, stream>>>( |
| 671 | hidden_sh, | 671 | hidden_sh, |
| 672 | route_weights, | 672 | route_weights, |
| 673 | dst, | 673 | dst, |
| @@ -299,7 +299,8 @@ void MoonEPShmemGradReduceFused( | |||
| 299 | int32_t projection, | 299 | int32_t projection, |
| 300 | int32_t ranks, | 300 | int32_t ranks, |
| 301 | int32_t slots, | 301 | int32_t slots, |
| 302 | - int32_t rank) | 302 | + int32_t rank, |
| 303 | + bool pointer_targets) | ||
| 303 | { | 304 | { |
| 304 | util_set_ffts_config(ffts_addr); | 305 | util_set_ffts_config(ffts_addr); |
| 305 | if ASCEND_IS_AIC { | 306 | if ASCEND_IS_AIC { |
| @@ -307,6 +308,7 @@ void MoonEPShmemGradReduceFused( | |||
| 307 | } | 308 | } |
| 308 | 309 | ||
| 309 | auto* grads = reinterpret_cast<__gm__ float*>(expert_grads_addr); | 310 | auto* grads = reinterpret_cast<__gm__ float*>(expert_grads_addr); |
| 311 | + auto* target_ptrs = reinterpret_cast<__gm__ uint64_t*>(expert_grads_addr); | ||
| 310 | auto* reduce = reinterpret_cast<__gm__ float*>(reduce_buffers_addr); | 312 | auto* reduce = reinterpret_cast<__gm__ float*>(reduce_buffers_addr); |
| 311 | auto* plan = reinterpret_cast<__gm__ int32_t*>(experts_to_copy_addr); | 313 | auto* plan = reinterpret_cast<__gm__ int32_t*>(experts_to_copy_addr); |
| 312 | const int32_t local_begin = rank * epn; | 314 | const int32_t local_begin = rank * epn; |
| @@ -324,19 +326,26 @@ void MoonEPShmemGradReduceFused( | |||
| 324 | 326 | ||
| 325 | for (int32_t local_expert = 0; local_expert < epn; ++local_expert) { | 327 | for (int32_t local_expert = 0; local_expert < epn; ++local_expert) { |
| 326 | const int32_t global_expert = local_begin + local_expert; | 328 | const int32_t global_expert = local_begin + local_expert; |
| 329 | + // Adapt pointer targets to the existing dense accumulation contract: | ||
| 330 | + // one expert allocation is a one-row dense view, addressed at row 0. | ||
| 331 | + // Keep global_expert unchanged for matching contributions in the plan. | ||
| 332 | + auto* accum_grads = pointer_targets ? | ||
| 333 | + reinterpret_cast<__gm__ float*>(target_ptrs[local_expert]) : | ||
| 334 | + grads; | ||
| 335 | + const int32_t accum_local_expert = pointer_targets ? 0 : local_expert; | ||
| 327 | for (int64_t tile = block; tile < tiles_per_expert; tile += block_count) { | 336 | for (int64_t tile = block; tile < tiles_per_expert; tile += block_count) { |
| 328 | const int64_t tile_begin = tile * kTileElements; | 337 | const int64_t tile_begin = tile * kTileElements; |
| 329 | const int32_t elements = static_cast<int32_t>( | 338 | const int32_t elements = static_cast<int32_t>( |
| 330 | matrix - tile_begin < kTileElements ? | 339 | matrix - tile_begin < kTileElements ? |
| 331 | matrix - tile_begin : kTileElements); | 340 | matrix - tile_begin : kTileElements); |
| 332 | AccumulatePlanTile( | 341 | AccumulatePlanTile( |
| 333 | - grads, | 342 | + accum_grads, |
| 334 | reduce, | 343 | reduce, |
| 335 | plan, | 344 | plan, |
| 336 | accum_ub, | 345 | accum_ub, |
| 337 | reduce_ping_ub, | 346 | reduce_ping_ub, |
| 338 | reduce_pong_ub, | 347 | reduce_pong_ub, |
| 339 | - local_expert, | 348 | + accum_local_expert, |
| 340 | global_expert, | 349 | global_expert, |
| 341 | matrix, | 350 | matrix, |
| 342 | tile_begin, | 351 | tile_begin, |
| @@ -347,27 +356,14 @@ void MoonEPShmemGradReduceFused( | |||
| 347 | } | 356 | } |
| 348 | } | 357 | } |
| 349 | 358 | ||
| 350 | - // Every AIV on every rank must reach this collective. Do not add an AIV | ||
| 351 | - // early return above it, including for empty plans or blocks with no work. | ||
| 352 | aclshmem_quiet(); | 359 | aclshmem_quiet(); |
| 353 | - // This kernel is [[core_ratio(0, 1)]] and launches AIV workers only. | 360 | + // All workers participate, including workers with no reduction tasks. |
| 354 | - // The installed CANN-SHMEM generic barrier also includes non-vector | ||
| 355 | - // participants and deadlocks for this launch shape; use its vector-only | ||
| 356 | - // device collective so the participant set matches the kernel grid. | ||
| 357 | aclshmemx_barrier_all_vec(); | 361 | aclshmemx_barrier_all_vec(); |
| 358 | - | 362 | + ClearLocalSlots(reduce, plan, accum_ub, matrix, slots, rank, |
| 359 | - ClearLocalSlots( | 363 | + block, block_count); |
| 360 | - reduce, | ||
| 361 | - plan, | ||
| 362 | - accum_ub, | ||
| 363 | - matrix, | ||
| 364 | - slots, | ||
| 365 | - rank, | ||
| 366 | - block, | ||
| 367 | - block_count); | ||
| 368 | } | 364 | } |
| 369 | 365 | ||
| 370 | -extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce( | 366 | +static int LaunchGradReduce( |
| 371 | void* stream, | 367 | void* stream, |
| 372 | void* expert_grads, | 368 | void* expert_grads, |
| 373 | void* reduce_buffers, | 369 | void* reduce_buffers, |
| @@ -378,7 +374,8 @@ extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce( | |||
| 378 | int32_t ranks, | 374 | int32_t ranks, |
| 379 | int32_t slots, | 375 | int32_t slots, |
| 380 | int32_t rank, | 376 | int32_t rank, |
| 381 | - int32_t blocks) | 377 | + int32_t blocks, |
| 378 | + bool pointer_targets) | ||
| 382 | { | 379 | { |
| 383 | if (stream == nullptr || expert_grads == nullptr || | 380 | if (stream == nullptr || expert_grads == nullptr || |
| 384 | reduce_buffers == nullptr || experts_to_copy == nullptr || | 381 | reduce_buffers == nullptr || experts_to_copy == nullptr || |
| @@ -404,6 +401,27 @@ extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce( | |||
| 404 | projection, | 401 | projection, |
| 405 | ranks, | 402 | ranks, |
| 406 | slots, | 403 | slots, |
| 407 | - rank); | 404 | + rank, |
| 405 | + pointer_targets); | ||
| 408 | return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL); | 406 | return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL); |
| 409 | } | 407 | } |
| 408 | + | ||
| 409 | +extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce( | ||
| 410 | + void* stream, void* expert_grads, void* reduce_buffers, | ||
| 411 | + const int32_t* experts_to_copy, int32_t epn, int32_t hidden, | ||
| 412 | + int32_t projection, int32_t ranks, int32_t slots, int32_t rank, | ||
| 413 | + int32_t blocks) | ||
| 414 | +{ | ||
| 415 | + return LaunchGradReduce(stream, expert_grads, reduce_buffers, experts_to_copy, | ||
| 416 | + epn, hidden, projection, ranks, slots, rank, blocks, false); | ||
| 417 | +} | ||
| 418 | + | ||
| 419 | +extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_targets( | ||
| 420 | + void* stream, void* target_ptrs, void* reduce_buffers, | ||
| 421 | + const int32_t* experts_to_copy, int32_t epn, int32_t hidden, | ||
| 422 | + int32_t projection, int32_t ranks, int32_t slots, int32_t rank, | ||
| 423 | + int32_t blocks) | ||
| 424 | +{ | ||
| 425 | + return LaunchGradReduce(stream, target_ptrs, reduce_buffers, experts_to_copy, | ||
| 426 | + epn, hidden, projection, ranks, slots, rank, blocks, true); | ||
| 427 | +} | ||
| @@ -65,7 +65,8 @@ void MoonEPShmemGradReduceUdmaFused( | |||
| 65 | int32_t projection, | 65 | int32_t projection, |
| 66 | int32_t ranks, | 66 | int32_t ranks, |
| 67 | int32_t slots, | 67 | int32_t slots, |
| 68 | - int32_t rank) | 68 | + int32_t rank, |
| 69 | + bool pointer_targets) | ||
| 69 | { | 70 | { |
| 70 | util_set_ffts_config(ffts_addr); | 71 | util_set_ffts_config(ffts_addr); |
| 71 | 72 | ||
| @@ -74,6 +75,7 @@ void MoonEPShmemGradReduceUdmaFused( | |||
| 74 | const int64_t matrix = static_cast<int64_t>(hidden) * projection; | 75 | const int64_t matrix = static_cast<int64_t>(hidden) * projection; |
| 75 | 76 | ||
| 76 | auto* grads = reinterpret_cast<__gm__ float*>(expert_grads_addr); | 77 | auto* grads = reinterpret_cast<__gm__ float*>(expert_grads_addr); |
| 78 | + auto* target_ptrs = reinterpret_cast<__gm__ uint64_t*>(expert_grads_addr); | ||
| 77 | auto* reduce = reinterpret_cast<__gm__ float*>(reduce_buffers_addr); | 79 | auto* reduce = reinterpret_cast<__gm__ float*>(reduce_buffers_addr); |
| 78 | auto* plan = reinterpret_cast<__gm__ int32_t*>(experts_to_copy_addr); | 80 | auto* plan = reinterpret_cast<__gm__ int32_t*>(experts_to_copy_addr); |
| 79 | auto* workspace = reinterpret_cast<__gm__ float*>(workspace_addr) + coreIdx * OUTER_LOOP_SIZE; | 81 | auto* workspace = reinterpret_cast<__gm__ float*>(workspace_addr) + coreIdx * OUTER_LOOP_SIZE; |
| @@ -101,6 +103,12 @@ void MoonEPShmemGradReduceUdmaFused( | |||
| 101 | if (dstRankIdx != rank) { | 103 | if (dstRankIdx != rank) { |
| 102 | continue; | 104 | continue; |
| 103 | } | 105 | } |
| 106 | + // Adapt each canonical allocation as a one-expert dense view, | ||
| 107 | + // just like the MTE kernel; leave the reduction itself unchanged. | ||
| 108 | + auto* accum_grads = pointer_targets ? | ||
| 109 | + reinterpret_cast<__gm__ float*>(target_ptrs[dstExpertIdx]) : | ||
| 110 | + grads; | ||
| 111 | + const int32_t accum_local_expert = pointer_targets ? 0 : dstExpertIdx; | ||
| 104 | 112 | ||
| 105 | for (int64_t slotOffset = 0; slotOffset < matrix; slotOffset += OUTER_LOOP_SIZE) | 113 | for (int64_t slotOffset = 0; slotOffset < matrix; slotOffset += OUTER_LOOP_SIZE) |
| 106 | { | 114 | { |
| @@ -108,22 +116,19 @@ void MoonEPShmemGradReduceUdmaFused( | |||
| 108 | if (srcRankIdx != dstRankIdx) { | 116 | if (srcRankIdx != dstRankIdx) { |
| 109 | aclshmemx_udma_get_nbi((__gm__ uint8_t*)(workspace), (__gm__ uint8_t*)(reduce + srcSlotIdx * matrix + slotOffset), wqe_scratch, loopSize * sizeof(float), srcRankIdx, 0); | 117 | aclshmemx_udma_get_nbi((__gm__ uint8_t*)(workspace), (__gm__ uint8_t*)(reduce + srcSlotIdx * matrix + slotOffset), wqe_scratch, loopSize * sizeof(float), srcRankIdx, 0); |
| 110 | aclshmemx_udma_quiet(srcRankIdx); | 118 | aclshmemx_udma_quiet(srcRankIdx); |
| 111 | - ComputeSingle(grads + dstExpertIdx * matrix + slotOffset, workspace, ubLocal, loopSize); | 119 | + ComputeSingle(accum_grads + accum_local_expert * matrix + slotOffset, workspace, ubLocal, loopSize); |
| 112 | } else { | 120 | } else { |
| 113 | - ComputeSingle(grads + dstExpertIdx * matrix + slotOffset, reduce + srcSlotIdx * matrix + slotOffset, ubLocal, loopSize); | 121 | + ComputeSingle(accum_grads + accum_local_expert * matrix + slotOffset, reduce + srcSlotIdx * matrix + slotOffset, ubLocal, loopSize); |
| 114 | } | 122 | } |
| 115 | } | 123 | } |
| 116 | } | 124 | } |
| 117 | } | 125 | } |
| 118 | 126 | ||
| 119 | - // Every remote GET was already completed by its owning AIV via | 127 | + // Each remote GET is completed by its owning AIV above. Preserve the |
| 120 | - // aclshmemx_udma_quiet. Do NOT use aclshmem_quiet() here: it drains every | 128 | + // dev_npu fix: generic quiet would race UDMA queue state across AIVs. |
| 121 | - // peer from every AIV, and SHMEM requires UDMA queue-state mutation | ||
| 122 | - // (submit/quiet/poll) to be serialized per jetty. Only the local MTE3 | ||
| 123 | - // atomic-add stores still need draining. | ||
| 124 | aclshmemx_mte_quiet(); | 129 | aclshmemx_mte_quiet(); |
| 130 | + // Preserve dense completion for both address contracts. Idle AIVs join too. | ||
| 125 | aclshmemx_barrier_all_vec(); | 131 | aclshmemx_barrier_all_vec(); |
| 126 | - | ||
| 127 | if (coreIdx == 0) { | 132 | if (coreIdx == 0) { |
| 128 | GlobalTensor<float> reduceGm_; | 133 | GlobalTensor<float> reduceGm_; |
| 129 | reduceGm_.SetGlobalBuffer(reduce); | 134 | reduceGm_.SetGlobalBuffer(reduce); |
| @@ -135,7 +140,7 @@ void MoonEPShmemGradReduceUdmaFused( | |||
| 135 | } | 140 | } |
| 136 | } | 141 | } |
| 137 | 142 | ||
| 138 | -extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_udma( | 143 | +static int LaunchGradReduceUdma( |
| 139 | void* stream, | 144 | void* stream, |
| 140 | void* expert_grads, | 145 | void* expert_grads, |
| 141 | void* reduce_buffers, | 146 | void* reduce_buffers, |
| @@ -147,7 +152,8 @@ extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_udma( | |||
| 147 | int32_t ranks, | 152 | int32_t ranks, |
| 148 | int32_t slots, | 153 | int32_t slots, |
| 149 | int32_t rank, | 154 | int32_t rank, |
| 150 | - int32_t blocks) | 155 | + int32_t blocks, |
| 156 | + bool pointer_targets) | ||
| 151 | { | 157 | { |
| 152 | if (stream == nullptr || expert_grads == nullptr || | 158 | if (stream == nullptr || expert_grads == nullptr || |
| 153 | reduce_buffers == nullptr || experts_to_copy == nullptr || | 159 | reduce_buffers == nullptr || experts_to_copy == nullptr || |
| @@ -157,7 +163,15 @@ extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_udma( | |||
| 157 | return ACL_ERROR_INVALID_PARAM; | 163 | return ACL_ERROR_INVALID_PARAM; |
| 158 | } | 164 | } |
| 159 | 165 | ||
| 160 | - (void)aclrtGetLastError(ACL_RT_THREAD_LEVEL); | 166 | + if (pointer_targets) { |
| 167 | + // Preserve an existing error instead of erasing the first failure. | ||
| 168 | + const auto status = aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL); | ||
| 169 | + if (status != ACL_SUCCESS) { | ||
| 170 | + return status; | ||
| 171 | + } | ||
| 172 | + } else { | ||
| 173 | + (void)aclrtGetLastError(ACL_RT_THREAD_LEVEL); | ||
| 174 | + } | ||
| 161 | const int32_t shmem_ranks = aclshmem_n_pes(); | 175 | const int32_t shmem_ranks = aclshmem_n_pes(); |
| 162 | if (shmem_ranks <= 0 || ranks != shmem_ranks) { | 176 | if (shmem_ranks <= 0 || ranks != shmem_ranks) { |
| 163 | return ACL_ERROR_INVALID_PARAM; | 177 | return ACL_ERROR_INVALID_PARAM; |
| @@ -165,15 +179,31 @@ extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_udma( | |||
| 165 | 179 | ||
| 166 | MoonEPShmemGradReduceUdmaFused<<<blocks, nullptr, stream>>>( | 180 | MoonEPShmemGradReduceUdmaFused<<<blocks, nullptr, stream>>>( |
| 167 | shmemx_get_ffts_config(), | 181 | shmemx_get_ffts_config(), |
| 168 | - reinterpret_cast<std::uint8_t*>(expert_grads), | 182 | + reinterpret_cast<uint8_t*>(expert_grads), |
| 169 | - reinterpret_cast<std::uint8_t*>(reduce_buffers), | 183 | + reinterpret_cast<uint8_t*>(reduce_buffers), |
| 170 | - reinterpret_cast<std::uint8_t*>(workspace), | 184 | + reinterpret_cast<uint8_t*>(workspace), |
| 171 | - reinterpret_cast<std::uint8_t*>(const_cast<int32_t*>(experts_to_copy)), | 185 | + reinterpret_cast<uint8_t*>(const_cast<int32_t*>(experts_to_copy)), |
| 172 | - epn, | 186 | + epn, hidden, projection, ranks, slots, rank, pointer_targets); |
| 173 | - hidden, | 187 | + |
| 174 | - projection, | ||
| 175 | - ranks, | ||
| 176 | - slots, | ||
| 177 | - rank); | ||
| 178 | return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL); | 188 | return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL); |
| 179 | } | 189 | } |
| 190 | + | ||
| 191 | +extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_udma( | ||
| 192 | + void* stream, void* expert_grads, void* reduce_buffers, void* workspace, | ||
| 193 | + const int32_t* experts_to_copy, int32_t epn, int32_t hidden, | ||
| 194 | + int32_t projection, int32_t ranks, int32_t slots, int32_t rank, | ||
| 195 | + int32_t blocks) | ||
| 196 | +{ | ||
| 197 | + return LaunchGradReduceUdma(stream, expert_grads, reduce_buffers, workspace, | ||
| 198 | + experts_to_copy, epn, hidden, projection, ranks, slots, rank, blocks, false); | ||
| 199 | +} | ||
| 200 | + | ||
| 201 | +extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_targets_udma( | ||
| 202 | + void* stream, void* target_ptrs, void* reduce_buffers, void* workspace, | ||
| 203 | + const int32_t* experts_to_copy, int32_t epn, int32_t hidden, | ||
| 204 | + int32_t projection, int32_t ranks, int32_t slots, int32_t rank, | ||
| 205 | + int32_t blocks) | ||
| 206 | +{ | ||
| 207 | + return LaunchGradReduceUdma(stream, target_ptrs, reduce_buffers, workspace, | ||
| 208 | + experts_to_copy, epn, hidden, projection, ranks, slots, rank, blocks, true); | ||
| 209 | +} | ||
| @@ -0,0 +1,103 @@ | |||
| 1 | +// SPDX-License-Identifier: Apache-2.0 | ||
| 2 | +// MTE implementation of prepared expert-pointer weight PUSH. | ||
| 3 | +#include <cstdint> | ||
| 4 | +#include "acl/acl.h" | ||
| 5 | +#include "kernel_operator.h" | ||
| 6 | +#include "shmem.h" | ||
| 7 | +#include "ascend_moonep/kernels/launch.h" | ||
| 8 | +#include "opdev/bfloat16.h" | ||
| 9 | +using namespace AscendC; | ||
| 10 | +namespace { | ||
| 11 | +constexpr int32_t kPrefetchUbBytes = 188 * 1024; | ||
| 12 | +constexpr uint64_t kPrefetchUbOffset = 64; | ||
| 13 | +__aicore__ inline int32_t PrefetchWorkerIndex() | ||
| 14 | +{ | ||
| 15 | + const int32_t sub_blocks = static_cast<int32_t>(GetSubBlockNum()); | ||
| 16 | + return sub_blocks > 0 ? static_cast<int32_t>(GetBlockIdx()) / sub_blocks : 0; | ||
| 17 | +} | ||
| 18 | + | ||
| 19 | +__aicore__ inline int64_t PrefetchCeilDiv(int64_t value, int64_t divisor) | ||
| 20 | +{ | ||
| 21 | + return (value + divisor - 1) / divisor; | ||
| 22 | +} | ||
| 23 | + | ||
| 24 | +} // namespace | ||
| 25 | + | ||
| 26 | +extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ | ||
| 27 | +void prefetch_pointer_push_mte( | ||
| 28 | + GM_ADDR source_ptrs_addr, | ||
| 29 | + GM_ADDR weight_slots_addr, | ||
| 30 | + GM_ADDR experts_to_copy_addr, | ||
| 31 | + int64_t row_elements, | ||
| 32 | + int32_t local_experts, | ||
| 33 | + int32_t ranks, | ||
| 34 | + int32_t slots, | ||
| 35 | + int32_t rank) | ||
| 36 | +{ | ||
| 37 | + if ASCEND_IS_AIC { | ||
| 38 | + return; | ||
| 39 | + } | ||
| 40 | + auto* source_ptrs = reinterpret_cast<__gm__ uint64_t*>(source_ptrs_addr); | ||
| 41 | + auto* weight_slots = reinterpret_cast<__gm__ bfloat16_t*>(weight_slots_addr); | ||
| 42 | + auto* plan = reinterpret_cast<__gm__ int32_t*>(experts_to_copy_addr); | ||
| 43 | + const int32_t block = PrefetchWorkerIndex(); | ||
| 44 | + const int32_t block_count = GetBlockNum(); | ||
| 45 | + const int32_t tile_elements = (kPrefetchUbBytes - static_cast<int32_t>(kPrefetchUbOffset)) / | ||
| 46 | + static_cast<int32_t>(sizeof(bfloat16_t)) / 2; | ||
| 47 | + const int64_t chunks = PrefetchCeilDiv(row_elements, tile_elements); | ||
| 48 | + const int64_t entries = static_cast<int64_t>(ranks) * slots; | ||
| 49 | + const int32_t local_begin = rank * local_experts; | ||
| 50 | + auto* ping = reinterpret_cast<__ubuf__ bfloat16_t*>(kPrefetchUbOffset); | ||
| 51 | + auto* pong = ping + tile_elements; | ||
| 52 | + int32_t buffer = 0; | ||
| 53 | + SetFlag<HardEvent::MTE3_MTE2>(EVENT_ID0); | ||
| 54 | + SetFlag<HardEvent::MTE3_MTE2>(EVENT_ID1); | ||
| 55 | + for (int64_t task = block; task < entries * chunks; task += block_count) { | ||
| 56 | + const int64_t entry = task / chunks; | ||
| 57 | + const int64_t chunk = task % chunks; | ||
| 58 | + const int32_t expert = plan[entry]; | ||
| 59 | + if (expert < local_begin || expert >= local_begin + local_experts) { | ||
| 60 | + continue; | ||
| 61 | + } | ||
| 62 | + const int32_t local_expert = expert - local_begin; | ||
| 63 | + const int32_t destination_pe = static_cast<int32_t>(entry / slots); | ||
| 64 | + const int32_t destination_slot = static_cast<int32_t>(entry % slots); | ||
| 65 | + const int64_t begin = chunk * tile_elements; | ||
| 66 | + const int32_t elements = static_cast<int32_t>( | ||
| 67 | + row_elements - begin < tile_elements ? row_elements - begin : tile_elements); | ||
| 68 | + const TEventID event = buffer == 0 ? EVENT_ID0 : EVENT_ID1; | ||
| 69 | + auto* ub = buffer == 0 ? ping : pong; | ||
| 70 | + WaitFlag<HardEvent::MTE3_MTE2>(event); | ||
| 71 | + auto* src = reinterpret_cast<__gm__ bfloat16_t*>(source_ptrs[local_expert]) + begin; | ||
| 72 | + auto* dst = weight_slots + static_cast<int64_t>(destination_slot) * row_elements + begin; | ||
| 73 | + aclshmemx_mte_put_nbi( | ||
| 74 | + dst, src, ub, | ||
| 75 | + static_cast<uint32_t>(tile_elements * sizeof(bfloat16_t)), | ||
| 76 | + static_cast<uint32_t>(elements), destination_pe, event); | ||
| 77 | + SetFlag<HardEvent::MTE3_MTE2>(event); | ||
| 78 | + buffer = 1 - buffer; | ||
| 79 | + } | ||
| 80 | + WaitFlag<HardEvent::MTE3_MTE2>(EVENT_ID0); | ||
| 81 | + WaitFlag<HardEvent::MTE3_MTE2>(EVENT_ID1); | ||
| 82 | + aclshmem_quiet(); | ||
| 83 | +} | ||
| 84 | + | ||
| 85 | +extern "C" ASCEND_MOONEP_EXPORT int moonep_prefetch_pointer_push_mte( | ||
| 86 | + void* stream, const uint64_t* source_ptrs, void* weight_slots, | ||
| 87 | + const int32_t* experts_to_copy, int64_t row_elements, int32_t local_experts, | ||
| 88 | + int32_t ranks, int32_t slots, int32_t rank, int32_t blocks) | ||
| 89 | +{ | ||
| 90 | + if (stream == nullptr || source_ptrs == nullptr || weight_slots == nullptr || | ||
| 91 | + experts_to_copy == nullptr || row_elements <= 0 || local_experts <= 0 || | ||
| 92 | + ranks <= 0 || slots <= 0 || rank < 0 || rank >= ranks || blocks <= 0 || | ||
| 93 | + ranks != aclshmem_n_pes()) { | ||
| 94 | + return ACL_ERROR_INVALID_PARAM; | ||
| 95 | + } | ||
| 96 | + (void)aclrtGetLastError(ACL_RT_THREAD_LEVEL); | ||
| 97 | + prefetch_pointer_push_mte<<<blocks, nullptr, stream>>>( | ||
| 98 | + reinterpret_cast<uint8_t*>(const_cast<uint64_t*>(source_ptrs)), | ||
| 99 | + reinterpret_cast<uint8_t*>(weight_slots), | ||
| 100 | + reinterpret_cast<uint8_t*>(const_cast<int32_t*>(experts_to_copy)), | ||
| 101 | + row_elements, local_experts, ranks, slots, rank); | ||
| 102 | + return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL); | ||
| 103 | +} | ||
| @@ -0,0 +1,175 @@ | |||
| 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 <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 | +__aicore__ inline void Run( | ||
| 68 | + GM_ADDR source_addr, GM_ADDR slots_addr, GM_ADDR plan_addr, | ||
| 69 | + int64_t experts, int64_t row_elements, int64_t slots) | ||
| 70 | +{ | ||
| 71 | + if ASCEND_IS_AIC { return; } | ||
| 72 | + if (UdmaAivWorkerIndex() != 0) { return; } | ||
| 73 | + auto* pointers = reinterpret_cast<__gm__ uint64_t*>(source_addr); | ||
| 74 | + auto* destination = reinterpret_cast<__gm__ bfloat16_t*>(slots_addr); | ||
| 75 | + auto* plan = reinterpret_cast<__gm__ int32_t*>(plan_addr); | ||
| 76 | + const int32_t ranks = aclshmem_n_pes(); | ||
| 77 | + const int32_t rank = aclshmem_my_pe(); | ||
| 78 | + const int64_t epn = (experts + ranks - 1) / ranks; | ||
| 79 | + const int32_t data_offset = UdmaAlignUp( | ||
| 80 | + kUdmaUbExpertTabOffset + UdmaAlignUp( | ||
| 81 | + static_cast<int32_t>(2 * slots * sizeof(int32_t)), 32), 32); | ||
| 82 | + TPipe pipe; | ||
| 83 | + TBuf<TPosition::VECOUT> tab_buf, wqe_buf, ub_buf; | ||
| 84 | + pipe.InitBuffer(tab_buf, data_offset); | ||
| 85 | + pipe.InitBuffer(wqe_buf, kUdmaWqeElements * sizeof(bfloat16_t)); | ||
| 86 | + pipe.InitBuffer(ub_buf, kUdmaCannShmemInternalUbStartBytes - | ||
| 87 | + data_offset - kUdmaWqeElements * sizeof(bfloat16_t)); | ||
| 88 | + auto tab = tab_buf.Get<int32_t>(); | ||
| 89 | + auto wqe = wqe_buf.Get<bfloat16_t>(); | ||
| 90 | + auto local = ub_buf.Get<bfloat16_t>(); | ||
| 91 | + auto* expert_tab = reinterpret_cast<__ubuf__ int32_t*>(tab.GetPhyAddr()); | ||
| 92 | + auto* slot_tab = expert_tab + slots; | ||
| 93 | + auto* scratch = reinterpret_cast<__ubuf__ bfloat16_t*>(wqe.GetPhyAddr()); | ||
| 94 | + auto* ub = reinterpret_cast<__ubuf__ bfloat16_t*>(local.GetPhyAddr()); | ||
| 95 | + Duplicate(wqe, static_cast<bfloat16_t>(0), kUdmaWqeElements); | ||
| 96 | + // SDK WQE construction uses scalar stores through the same raw UB pointer. | ||
| 97 | + // Order the vector clear before those stores; Tensor auto-sync cannot | ||
| 98 | + // infer this pointer handoff. SDK and local-copy events use IDs 0 and 1. | ||
| 99 | + SetFlag<HardEvent::V_S>(EVENT_ID2); | ||
| 100 | + WaitFlag<HardEvent::V_S>(EVENT_ID2); | ||
| 101 | + // Validate the complete plan before this owner submits any payload. | ||
| 102 | + for (int64_t i = 0; i < ranks * slots; ++i) { | ||
| 103 | + if (plan[i] < -1 || plan[i] >= experts) { | ||
| 104 | + AscendC::printf("URMA_PUSH_INVALID_EXPERT rank=%d entry=%ld expert=%d\n", | ||
| 105 | + rank, i, plan[i]); | ||
| 106 | + trap(); | ||
| 107 | + } | ||
| 108 | + } | ||
| 109 | + const int64_t max_elements = kUdmaMaxTransferBytes / sizeof(bfloat16_t); | ||
| 110 | + for (int32_t peer = 0; peer < ranks; ++peer) { | ||
| 111 | + int64_t active = 0; | ||
| 112 | + for (int64_t slot = 0; slot < slots; ++slot) { | ||
| 113 | + const int32_t expert = plan[peer * slots + slot]; | ||
| 114 | + if (expert >= 0 && expert / epn == rank) { | ||
| 115 | + expert_tab[active] = expert % epn; | ||
| 116 | + slot_tab[active++] = slot; | ||
| 117 | + } | ||
| 118 | + } | ||
| 119 | + for (int64_t i = 0; i < active; ++i) { | ||
| 120 | + __gm__ bfloat16_t* source; | ||
| 121 | + source = reinterpret_cast<__gm__ bfloat16_t*>(pointers[expert_tab[i]]); | ||
| 122 | + if (source == nullptr) { | ||
| 123 | + AscendC::printf("URMA_PUSH_NULL_SOURCE rank=%d expert=%d\n", | ||
| 124 | + rank, expert_tab[i]); | ||
| 125 | + trap(); | ||
| 126 | + } | ||
| 127 | + for (int64_t offset = 0; offset < row_elements; offset += max_elements) { | ||
| 128 | + const uint32_t count = static_cast<uint32_t>( | ||
| 129 | + row_elements - offset < max_elements ? row_elements - offset : max_elements); | ||
| 130 | + auto* dst = destination + slot_tab[i] * row_elements + offset; | ||
| 131 | + if (peer == rank) { | ||
| 132 | + UdmaCopyLocalExpertChunk(dst, source + offset, count, ub); | ||
| 133 | + } else { | ||
| 134 | + aclshmemx_udma_put_nbi(dst, source + offset, scratch, | ||
| 135 | + count, peer, EVENT_ID0); | ||
| 136 | + } | ||
| 137 | + } | ||
| 138 | + } | ||
| 139 | + } | ||
| 140 | + // One AIV issues all peers before waiting for their payloads. The SDK has | ||
| 141 | + // finished publishing each UB-staged WQE before put_nbi returns; the WQE | ||
| 142 | + // refers to the retained GM source, not this reusable UB scratch. Queue | ||
| 143 | + // credit and any overflow drain remain owned by the default SDK path. | ||
| 144 | + // No peer-visible publication is permitted until every required quiet has | ||
| 145 | + // returned. The caller's post barrier and consumer events are unchanged. | ||
| 146 | + for (int32_t peer = 0; peer < ranks; ++peer) { | ||
| 147 | + if (peer != rank) { | ||
| 148 | + aclshmemx_udma_quiet(peer); | ||
| 149 | + } | ||
| 150 | + } | ||
| 151 | + aclshmem_quiet(); | ||
| 152 | +} | ||
| 153 | +} // namespace moonep_urma_push | ||
| 154 | + | ||
| 155 | +extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ | ||
| 156 | +void prefetch_pointer_push_udma(GM_ADDR pointers, GM_ADDR slots, GM_ADDR plan, | ||
| 157 | + int64_t experts, int64_t row_elements, int64_t num_slots) { | ||
| 158 | + moonep_urma_push::Run(pointers,slots,plan,experts,row_elements,num_slots); | ||
| 159 | +} | ||
| 160 | +extern "C" ASCEND_MOONEP_EXPORT int prefetch_pointer_push_udma_available() { return 1; } | ||
| 161 | +extern "C" ASCEND_MOONEP_EXPORT int moonep_prefetch_pointer_push_udma( | ||
| 162 | + void* stream, uint8_t* pointers, uint8_t* slots, uint8_t* plan, | ||
| 163 | + int64_t experts, int64_t row_elements, int64_t num_slots) { | ||
| 164 | + const auto status = aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL); | ||
| 165 | + if (status != ACL_SUCCESS) { | ||
| 166 | + return status; | ||
| 167 | + } | ||
| 168 | + prefetch_pointer_push_udma<<<1,nullptr,stream>>>(pointers,slots,plan,experts,row_elements,num_slots); | ||
| 169 | + return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL); | ||
| 170 | +} | ||
| 171 | +#else | ||
| 172 | +extern "C" ASCEND_MOONEP_EXPORT int prefetch_pointer_push_udma_available() { return 0; } | ||
| 173 | +extern "C" ASCEND_MOONEP_EXPORT int moonep_prefetch_pointer_push_udma( | ||
| 174 | + void*,uint8_t*,uint8_t*,uint8_t*,int64_t,int64_t,int64_t) { return -1; } | ||
| 175 | +#endif | ||
| @@ -16,8 +16,10 @@ from .launchers import ( | |||
| 16 | launch_dispatch_op, | 16 | launch_dispatch_op, |
| 17 | launch_dispatch_profile_op, | 17 | launch_dispatch_profile_op, |
| 18 | launch_grad_reduce, | 18 | launch_grad_reduce, |
| 19 | + launch_grad_reduce_targets, | ||
| 19 | launch_planning_op, | 20 | launch_planning_op, |
| 20 | launch_prefetch, | 21 | launch_prefetch, |
| 22 | + launch_prefetch_from_ptrs, | ||
| 21 | ) | 23 | ) |
| 22 | 24 | ||
| 23 | 25 | ||
| @@ -122,6 +124,7 @@ class DispatchOp(KernelOp): | |||
| 122 | (dest = aclshmem_ptr(ctx['hidden_buf'].data_ptr(), drank) + loff*H*2), | 124 | (dest = aclshmem_ptr(ctx['hidden_buf'].data_ptr(), drank) + loff*H*2), |
| 123 | writes weights into ctx['weights_buf'] (remote rank's symmetric chunk). | 125 | writes weights into ctx['weights_buf'] (remote rank's symmetric chunk). |
| 124 | - build_dedup_map True only right after fresh planning. | 126 | - build_dedup_map True only right after fresh planning. |
| 127 | + - MTE launch width follows self.num_sms; UDMA keeps its fixed schedule. | ||
| 125 | - shmem_instance_id: shmem runtime instance to operate on (default 0; the | 128 | - shmem_instance_id: shmem runtime instance to operate on (default 0; the |
| 126 | shmem Python API currently supports a single instance). | 129 | shmem Python API currently supports a single instance). |
| 127 | v1 degrade: host put segment scatter per plan.dst ranges. | 130 | v1 degrade: host put segment scatter per plan.dst ranges. |
| @@ -148,6 +151,7 @@ class DispatchOp(KernelOp): | |||
| 148 | int(ctx["K"]), | 151 | int(ctx["K"]), |
| 149 | int(ctx["R"]), | 152 | int(ctx["R"]), |
| 150 | int(ctx["rank"]), | 153 | int(ctx["rank"]), |
| 154 | + num_sms=self.num_sms, | ||
| 151 | ) | 155 | ) |
| 152 | 156 | ||
| 153 | def compute_profile(self, ctx, hidden_sh, route_weights_sk, plan, | 157 | def compute_profile(self, ctx, hidden_sh, route_weights_sk, plan, |
| @@ -186,6 +190,7 @@ class CombineOp(KernelOp): | |||
| 186 | - optional weight gather from ``ctx['weights_buf']`` into user-facing | 190 | - optional weight gather from ``ctx['weights_buf']`` into user-facing |
| 187 | output_sk [S, K] fp32 | 191 | output_sk [S, K] fp32 |
| 188 | - launcher selects native/UDMA from ASCEND_MOONEP_COMBINE_USE_UDMA | 192 | - launcher selects native/UDMA from ASCEND_MOONEP_COMBINE_USE_UDMA |
| 193 | + - MTE launch width follows self.num_sms; UDMA keeps its fixed schedule | ||
| 189 | """ | 194 | """ |
| 190 | 195 | ||
| 191 | def compute(self, ctx, output_sh, plan, output_sk=None, | 196 | def compute(self, ctx, output_sh, plan, output_sk=None, |
| @@ -209,6 +214,7 @@ class CombineOp(KernelOp): | |||
| 209 | int(ctx["K"]), | 214 | int(ctx["K"]), |
| 210 | int(ctx["R"]), | 215 | int(ctx["R"]), |
| 211 | int(ctx["rank"]), | 216 | int(ctx["rank"]), |
| 217 | + num_sms=self.num_sms, | ||
| 212 | ) | 218 | ) |
| 213 | 219 | ||
| 214 | class PrefetchOp(KernelOp): | 220 | class PrefetchOp(KernelOp): |
| @@ -220,7 +226,10 @@ class PrefetchOp(KernelOp): | |||
| 220 | - experts_to_copy [B] int32: global expert id to pull into slot b (-1 empty) | 226 | - experts_to_copy [B] int32: global expert id to pull into slot b (-1 empty) |
| 221 | - shmem_instance_id: shmem runtime instance to operate on (default 0; the | 227 | - shmem_instance_id: shmem runtime instance to operate on (default 0; the |
| 222 | shmem Python API currently supports a single instance). | 228 | shmem Python API currently supports a single instance). |
| 223 | - Cross-rank: pull home rows via host get (v1) or device RMA. | 229 | + compute_from_ptrs(ctx, source_ptrs, weight_slots, experts_to_copy): |
| 230 | + - setup-prepared ordinary BF16 sources via INT64 [E/R] addresses | ||
| 231 | + - symmetric BF16 [B,M,N] slots and shared INT32 [R,B] plan | ||
| 232 | + - launcher selects MTE/URMA from the prefetch environment flag. | ||
| 224 | """ | 233 | """ |
| 225 | 234 | ||
| 226 | def compute(self, ctx, weight_home, weight_slots, experts_to_copy, | 235 | def compute(self, ctx, weight_home, weight_slots, experts_to_copy, |
| @@ -249,6 +258,26 @@ class PrefetchOp(KernelOp): | |||
| 249 | self.num_sms, | 258 | self.num_sms, |
| 250 | ) | 259 | ) |
| 251 | 260 | ||
| 261 | + def compute_from_ptrs(self, ctx, source_ptrs, weight_slots, experts_to_copy): | ||
| 262 | + """Push prepared expert sources through the registered custom class.""" | ||
| 263 | + ranks, experts, slots = int(ctx['R']), int(ctx['E']), int(ctx['B']) | ||
| 264 | + if ranks <= 0 or experts % ranks: | ||
| 265 | + raise RuntimeError(f'invalid expert layout for prefetch: E={experts}, R={ranks}') | ||
| 266 | + local_experts = experts // ranks | ||
| 267 | + if weight_slots.ndim != 3: | ||
| 268 | + raise ValueError('PrefetchOp.compute_from_ptrs: weight_slots must be [B,M,N]') | ||
| 269 | + rows, columns = map(int, weight_slots.shape[1:]) | ||
| 270 | + _collect_inputs( | ||
| 271 | + 'PrefetchOp.compute_from_ptrs', | ||
| 272 | + tensors=( | ||
| 273 | + ('expert source pointers', source_ptrs, [local_experts], torch.int64), | ||
| 274 | + ('weight_slots', weight_slots, [slots, rows, columns], torch.bfloat16), | ||
| 275 | + ('experts_to_copy', experts_to_copy, [ranks, slots], torch.int32), | ||
| 276 | + ), | ||
| 277 | + ) | ||
| 278 | + return launch_prefetch_from_ptrs( | ||
| 279 | + source_ptrs, weight_slots, experts_to_copy, local_experts) | ||
| 280 | + | ||
| 252 | 281 | ||
| 253 | class GradReduceOp(KernelOp): | 282 | class GradReduceOp(KernelOp): |
| 254 | """Corresponds to ``moonep.launch_grad_reduce``. | 283 | """Corresponds to ``moonep.launch_grad_reduce``. |
| @@ -270,6 +299,18 @@ class GradReduceOp(KernelOp): | |||
| 270 | - shmem_instance_id: shmem runtime instance to operate on (default 0; the | 299 | - shmem_instance_id: shmem runtime instance to operate on (default 0; the |
| 271 | shmem Python API currently supports a single instance). | 300 | shmem Python API currently supports a single instance). |
| 272 | Cross-rank: home rank gets each peer's reduce-buffer rows (host get / RMA). | 301 | Cross-rank: home rank gets each peer's reduce-buffer rows (host get / RMA). |
| 302 | + | ||
| 303 | + compute_targets(ctx, target_ptrs, reduce_buffer, experts_to_copy, rank, | ||
| 304 | + num_sms, shmem_instance_id=0): | ||
| 305 | + - explicit alternative for setup-frozen INT64 [epn] canonical pointers; | ||
| 306 | + no method or launcher selects this contract by inspecting dtype. | ||
| 307 | + - targets are ordinary local contiguous FP32 [H,H'] matrices, disjoint, | ||
| 308 | + address-stable and kept alive by the caller until completion. | ||
| 309 | + - only the [B,H,H'] source bank must be symmetric. MTE is ordered. | ||
| 310 | + Canonical UDMA uses the fused atomic-add kernel with unspecified | ||
| 311 | + accumulation order and setup-owned ctx['_grad_reduce_target_workspace']. | ||
| 312 | + Like dense, targets fuse the AIV WORLD barrier and valid-slot clear. | ||
| 313 | + The caller must publish all ranks' input slots before submission. | ||
| 273 | """ | 314 | """ |
| 274 | 315 | ||
| 275 | def compute(self, ctx, full_grad_home, reduce_buffer, experts_to_copy, | 316 | def compute(self, ctx, full_grad_home, reduce_buffer, experts_to_copy, |
| @@ -322,3 +363,29 @@ class GradReduceOp(KernelOp): | |||
| 322 | barrier_off=0, | 363 | barrier_off=0, |
| 323 | grid_sync_bar=None, | 364 | grid_sync_bar=None, |
| 324 | ) | 365 | ) |
| 366 | + | ||
| 367 | + def compute_targets(self, ctx, target_ptrs, reduce_buffer, experts_to_copy, | ||
| 368 | + rank, num_sms, shmem_instance_id: int = 0): | ||
| 369 | + """Reduce symmetric slots into explicitly supplied canonical pointers.""" | ||
| 370 | + R = int(ctx["R"]); E = int(ctx["E"]); B = int(ctx["B"]) | ||
| 371 | + if R <= 0 or E % R: | ||
| 372 | + raise RuntimeError(f"invalid expert layout for grad reduce: E={E}, R={R}") | ||
| 373 | + epn = E // R | ||
| 374 | + if reduce_buffer.ndim != 3: | ||
| 375 | + raise ValueError("GradReduceOp.compute_targets: reduce_buffer must be [B,H,H_prime]") | ||
| 376 | + H, H_prime = map(int, reduce_buffer.shape[1:]) | ||
| 377 | + _collect_inputs( | ||
| 378 | + "GradReduceOp.compute_targets", | ||
| 379 | + tensors=( | ||
| 380 | + ("canonical target pointers", target_ptrs, [epn], torch.int64), | ||
| 381 | + ("reduce_buffer", reduce_buffer, [B, H, H_prime], torch.float32), | ||
| 382 | + ("experts_to_copy", experts_to_copy, [R, B], torch.int32), | ||
| 383 | + ), | ||
| 384 | + scalars=(("rank", rank), ("num_sms", num_sms), | ||
| 385 | + ("shmem_instance_id", shmem_instance_id)), | ||
| 386 | + ) | ||
| 387 | + workspace = ctx.get('_grad_reduce_target_workspace') | ||
| 388 | + launch_args = {} if workspace is None else {'udma_workspace': workspace} | ||
| 389 | + launch_grad_reduce_targets( | ||
| 390 | + target_ptrs, reduce_buffer, experts_to_copy, | ||
| 391 | + rank=int(rank), num_sms=int(num_sms), **launch_args) | ||
| @@ -139,6 +139,7 @@ def _npu_extension(): | |||
| 139 | sources = [ | 139 | sources = [ |
| 140 | os.path.join("native", "csrc", "pybind.cpp"), | 140 | os.path.join("native", "csrc", "pybind.cpp"), |
| 141 | os.path.join("native", "csrc", "acl_shared_buffer.cpp"), | 141 | os.path.join("native", "csrc", "acl_shared_buffer.cpp"), |
| 142 | + os.path.join("native", "csrc", "barrier.cpp"), | ||
| 142 | os.path.join("native", "csrc", "torch_classes.cpp"), | 143 | os.path.join("native", "csrc", "torch_classes.cpp"), |
| 143 | os.path.join("native", "csrc", "launcher.cpp"), | 144 | os.path.join("native", "csrc", "launcher.cpp"), |
| 144 | os.path.join("native", "csrc", "ops", "moonep_combine.cpp"), | 145 | os.path.join("native", "csrc", "ops", "moonep_combine.cpp"), |
| @@ -0,0 +1,92 @@ | |||
| 1 | +# SPDX-License-Identifier: Apache-2.0 | ||
| 2 | +"""Prepared communication-bank correctness through Buffer.dispatch/combine. | ||
| 3 | + | ||
| 4 | +Like test_buffer_combine.py, verify exact round trips through the Buffer API. | ||
| 5 | +Keep three zero-copy results live in distinct caller-owned banks, then switch | ||
| 6 | +back to the default storage and check that copying results survive later calls. | ||
| 7 | +Dispatch and Combine use MTE; expert pointer operations are tested separately. | ||
| 8 | + | ||
| 9 | +Run in fresh workers (EP2 or EP8): | ||
| 10 | + torchrun --nproc-per-node=2 -m pytest -s -x \ | ||
| 11 | + test_npu/buffer_test/test_buffer_comm_buffers.py | ||
| 12 | +""" | ||
| 13 | +import torch | ||
| 14 | +import torch.distributed as dist | ||
| 15 | +import torch_npu | ||
| 16 | +import pytest | ||
| 17 | + | ||
| 18 | +from kernel_test_utils import init_shmem | ||
| 19 | +from npu_patch import Buffer, ShmemRuntime | ||
| 20 | +from npu_patch.buffer_c import create_vmm_physical, reset_symmetric_descriptors | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +# Retain backing on failure; the launcher must stop all workers together. | ||
| 24 | +_KEEPALIVE = [] | ||
| 25 | + | ||
| 26 | + | ||
| 27 | +def test_buffer_comm_buffers(dist_env): | ||
| 28 | + rank, world = dist_env | ||
| 29 | + if world not in (2, 8): | ||
| 30 | + pytest.skip("communication-bank recipe requires EP2 or EP8") | ||
| 31 | + if ShmemRuntime.is_initialized(): | ||
| 32 | + raise RuntimeError("run this test in fresh workers without an active SHMEM heap") | ||
| 33 | + s, h, k, local, b = 16, 128, 1, 2, 2 | ||
| 34 | + device = torch.device("npu", torch.npu.current_device()) | ||
| 35 | + buffer = Buffer(S=s, H=h, K=k, E=world * local, B=b, num_ep_ranks=world, | ||
| 36 | + group=dist.group.WORLD, explicitly_destroy=True, use_udma=False) | ||
| 37 | + sources = [] | ||
| 38 | + _KEEPALIVE.extend((buffer, sources)) | ||
| 39 | + for _ in range(3): | ||
| 40 | + for shape, dtype in (((s * k, h), torch.bfloat16), ((s * k,), torch.int32)): | ||
| 41 | + sources.append(create_vmm_physical(shape, dtype, device.index)[0]) | ||
| 42 | + # Register every bank in the same order on all ranks before SHMEM init. | ||
| 43 | + init_shmem(group=dist.group.WORLD, enable_udma=False) | ||
| 44 | + banks = [buffer.prepare_comm_buffers(*sources[i:i + 2]) for i in range(0, 6, 2)] | ||
| 45 | + current = torch_npu.npu.current_stream() | ||
| 46 | + routes = torch.zeros(s, k, dtype=torch.int32, device=device) | ||
| 47 | + counts = torch.bincount(routes.flatten().long(), minlength=world * local).int() | ||
| 48 | + probabilities = torch.ones(s, k, dtype=torch.float32, device=device) | ||
| 49 | + saved = [] | ||
| 50 | + copied = [] | ||
| 51 | + _KEEPALIVE.extend((saved, copied)) | ||
| 52 | + for value, bank in zip((1, 2, 3), banks): | ||
| 53 | + hidden = torch.full((s, h), rank * 4 + value, dtype=torch.bfloat16, device=device) | ||
| 54 | + buffer.set_comm_buffers(bank) | ||
| 55 | + out, probs, _, plan, done = buffer.dispatch( | ||
| 56 | + hidden, probabilities, routes, counts, async_finish=True, | ||
| 57 | + zero_copy=True, router_weights_zero_copy=True) | ||
| 58 | + assert out.data_ptr() == bank.hidden.data_ptr() | ||
| 59 | + assert probs.data_ptr() == bank.route.data_ptr() | ||
| 60 | + saved.append((hidden, out, plan, done, bank)) | ||
| 61 | + # Each earlier zero-copy result must survive the other banks' dispatches. | ||
| 62 | + for hidden, out, plan, done, bank in saved: | ||
| 63 | + current.wait_event(done) | ||
| 64 | + buffer.set_comm_buffers(bank) | ||
| 65 | + combined, _, event = buffer.combine(plan, out, async_finish=True, zero_copy=True) | ||
| 66 | + current.wait_event(event) | ||
| 67 | + torch.npu.synchronize() | ||
| 68 | + torch.testing.assert_close(combined, hidden, atol=0, rtol=0) | ||
| 69 | + | ||
| 70 | + # None explicitly restores the default communication storage. | ||
| 71 | + buffer.set_comm_buffers(None) | ||
| 72 | + for value in (5, 6): | ||
| 73 | + hidden = torch.full((s, h), value, dtype=torch.bfloat16, device=device) | ||
| 74 | + out, _, _, plan, event = buffer.dispatch( | ||
| 75 | + hidden, probabilities, routes, counts, async_finish=True) | ||
| 76 | + copied.append((hidden, out, plan, event)) | ||
| 77 | + for hidden, out, plan, event in copied: | ||
| 78 | + current.wait_event(event) | ||
| 79 | + result, _, event = buffer.combine(plan, out, async_finish=True) | ||
| 80 | + current.wait_event(event) | ||
| 81 | + torch.npu.synchronize() | ||
| 82 | + torch.testing.assert_close(result, hidden, atol=0, rtol=0) | ||
| 83 | + | ||
| 84 | + # Only successful, globally drained execution may release symmetric backing. | ||
| 85 | + torch.npu.synchronize() | ||
| 86 | + dist.barrier() | ||
| 87 | + ShmemRuntime.finalize() | ||
| 88 | + buffer.destroy() | ||
| 89 | + for source in sources: | ||
| 90 | + source._vmm_allocation.destroy() | ||
| 91 | + reset_symmetric_descriptors() | ||
| 92 | + _KEEPALIVE.clear() | ||
| @@ -0,0 +1,184 @@ | |||
| 1 | +# SPDX-License-Identifier: Apache-2.0 | ||
| 2 | +"""Canonical pointer-target correctness through the low-level launcher. | ||
| 3 | + | ||
| 4 | +Same structure as ``test_buffer_grad_reduce.py`` (buffer-backed VMM chunks, | ||
| 5 | +per-case SHMEM init, direct ``npu_patch.launchers`` call, same ``CASES`` / | ||
| 6 | +``PLAN_BUILDERS`` / data generators / reference verification): the only | ||
| 7 | +difference is the input — this variant hands the op a frozen INT64 ``[epn]`` | ||
| 8 | +table of ordinary FP32 ``[H, H']`` target addresses instead of an | ||
| 9 | +``[epn, H, H']`` home-grad chunk, which is exactly what | ||
| 10 | +``launch_grad_reduce_targets`` takes. | ||
| 11 | + | ||
| 12 | +Run in fresh workers (EP2 or EP8; URMA requires Ascend950 + matching libraries): | ||
| 13 | + torchrun --nproc-per-node=2 -m pytest -s -x \ | ||
| 14 | + test_npu/buffer_test/test_buffer_grad_reduce_targets.py -k mte | ||
| 15 | +Replace -k mte with -k urma to select URMA, or omit it to run both transports. | ||
| 16 | +""" | ||
| 17 | +import pytest | ||
| 18 | +import torch | ||
| 19 | +import torch.distributed as dist | ||
| 20 | +import torch_npu | ||
| 21 | + | ||
| 22 | +from kernel_test_utils import init_shmem | ||
| 23 | +from npu_patch import ShmemRuntime | ||
| 24 | +from npu_patch._device import local_device_index | ||
| 25 | +from npu_patch.buffer_c import ( | ||
| 26 | + create_vmm_physical, | ||
| 27 | + reset_symmetric_descriptors, | ||
| 28 | + sym_tensor, | ||
| 29 | +) | ||
| 30 | +from npu_patch.launchers import launch_grad_reduce_targets | ||
| 31 | +# Reuse the dense variant verbatim: same cases, same plans, same data | ||
| 32 | +# generators and the same reference verification. | ||
| 33 | +from test_buffer_grad_reduce import ( | ||
| 34 | + CASES, | ||
| 35 | + PLAN_BUILDERS, | ||
| 36 | + _configure_udma_env, | ||
| 37 | + _make_data_fns, | ||
| 38 | + _verify, | ||
| 39 | +) | ||
| 40 | + | ||
| 41 | + | ||
| 42 | +import os | ||
| 43 | + | ||
| 44 | +# Documented canonical UDMA scratch contract: 512*1024*max(2*min(blocks,64),R*B) | ||
| 45 | +# FP32 elements per rank. It is already scratch, so the plan-size stress case | ||
| 46 | +# (R*B = 16384..65536) would need 32..128 GiB and cannot be honoured on a 64 GiB | ||
| 47 | +# die next to the case's own tensors; that case stays MTE-covered. | ||
| 48 | +_UDMA_SCRATCH_LIMIT_BYTES = 16 * 1024 ** 3 | ||
| 49 | + | ||
| 50 | + | ||
| 51 | +def _udma_scratch_elements(blocks, R, B): | ||
| 52 | + """Setup-owned local FP32 scratch the canonical UDMA entry validates.""" | ||
| 53 | + return 512 * 1024 * max(2 * min(blocks, 64), R * B) | ||
| 54 | + | ||
| 55 | + | ||
| 56 | +@pytest.fixture(scope="module") | ||
| 57 | +def dist_env(): | ||
| 58 | + if "RANK" not in os.environ: | ||
| 59 | + pytest.skip("test_buffer_grad_reduce_targets requires torchrun with at least 2 NPUs") | ||
| 60 | + | ||
| 61 | + rank = int(os.environ["RANK"]) | ||
| 62 | + local_rank = int(os.environ.get("LOCAL_RANK", rank)) | ||
| 63 | + torch.npu.set_device(local_device_index(local_rank)) | ||
| 64 | + owns_process_group = not dist.is_initialized() | ||
| 65 | + if owns_process_group: | ||
| 66 | + dist.init_process_group( | ||
| 67 | + backend="hccl", device_id=torch.device(f"npu:{local_device_index(local_rank)}")) | ||
| 68 | + rank = dist.get_rank() | ||
| 69 | + R = dist.get_world_size() | ||
| 70 | + if R < 2: | ||
| 71 | + if owns_process_group: | ||
| 72 | + dist.destroy_process_group() | ||
| 73 | + pytest.skip("test_buffer_grad_reduce_targets requires at least 2 NPUs") | ||
| 74 | + | ||
| 75 | + yield rank, local_rank, R | ||
| 76 | + | ||
| 77 | + if ShmemRuntime.is_initialized(): | ||
| 78 | + ShmemRuntime.finalize() | ||
| 79 | + | ||
| 80 | + | ||
| 81 | +def _launch_grad_reduce_targets( | ||
| 82 | + target_ptrs, reduce_buffers, plan, epn, H, Hp, R, B, rank, blocks, | ||
| 83 | + udma_workspace, | ||
| 84 | +): | ||
| 85 | + """Direct canonical-pointer launcher (no Buffer wrapper). | ||
| 86 | + | ||
| 87 | + The dense test calls ``launch_grad_reduce`` the same way; this variant only | ||
| 88 | + swaps the home-grad chunk for the pointer table. | ||
| 89 | + """ | ||
| 90 | + launch_grad_reduce_targets( | ||
| 91 | + target_ptrs, reduce_buffers, plan, | ||
| 92 | + rank=rank, num_sms=blocks, udma_workspace=udma_workspace, | ||
| 93 | + ) | ||
| 94 | + | ||
| 95 | + | ||
| 96 | +def run_case(rank, local_rank, R, case, use_udma): | ||
| 97 | + dev = f"npu:{local_device_index(local_rank)}" | ||
| 98 | + epn = case["epn"] | ||
| 99 | + E = R * epn | ||
| 100 | + H = case["H"] | ||
| 101 | + Hp = case["Hp"] | ||
| 102 | + # Buffer uses exact-size per-PE symmetric chunks; the slot bank is an | ||
| 103 | + # independent input (``base_B``), exactly as in the dense variant. | ||
| 104 | + B = case["base_B"] | ||
| 105 | + blocks = case["num_sms"] | ||
| 106 | + seed = case.get("seed", 0) | ||
| 107 | + | ||
| 108 | + scratch_elements = _udma_scratch_elements(blocks, R, B) | ||
| 109 | + if use_udma and scratch_elements * 4 > _UDMA_SCRATCH_LIMIT_BYTES: | ||
| 110 | + pytest.skip( | ||
| 111 | + f"{case['name']}: canonical UDMA scratch would need " | ||
| 112 | + f"{scratch_elements * 4 >> 30} GiB per rank " | ||
| 113 | + f"(contract 512*1024*max(2*min(blocks,64),R*B))") | ||
| 114 | + | ||
| 115 | + plan = PLAN_BUILDERS[case.get("plan", "ring")](R, B, epn, dev, seed) | ||
| 116 | + grads_fn, slot_fn = _make_data_fns( | ||
| 117 | + case.get("data", "affine"), rank, epn, B, H, Hp, dev, seed) | ||
| 118 | + | ||
| 119 | + target_table = None | ||
| 120 | + reduce_buffers_src = None | ||
| 121 | + udma_workspace = None | ||
| 122 | + try: | ||
| 123 | + # Canonical targets are ordinary FP32 memory: one contiguous | ||
| 124 | + # ``[epn, H, H']`` table sliced per expert, so the pointer table is | ||
| 125 | + # simply its rows and the reference verification can compare the table. | ||
| 126 | + target_table = torch.empty( | ||
| 127 | + (epn, H, Hp), dtype=torch.float32, device=dev) | ||
| 128 | + target_ptrs = torch.tensor( | ||
| 129 | + [target_table.data_ptr() + i * H * Hp * 4 for i in range(epn)], | ||
| 130 | + dtype=torch.int64, device=dev) | ||
| 131 | + # Only the B-slot source bank is symmetric. | ||
| 132 | + reduce_buffers_src, _, _ = create_vmm_physical( | ||
| 133 | + (B, H, Hp), torch.float32, local_device_index(local_rank)) | ||
| 134 | + | ||
| 135 | + _configure_udma_env(use_udma) | ||
| 136 | + if not ShmemRuntime.is_initialized(): | ||
| 137 | + if use_udma: | ||
| 138 | + init_shmem(group=None, enable_udma=True, qp_count=2) | ||
| 139 | + else: | ||
| 140 | + init_shmem(group=None) | ||
| 141 | + reduce_buffers = sym_tensor(reduce_buffers_src) | ||
| 142 | + if use_udma: | ||
| 143 | + udma_workspace = torch.empty( | ||
| 144 | + scratch_elements, dtype=torch.float32, device=dev) | ||
| 145 | + | ||
| 146 | + reduce_buffers.zero_() | ||
| 147 | + target_table.copy_(grads_fn()) | ||
| 148 | + reduce_buffers.copy_(slot_fn(rank)) | ||
| 149 | + torch.npu.synchronize() | ||
| 150 | + dist.barrier() | ||
| 151 | + | ||
| 152 | + _launch_grad_reduce_targets( | ||
| 153 | + target_ptrs, reduce_buffers, plan, epn, H, Hp, R, B, rank, blocks, | ||
| 154 | + udma_workspace, | ||
| 155 | + ) | ||
| 156 | + torch.npu.synchronize() | ||
| 157 | + dist.barrier() | ||
| 158 | + | ||
| 159 | + _verify(rank, R, epn, B, plan, grads_fn, slot_fn, | ||
| 160 | + target_table, reduce_buffers, | ||
| 161 | + f"{case['name']} grad_reduce_targets failed") | ||
| 162 | + | ||
| 163 | + if rank == 0: | ||
| 164 | + print(f"[PASS] {case['name']} epn={epn} B={B} H={H} Hp={Hp} " | ||
| 165 | + f"blocks={blocks} udma={use_udma}", flush=True) | ||
| 166 | + finally: | ||
| 167 | + # Re-init per case: finalize (tear down symmetric mappings) first, then | ||
| 168 | + # reverse the VMM allocation, then clear the descriptor registry. | ||
| 169 | + dist.barrier() | ||
| 170 | + if ShmemRuntime.is_initialized(): | ||
| 171 | + ShmemRuntime.finalize() | ||
| 172 | + alloc = getattr(reduce_buffers_src, "_vmm_allocation", None) | ||
| 173 | + if alloc is not None: | ||
| 174 | + alloc.destroy() | ||
| 175 | + reset_symmetric_descriptors() | ||
| 176 | + | ||
| 177 | + | ||
| 178 | +@pytest.mark.parametrize("use_udma", [True, False], ids=["urma", "mte"]) | ||
| 179 | +@pytest.mark.parametrize("case", CASES, ids=[case["name"] for case in CASES]) | ||
| 180 | +def test_buffer_grad_reduce_targets(dist_env, case, use_udma): | ||
| 181 | + rank, local_rank, R = dist_env | ||
| 182 | + if R not in (2, 8): | ||
| 183 | + pytest.skip("canonical pointer GradReduce recipe requires EP2 or EP8") | ||
| 184 | + run_case(rank, local_rank, R, case, use_udma) | ||
| @@ -0,0 +1,197 @@ | |||
| 1 | +# SPDX-License-Identifier: Apache-2.0 | ||
| 2 | +"""Canonical pointer PUSH correctness through the low-level launcher. | ||
| 3 | + | ||
| 4 | +Same structure as ``test_buffer_prefetch.py`` (per-rank ``[epn + B, H, H']`` | ||
| 5 | +buffer-backed chunk, per-case SHMEM init, ``map_to_sym_ptr`` translation, same | ||
| 6 | +``CASES`` / per-expert payload generator / per-slot reference check): the only | ||
| 7 | +difference is the input — this variant hands the op a frozen INT64 ``[epn]`` | ||
| 8 | +table of ordinary BF16 source addresses plus the whole ``[R, B]`` plan, which is | ||
| 9 | +exactly what ``launch_prefetch_from_ptrs`` takes. The GET variant instead passes | ||
| 10 | +the ``[E, H, H']`` symmetric home view and this rank's ``[B]`` request row. | ||
| 11 | + | ||
| 12 | +PUSH semantics (see ``npu_patch/native/kernels/prefetch_pointer_push_mte.cpp``): | ||
| 13 | +the plan is row-major ``[destination PE, destination slot]``; the PE that owns | ||
| 14 | +the listed expert pushes its own row into that slot. Replicating one request row | ||
| 15 | +across all destinations therefore reproduces the GET expectations exactly — every | ||
| 16 | +rank ends up with the same expert set in its own slots, pulled by the owner | ||
| 17 | +instead of fetched by the consumer. | ||
| 18 | + | ||
| 19 | +Run in fresh workers (EP2 or EP8; URMA requires Ascend950 + matching libraries): | ||
| 20 | + torchrun --nproc-per-node=2 -m pytest -s -x \ | ||
| 21 | + test_npu/buffer_test/test_buffer_prefetch_push.py -k mte | ||
| 22 | +Replace -k mte with -k urma to select URMA, or omit it to run both transports. | ||
| 23 | +""" | ||
| 24 | +import os | ||
| 25 | +import sys | ||
| 26 | + | ||
| 27 | +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | ||
| 28 | +from kernel_test_utils import init_shmem | ||
| 29 | + | ||
| 30 | +import pytest | ||
| 31 | +import torch | ||
| 32 | +import torch.distributed as dist | ||
| 33 | +import torch_npu | ||
| 34 | + | ||
| 35 | +from npu_patch._device import local_device_index | ||
| 36 | +from npu_patch import ShmemRuntime | ||
| 37 | +from npu_patch.buffer_c import ( | ||
| 38 | + create_sym_tensor_from_ptr, | ||
| 39 | + map_to_sym_ptr, | ||
| 40 | + reset_symmetric_descriptors, | ||
| 41 | +) | ||
| 42 | +from npu_patch.launchers import launch_prefetch_from_ptrs | ||
| 43 | +# Reuse the GET variant verbatim: same cases, same chunk layout, same per-expert | ||
| 44 | +# payload generator and the same transport toggles. | ||
| 45 | +from test_buffer_prefetch import ( | ||
| 46 | + CASES, | ||
| 47 | + _configure_udma_env, | ||
| 48 | + _expert_value, | ||
| 49 | + make_symmetric_experts, | ||
| 50 | +) | ||
| 51 | + | ||
| 52 | + | ||
| 53 | +@pytest.fixture(scope="module") | ||
| 54 | +def dist_env(): | ||
| 55 | + if "RANK" not in os.environ: | ||
| 56 | + pytest.skip("test_buffer_prefetch_push requires torchrun with at least 2 NPUs") | ||
| 57 | + | ||
| 58 | + rank = int(os.environ["RANK"]) | ||
| 59 | + local_rank = int(os.environ.get("LOCAL_RANK", rank)) | ||
| 60 | + torch.npu.set_device(local_device_index(local_rank)) | ||
| 61 | + owns_process_group = not dist.is_initialized() | ||
| 62 | + if owns_process_group: | ||
| 63 | + dist.init_process_group( | ||
| 64 | + backend="hccl", device_id=torch.device(f"npu:{local_device_index(local_rank)}")) | ||
| 65 | + rank = dist.get_rank() | ||
| 66 | + R = dist.get_world_size() | ||
| 67 | + if R < 2: | ||
| 68 | + if owns_process_group: | ||
| 69 | + dist.destroy_process_group() | ||
| 70 | + pytest.skip("test_buffer_prefetch_push requires at least 2 NPUs") | ||
| 71 | + | ||
| 72 | + yield rank, local_rank, R | ||
| 73 | + | ||
| 74 | + if ShmemRuntime.is_initialized(): | ||
| 75 | + ShmemRuntime.finalize() | ||
| 76 | + | ||
| 77 | + | ||
| 78 | +def push_plan(expert_ids, R, device): | ||
| 79 | + """Replicated ``[destination PE, destination slot]`` table, independent of the | ||
| 80 | + token planner's load balance. | ||
| 81 | + | ||
| 82 | + The PUSH kernel walks the plan by ``destination_pe = entry / B`` and lets the | ||
| 83 | + owner of ``plan[destination_pe, slot]`` write into that destination's slot, | ||
| 84 | + so repeating one request row on every destination gives every rank the same | ||
| 85 | + per-slot expectations as the GET variant. | ||
| 86 | + """ | ||
| 87 | + return torch.tensor([list(expert_ids)] * R, dtype=torch.int32, device=device) | ||
| 88 | + | ||
| 89 | + | ||
| 90 | +def run_case(rank, local_rank, R, case, use_udma): | ||
| 91 | + E = case["E"] | ||
| 92 | + H = case["H"] | ||
| 93 | + Hp = case["Hp"] | ||
| 94 | + B = case["B"] | ||
| 95 | + device = f"npu:{local_device_index(local_rank)}" | ||
| 96 | + | ||
| 97 | + assert H % 128 == 0 and Hp % 128 == 0, \ | ||
| 98 | + f"{case['name']}: H/Hp must be multiples of 128" | ||
| 99 | + | ||
| 100 | + keepalive = make_symmetric_experts(R, E, H, Hp, B, local_rank) | ||
| 101 | + allocation = getattr(keepalive, "_vmm_allocation", None) | ||
| 102 | + epn = (E + R - 1) // R | ||
| 103 | + row_bytes = H * Hp * 2 | ||
| 104 | + try: | ||
| 105 | + local_expert = keepalive[:epn] | ||
| 106 | + push_slots_src = keepalive[epn:] | ||
| 107 | + local_expert.zero_() | ||
| 108 | + for expert in range(rank * epn, min((rank + 1) * epn, E)): | ||
| 109 | + local_expert[expert - rank * epn].copy_( | ||
| 110 | + _expert_value(expert, H, Hp, device) | ||
| 111 | + ) | ||
| 112 | + | ||
| 113 | + # Setup-frozen canonical sources: only this rank's own epn rows, as | ||
| 114 | + # ordinary addresses. The kernel adds the destination offset itself. | ||
| 115 | + source_ptrs = torch.tensor( | ||
| 116 | + [local_expert.data_ptr() + index * row_bytes for index in range(epn)], | ||
| 117 | + dtype=torch.int64, device=device, | ||
| 118 | + ) | ||
| 119 | + | ||
| 120 | + expert_ids = case["experts"](E) | ||
| 121 | + assert len(expert_ids) == B | ||
| 122 | + sentinel = -123.0 | ||
| 123 | + push_slots_src.fill_(sentinel) | ||
| 124 | + plan = push_plan(expert_ids, R, device) | ||
| 125 | + | ||
| 126 | + torch.npu.synchronize() | ||
| 127 | + dist.barrier() | ||
| 128 | + | ||
| 129 | + # buffer-backed only: chunk already registered -> init_shmem (auto-picks the UID/IP-port bootstrap) | ||
| 130 | + # -> map_to_sym_ptr translates it into a local symmetric tensor (data_ptr = symmetric base) before | ||
| 131 | + # the kernel writes into it with aclshmem RMA. | ||
| 132 | + _configure_udma_env(use_udma) | ||
| 133 | + if not ShmemRuntime.is_initialized(): | ||
| 134 | + if use_udma: | ||
| 135 | + init_shmem(group=None, enable_udma=True, qp_count=2) | ||
| 136 | + else: | ||
| 137 | + init_shmem(group=None) | ||
| 138 | + | ||
| 139 | + symmetric_base = map_to_sym_ptr( | ||
| 140 | + keepalive.data_ptr(), "prefetch_push_chunk" | ||
| 141 | + ) | ||
| 142 | + push_slots = create_sym_tensor_from_ptr( | ||
| 143 | + symmetric_base + epn * row_bytes, | ||
| 144 | + [B, H, Hp], | ||
| 145 | + torch.bfloat16, | ||
| 146 | + device, | ||
| 147 | + ) | ||
| 148 | + | ||
| 149 | + launch_prefetch_from_ptrs(source_ptrs, push_slots, plan, epn) | ||
| 150 | + torch.npu.synchronize() | ||
| 151 | + | ||
| 152 | + ok = True | ||
| 153 | + for slot, expert in enumerate(expert_ids): | ||
| 154 | + expected = ( | ||
| 155 | + torch.full_like(push_slots[slot], sentinel) | ||
| 156 | + if expert < 0 | ||
| 157 | + else _expert_value(expert, H, Hp, device) | ||
| 158 | + ) | ||
| 159 | + if not torch.equal(push_slots[slot], expected): | ||
| 160 | + ok = False | ||
| 161 | + max_diff = ( | ||
| 162 | + push_slots[slot].float() - expected.float() | ||
| 163 | + ).abs().max().item() | ||
| 164 | + print( | ||
| 165 | + f"[rank {rank}] {case['name']} mismatch: buffer={slot}, " | ||
| 166 | + f"expert={expert}, max_abs_diff={max_diff}" | ||
| 167 | + ) | ||
| 168 | + | ||
| 169 | + ok_tensor = torch.tensor( | ||
| 170 | + [int(ok)], dtype=torch.int32, device=device | ||
| 171 | + ) | ||
| 172 | + dist.all_reduce(ok_tensor, op=dist.ReduceOp.MIN) | ||
| 173 | + assert ok_tensor.item() == 1, f"{case['name']} failed" | ||
| 174 | + if rank == 0: | ||
| 175 | + print( | ||
| 176 | + f" [PASS] {case['name']} ({'urma' if use_udma else 'mte'}): " | ||
| 177 | + f"E={E}, B={B}, H={H}, Hp={Hp}, epn={epn}" | ||
| 178 | + ) | ||
| 179 | + dist.barrier() | ||
| 180 | + finally: | ||
| 181 | + # Re-init per case: finalize first (tear down the symmetric mappings), then the VMM undo | ||
| 182 | + # ops, then clear the registry. Reversed, the next init's get_buffer_ptr would not see the new chunk. | ||
| 183 | + if ShmemRuntime.is_initialized(): | ||
| 184 | + ShmemRuntime.finalize() | ||
| 185 | + if allocation is not None: | ||
| 186 | + allocation.destroy() | ||
| 187 | + reset_symmetric_descriptors() | ||
| 188 | + torch.npu.synchronize() | ||
| 189 | + | ||
| 190 | + | ||
| 191 | +@pytest.mark.parametrize("use_udma", [True, False], ids=["urma", "mte"]) | ||
| 192 | +@pytest.mark.parametrize("case", CASES, ids=[case["name"] for case in CASES]) | ||
| 193 | +def test_buffer_prefetch_push(dist_env, case, use_udma): | ||
| 194 | + rank, local_rank, R = dist_env | ||
| 195 | + if R not in (2, 8): | ||
| 196 | + pytest.skip("pointer PUSH recipe requires EP2 or EP8") | ||
| 197 | + run_case(rank, local_rank, R, case, use_udma) | ||
| @@ -24,12 +24,16 @@ Ascend adaptations: | |||
| 24 | 24 | ||
| 25 | Run with: | 25 | Run with: |
| 26 | torchrun --nproc_per_node=8 -m pytest -s test_npu/mte/test_e2e.py | 26 | torchrun --nproc_per_node=8 -m pytest -s test_npu/mte/test_e2e.py |
| 27 | + | ||
| 28 | +Shape IDs are default (S4096/H256/K16/E64/Hp512) and dsv4 | ||
| 29 | +(S4096/H7168/K6/E48/Hp3072, EP8). Select one with -k default or -k dsv4. | ||
| 27 | """ | 30 | """ |
| 28 | 31 | ||
| 29 | import os | 32 | import os |
| 30 | import sys | 33 | import sys |
| 31 | 34 | ||
| 32 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | 35 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
| 36 | +import pytest | ||
| 33 | import torch | 37 | import torch |
| 34 | import torch.distributed as dist | 38 | import torch.distributed as dist |
| 35 | 39 | ||
| @@ -278,19 +282,19 @@ def assert_raises_assertion(expected_substr, fn): | |||
| 278 | raise AssertionError(f"expected AssertionError containing {expected_substr!r}") | 282 | raise AssertionError(f"expected AssertionError containing {expected_substr!r}") |
| 279 | 283 | ||
| 280 | 284 | ||
| 281 | -def test_e2e(): | 285 | +@pytest.mark.parametrize("S,H,K,E,Hp,ep_size", [ |
| 286 | + pytest.param(4096, 256, 16, 64, 512, None, id="default"), | ||
| 287 | + pytest.param(4096, 7168, 6, 48, 3072, 8, id="dsv4"), | ||
| 288 | +]) | ||
| 289 | +def test_e2e(S, H, K, E, Hp, ep_size): | ||
| 282 | """MTE-only end-to-end: the full dispatch / prefetch / combine / reduce_grad chain.""" | 290 | """MTE-only end-to-end: the full dispatch / prefetch / combine / reduce_grad chain.""" |
| 283 | rank, R = setup() | 291 | rank, R = setup() |
| 284 | - # S=128/H=64 mirrors test_npu/buffer_test/test_buffer_plan.py's default config, which is | 292 | + if ep_size is not None and R != ep_size: |
| 285 | - # stable on this hardware; larger S/H intermittently trigger a MaskedSelectV3 | 293 | + pytest.skip(f"this shape requires {ep_size} EP ranks, got {R}") |
| 286 | - # OOB (507035) in the planning kernel (see docs/planning_operator_test_notes.md). | ||
| 287 | - S, H, K, E = 4096, 256, 16, 64 | ||
| 288 | # The Ascend planning kernel requires num_prefetch_slots == E / R. | 294 | # The Ascend planning kernel requires num_prefetch_slots == E / R. |
| 289 | B = E // R | 295 | B = E // R |
| 290 | epn = E // R | 296 | epn = E // R |
| 291 | - # Hp=512 makes epn*row = 8*256*512*2 = 2 MiB an exact multiple of the VMM granularity, | 297 | + # Both eight-rank shapes have 2 MiB-aligned BF16 local home segments. |
| 292 | - # so the full_weight projection can place the home rows exactly at [rank*epn, (rank+1)*epn). | ||
| 293 | - Hp = 512 | ||
| 294 | num_sms = 32 | 298 | num_sms = 32 |
| 295 | device = local_device_index() | 299 | device = local_device_index() |
| 296 | dev = f"npu:{device}" | 300 | dev = f"npu:{device}" |
| @@ -537,4 +541,4 @@ def setup(): | |||
| 537 | 541 | ||
| 538 | 542 | ||
| 539 | if __name__ == "__main__": | 543 | if __name__ == "__main__": |
| 540 | - test_e2e() | 544 | + test_e2e(4096, 256, 16, 64, 512, None) |
| @@ -0,0 +1,217 @@ | |||
| 1 | +# SPDX-License-Identifier: Apache-2.0 | ||
| 2 | +"""MTE canonical-pointer GradReduce correctness and custom-class compatibility. | ||
| 3 | + | ||
| 4 | +Same structure as this directory's dense ``test_grad_reduce.py`` (buffer-backed | ||
| 5 | +VMM source bank, per-case SHMEM init, direct ``npu_patch.launchers`` call, same | ||
| 6 | +``CASES`` / ``PLAN_BUILDERS`` / data generators / reference verification): the | ||
| 7 | +only difference is the input — this variant hands the op a frozen INT64 ``[epn]`` | ||
| 8 | +table of ordinary FP32 ``[H, H']`` target addresses instead of an | ||
| 9 | +``[epn, H, H']`` home-grad chunk, which is exactly what | ||
| 10 | +``launch_grad_reduce_targets`` takes. Only the ``[B, H, H']`` source bank is | ||
| 11 | +symmetric. | ||
| 12 | + | ||
| 13 | +``test_grad_reduce_targets_custom_class`` keeps the narrower API contract checks | ||
| 14 | +that the case suite does not cover: reverse-ordered, separately allocated and | ||
| 15 | +therefore non-contiguous targets, the original custom-class signature (including | ||
| 16 | +its default arguments and an ignored explicit scratch), the ``GradReduceOp`` | ||
| 17 | +ctx path, and a late producer behind the caller's readiness fence. | ||
| 18 | + | ||
| 19 | +Run in fresh workers, with a whole-job external hard timeout: | ||
| 20 | + torchrun --nproc-per-node=8 -m pytest -s -x \ | ||
| 21 | + test_npu/mte/test_grad_reduce_targets.py | ||
| 22 | +""" | ||
| 23 | +import os | ||
| 24 | +import time | ||
| 25 | + | ||
| 26 | +import pytest | ||
| 27 | +import torch | ||
| 28 | +import torch.distributed as dist | ||
| 29 | +import torch_npu | ||
| 30 | + | ||
| 31 | +from kernel_test_utils import init_shmem | ||
| 32 | +from npu_patch import ShmemRuntime | ||
| 33 | +from npu_patch._device import local_device_index | ||
| 34 | +from npu_patch.buffer_c import create_vmm_physical, reset_symmetric_descriptors, sym_tensor | ||
| 35 | +from npu_patch.launchers import launch_grad_reduce_targets | ||
| 36 | +from npu_patch.ops import GradReduceOp | ||
| 37 | +# Reuse the dense variant verbatim: same cases, same plans, same data | ||
| 38 | +# generators and the same reference verification. | ||
| 39 | +from test_grad_reduce import ( | ||
| 40 | + CASES, | ||
| 41 | + PLAN_BUILDERS, | ||
| 42 | + _make_data_fns, | ||
| 43 | + _verify, | ||
| 44 | + dist_env, | ||
| 45 | +) | ||
| 46 | + | ||
| 47 | +_USE_UDMA_ENV = "ASCEND_MOONEP_USE_UDMA" | ||
| 48 | +_GRAD_REDUCE_UDMA_ENV = "ASCEND_MOONEP_GRAD_REDUCE_USE_UDMA" | ||
| 49 | + | ||
| 50 | +# Failed native work must be stopped collectively by the external launcher. | ||
| 51 | +_KEEPALIVE = [] | ||
| 52 | + | ||
| 53 | + | ||
| 54 | +def _configure_udma_env(use_udma): | ||
| 55 | + """Set/unset the UDMA toggles consumed by the grad reduce launch.""" | ||
| 56 | + if use_udma: | ||
| 57 | + os.environ[_USE_UDMA_ENV] = "1" | ||
| 58 | + os.environ[_GRAD_REDUCE_UDMA_ENV] = "1" | ||
| 59 | + else: | ||
| 60 | + os.environ.pop(_USE_UDMA_ENV, None) | ||
| 61 | + os.environ.pop(_GRAD_REDUCE_UDMA_ENV, None) | ||
| 62 | + | ||
| 63 | + | ||
| 64 | +def run_case(rank, local_rank, R, case): | ||
| 65 | + dev = f"npu:{local_device_index(local_rank)}" | ||
| 66 | + epn = case["epn"] | ||
| 67 | + E = R * epn | ||
| 68 | + H = case["H"] | ||
| 69 | + Hp = case["Hp"] | ||
| 70 | + # The slot bank is an independent input (``base_B``), exactly as in the dense | ||
| 71 | + # variant: it needs one B-row symmetric chunk, not one row per local expert. | ||
| 72 | + B = case["base_B"] | ||
| 73 | + blocks = case["num_sms"] | ||
| 74 | + seed = case.get("seed", 0) | ||
| 75 | + | ||
| 76 | + plan = PLAN_BUILDERS[case.get("plan", "ring")](R, B, epn, dev, seed) | ||
| 77 | + grads_fn, slot_fn = _make_data_fns( | ||
| 78 | + case.get("data", "affine"), rank, epn, B, H, Hp, dev, seed) | ||
| 79 | + | ||
| 80 | + target_table = None | ||
| 81 | + reduce_buffers_src = None | ||
| 82 | + try: | ||
| 83 | + # Canonical targets are ordinary FP32 memory: one contiguous | ||
| 84 | + # ``[epn, H, H']`` table sliced per expert, so the pointer table is | ||
| 85 | + # simply its rows and the reference verification can compare the table. | ||
| 86 | + target_table = torch.empty( | ||
| 87 | + (epn, H, Hp), dtype=torch.float32, device=dev) | ||
| 88 | + target_ptrs = torch.tensor( | ||
| 89 | + [target_table.data_ptr() + i * H * Hp * 4 for i in range(epn)], | ||
| 90 | + dtype=torch.int64, device=dev) | ||
| 91 | + # Only the B-slot source bank is symmetric. | ||
| 92 | + reduce_buffers_src, _, _ = create_vmm_physical( | ||
| 93 | + (B, H, Hp), torch.float32, local_device_index(local_rank)) | ||
| 94 | + | ||
| 95 | + _configure_udma_env(False) | ||
| 96 | + if not ShmemRuntime.is_initialized(): | ||
| 97 | + init_shmem(group=None) | ||
| 98 | + reduce_buffers = sym_tensor(reduce_buffers_src) | ||
| 99 | + | ||
| 100 | + reduce_buffers.zero_() | ||
| 101 | + target_table.copy_(grads_fn()) | ||
| 102 | + reduce_buffers.copy_(slot_fn(rank)) | ||
| 103 | + torch.npu.synchronize() | ||
| 104 | + dist.barrier() | ||
| 105 | + | ||
| 106 | + launch_grad_reduce_targets( | ||
| 107 | + target_ptrs, reduce_buffers, plan, rank=rank, num_sms=blocks, | ||
| 108 | + ) | ||
| 109 | + torch.npu.synchronize() | ||
| 110 | + dist.barrier() | ||
| 111 | + | ||
| 112 | + _verify(rank, R, epn, B, plan, grads_fn, slot_fn, | ||
| 113 | + target_table, reduce_buffers, | ||
| 114 | + f"{case['name']} grad_reduce_targets failed") | ||
| 115 | + | ||
| 116 | + if rank == 0: | ||
| 117 | + print(f"[PASS] {case['name']} epn={epn} B={B} H={H} Hp={Hp} " | ||
| 118 | + f"blocks={blocks} udma=False", flush=True) | ||
| 119 | + finally: | ||
| 120 | + # Re-init per case: finalize (tear down symmetric mappings) first, then | ||
| 121 | + # reverse the VMM allocation, then clear the descriptor registry. | ||
| 122 | + dist.barrier() | ||
| 123 | + if ShmemRuntime.is_initialized(): | ||
| 124 | + ShmemRuntime.finalize() | ||
| 125 | + alloc = getattr(reduce_buffers_src, "_vmm_allocation", None) | ||
| 126 | + if alloc is not None: | ||
| 127 | + alloc.destroy() | ||
| 128 | + reset_symmetric_descriptors() | ||
| 129 | + | ||
| 130 | + | ||
| 131 | +@pytest.mark.parametrize("case", CASES, ids=[case["name"] for case in CASES]) | ||
| 132 | +def test_grad_reduce_targets(dist_env, case): | ||
| 133 | + rank, local_rank, R = dist_env | ||
| 134 | + run_case(rank, local_rank, R, case) | ||
| 135 | + | ||
| 136 | + | ||
| 137 | +@pytest.mark.parametrize("shape", [(129, 101), (6144, 7168), (7168, 3072)], | ||
| 138 | + ids=["tail_tile", "fc1", "fc2"]) | ||
| 139 | +def test_grad_reduce_targets_custom_class(dist_env, shape, monkeypatch): | ||
| 140 | + rank, local_rank, ranks = dist_env | ||
| 141 | + if ShmemRuntime.is_initialized(): | ||
| 142 | + raise RuntimeError("run this test without an active SHMEM heap") | ||
| 143 | + device = f"npu:{local_device_index(local_rank)}" | ||
| 144 | + local, b, blocks = 6, 6, 32 | ||
| 145 | + h, hp = shape | ||
| 146 | + monkeypatch.setenv("ASCEND_MOONEP_GRAD_REDUCE_USE_UDMA", "0") | ||
| 147 | + source, _, _ = create_vmm_physical((b, h, hp), torch.float32, | ||
| 148 | + local_device_index(local_rank)) | ||
| 149 | + _KEEPALIVE.append(source) | ||
| 150 | + init_shmem(enable_udma=False) | ||
| 151 | + slots = sym_tensor(source) | ||
| 152 | + slots.zero_() | ||
| 153 | + targets = tuple(torch.full((h, hp), float(100 + expert), dtype=torch.float32, | ||
| 154 | + device=device) for expert in range(local))[::-1] | ||
| 155 | + table = torch.tensor([target.data_ptr() for target in targets], dtype=torch.int64, device=device) | ||
| 156 | + addresses = tuple(target.data_ptr() for target in targets) | ||
| 157 | + wanted = [float(100 + local - 1 - expert) for expert in range(local)] | ||
| 158 | + op = GradReduceOp(ws_bytes=0, num_sms=blocks) | ||
| 159 | + ctx = dict(E=ranks * local, R=ranks, B=b) | ||
| 160 | + # Supplied scratch must not override an explicit MTE flag. | ||
| 161 | + unused_scratch = torch.empty(1, dtype=torch.float32, device=device) | ||
| 162 | + _KEEPALIVE.extend((targets, table, op, unused_scratch)) | ||
| 163 | + plan_cases = ("random", "empty", "asymmetric", "hotspot", "ring") | ||
| 164 | + for iteration, name in enumerate(plan_cases): | ||
| 165 | + final_round = iteration == len(plan_cases) - 1 | ||
| 166 | + plan = (torch.zeros((ranks, b), dtype=torch.int32, device=device) | ||
| 167 | + if name == "hotspot" else | ||
| 168 | + PLAN_BUILDERS[name](ranks, b, local, device, 7 + iteration)) | ||
| 169 | + _KEEPALIVE.append(plan) | ||
| 170 | + rows = plan.cpu().tolist() | ||
| 171 | + # Exercise a late producer; the caller's readiness fence must cover it. | ||
| 172 | + if rank == ranks - 1 and iteration == 2: | ||
| 173 | + time.sleep(.05) | ||
| 174 | + was_clean = [] | ||
| 175 | + for slot, expert in enumerate(rows[rank]): | ||
| 176 | + if expert >= 0: | ||
| 177 | + was_clean.append(torch.all(slots[slot] == 0)) | ||
| 178 | + slots[slot].add_(1 + rank * b + slot + iteration * 100) | ||
| 179 | + elif final_round: | ||
| 180 | + slots[slot].fill_(-1234) | ||
| 181 | + for peer, row in enumerate(rows): | ||
| 182 | + for slot, expert in enumerate(row): | ||
| 183 | + index = expert - rank * local | ||
| 184 | + if expert >= 0 and 0 <= index < local: | ||
| 185 | + wanted[index] += 1 + peer * b + slot + iteration * 100 | ||
| 186 | + # Native completion covers reduction/clear, not cross-rank publication. | ||
| 187 | + torch.npu.synchronize() | ||
| 188 | + dist.barrier() | ||
| 189 | + if iteration == 0: | ||
| 190 | + # The original custom-class signature defaults to MTE. | ||
| 191 | + torch.classes.AscendMoonEP.GradReduce().compute_targets( | ||
| 192 | + table, slots, plan, local, h, hp, ranks, b, rank, blocks) | ||
| 193 | + elif iteration == 1: | ||
| 194 | + torch.classes.AscendMoonEP.GradReduce().compute_targets( | ||
| 195 | + table, slots, plan, local, h, hp, ranks, b, rank, blocks, | ||
| 196 | + False, unused_scratch) | ||
| 197 | + else: | ||
| 198 | + op.compute_targets(ctx, table, slots, plan, rank, blocks) | ||
| 199 | + torch.npu.synchronize() | ||
| 200 | + checks = was_clean + [torch.all(target == value) for target, value in zip(targets, wanted)] | ||
| 201 | + checks += [torch.all(slots[slot] == (0 if expert >= 0 or not final_round else -1234)) | ||
| 202 | + for slot, expert in enumerate(rows[rank])] | ||
| 203 | + ok = torch.stack(checks).all().to(torch.int32) | ||
| 204 | + dist.all_reduce(ok, op=dist.ReduceOp.MIN) | ||
| 205 | + assert bool(ok), f"MTE canonical {shape} round={iteration} failed" | ||
| 206 | + assert tuple(target.data_ptr() for target in targets) == addresses | ||
| 207 | + if rank == 0: | ||
| 208 | + print(f"[PASS] MTE canonical targets shape={shape} blocks={blocks} " | ||
| 209 | + f"changed_plans={len(plan_cases)} valid_slot_clear=True") | ||
| 210 | + # Release only after successful completion on every rank. | ||
| 211 | + torch.npu.synchronize() | ||
| 212 | + dist.barrier() | ||
| 213 | + ShmemRuntime.finalize() | ||
| 214 | + op.destroy() | ||
| 215 | + source._vmm_allocation.destroy() | ||
| 216 | + reset_symmetric_descriptors() | ||
| 217 | + _KEEPALIVE.clear() | ||
| @@ -37,12 +37,16 @@ References: | |||
| 37 | 37 | ||
| 38 | Run with: | 38 | Run with: |
| 39 | torchrun --nproc_per_node=8 -m pytest -s test_npu/urma/test_e2e_urma.py | 39 | torchrun --nproc_per_node=8 -m pytest -s test_npu/urma/test_e2e_urma.py |
| 40 | + | ||
| 41 | +Shape IDs are default (S4096/H256/K16/E64/Hp512) and dsv4 | ||
| 42 | +(S4096/H7168/K6/E48/Hp3072, EP8). Select one with -k default or -k dsv4. | ||
| 40 | """ | 43 | """ |
| 41 | 44 | ||
| 42 | import os | 45 | import os |
| 43 | import sys | 46 | import sys |
| 44 | 47 | ||
| 45 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | 48 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
| 49 | +import pytest | ||
| 46 | import torch | 50 | import torch |
| 47 | import torch.distributed as dist | 51 | import torch.distributed as dist |
| 48 | 52 | ||
| @@ -310,20 +314,20 @@ def assert_raises_assertion(expected_substr, fn): | |||
| 310 | raise AssertionError(f"expected AssertionError containing {expected_substr!r}") | 314 | raise AssertionError(f"expected AssertionError containing {expected_substr!r}") |
| 311 | 315 | ||
| 312 | 316 | ||
| 313 | -def test_e2e_urma(): | 317 | +@pytest.mark.parametrize("S,H,K,E,Hp,ep_size", [ |
| 318 | + pytest.param(4096, 256, 16, 64, 512, None, id="default"), | ||
| 319 | + pytest.param(4096, 7168, 6, 48, 3072, 8, id="dsv4"), | ||
| 320 | +]) | ||
| 321 | +def test_e2e_urma(S, H, K, E, Hp, ep_size): | ||
| 314 | """Full URMA operator-chain e2e: dispatch / prefetch / combine / reduce_grad.""" | 322 | """Full URMA operator-chain e2e: dispatch / prefetch / combine / reduce_grad.""" |
| 315 | enable_urma_env() | 323 | enable_urma_env() |
| 316 | rank, R = setup() | 324 | rank, R = setup() |
| 317 | - # S=128/H=64 mirrors test_npu/buffer_test/test_buffer_plan.py's default config, which is | 325 | + if ep_size is not None and R != ep_size: |
| 318 | - # stable on this hardware; larger S/H intermittently trigger a MaskedSelectV3 | 326 | + pytest.skip(f"this shape requires {ep_size} EP ranks, got {R}") |
| 319 | - # OOB (507035) in the planning kernel (see docs/planning_operator_test_notes.md). | ||
| 320 | - S, H, K, E = 4096, 256, 16, 64 | ||
| 321 | # The Ascend planning kernel requires num_prefetch_slots == E / R. | 327 | # The Ascend planning kernel requires num_prefetch_slots == E / R. |
| 322 | B = E // R | 328 | B = E // R |
| 323 | epn = E // R | 329 | epn = E // R |
| 324 | - # Hp=512 makes epn*row = 8*256*512*2 = 2 MiB, an exact multiple of the VMM granularity, | 330 | + # Both eight-rank shapes have 2 MiB-aligned BF16 local home segments. |
| 325 | - # so the full_weight projection can place the home segment exactly at [rank*epn, (rank+1)*epn). | ||
| 326 | - Hp = 512 | ||
| 327 | num_sms = 32 | 331 | num_sms = 32 |
| 328 | device = local_device_index() | 332 | device = local_device_index() |
| 329 | dev = f"npu:{device}" | 333 | dev = f"npu:{device}" |
| @@ -582,4 +586,4 @@ def setup(): | |||
| 582 | 586 | ||
| 583 | 587 | ||
| 584 | if __name__ == "__main__": | 588 | if __name__ == "__main__": |
| 585 | - test_e2e_urma() | 589 | + test_e2e_urma(4096, 256, 16, 64, 512, None) |
| @@ -0,0 +1,227 @@ | |||
| 1 | +# SPDX-License-Identifier: Apache-2.0 | ||
| 2 | +"""URMA canonical-pointer GradReduce correctness with setup-owned scratch. | ||
| 3 | + | ||
| 4 | +Same structure as this directory's dense ``test_grad_reduce_udma.py`` | ||
| 5 | +(buffer-backed VMM source bank, per-case UDMA-enabled SHMEM init, direct | ||
| 6 | +``npu_patch.launchers`` call, same ``CASES`` / ``PLAN_BUILDERS`` / data | ||
| 7 | +generators / reference verification): the only difference is the input — this | ||
| 8 | +variant hands the op a frozen INT64 ``[epn]`` table of ordinary FP32 ``[H, H']`` | ||
| 9 | +target addresses instead of an ``[epn, H, H']`` home-grad chunk, plus the | ||
| 10 | +setup-owned UDMA scratch the canonical entry requires. Only the ``[B, H, H']`` | ||
| 11 | +source bank is symmetric. | ||
| 12 | + | ||
| 13 | +``test_grad_reduce_targets_udma_custom_class`` keeps the narrower API contract | ||
| 14 | +checks that the case suite does not cover: reverse-ordered, separately allocated | ||
| 15 | +and therefore non-contiguous targets, the ``GradReduceOp`` ctx path with an | ||
| 16 | +explicit scratch, and a late producer behind the caller's readiness fence. | ||
| 17 | + | ||
| 18 | +Requires Ascend950 and matching UDMA extension/kernel/SHMEM libraries. | ||
| 19 | + | ||
| 20 | +Run in fresh workers, with a whole-job external hard timeout: | ||
| 21 | + torchrun --nproc-per-node=8 -m pytest -s -x \ | ||
| 22 | + test_npu/urma/test_grad_reduce_targets_udma.py | ||
| 23 | +""" | ||
| 24 | +import os | ||
| 25 | +import time | ||
| 26 | + | ||
| 27 | +import pytest | ||
| 28 | +import torch | ||
| 29 | +import torch.distributed as dist | ||
| 30 | +import torch_npu | ||
| 31 | + | ||
| 32 | +from kernel_test_utils import init_shmem | ||
| 33 | +from npu_patch import ShmemRuntime | ||
| 34 | +from npu_patch._device import local_device_index | ||
| 35 | +from npu_patch.buffer_c import create_vmm_physical, reset_symmetric_descriptors, sym_tensor | ||
| 36 | +from npu_patch.launchers import launch_grad_reduce_targets | ||
| 37 | +from npu_patch.ops import GradReduceOp | ||
| 38 | +# Reuse the dense variant verbatim: same cases, same plans, same data | ||
| 39 | +# generators and the same reference verification. | ||
| 40 | +from test_grad_reduce_udma import ( | ||
| 41 | + CASES, | ||
| 42 | + PLAN_BUILDERS, | ||
| 43 | + _make_data_fns, | ||
| 44 | + _verify_reduce, | ||
| 45 | + dist_env, | ||
| 46 | +) | ||
| 47 | + | ||
| 48 | +_USE_UDMA_ENV = "ASCEND_MOONEP_USE_UDMA" | ||
| 49 | +_GRAD_REDUCE_UDMA_ENV = "ASCEND_MOONEP_GRAD_REDUCE_USE_UDMA" | ||
| 50 | +# Documented canonical UDMA scratch contract: 512*1024*max(2*min(blocks,64),R*B) | ||
| 51 | +# FP32 elements per rank. It is already scratch, so the plan-size stress case | ||
| 52 | +# (R*B = 16384..65536) would need 32..128 GiB and cannot be honoured on a 64 GiB | ||
| 53 | +# die next to the case's own tensors; that case stays MTE-covered. | ||
| 54 | +_UDMA_SCRATCH_LIMIT_BYTES = 16 * 1024 ** 3 | ||
| 55 | + | ||
| 56 | +_KEEPALIVE = [] | ||
| 57 | + | ||
| 58 | + | ||
| 59 | +def _configure_udma_env(use_udma): | ||
| 60 | + """Set/unset the UDMA toggles consumed by the grad reduce launch.""" | ||
| 61 | + if use_udma: | ||
| 62 | + os.environ[_USE_UDMA_ENV] = "1" | ||
| 63 | + os.environ[_GRAD_REDUCE_UDMA_ENV] = "1" | ||
| 64 | + else: | ||
| 65 | + os.environ.pop(_USE_UDMA_ENV, None) | ||
| 66 | + os.environ.pop(_GRAD_REDUCE_UDMA_ENV, None) | ||
| 67 | + | ||
| 68 | + | ||
| 69 | +def _udma_scratch_elements(blocks, R, B): | ||
| 70 | + """Setup-owned local FP32 scratch the canonical UDMA entry validates.""" | ||
| 71 | + return 512 * 1024 * max(2 * min(blocks, 64), R * B) | ||
| 72 | + | ||
| 73 | + | ||
| 74 | +def run_case(rank, local_rank, R, case): | ||
| 75 | + dev = f"npu:{local_device_index(local_rank)}" | ||
| 76 | + epn = case["epn"] | ||
| 77 | + E = R * epn | ||
| 78 | + H = case["H"] | ||
| 79 | + Hp = case["Hp"] | ||
| 80 | + # The slot bank is an independent input (``base_B``), exactly as in the dense | ||
| 81 | + # variant: it needs one B-row symmetric chunk, not one row per local expert. | ||
| 82 | + B = case["base_B"] | ||
| 83 | + blocks = case["num_sms"] | ||
| 84 | + seed = case.get("seed", 0) | ||
| 85 | + | ||
| 86 | + scratch_elements = _udma_scratch_elements(blocks, R, B) | ||
| 87 | + if scratch_elements * 4 > _UDMA_SCRATCH_LIMIT_BYTES: | ||
| 88 | + pytest.skip( | ||
| 89 | + f"{case['name']}: canonical UDMA scratch would need " | ||
| 90 | + f"{scratch_elements * 4 >> 30} GiB per rank " | ||
| 91 | + f"(contract 512*1024*max(2*min(blocks,64),R*B))") | ||
| 92 | + | ||
| 93 | + plan = PLAN_BUILDERS[case.get("plan", "ring")](R, B, epn, dev, seed) | ||
| 94 | + grads_fn, slot_fn = _make_data_fns( | ||
| 95 | + case.get("data", "affine"), rank, epn, B, H, Hp, dev, seed) | ||
| 96 | + | ||
| 97 | + target_table = None | ||
| 98 | + reduce_buffers_src = None | ||
| 99 | + try: | ||
| 100 | + # Canonical targets are ordinary FP32 memory: one contiguous | ||
| 101 | + # ``[epn, H, H']`` table sliced per expert, so the pointer table is | ||
| 102 | + # simply its rows and the reference verification can compare the table. | ||
| 103 | + target_table = torch.empty( | ||
| 104 | + (epn, H, Hp), dtype=torch.float32, device=dev) | ||
| 105 | + target_ptrs = torch.tensor( | ||
| 106 | + [target_table.data_ptr() + i * H * Hp * 4 for i in range(epn)], | ||
| 107 | + dtype=torch.int64, device=dev) | ||
| 108 | + # Only the B-slot source bank is symmetric; the scratch is setup-owned. | ||
| 109 | + reduce_buffers_src, _, _ = create_vmm_physical( | ||
| 110 | + (B, H, Hp), torch.float32, local_device_index(local_rank)) | ||
| 111 | + udma_workspace = torch.empty( | ||
| 112 | + scratch_elements, dtype=torch.float32, device=dev) | ||
| 113 | + | ||
| 114 | + _configure_udma_env(True) | ||
| 115 | + if not ShmemRuntime.is_initialized(): | ||
| 116 | + init_shmem(group=None, enable_udma=True, qp_count=2) | ||
| 117 | + reduce_buffers = sym_tensor(reduce_buffers_src) | ||
| 118 | + | ||
| 119 | + reduce_buffers.zero_() | ||
| 120 | + target_table.copy_(grads_fn()) | ||
| 121 | + reduce_buffers.copy_(slot_fn(rank)) | ||
| 122 | + torch.npu.synchronize() | ||
| 123 | + dist.barrier() | ||
| 124 | + | ||
| 125 | + launch_grad_reduce_targets( | ||
| 126 | + target_ptrs, reduce_buffers, plan, rank=rank, num_sms=blocks, | ||
| 127 | + udma_workspace=udma_workspace, | ||
| 128 | + ) | ||
| 129 | + torch.npu.synchronize() | ||
| 130 | + dist.barrier() | ||
| 131 | + | ||
| 132 | + _verify_reduce(rank, R, epn, B, plan.cpu(), grads_fn, slot_fn, | ||
| 133 | + target_table, reduce_buffers, | ||
| 134 | + f"{case['name']} grad_reduce_targets failed") | ||
| 135 | + | ||
| 136 | + if rank == 0: | ||
| 137 | + print(f"[PASS] {case['name']} epn={epn} B={B} H={H} Hp={Hp} " | ||
| 138 | + f"blocks={blocks} udma=True", flush=True) | ||
| 139 | + finally: | ||
| 140 | + # Re-init per case: finalize (tear down symmetric mappings) first, then | ||
| 141 | + # reverse the VMM allocation, then clear the descriptor registry. | ||
| 142 | + dist.barrier() | ||
| 143 | + if ShmemRuntime.is_initialized(): | ||
| 144 | + ShmemRuntime.finalize() | ||
| 145 | + alloc = getattr(reduce_buffers_src, "_vmm_allocation", None) | ||
| 146 | + if alloc is not None: | ||
| 147 | + alloc.destroy() | ||
| 148 | + reset_symmetric_descriptors() | ||
| 149 | + | ||
| 150 | + | ||
| 151 | +@pytest.mark.parametrize("case", CASES, ids=[case["name"] for case in CASES]) | ||
| 152 | +def test_grad_reduce_targets_udma(dist_env, case): | ||
| 153 | + rank, local_rank, R = dist_env | ||
| 154 | + run_case(rank, local_rank, R, case) | ||
| 155 | + | ||
| 156 | + | ||
| 157 | +@pytest.mark.parametrize("shape", [(129, 101), (6144, 7168), (7168, 3072)], | ||
| 158 | + ids=["tail_tile", "fc1", "fc2"]) | ||
| 159 | +def test_grad_reduce_targets_udma_custom_class(dist_env, shape, monkeypatch): | ||
| 160 | + rank, local_rank, ranks = dist_env | ||
| 161 | + if ShmemRuntime.is_initialized(): | ||
| 162 | + raise RuntimeError("run this test without an active SHMEM heap") | ||
| 163 | + device = f"npu:{local_device_index(local_rank)}" | ||
| 164 | + local, b, blocks = 6, 6, 32 | ||
| 165 | + h, hp = shape | ||
| 166 | + monkeypatch.setenv("ASCEND_MOONEP_GRAD_REDUCE_USE_UDMA", "1") | ||
| 167 | + source, _, _ = create_vmm_physical((b, h, hp), torch.float32, | ||
| 168 | + local_device_index(local_rank)) | ||
| 169 | + _KEEPALIVE.append(source) | ||
| 170 | + init_shmem(enable_udma=True, qp_count=2) | ||
| 171 | + slots = sym_tensor(source) | ||
| 172 | + slots.zero_() | ||
| 173 | + targets = tuple(torch.full((h, hp), float(100 + expert), dtype=torch.float32, | ||
| 174 | + device=device) for expert in range(local))[::-1] | ||
| 175 | + table = torch.tensor([target.data_ptr() for target in targets], dtype=torch.int64, device=device) | ||
| 176 | + addresses = tuple(target.data_ptr() for target in targets) | ||
| 177 | + wanted = [float(100 + local - 1 - expert) for expert in range(local)] | ||
| 178 | + op = GradReduceOp(ws_bytes=0, num_sms=blocks) | ||
| 179 | + # Match launch_grad_reduce_targets / native GradReduceTargets' scratch contract. | ||
| 180 | + elements = 512 * 1024 * max(2 * min(blocks, 64), ranks * b) | ||
| 181 | + ctx = dict(E=ranks * local, R=ranks, B=b, | ||
| 182 | + _grad_reduce_target_workspace=torch.empty(elements, dtype=torch.float32, device=device)) | ||
| 183 | + _KEEPALIVE.extend((targets, table, op, ctx)) | ||
| 184 | + plan_cases = ("random", "empty", "asymmetric", "hotspot", "ring") | ||
| 185 | + for iteration, name in enumerate(plan_cases): | ||
| 186 | + final_round = iteration == len(plan_cases) - 1 | ||
| 187 | + plan = (torch.zeros((ranks, b), dtype=torch.int32, device=device) | ||
| 188 | + if name == "hotspot" else | ||
| 189 | + PLAN_BUILDERS[name](ranks, b, local, device, 7 + iteration)) | ||
| 190 | + _KEEPALIVE.append(plan) | ||
| 191 | + rows = plan.cpu().tolist() | ||
| 192 | + if rank == ranks - 1 and iteration == 2: | ||
| 193 | + time.sleep(.05) | ||
| 194 | + was_clean = [] | ||
| 195 | + for slot, expert in enumerate(rows[rank]): | ||
| 196 | + if expert >= 0: | ||
| 197 | + was_clean.append(torch.all(slots[slot] == 0)) | ||
| 198 | + slots[slot].add_(1 + rank * b + slot + iteration * 100) | ||
| 199 | + elif final_round: | ||
| 200 | + slots[slot].fill_(-1234) | ||
| 201 | + for peer, row in enumerate(rows): | ||
| 202 | + for slot, expert in enumerate(row): | ||
| 203 | + index = expert - rank * local | ||
| 204 | + if expert >= 0 and 0 <= index < local: | ||
| 205 | + wanted[index] += 1 + peer * b + slot + iteration * 100 | ||
| 206 | + # Wait for local writes, then for all peer producers, before native reads. | ||
| 207 | + torch.npu.synchronize() | ||
| 208 | + dist.barrier() | ||
| 209 | + op.compute_targets(ctx, table, slots, plan, rank, blocks) | ||
| 210 | + torch.npu.synchronize() | ||
| 211 | + checks = was_clean + [torch.all(target == value) for target, value in zip(targets, wanted)] | ||
| 212 | + checks += [torch.all(slots[slot] == (0 if expert >= 0 or not final_round else -1234)) | ||
| 213 | + for slot, expert in enumerate(rows[rank])] | ||
| 214 | + ok = torch.stack(checks).all().to(torch.int32) | ||
| 215 | + dist.all_reduce(ok, op=dist.ReduceOp.MIN) | ||
| 216 | + assert bool(ok), f"URMA canonical {shape} round={iteration} failed" | ||
| 217 | + assert tuple(target.data_ptr() for target in targets) == addresses | ||
| 218 | + if rank == 0: | ||
| 219 | + print(f"[PASS] URMA canonical targets shape={shape} blocks={blocks} " | ||
| 220 | + f"changed_plans={len(plan_cases)} valid_slot_clear=True") | ||
| 221 | + torch.npu.synchronize() | ||
| 222 | + dist.barrier() | ||
| 223 | + ShmemRuntime.finalize() | ||
| 224 | + op.destroy() | ||
| 225 | + source._vmm_allocation.destroy() | ||
| 226 | + reset_symmetric_descriptors() | ||
| 227 | + _KEEPALIVE.clear() | ||


合并成一个文件