Draft
[WIP]experiment/contiguous-grad-lplusb #5
&NewgateAdd on 25 days ago
[WIP]experiment/contiguous-grad-lplusb #5
Draft
Merged fromexperiment/contiguous-grad-lplusbintodev_server_dedup/fork
Total: 50 files changed+4273-164
| @@ -0,0 +1,57 @@ | |||
| 1 | +# 连续 main_grad / L+B 实验 | ||
| 2 | + | ||
| 3 | +更新时间:2026-11-11。 | ||
| 4 | +实验分支:`experiment/contiguous-grad-lplusb`。 | ||
| 5 | +基线:MoonEP `deb8c7806904c72a95732c336205aef794c2816e`。 | ||
| 6 | +原分支 `dev_server_dedup_async_migrate` 和其未提交 Planning 参数修改保留。 | ||
| 7 | + | ||
| 8 | +## 框架前提 | ||
| 9 | + | ||
| 10 | +框架必须先完成 DDP/优化器存储接线,让 canonical `main_grad` 的本地 L 行 | ||
| 11 | +按专家序号升序,成为同一 Tensor storage 的连续 `[L,M,N]` 视图。该 storage | ||
| 12 | +必须覆盖完整 L 区域;归约写入直接由 DDP/优化器消费,不能使用另外分配的副本。 | ||
| 13 | +只提供地址相邻的独立 Tensor 或反向专家顺序不满足此接口。 | ||
| 14 | + | ||
| 15 | +框架可提供完整连续 `[L+B,M,N]` VMM,传入 | ||
| 16 | +`refs=tuple(full_grad[:L])` 和 `slot_source=full_grad[L:]`。 | ||
| 17 | +B 源视图需携带框架的 `_vmm_allocation` 所有者,底层 allocation 在 SHMEM init | ||
| 18 | +前注册,绑定在 init 后创建。`sym_tensor()` 处理 B 视图的 allocation 内偏移。 | ||
| 19 | +准备和提交遵守同一调用流约定;调用者继续负责最后一次使用到 bank 复用的顺序。 | ||
| 20 | + | ||
| 21 | +MoonEP dense 算子分别接收 L home 和 B symmetric view,不要求这两个参数的 VA | ||
| 22 | +彼此紧邻;统一 L+B 是框架可采用的分配方式。MoonEP 不执行 VMM 重映射,也不改 | ||
| 23 | +DDP bucket、参数索引或优化器。当前 MindSpeed 的独立梯度目标不能直接使用本分支。 | ||
| 24 | + | ||
| 25 | +## 调用与删除范围 | ||
| 26 | + | ||
| 27 | +`prepare_lplusb(FP32 refs, slot_source)` -> 零拷贝 `binding.home[L,M,N]` -> | ||
| 28 | +`reduce_grad(..., lplusb=binding)` -> `GradReduceOp.compute()` -> | ||
| 29 | +`launch_grad_reduce()` -> 原 `GradReduce.compute()` / dense MTE、UDMA kernel。 | ||
| 30 | +同步私有 `_reduce_expert_grads()` 也复用同一入口。 | ||
| 31 | + | ||
| 32 | +删除梯度 INT64 table、`compute_targets()`、`launch_grad_reduce_targets()`、 | ||
| 33 | +对应 C++/C 导出和 kernel pointer_targets 分支、旧私有 owner-reduce kernel、 | ||
| 34 | +梯度 pointer ABI 及独立目标测试。设备测试改为统一 L+B VMM 和真实 home 行。 | ||
| 35 | +BF16 权重仍允许独立 Parameter,保留其 owner PUSH 地址表与所有传输实现。 | ||
| 36 | + | ||
| 37 | +保留 refs 地址/布局签名、异步 Q0 对调用流的 wait_stream、完成事件和 backing | ||
| 38 | +生命周期。原 dense compute 增加可选 workspace,接收 setup 预分配 scratch; | ||
| 39 | +历史 standalone 调用可省略而由 native 分配。MTE/UDMA 都使用现有公共 barrier | ||
| 40 | +选择器,覆盖发布 B、读取完成到清槽、发布 home/清槽三个边界;环境变量 | ||
| 41 | +`MOONEP_GRAD_REDUCE_NATIVE_BARRIER_MODE=aiv` 仍选固定 1 AIV,默认 mixed。 | ||
| 42 | +MTE 仍按 plan 顺序加和,UDMA 仍为原 atomic-add 顺序,不新增确定性承诺。 | ||
| 43 | + | ||
| 44 | +## ABI 与验证 | ||
| 45 | + | ||
| 46 | +provider ABI 改为 `lplusb-contiguous-grad-v1`,L+B native ABI 为 3, | ||
| 47 | +新增 `GRAD_REDUCE_DENSE_ABI=1`。必须同时重建 `_C` 和 kernel 库;旧 pointer | ||
| 48 | +版本二进制不能与本分支混用。SHMEM ABI 未改,MindSpeed 仓未修改。 | ||
| 49 | + | ||
| 50 | +本地 CPU:23 项 Tensor 存储/API/流顺序测试,29 项编译后 kernel host launcher | ||
| 51 | +测试,16 项编译后 native operator 元数据/workspace/barrier 测试通过,共 68 项。 | ||
| 52 | +Python 源码语法和 Git diff 空白检查通过。编译测试使用本机现有 Zig C++ 编译器, | ||
| 53 | +仅替换 tensor/runtime 元数据或 kernel launch,未编译 AscendC 设备代码。 | ||
| 54 | + | ||
| 55 | +复查:`python -B -m pytest -q -p no:cacheprovider test_host`。 | ||
| 56 | +需 PyTorch、pytest 和可用 `g++`/`c++`;无 C++ 编译器时编译项会 skip,不算完整通过。 | ||
| 57 | +本轮未访问远端、未构建 native NPU 库、未执行设备精度/profile;设备结果未验证。 | ||
| @@ -10,6 +10,13 @@ CMake)暴露 C ABI launcher,再由 PyTorch C++ extension `npu_patch._C` 调 | |||
| 10 | 当前构建目标仅面向 **Ascend950 / A5**:UDRMA/UDMA(URMA)通信依赖 A5 的 | 10 | 当前构建目标仅面向 **Ascend950 / A5**:UDRMA/UDMA(URMA)通信依赖 A5 的 |
| 11 | 对称内存 RMA 能力(SIMT),故不支持 A2/A3 等其它芯片。 | 11 | 对称内存 RMA 能力(SIMT),故不支持 A2/A3 等其它芯片。 |
| 12 | 12 | ||
| 13 | +## 连续梯度实验分支(2026-11-11) | ||
| 14 | + | ||
| 15 | +本分支假设框架已将真实 `main_grad` 绑定到连续、按专家顺序排列的 VMM | ||
| 16 | +存储。FP32 L+B 绑定复用 dense `GradReduce.compute()`,不再建立梯度地址表。 | ||
| 17 | +当前 MindSpeed 尚未在本任务中做该改造,不能直接替换现有集成。 | ||
| 18 | +接口、ABI、重编要求和本地验证见 [CONTIGUOUS_GRAD.md](CONTIGUOUS_GRAD.md)。 | ||
| 19 | + | ||
| 13 | ## 目录结构 | 20 | ## 目录结构 |
| 14 | 21 | ||
| 15 | ```text | 22 | ```text |
| @@ -260,6 +267,11 @@ ShmemRuntime.finalize() | |||
| 260 | buffer.destroy() | 267 | buffer.destroy() |
| 261 | ``` | 268 | ``` |
| 262 | 269 | ||
| 270 | +`planning_num_sms` 可独立设置主 Planning(含融合的 Combine plan 生成)的 AIV 核数, | ||
| 271 | +范围为 8~56,未指定时使用 `num_sms`;Planning 工作区按同一核数预分配。例如 | ||
| 272 | +`Buffer(..., num_sms=32, planning_num_sms=8, grad_reduce_num_sms=16)`。 | ||
| 273 | +独立 `prepare_combine_plan()` 的准备 kernel 仍沿用 64 核。 | ||
| 274 | + | ||
| 263 | ### ubmem(MTE)与 urma(URMA/UDMA)路径:初始化与调用 | 275 | ### ubmem(MTE)与 urma(URMA/UDMA)路径:初始化与调用 |
| 264 | 276 | ||
| 265 | planning / dispatch / combine / prefetch / reduce_grad 各有两条 kernel 路径, | 277 | planning / dispatch / combine / prefetch / reduce_grad 各有两条 kernel 路径, |
| @@ -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 .native_async import CommBuffers, LPlusBBinding | ||
| 135 | 136 | ||
| 136 | return { | 137 | return { |
| 137 | "Buffer": Buffer, | 138 | "Buffer": Buffer, |
| 139 | + "CommBuffers": CommBuffers, | ||
| 140 | + "LPlusBBinding": LPlusBBinding, | ||
| 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", "LPlusBBinding", "MoonEPCommPlan", "ShmemRuntime", "runtime_library_info" |
| 146 | }) | 149 | }) |
| 147 | _BUF_API_CACHE = None | 150 | _BUF_API_CACHE = None |
| 148 | 151 | ||
| @@ -156,16 +159,22 @@ 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_prefetch, launch_prefetch_push |
| 160 | 163 | ||
| 161 | __all__ = [ | 164 | __all__ = [ |
| 162 | "ShmemInstance", | 165 | "ShmemInstance", |
| 163 | "GradReduce", | 166 | "GradReduce", |
| 164 | "launch_grad_reduce", | 167 | "launch_grad_reduce", |
| 165 | "Buffer", | 168 | "Buffer", |
| 169 | + "CommBuffers", | ||
| 170 | + "LPlusBBinding", | ||
| 166 | "MoonEPCommPlan", | 171 | "MoonEPCommPlan", |
| 167 | "ShmemRuntime", | 172 | "ShmemRuntime", |
| 168 | "runtime_library_info", | 173 | "runtime_library_info", |
| 169 | "PrefetchWeight", | 174 | "PrefetchWeight", |
| 170 | "launch_prefetch", | 175 | "launch_prefetch", |
| 176 | + "launch_prefetch_push", | ||
| 171 | ] | 177 | ] |
| 178 | + | ||
| 179 | +from .prefetch_pointer import launch_prefetch_push_ptrs, drain_prefetch_push | ||
| 180 | +__all__ += ["launch_prefetch_push_ptrs", "drain_prefetch_push"] | ||
| @@ -0,0 +1,54 @@ | |||
| 1 | +{ | ||
| 2 | + "schema": 2, | ||
| 3 | + "provider_abi": "lplusb-contiguous-grad-v1", | ||
| 4 | + "devices": [ | ||
| 5 | + "Ascend 950DT", | ||
| 6 | + "Ascend 950PR" | ||
| 7 | + ], | ||
| 8 | + "activation_dtypes": [ | ||
| 9 | + "bfloat16" | ||
| 10 | + ], | ||
| 11 | + "weight_dtypes": [ | ||
| 12 | + "bfloat16" | ||
| 13 | + ], | ||
| 14 | + "gradient_target_dtypes": [ | ||
| 15 | + "float32" | ||
| 16 | + ], | ||
| 17 | + "layout": "LOCAL_L_PLUS_B", | ||
| 18 | + "ordinary_source_owner_push": true, | ||
| 19 | + "direct_owner_reduce": true, | ||
| 20 | + "explicit_comm_buffers": true, | ||
| 21 | + "completion_model": { | ||
| 22 | + "synchronous": "current_stream", | ||
| 23 | + "asynchronous": "comm_stream_event" | ||
| 24 | + }, | ||
| 25 | + "vmm_granularity_query": true, | ||
| 26 | + "router_topk_max": null, | ||
| 27 | + "native_abis": { | ||
| 28 | + "LPLUS_B_BUFFER_SYNC_ABI": 3, | ||
| 29 | + "PREFETCH_PUSH_POINTER_ABI": 1, | ||
| 30 | + "GRAD_REDUCE_DENSE_ABI": 1 | ||
| 31 | + }, | ||
| 32 | + "async": { | ||
| 33 | + "schema": 1, | ||
| 34 | + "completion_modes": [ | ||
| 35 | + "collective" | ||
| 36 | + ], | ||
| 37 | + "lane_count": 1, | ||
| 38 | + "strict_zero_copy": true | ||
| 39 | + }, | ||
| 40 | + "prefetch_engines": [ | ||
| 41 | + "mte", | ||
| 42 | + "urma" | ||
| 43 | + ], | ||
| 44 | + "urma_push": { | ||
| 45 | + "schema": 1, | ||
| 46 | + "pointer_source": true, | ||
| 47 | + "native_abi": 1, | ||
| 48 | + "completion_modes": [ | ||
| 49 | + "collective" | ||
| 50 | + ], | ||
| 51 | + "shared_core_sha256": "26e966899f19fe199148b73c00920c126da7a64f2aff3eb1ea20283340cd84b2" | ||
| 52 | + }, | ||
| 53 | + "gradient_target_layout": "contiguous_local_expert_order" | ||
| 54 | +} | ||
| @@ -220,7 +220,7 @@ def _check_combine_inputs( | |||
| 220 | ) | 220 | ) |
| 221 | hidden_key = "hidden_buf_local" if use_udma else "hidden_buf" | 221 | hidden_key = "hidden_buf_local" if use_udma else "hidden_buf" |
| 222 | _check_tensor( | 222 | _check_tensor( |
| 223 | - ctx[hidden_key], | 223 | + ctx[hidden_key][:NvS], |
| 224 | f"ctx.{hidden_key}", | 224 | f"ctx.{hidden_key}", |
| 225 | (NvS, H), | 225 | (NvS, H), |
| 226 | torch.bfloat16, | 226 | torch.bfloat16, |
| @@ -228,7 +228,7 @@ def _check_combine_inputs( | |||
| 228 | ) | 228 | ) |
| 229 | if output_sk is not None: | 229 | if output_sk is not None: |
| 230 | weights_key = "weights_buf_local" if use_udma else "weights_buf" | 230 | weights_key = "weights_buf_local" if use_udma else "weights_buf" |
| 231 | - weights_buf = ctx[weights_key].view(torch.float32) | 231 | + weights_buf = ctx[weights_key].view(torch.float32)[:NvS] |
| 232 | _check_tensor( | 232 | _check_tensor( |
| 233 | weights_buf, | 233 | weights_buf, |
| 234 | f"ctx.{weights_key}(fp32 view)", | 234 | f"ctx.{weights_key}(fp32 view)", |
| @@ -290,7 +290,8 @@ def launch_combine( | |||
| 290 | def launch_combine_prepared(ctx, output_sh, plan, execution_plan, output_sk=None): | 290 | def launch_combine_prepared(ctx, output_sh, plan, execution_plan, output_sk=None): |
| 291 | import torch | 291 | import torch |
| 292 | import torch_npu | 292 | import torch_npu |
| 293 | - from .planning import CombineExecutionPlan, _routes, _key | 293 | + from .planning import (CombineExecutionPlan, _routes, _key, |
| 294 | + _combine_workspace_layout, prepare_combine_plan) | ||
| 294 | 295 | ||
| 295 | if not isinstance(execution_plan, CombineExecutionPlan): | 296 | if not isinstance(execution_plan, CombineExecutionPlan): |
| 296 | raise TypeError('execution_plan must be returned by prepare_combine_plan') | 297 | raise TypeError('execution_plan must be returned by prepare_combine_plan') |
| @@ -300,11 +301,21 @@ def launch_combine_prepared(ctx, output_sh, plan, execution_plan, output_sk=None | |||
| 300 | execution_plan.validate(ctx, plan) | 301 | execution_plan.validate(ctx, plan) |
| 301 | stream = torch_npu.npu.current_stream() | 302 | stream = torch_npu.npu.current_stream() |
| 302 | stream.wait_event(execution_plan.ready) | 303 | stream.wait_event(execution_plan.ready) |
| 303 | - weights = ctx['weights_buf_local'].view(torch.float32) if output_sk is not None else None | 304 | + if ('_capacity_ctx' in ctx and |
| 305 | + ctx['_capacity_ctx'].get('_combine_workspace_layout') != _combine_workspace_layout(ctx)): | ||
| 306 | + # Buffer's ordered communication lane may revisit an older, shorter | ||
| 307 | + # route after planning/combining a different size. Its immutable tables | ||
| 308 | + # remain valid, but that intervening layout can overwrite its ready | ||
| 309 | + # slots with payload. Rebuild through the upstream collective planner | ||
| 310 | + # before payload launch; every rank follows the same logical sizes. | ||
| 311 | + execution_plan = prepare_combine_plan(ctx, plan) | ||
| 312 | + n = int(ctx['NvS']) | ||
| 313 | + hidden = ctx['hidden_buf_local'][:n] | ||
| 314 | + weights = ctx['weights_buf_local'].view(torch.float32)[:n] if output_sk is not None else None | ||
| 304 | torch.classes.AscendMoonEP.CombineUrma().compute_prepared( | 315 | torch.classes.AscendMoonEP.CombineUrma().compute_prepared( |
| 305 | - ctx['hidden_buf_local'], weights, ctx['combine_sync_buffer'], ctx['combine_workspace'], | 316 | + hidden, weights, ctx['combine_sync_buffer'], ctx['combine_workspace'], |
| 306 | *_routes(plan), output_sh, output_sk, execution_plan.storage, *_key(ctx)) | 317 | *_routes(plan), output_sh, output_sk, execution_plan.storage, *_key(ctx)) |
| 307 | - for tensor in (execution_plan.storage, *_routes(plan), ctx['hidden_buf_local'], weights, | 318 | + for tensor in (execution_plan.storage, *_routes(plan), hidden, weights, |
| 308 | ctx['combine_workspace'], ctx['combine_sync_buffer'], output_sh, | 319 | ctx['combine_workspace'], ctx['combine_sync_buffer'], output_sh, |
| 309 | output_sk): | 320 | output_sk): |
| 310 | if tensor is not None: | 321 | if tensor is not None: |
| @@ -118,14 +118,14 @@ def _check_dispatch_inputs( | |||
| 118 | hidden_sh.device, | 118 | hidden_sh.device, |
| 119 | ) | 119 | ) |
| 120 | _check_tensor( | 120 | _check_tensor( |
| 121 | - ctx["hidden_buf"], | 121 | + ctx["hidden_buf"][:NvS], |
| 122 | "ctx.hidden_buf", | 122 | "ctx.hidden_buf", |
| 123 | (NvS, H), | 123 | (NvS, H), |
| 124 | torch.bfloat16, | 124 | torch.bfloat16, |
| 125 | hidden_sh.device, | 125 | hidden_sh.device, |
| 126 | ) | 126 | ) |
| 127 | if route_weights_sk is not None: | 127 | if route_weights_sk is not None: |
| 128 | - weights_buf = ctx["weights_buf"].view(torch.float32) | 128 | + weights_buf = ctx["weights_buf"].view(torch.float32)[:NvS] |
| 129 | _check_tensor( | 129 | _check_tensor( |
| 130 | weights_buf, | 130 | weights_buf, |
| 131 | "ctx.weights_buf(fp32 view)", | 131 | "ctx.weights_buf(fp32 view)", |
| @@ -9,7 +9,7 @@ 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_grad_reduce(remote_expert_grads, reduce_buffers, plan, rank, ...)`` | 15 | - ``launch_grad_reduce(remote_expert_grads, reduce_buffers, plan, rank, ...)`` |
| @@ -142,11 +142,14 @@ def launch_dispatch_op( | |||
| 142 | world_size: int, | 142 | world_size: int, |
| 143 | rank: int, | 143 | rank: int, |
| 144 | server_dedup: bool = False, | 144 | server_dedup: bool = False, |
| 145 | + num_sms: int = 32, | ||
| 145 | ) -> None: | 146 | ) -> None: |
| 147 | + """Launch dispatch; num_sms controls only the MTE AIV launch width.""" | ||
| 146 | global _DISPATCH | 148 | global _DISPATCH |
| 147 | if _DISPATCH is None: | 149 | if _DISPATCH is None: |
| 148 | _DISPATCH = torch.classes.AscendMoonEP.Dispatch() | 150 | _DISPATCH = torch.classes.AscendMoonEP.Dispatch() |
| 149 | - _DISPATCH.compute( | 151 | + use_udma = _env_use_udma('dispatch') |
| 152 | + args = ( | ||
| 150 | hidden_sh, | 153 | hidden_sh, |
| 151 | route_weights, | 154 | route_weights, |
| 152 | dst, | 155 | dst, |
| @@ -161,9 +164,12 @@ def launch_dispatch_op( | |||
| 161 | num_topk, | 164 | num_topk, |
| 162 | world_size, | 165 | world_size, |
| 163 | rank, | 166 | rank, |
| 164 | - _env_use_udma('dispatch'), | 167 | + use_udma, |
| 165 | bool(server_dedup), | 168 | bool(server_dedup), |
| 166 | ) | 169 | ) |
| 170 | + if not use_udma: | ||
| 171 | + args += (num_sms,) | ||
| 172 | + _DISPATCH.compute(*args) | ||
| 167 | 173 | ||
| 168 | 174 | ||
| 169 | def launch_dispatch_profile_op( | 175 | def launch_dispatch_profile_op( |
| @@ -225,6 +231,7 @@ def launch_combine_op( | |||
| 225 | world_size: int, | 231 | world_size: int, |
| 226 | rank: int, | 232 | rank: int, |
| 227 | server_dedup: bool = False, | 233 | server_dedup: bool = False, |
| 234 | + num_sms: int = 32, | ||
| 228 | ) -> None: | 235 | ) -> None: |
| 229 | """Select the native / legacy-rank / server-dedup combine kernel. | 236 | """Select the native / legacy-rank / server-dedup combine kernel. |
| 230 | 237 | ||
| @@ -233,6 +240,7 @@ def launch_combine_op( | |||
| 233 | the execution plan prepared by the planner. | 240 | the execution plan prepared by the planner. |
| 234 | - ``use_udma and not server_dedup``: legacy rank-level dedup kernel, which | 241 | - ``use_udma and not server_dedup``: legacy rank-level dedup kernel, which |
| 235 | only needs the plan's dst/dup tables. | 242 | only needs the plan's dst/dup tables. |
| 243 | + - ``num_sms`` controls only the MTE AIV launch width. | ||
| 236 | """ | 244 | """ |
| 237 | global _COMBINE, _COMBINE_UDMA | 245 | global _COMBINE, _COMBINE_UDMA |
| 238 | use_udma = _env_use_udma("combine") | 246 | use_udma = _env_use_udma("combine") |
| @@ -306,6 +314,7 @@ def launch_combine_op( | |||
| 306 | world_size, | 314 | world_size, |
| 307 | rank, | 315 | rank, |
| 308 | False, | 316 | False, |
| 317 | + num_sms, | ||
| 309 | ) | 318 | ) |
| 310 | 319 | ||
| 311 | if route_weights_sk_out is not None and sk_stride != num_topk: | 320 | if route_weights_sk_out is not None and sk_stride != num_topk: |
| @@ -404,6 +413,57 @@ def launch_prefetch( | |||
| 404 | num_experts, num_sms, 0, _env_use_udma('prefetch'), rank_barriers) | 413 | num_experts, num_sms, 0, _env_use_udma('prefetch'), rank_barriers) |
| 405 | 414 | ||
| 406 | 415 | ||
| 416 | +# The URMA PUSH layout validator is licensed under Apache-2.0. | ||
| 417 | +def _validate_push_layout(home, slots, plan, num_sms, *, bf16, int32): | ||
| 418 | + """Validate tensor metadata without reading device data or synchronizing.""" | ||
| 419 | + if type(num_sms) is not int or num_sms <= 0: | ||
| 420 | + raise ValueError("num_sms must be a positive integer") | ||
| 421 | + if any(t.device.type != "npu" for t in (home, slots, plan)): | ||
| 422 | + raise ValueError("URMA PUSH inputs must be NPU tensors") | ||
| 423 | + if not home.device == slots.device == plan.device: | ||
| 424 | + raise ValueError("URMA PUSH inputs must share one NPU") | ||
| 425 | + if home.dtype != bf16 or slots.dtype != bf16 or plan.dtype != int32: | ||
| 426 | + raise TypeError("URMA PUSH requires BF16 weights and INT32 plan") | ||
| 427 | + if home.ndim != 3 or slots.ndim != 3 or plan.ndim != 2: | ||
| 428 | + raise ValueError("expected home[E,M,N], slots[B,M,N], plan[EP,B]") | ||
| 429 | + if any(not t.is_contiguous() for t in (home, slots, plan)): | ||
| 430 | + raise ValueError("URMA PUSH inputs must be contiguous") | ||
| 431 | + if not 0 < home.shape[0] <= 2147483647 or min(home.shape[1:]) <= 0: | ||
| 432 | + raise ValueError("invalid expert count or projection dimensions") | ||
| 433 | + if home.shape[1:] != slots.shape[1:] or slots.shape[0] != plan.shape[1]: | ||
| 434 | + raise ValueError("incompatible projection or slot shapes") | ||
| 435 | + if not 0 < plan.shape[0] <= 2147483647: | ||
| 436 | + raise ValueError("plan EP must be positive and fit int32") | ||
| 437 | + if slots.shape[0] > 15736: | ||
| 438 | + raise ValueError("plan exceeds URMA PUSH UB scratch capacity") | ||
| 439 | + | ||
| 440 | + | ||
| 441 | +def launch_prefetch_push(remote_expert, prefetch_buffers, experts_to_copy, num_sms): | ||
| 442 | + """Collectively push BF16 owner weights into symmetric consumer slots. | ||
| 443 | + | ||
| 444 | + All ranks call with the same contiguous INT32 [EP,B] plan (-1 means empty). | ||
| 445 | + Returns the destination tensor after enqueueing completion barriers on the | ||
| 446 | + current stream. Retain inputs and backing through a completion event; order | ||
| 447 | + producer writes and previous slot consumers before this call. | ||
| 448 | + Requires ShmemRuntime.init_with_buffer(enable_udma=True, qp_count=2). | ||
| 449 | + """ | ||
| 450 | + from .shmem_runtime import ShmemRuntime | ||
| 451 | + _validate_push_layout(remote_expert, prefetch_buffers, experts_to_copy, num_sms, | ||
| 452 | + bf16=torch.bfloat16, int32=torch.int32) | ||
| 453 | + if not ShmemRuntime.is_initialized() or not ShmemRuntime._udma_enabled: | ||
| 454 | + raise RuntimeError("URMA PUSH requires an initialized URMA SHMEM runtime") | ||
| 455 | + if "950" not in torch.npu.get_device_name(remote_expert.device): | ||
| 456 | + raise RuntimeError("URMA PUSH requires Ascend950") | ||
| 457 | + global _PREFETCH_WEIGHT | ||
| 458 | + if _PREFETCH_WEIGHT is None: | ||
| 459 | + _PREFETCH_WEIGHT = torch.classes.AscendMoonEP.PrefetchWeight(0) | ||
| 460 | + if not _PREFETCH_WEIGHT.push_available(): | ||
| 461 | + raise RuntimeError("native build does not provide URMA PUSH") | ||
| 462 | + return _PREFETCH_WEIGHT.compute_push( | ||
| 463 | + remote_expert, prefetch_buffers, experts_to_copy, | ||
| 464 | + int(remote_expert.shape[0]), num_sms, 0, True) | ||
| 465 | + | ||
| 466 | + | ||
| 407 | def launch_grad_reduce( | 467 | def launch_grad_reduce( |
| 408 | remote_expert_grads: torch.Tensor, | 468 | remote_expert_grads: torch.Tensor, |
| 409 | remote_reduce_buffers: torch.Tensor, | 469 | remote_reduce_buffers: torch.Tensor, |
| @@ -414,16 +474,25 @@ def launch_grad_reduce( | |||
| 414 | meta_stride: int, | 474 | meta_stride: int, |
| 415 | barrier_off: int, | 475 | barrier_off: int, |
| 416 | grid_sync_bar: torch.Tensor, | 476 | grid_sync_bar: torch.Tensor, |
| 477 | + *, | ||
| 478 | + use_udma: bool | None = None, | ||
| 479 | + udma_workspace: torch.Tensor | None = None, | ||
| 417 | ) -> None: | 480 | ) -> None: |
| 418 | """Accumulate symmetric reduce slots into owner gradients. | 481 | """Accumulate symmetric reduce slots into owner gradients. |
| 419 | 482 | ||
| 420 | - ``remote_expert_grads`` and ``remote_reduce_buffers`` must be separate | 483 | + ``remote_expert_grads`` is a contiguous local FP32 [L,H,H'] view of |
| 421 | - symmetric allocations from the active CANN-SHMEM heap. Every PE owns one | 484 | + canonical main_grad storage. Only ``remote_reduce_buffers`` must be |
| 485 | + symmetric. Every PE owns one | ||
| 422 | local ``remote_reduce_buffers[B, H, H']`` chunk; the ``[R, B]`` plan selects | 486 | local ``remote_reduce_buffers[B, H, H']`` chunk; the ``[R, B]`` plan selects |
| 423 | the source PE and its local slot. The allocations do not need to be | 487 | the source PE and its local slot. The allocations do not need to be |
| 424 | adjacent in virtual address space. ``meta_buf``, ``meta_stride``, | 488 | adjacent in virtual address space. ``meta_buf``, ``meta_stride``, |
| 425 | ``barrier_off`` and ``grid_sync_bar`` are retained only for MoonEP API | 489 | ``barrier_off`` and ``grid_sync_bar`` are retained only for MoonEP API |
| 426 | compatibility; the Ascend implementation ignores them. | 490 | compatibility; the Ascend implementation ignores them. |
| 491 | + | ||
| 492 | + MTE and UDMA submit pre/post barriers and clear only valid source slots. | ||
| 493 | + Buffer bindings supply setup-owned UDMA scratch; standalone callers may | ||
| 494 | + omit it and use the native fallback allocation. UDMA accumulation retains | ||
| 495 | + its atomic-add ordering, while MTE scans contributions in plan order. | ||
| 427 | """ | 496 | """ |
| 428 | del meta_buf, meta_stride, barrier_off, grid_sync_bar | 497 | del meta_buf, meta_stride, barrier_off, grid_sync_bar |
| 429 | 498 | ||
| @@ -458,6 +527,12 @@ def launch_grad_reduce( | |||
| 458 | assert remote_reduce_buffers.device == device | 527 | assert remote_reduce_buffers.device == device |
| 459 | assert experts_to_copy.device == device | 528 | assert experts_to_copy.device == device |
| 460 | 529 | ||
| 530 | + from . import _C | ||
| 531 | + if getattr(_C, 'GRAD_REDUCE_DENSE_ABI', None) != 1: | ||
| 532 | + raise RuntimeError('rebuild native GradReduce dense ABI v1') | ||
| 533 | + if use_udma is None: | ||
| 534 | + use_udma = _env_use_udma('grad_reduce') | ||
| 535 | + | ||
| 461 | global _GRAD_REDUCE | 536 | global _GRAD_REDUCE |
| 462 | if _GRAD_REDUCE is None: | 537 | if _GRAD_REDUCE is None: |
| 463 | _GRAD_REDUCE = torch.classes.AscendMoonEP.GradReduce() | 538 | _GRAD_REDUCE = torch.classes.AscendMoonEP.GradReduce() |
| @@ -472,5 +547,6 @@ def launch_grad_reduce( | |||
| 472 | B, | 547 | B, |
| 473 | rank, | 548 | rank, |
| 474 | min(num_sms, 64), | 549 | min(num_sms, 64), |
| 475 | - _env_use_udma('grad_reduce'), | 550 | + use_udma, |
| 551 | + udma_workspace if use_udma else None, | ||
| 476 | ) | 552 | ) |
| @@ -85,6 +85,8 @@ include("${CMAKE_SOURCE_DIR}/cmake/AscendMoonEPKernel.cmake") | |||
| 85 | ascend_moonep_add_kernel_library( | 85 | ascend_moonep_add_kernel_library( |
| 86 | ascend_moonep_kernels | 86 | ascend_moonep_kernels |
| 87 | SOURCES | 87 | SOURCES |
| 88 | + kernels/lplusb_runtime.cpp | ||
| 89 | + kernels/barrier.cpp | ||
| 88 | kernels/barrier_bench.cpp | 90 | kernels/barrier_bench.cpp |
| 89 | kernels/moonep_combine.cpp | 91 | kernels/moonep_combine.cpp |
| 90 | kernels/moonep_combine_udma.cpp | 92 | kernels/moonep_combine_udma.cpp |
| @@ -95,6 +97,8 @@ ascend_moonep_add_kernel_library( | |||
| 95 | kernels/planning.cpp | 97 | kernels/planning.cpp |
| 96 | kernels/prefetch.cpp | 98 | kernels/prefetch.cpp |
| 97 | kernels/prefetch_udma.cpp | 99 | kernels/prefetch_udma.cpp |
| 100 | + kernels/prefetch_push_udma.cpp | ||
| 101 | + kernels/prefetch_pointer_push_udma.cpp | ||
| 98 | INCLUDES | 102 | INCLUDES |
| 99 | include | 103 | include |
| 100 | kernels | 104 | kernels |
| @@ -0,0 +1,165 @@ | |||
| 1 | +#include "csrc/lplusb_runtime.h" | ||
| 2 | +#include "csrc/ops/prefetch.h" | ||
| 3 | + | ||
| 4 | +#include <acl/acl.h> | ||
| 5 | +#include <limits> | ||
| 6 | + | ||
| 7 | +#include <torch_npu/csrc/core/npu/NPUStream.h> | ||
| 8 | + | ||
| 9 | +#include "ascend_moonep/kernels/launch.h" | ||
| 10 | +#include "csrc/common/check.h" | ||
| 11 | +#include "shmem.h" | ||
| 12 | + | ||
| 13 | +namespace ascend_moonep { | ||
| 14 | +namespace { | ||
| 15 | + | ||
| 16 | +void CheckCommon( | ||
| 17 | + const torch::Tensor& pointer_table, | ||
| 18 | + const torch::Tensor& slots, | ||
| 19 | + const torch::Tensor& plan, | ||
| 20 | + int64_t rank, | ||
| 21 | + int64_t local_experts) | ||
| 22 | +{ | ||
| 23 | + TORCH_CHECK(pointer_table.device().type() == c10::DeviceType::PrivateUse1, | ||
| 24 | + "pointer table must be an NPU tensor"); | ||
| 25 | + TORCH_CHECK(slots.device().type() == c10::DeviceType::PrivateUse1, | ||
| 26 | + "slot arena must be an NPU tensor"); | ||
| 27 | + TORCH_CHECK(plan.device().type() == c10::DeviceType::PrivateUse1, | ||
| 28 | + "experts_to_copy must be an NPU tensor"); | ||
| 29 | + TORCH_CHECK(pointer_table.device() == slots.device() && slots.device() == plan.device(), | ||
| 30 | + "pointer table, slot arena and plan must be on the same NPU"); | ||
| 31 | + TORCH_CHECK(pointer_table.scalar_type() == torch::kInt64 && | ||
| 32 | + pointer_table.dim() == 1 && pointer_table.is_contiguous(), | ||
| 33 | + "pointer table must be contiguous INT64 [L]"); | ||
| 34 | + TORCH_CHECK(plan.scalar_type() == torch::kInt32 && plan.dim() == 2 && plan.is_contiguous(), | ||
| 35 | + "experts_to_copy must be contiguous INT32 [R,B]"); | ||
| 36 | + TORCH_CHECK(slots.is_contiguous() && slots.dim() >= 2, | ||
| 37 | + "slot arena must be contiguous [B,...]"); | ||
| 38 | + TORCH_CHECK(local_experts > 0 && pointer_table.numel() == local_experts, | ||
| 39 | + "pointer table length must equal local_experts"); | ||
| 40 | + TORCH_CHECK(plan.size(1) == slots.size(0) && plan.size(0) > 0, | ||
| 41 | + "plan [R,B] must match the slot arena B dimension"); | ||
| 42 | + TORCH_CHECK(rank >= 0 && rank < plan.size(0), "rank is outside the EP group"); | ||
| 43 | + for (int64_t dim = 1; dim < slots.dim(); ++dim) { | ||
| 44 | + TORCH_CHECK(slots.size(dim) > 0, "slot rows must have positive dimensions"); | ||
| 45 | + } | ||
| 46 | + TORCH_CHECK(local_experts <= std::numeric_limits<int32_t>::max() && | ||
| 47 | + plan.size(0) <= std::numeric_limits<int32_t>::max() && | ||
| 48 | + plan.size(1) <= std::numeric_limits<int32_t>::max(), | ||
| 49 | + "L/R/B exceeds the private kernel int32 contract"); | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +int64_t RowElements(const torch::Tensor& slots) { | ||
| 53 | + int64_t elements = 1; | ||
| 54 | + for (int64_t dim = 1; dim < slots.dim(); ++dim) { | ||
| 55 | + TORCH_CHECK(elements <= std::numeric_limits<int64_t>::max() / slots.size(dim), | ||
| 56 | + "slot row extent overflows INT64"); | ||
| 57 | + elements *= slots.size(dim); | ||
| 58 | + } | ||
| 59 | + return elements; | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +int32_t VectorBlocks() | ||
| 63 | +{ | ||
| 64 | + int32_t device_id = 0; | ||
| 65 | + int64_t cores = 0; | ||
| 66 | + ASCEND_MOONEP_CHECK_ACL(aclrtGetDevice(&device_id)); | ||
| 67 | + ASCEND_MOONEP_CHECK_ACL( | ||
| 68 | + aclrtGetDeviceInfo(device_id, ACL_DEV_ATTR_AICORE_CORE_NUM, &cores)); | ||
| 69 | + TORCH_CHECK(cores > 0 && cores <= std::numeric_limits<int32_t>::max(), | ||
| 70 | + "current NPU reports an invalid AICore count"); | ||
| 71 | + return static_cast<int32_t>(cores); | ||
| 72 | +} | ||
| 73 | + | ||
| 74 | +} // namespace | ||
| 75 | + | ||
| 76 | +// Compatibility with earlier private L+B ABI; transport belongs to #9. | ||
| 77 | +bool LPlusBUrmaAvailable() { return ops::PrefetchPushPointersAvailable(); } | ||
| 78 | + | ||
| 79 | +void LPlusBOwnerPushUrmaContiguous(torch::Tensor home, torch::Tensor slots, | ||
| 80 | + torch::Tensor plan, int64_t rank, int64_t global_experts) { | ||
| 81 | + TORCH_CHECK(rank == aclshmem_my_pe(), "rank differs from SHMEM"); | ||
| 82 | + ops::LaunchPrefetchPushLocal(home, slots, plan, global_experts); | ||
| 83 | +} | ||
| 84 | + | ||
| 85 | +void LPlusBOwnerPushUrma(torch::Tensor pointers, torch::Tensor slots, | ||
| 86 | + torch::Tensor plan, int64_t rank, int64_t local_experts) { | ||
| 87 | + TORCH_CHECK(rank == aclshmem_my_pe(), "rank differs from SHMEM"); | ||
| 88 | + ops::LaunchPrefetchPushPointers(pointers, slots, plan, local_experts); | ||
| 89 | +} | ||
| 90 | + | ||
| 91 | +void LPlusBOwnerPush( | ||
| 92 | + torch::Tensor source_ptrs, | ||
| 93 | + torch::Tensor weight_slots, | ||
| 94 | + torch::Tensor experts_to_copy, | ||
| 95 | + int64_t rank, | ||
| 96 | + int64_t local_experts) | ||
| 97 | +{ | ||
| 98 | + CheckCommon(source_ptrs, weight_slots, experts_to_copy, rank, local_experts); | ||
| 99 | + TORCH_CHECK(weight_slots.scalar_type() == torch::kBFloat16, | ||
| 100 | + "weight slot arena must be BF16"); | ||
| 101 | + aclrtStream stream = c10_npu::getCurrentNPUStream().stream(); | ||
| 102 | + aclshmemx_barrier_all_on_stream(stream); | ||
| 103 | + const int ret = moonep_lplusb_owner_push( | ||
| 104 | + stream, | ||
| 105 | + reinterpret_cast<const uint64_t*>(source_ptrs.data_ptr<int64_t>()), | ||
| 106 | + weight_slots.data_ptr(), experts_to_copy.data_ptr<int32_t>(), | ||
| 107 | + RowElements(weight_slots), | ||
| 108 | + static_cast<int32_t>(local_experts), static_cast<int32_t>(experts_to_copy.size(0)), | ||
| 109 | + static_cast<int32_t>(experts_to_copy.size(1)), static_cast<int32_t>(rank), | ||
| 110 | + VectorBlocks()); | ||
| 111 | + TORCH_CHECK(ret == 0, "L+B owner-push kernel failed with ACL error: ", ret); | ||
| 112 | + // On return, all writes are peer-visible on the same ordered stream. | ||
| 113 | + aclshmemx_barrier_all_on_stream(stream); | ||
| 114 | +} | ||
| 115 | + | ||
| 116 | +void LPlusBOwnerReadyInit(torch::Tensor ready) | ||
| 117 | +{ | ||
| 118 | + TORCH_CHECK(ready.device().type() == c10::DeviceType::PrivateUse1 && | ||
| 119 | + ready.scalar_type() == torch::kInt32 && ready.is_contiguous() && | ||
| 120 | + ready.dim() == 2 && ready.size(0) > 0 && ready.size(1) == 16, | ||
| 121 | + "owner-ready initialization requires INT32 [R,16] on NPU"); | ||
| 122 | + // Setup only, before SHMEM init. Synchronous memset has no pending stream | ||
| 123 | + // writer to an allocation which a failed setup may need to unwind. | ||
| 124 | + const size_t bytes = static_cast<size_t>(ready.numel()) * sizeof(int32_t); | ||
| 125 | + ASCEND_MOONEP_CHECK_ACL(aclrtMemset(ready.data_ptr(), bytes, 0, bytes)); | ||
| 126 | +} | ||
| 127 | + | ||
| 128 | +void LPlusBOwnerPushReady( | ||
| 129 | + torch::Tensor source_ptrs, torch::Tensor weight_slots, | ||
| 130 | + torch::Tensor experts_to_copy, torch::Tensor ready, | ||
| 131 | + int64_t rank, int64_t local_experts, int64_t epoch) | ||
| 132 | +{ | ||
| 133 | + CheckCommon(source_ptrs, weight_slots, experts_to_copy, rank, local_experts); | ||
| 134 | + TORCH_CHECK(weight_slots.scalar_type() == torch::kBFloat16, "weight slot arena must be BF16"); | ||
| 135 | + TORCH_CHECK(ready.device() == weight_slots.device() && ready.scalar_type() == torch::kInt32 && | ||
| 136 | + ready.is_contiguous() && ready.dim() == 2 && | ||
| 137 | + ready.size(0) == experts_to_copy.size(0) && ready.size(1) == 16 && | ||
| 138 | + reinterpret_cast<uintptr_t>(ready.data_ptr()) % 64 == 0, | ||
| 139 | + "owner-ready bank must be aligned INT32 [R,16] on the slot NPU"); | ||
| 140 | + TORCH_CHECK(epoch > 0 && epoch <= std::numeric_limits<int32_t>::max(), | ||
| 141 | + "owner-ready epoch must be positive INT32; wrapping is forbidden"); | ||
| 142 | + TORCH_CHECK(local_experts <= std::numeric_limits<int32_t>::max() / experts_to_copy.size(0), | ||
| 143 | + "global expert IDs exceed INT32"); | ||
| 144 | + aclrtStream stream = c10_npu::getCurrentNPUStream().stream(); | ||
| 145 | + // Preserve the existing source/plan readiness rendezvous. Bank reuse also | ||
| 146 | + // retains the caller's separate peer-final-use collective. | ||
| 147 | + aclshmemx_barrier_all_on_stream(stream); | ||
| 148 | + const int push_ret = moonep_lplusb_owner_push( | ||
| 149 | + stream, reinterpret_cast<const uint64_t*>(source_ptrs.data_ptr<int64_t>()), | ||
| 150 | + weight_slots.data_ptr(), experts_to_copy.data_ptr<int32_t>(), | ||
| 151 | + RowElements(weight_slots), | ||
| 152 | + static_cast<int32_t>(local_experts), static_cast<int32_t>(experts_to_copy.size(0)), | ||
| 153 | + static_cast<int32_t>(experts_to_copy.size(1)), static_cast<int32_t>(rank), VectorBlocks()); | ||
| 154 | + TORCH_CHECK(push_ret == 0, "L+B owner-push kernel failed with ACL error: ", push_ret); | ||
| 155 | + const int ready_ret = moonep_lplusb_owner_ready( | ||
| 156 | + stream, ready.data_ptr<int32_t>(), experts_to_copy.data_ptr<int32_t>(), | ||
| 157 | + static_cast<int32_t>(local_experts), static_cast<int32_t>(experts_to_copy.size(0)), | ||
| 158 | + static_cast<int32_t>(experts_to_copy.size(1)), static_cast<int32_t>(rank), | ||
| 159 | + static_cast<int32_t>(epoch)); | ||
| 160 | + TORCH_CHECK(ready_ret == 0, "L+B owner-ready kernel failed with ACL error: ", ready_ret); | ||
| 161 | + // Q0's next event now proves this receiver's required incoming writes. | ||
| 162 | + // Do not add a global post-barrier here: it would defeat that admission. | ||
| 163 | +} | ||
| 164 | + | ||
| 165 | +} // namespace ascend_moonep | ||
| @@ -0,0 +1,28 @@ | |||
| 1 | +#pragma once | ||
| 2 | + | ||
| 3 | +#include <torch/extension.h> | ||
| 4 | + | ||
| 5 | +namespace ascend_moonep { | ||
| 6 | + | ||
| 7 | +bool LPlusBUrmaAvailable(); | ||
| 8 | +void LPlusBOwnerPushUrmaContiguous(torch::Tensor home, torch::Tensor slots, | ||
| 9 | + torch::Tensor plan, int64_t rank, int64_t global_experts); | ||
| 10 | +void LPlusBOwnerPushUrma(torch::Tensor pointers, torch::Tensor slots, | ||
| 11 | + torch::Tensor plan, int64_t rank, int64_t local_experts); | ||
| 12 | + | ||
| 13 | +void LPlusBOwnerReadyInit(torch::Tensor ready); | ||
| 14 | + | ||
| 15 | +void LPlusBOwnerPush( | ||
| 16 | + torch::Tensor source_ptrs, | ||
| 17 | + torch::Tensor weight_slots, | ||
| 18 | + torch::Tensor experts_to_copy, | ||
| 19 | + int64_t rank, | ||
| 20 | + int64_t local_experts); | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +void LPlusBOwnerPushReady( | ||
| 24 | + torch::Tensor source_ptrs, torch::Tensor weight_slots, | ||
| 25 | + torch::Tensor experts_to_copy, torch::Tensor ready, | ||
| 26 | + int64_t rank, int64_t local_experts, int64_t epoch); | ||
| 27 | + | ||
| 28 | +} // namespace ascend_moonep | ||
| @@ -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 | ||
| @@ -81,10 +83,8 @@ void GradReduce( | |||
| 81 | int64_t slots, | 83 | int64_t slots, |
| 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. | 87 | + torch::Tensor udma_workspace) { |
| 86 | - // Keep the unified ABI and deliberately use the existing SHMEM path. | ||
| 87 | - (void)use_udma; | ||
| 88 | aclrtStream stream = c10_npu::getCurrentNPUStream().stream(); | 88 | aclrtStream stream = c10_npu::getCurrentNPUStream().stream(); |
| 89 | 89 | ||
| 90 | CheckNpuContiguous(expert_grads, "expert_grads"); | 90 | CheckNpuContiguous(expert_grads, "expert_grads"); |
| @@ -113,12 +113,37 @@ void GradReduce( | |||
| 113 | "epn must be positive"); | 113 | "epn must be positive"); |
| 114 | CheckInt32(epn, "epn"); | 114 | CheckInt32(epn, "epn"); |
| 115 | if (use_udma) { | 115 | if (use_udma) { |
| 116 | - torch::Tensor workspace = torch::empty(512 * 1024 * (blocks * 2), expert_grads.options()); | 116 | + const int64_t regions = std::max<int64_t>(blocks * 2, ranks * slots); |
| 117 | + constexpr int64_t tile = 512 * 1024; | ||
| 118 | + TORCH_CHECK(regions <= std::numeric_limits<int64_t>::max() / (tile * sizeof(float)), | ||
| 119 | + "UDMA workspace byte count exceeds int64"); | ||
| 120 | + // Legacy dense callers may omit scratch. Prepared Buffer bindings | ||
| 121 | + // always supply setup-owned scratch and allocate nothing here. | ||
| 122 | + if (!udma_workspace.defined()) { | ||
| 123 | + udma_workspace = torch::empty(tile * regions, expert_grads.options()); | ||
| 124 | + } | ||
| 125 | + CheckNpuContiguous(udma_workspace, "udma_workspace"); | ||
| 126 | + TORCH_CHECK(udma_workspace.scalar_type() == torch::kFloat32 && | ||
| 127 | + udma_workspace.device() == reduce_buffers.device(), | ||
| 128 | + "udma_workspace device/dtype is invalid"); | ||
| 129 | + TORCH_CHECK(udma_workspace.numel() >= tile * regions, | ||
| 130 | + "udma_workspace must be local FP32 scratch with at least " | ||
| 131 | + "512*1024*max(blocks*2,ranks*slots) elements on the source device"); | ||
| 132 | + } | ||
| 133 | + | ||
| 134 | + // Publish Q1 slots before peer reads, then publish home updates and | ||
| 135 | + // cleared valid slots before the caller records its completion event. | ||
| 136 | + // Prepared Buffer scratch is allocated during setup. Legacy callers may | ||
| 137 | + // use the fallback allocation above. Both lifetimes cover this operation. | ||
| 138 | + const int pre_barrier_status = moonep_grad_reduce_native_barrier(stream); | ||
| 139 | + TORCH_CHECK(pre_barrier_status == ACL_SUCCESS, | ||
| 140 | + "GR native barrier launch failed: ", pre_barrier_status); | ||
| 141 | + if (use_udma) { | ||
| 117 | const int ret = moonep_shmem_grad_reduce_udma( | 142 | const int ret = moonep_shmem_grad_reduce_udma( |
| 118 | stream, | 143 | stream, |
| 119 | expert_grads.data_ptr(), | 144 | expert_grads.data_ptr(), |
| 120 | reduce_buffers.data_ptr(), | 145 | reduce_buffers.data_ptr(), |
| 121 | - workspace.data_ptr(), | 146 | + udma_workspace.data_ptr(), |
| 122 | experts_to_copy.data_ptr<int32_t>(), | 147 | experts_to_copy.data_ptr<int32_t>(), |
| 123 | static_cast<int32_t>(epn), | 148 | static_cast<int32_t>(epn), |
| 124 | static_cast<int32_t>(hidden), | 149 | static_cast<int32_t>(hidden), |
| @@ -143,6 +168,9 @@ void GradReduce( | |||
| 143 | static_cast<int32_t>(blocks)); | 168 | static_cast<int32_t>(blocks)); |
| 144 | TORCH_CHECK(ret == 0, "grad_reduce kernel failed with ACL error: ", ret); | 169 | TORCH_CHECK(ret == 0, "grad_reduce kernel failed with ACL error: ", ret); |
| 145 | } | 170 | } |
| 171 | + const int post_barrier_status = moonep_grad_reduce_native_barrier(stream); | ||
| 172 | + TORCH_CHECK(post_barrier_status == ACL_SUCCESS, | ||
| 173 | + "GR native barrier launch failed: ", post_barrier_status); | ||
| 146 | } | 174 | } |
| 147 | 175 | ||
| 148 | } // namespace ascend_moonep::ops | 176 | } // namespace ascend_moonep::ops |
| @@ -17,6 +17,7 @@ void GradReduce( | |||
| 17 | int64_t slots, | 17 | int64_t slots, |
| 18 | int64_t rank, | 18 | int64_t rank, |
| 19 | int64_t blocks, | 19 | int64_t blocks, |
| 20 | - bool use_udma); | 20 | + bool use_udma, |
| 21 | + torch::Tensor udma_workspace = {}); | ||
| 21 | 22 | ||
| 22 | } // namespace ascend_moonep::ops | 23 | } // 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); |
| 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 |
| @@ -185,13 +185,18 @@ MoonEPDispatch( | |||
| 185 | int64_t R, | 185 | int64_t R, |
| 186 | int64_t rank, | 186 | int64_t rank, |
| 187 | bool use_udma, | 187 | bool use_udma, |
| 188 | - bool server_dedup) { | 188 | + bool server_dedup, |
| 189 | + int64_t num_sms) { | ||
| 189 | 190 | ||
| 190 | auto args = CheckDispatchArgs( | 191 | auto args = CheckDispatchArgs( |
| 191 | hidden_sh, route_weights, dst, dup_groups, dup_loffs, dup_counts, | 192 | hidden_sh, route_weights, dst, dup_groups, dup_loffs, dup_counts, |
| 192 | hidden_buf, route_weights_buf, S, H, K, R, rank, use_udma, server_dedup); | 193 | hidden_buf, route_weights_buf, S, H, K, R, rank, use_udma, server_dedup); |
| 193 | 194 | ||
| 194 | if (!use_udma) { | 195 | if (!use_udma) { |
| 196 | + TORCH_CHECK(num_sms > 0 && | ||
| 197 | + static_cast<uint64_t>(num_sms) <= std::numeric_limits<uint32_t>::max(), | ||
| 198 | + "num_sms must be a positive uint32 launch width"); | ||
| 199 | + args.tiling.block_dim = static_cast<uint32_t>(num_sms); | ||
| 195 | // Peer-to-peer MTE path: rank-level dedup only, no UDMA messaging. | 200 | // Peer-to-peer MTE path: rank-level dedup only, no UDMA messaging. |
| 196 | LaunchMoonEPDispatchKernel( | 201 | LaunchMoonEPDispatchKernel( |
| 197 | hidden_sh, args.route_weights, dst, | 202 | hidden_sh, args.route_weights, dst, |
| @@ -23,7 +23,8 @@ MoonEPDispatch( | |||
| 23 | int64_t R, | 23 | int64_t R, |
| 24 | int64_t rank, | 24 | int64_t rank, |
| 25 | bool use_udma, | 25 | bool use_udma, |
| 26 | - bool server_dedup); | 26 | + bool server_dedup, |
| 27 | + int64_t num_sms = 32); | ||
| 27 | 28 | ||
| 28 | void | 29 | void |
| 29 | MoonEPDispatchProfile( | 30 | MoonEPDispatchProfile( |
| @@ -3,6 +3,7 @@ | |||
| 3 | #include <acl/acl.h> | 3 | #include <acl/acl.h> |
| 4 | #include <algorithm> | 4 | #include <algorithm> |
| 5 | #include <cstdint> | 5 | #include <cstdint> |
| 6 | +#include <limits> | ||
| 6 | 7 | ||
| 7 | #include <torch_npu/csrc/core/npu/NPUStream.h> | 8 | #include <torch_npu/csrc/core/npu/NPUStream.h> |
| 8 | 9 | ||
| @@ -13,6 +14,15 @@ | |||
| 13 | 14 | ||
| 14 | namespace { | 15 | namespace { |
| 15 | 16 | ||
| 17 | +void PrefetchBarrier(aclrtStream stream, bool aiv_only) { | ||
| 18 | + if (aiv_only) { | ||
| 19 | + TORCH_CHECK(moonep_prefetch_barrier_vec(stream) == ACL_SUCCESS, | ||
| 20 | + "URMA prefetch AIV barrier launch failed"); | ||
| 21 | + } else { | ||
| 22 | + aclshmemx_barrier_all_on_stream(stream); | ||
| 23 | + } | ||
| 24 | +} | ||
| 25 | + | ||
| 16 | void CheckNpuContiguous(const torch::Tensor& tensor, const char* name) { | 26 | void CheckNpuContiguous(const torch::Tensor& tensor, const char* name) { |
| 17 | TORCH_CHECK( | 27 | TORCH_CHECK( |
| 18 | tensor.device().type() == c10::DeviceType::PrivateUse1, | 28 | tensor.device().type() == c10::DeviceType::PrivateUse1, |
| @@ -41,6 +51,9 @@ torch::Tensor LaunchPrefetch( | |||
| 41 | bool use_udma, | 51 | bool use_udma, |
| 42 | bool rank_barriers) { | 52 | bool rank_barriers) { |
| 43 | // The current SHMEM runtime is a single global instance. | 53 | // The current SHMEM runtime is a single global instance. |
| 54 | + | ||
| 55 | + TORCH_CHECK(!use_udma || prefetch_weight_push_udma_available() == 1, | ||
| 56 | + "requested URMA GET is unavailable in this native build"); | ||
| 44 | (void)instance_id; | 57 | (void)instance_id; |
| 45 | (void)num_sms; | 58 | (void)num_sms; |
| 46 | // remote_expert is a logical cross-PE view. Its data pointer is the local | 59 | // remote_expert is a logical cross-PE view. Its data pointer is the local |
| @@ -122,4 +135,108 @@ torch::Tensor LaunchPrefetch( | |||
| 122 | return prefetch_buffers; | 135 | return prefetch_buffers; |
| 123 | } | 136 | } |
| 124 | 137 | ||
| 138 | + | ||
| 139 | +torch::Tensor LaunchPrefetchPush( | ||
| 140 | + torch::Tensor home, torch::Tensor slots, torch::Tensor plan, | ||
| 141 | + int64_t num_sms, int64_t instance_id, bool use_udma) { | ||
| 142 | + TORCH_CHECK(use_udma, "compute_push requires URMA; no MTE fallback"); | ||
| 143 | + TORCH_CHECK(prefetch_weight_push_udma_available() == 1, | ||
| 144 | + "URMA PUSH requires a native Ascend950 build"); | ||
| 145 | + TORCH_CHECK(instance_id == 0 && num_sms > 0, "invalid instance_id or num_sms"); | ||
| 146 | + CheckNpuContiguous(home, "home"); | ||
| 147 | + CheckNpuContiguous(slots, "slots"); | ||
| 148 | + CheckNpuContiguous(plan, "plan"); | ||
| 149 | + TORCH_CHECK(home.device() == slots.device() && home.device() == plan.device(), | ||
| 150 | + "home, slots and plan must share an NPU"); | ||
| 151 | + TORCH_CHECK(home.scalar_type() == torch::kBFloat16 && | ||
| 152 | + slots.scalar_type() == torch::kBFloat16 && | ||
| 153 | + plan.scalar_type() == torch::kInt32, "expected BF16 weights and INT32 plan"); | ||
| 154 | + TORCH_CHECK(home.dim() == 3 && slots.dim() == 3 && plan.dim() == 2, | ||
| 155 | + "expected home[E,M,N], slots[B,M,N], plan[EP,B]"); | ||
| 156 | + TORCH_CHECK(home.size(0) > 0 && home.size(0) <= INT32_MAX && | ||
| 157 | + home.size(1) > 0 && home.size(2) > 0, | ||
| 158 | + "home dimensions must be positive"); | ||
| 159 | + TORCH_CHECK(home.size(1) == slots.size(1) && home.size(2) == slots.size(2) && | ||
| 160 | + slots.size(0) == plan.size(1), "incompatible projection or slot shapes"); | ||
| 161 | + TORCH_CHECK(plan.size(0) == aclshmem_n_pes() && plan.size(0) > 0 && | ||
| 162 | + plan.size(0) <= INT32_MAX, | ||
| 163 | + "plan EP must match the initialized SHMEM group"); | ||
| 164 | + // Reserve the official WQE scratch plus a full local-copy tile below 188 KiB. | ||
| 165 | + TORCH_CHECK(slots.size(0) <= 15736, "plan exceeds URMA PUSH UB scratch capacity"); | ||
| 166 | + aclrtStream stream = c10_npu::getCurrentNPUStream().stream(); | ||
| 167 | + aclshmemx_barrier_all_on_stream(stream); | ||
| 168 | + ASCEND_MOONEP_CHECK_ACL(prefetch_weight_push_udma_do(stream, | ||
| 169 | + static_cast<uint8_t*>(home.data_ptr()), static_cast<uint8_t*>(slots.data_ptr()), | ||
| 170 | + static_cast<uint8_t*>(plan.data_ptr()), home.size(0), | ||
| 171 | + home.size(1) * home.size(2), slots.size(0))); | ||
| 172 | + aclshmemx_barrier_all_on_stream(stream); | ||
| 173 | + return slots; | ||
| 174 | +} | ||
| 175 | + | ||
| 176 | +bool PrefetchPushPointersAvailable() { | ||
| 177 | + return prefetch_pointer_push_udma_available() == 1; | ||
| 178 | +} | ||
| 179 | + | ||
| 180 | +namespace { | ||
| 181 | +int64_t CheckPushProjection(const torch::Tensor& source, const torch::Tensor& slots, | ||
| 182 | + const torch::Tensor& plan, int64_t local_experts) { | ||
| 183 | + CheckNpuContiguous(source, "source"); | ||
| 184 | + CheckNpuContiguous(slots, "slots"); | ||
| 185 | + CheckNpuContiguous(plan, "plan"); | ||
| 186 | + TORCH_CHECK(source.device() == slots.device() && slots.device() == plan.device(), | ||
| 187 | + "source, slots and plan must share one NPU"); | ||
| 188 | + TORCH_CHECK(slots.scalar_type() == torch::kBFloat16 && | ||
| 189 | + plan.scalar_type() == torch::kInt32 && slots.dim() == 3 && plan.dim() == 2, | ||
| 190 | + "expected BF16 slots[B,M,N] and INT32 plan[EP,B]"); | ||
| 191 | + const int64_t ep = plan.size(0); | ||
| 192 | + TORCH_CHECK(ep > 0 && ep == aclshmem_n_pes() && local_experts > 0 && | ||
| 193 | + local_experts <= INT32_MAX / ep, | ||
| 194 | + "local expert count or SHMEM topology differs"); | ||
| 195 | + TORCH_CHECK(plan.size(1) == slots.size(0) && slots.size(0) <= 15736 && | ||
| 196 | + slots.size(1) > 0 && slots.size(2) > 0 && | ||
| 197 | + slots.size(1) <= std::numeric_limits<int64_t>::max() / slots.size(2), | ||
| 198 | + "invalid projection, slots or URMA UB extent"); | ||
| 199 | + return slots.size(1) * slots.size(2); | ||
| 200 | +} | ||
| 201 | +} | ||
| 202 | + | ||
| 203 | +torch::Tensor LaunchPrefetchPushPointers(torch::Tensor pointers, torch::Tensor slots, | ||
| 204 | + torch::Tensor plan, int64_t local_experts, bool aiv_barrier) { | ||
| 205 | + TORCH_CHECK(PrefetchPushPointersAvailable(), "URMA pointer PUSH unavailable; no MTE fallback"); | ||
| 206 | + const int64_t elements = CheckPushProjection(pointers, slots, plan, local_experts); | ||
| 207 | + TORCH_CHECK(pointers.scalar_type() == torch::kInt64 && pointers.dim() == 1 && | ||
| 208 | + pointers.numel() == local_experts, "expected INT64 pointer table[L]"); | ||
| 209 | + aclrtStream stream = c10_npu::getCurrentNPUStream().stream(); | ||
| 210 | + PrefetchBarrier(stream, aiv_barrier); | ||
| 211 | + ASCEND_MOONEP_CHECK_ACL(moonep_prefetch_pointer_push_udma(stream, | ||
| 212 | + reinterpret_cast<uint8_t*>(pointers.data_ptr()), | ||
| 213 | + reinterpret_cast<uint8_t*>(slots.data_ptr()), | ||
| 214 | + reinterpret_cast<uint8_t*>(plan.data_ptr()), | ||
| 215 | + local_experts * plan.size(0), elements, slots.size(0))); | ||
| 216 | + PrefetchBarrier(stream, aiv_barrier); | ||
| 217 | + return slots; | ||
| 218 | +} | ||
| 219 | + | ||
| 220 | +torch::Tensor LaunchPrefetchPushLocal(torch::Tensor home, torch::Tensor slots, | ||
| 221 | + torch::Tensor plan, int64_t global_experts, bool aiv_barrier) { | ||
| 222 | + TORCH_CHECK(prefetch_weight_push_udma_available() == 1, | ||
| 223 | + "URMA contiguous PUSH unavailable; no MTE fallback"); | ||
| 224 | + TORCH_CHECK(home.dim() == 3 && home.scalar_type() == torch::kBFloat16 && | ||
| 225 | + plan.dim() == 2 && plan.size(0) > 0 && global_experts > 0 && | ||
| 226 | + global_experts % plan.size(0) == 0 && | ||
| 227 | + home.size(0) == global_experts / plan.size(0), | ||
| 228 | + "expected legal local_home[L,M,N] and explicit global E"); | ||
| 229 | + const int64_t elements = CheckPushProjection(home, slots, plan, home.size(0)); | ||
| 230 | + TORCH_CHECK(home.size(1) == slots.size(1) && home.size(2) == slots.size(2), | ||
| 231 | + "home and slots projection differs"); | ||
| 232 | + aclrtStream stream = c10_npu::getCurrentNPUStream().stream(); | ||
| 233 | + PrefetchBarrier(stream, aiv_barrier); | ||
| 234 | + ASCEND_MOONEP_CHECK_ACL(prefetch_weight_push_udma_do(stream, | ||
| 235 | + reinterpret_cast<uint8_t*>(home.data_ptr()), | ||
| 236 | + reinterpret_cast<uint8_t*>(slots.data_ptr()), | ||
| 237 | + reinterpret_cast<uint8_t*>(plan.data_ptr()), | ||
| 238 | + global_experts, elements, slots.size(0))); | ||
| 239 | + PrefetchBarrier(stream, aiv_barrier); | ||
| 240 | + return slots; | ||
| 241 | +} | ||
| 125 | } // namespace ascend_moonep::ops | 242 | } // namespace ascend_moonep::ops |
| @@ -13,4 +13,14 @@ torch::Tensor LaunchPrefetch( | |||
| 13 | bool use_udma, | 13 | bool use_udma, |
| 14 | bool rank_barriers = true); | 14 | bool rank_barriers = true); |
| 15 | 15 | ||
| 16 | + | ||
| 17 | +torch::Tensor LaunchPrefetchPush( | ||
| 18 | + torch::Tensor home, torch::Tensor slots, torch::Tensor plan, | ||
| 19 | + int64_t num_sms, int64_t instance_id, bool use_udma); | ||
| 20 | +// Stateless submissions: caller owns Tensor/table lifetime and consumer final use. | ||
| 21 | +bool PrefetchPushPointersAvailable(); | ||
| 22 | +torch::Tensor LaunchPrefetchPushPointers(torch::Tensor pointers, torch::Tensor slots, | ||
| 23 | + torch::Tensor plan, int64_t local_experts, bool aiv_barrier = false); | ||
| 24 | +torch::Tensor LaunchPrefetchPushLocal(torch::Tensor home, torch::Tensor slots, | ||
| 25 | + torch::Tensor plan, int64_t global_experts, bool aiv_barrier = false); | ||
| 16 | } // namespace ascend_moonep::ops | 26 | } // namespace ascend_moonep::ops |
| @@ -2,7 +2,9 @@ | |||
| 2 | 2 | ||
| 3 | #include "acl_shared_buffer.h" | 3 | #include "acl_shared_buffer.h" |
| 4 | #include "launcher.h" | 4 | #include "launcher.h" |
| 5 | +#include "lplusb_runtime.h" | ||
| 5 | #include "shmem.h" | 6 | #include "shmem.h" |
| 7 | +#include "csrc/ops/prefetch.h" | ||
| 6 | 8 | ||
| 7 | PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { | 9 | PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { |
| 8 | m.doc() = "MoonEP NPU symmetric-memory extension (shmem C++ backend)"; | 10 | m.doc() = "MoonEP NPU symmetric-memory extension (shmem C++ backend)"; |
| @@ -12,6 +14,42 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { | |||
| 12 | py::int_(sizeof(aclshmemx_buffer_optional_attr_t)); | 14 | py::int_(sizeof(aclshmemx_buffer_optional_attr_t)); |
| 13 | 15 | ||
| 14 | using py::arg; | 16 | using py::arg; |
| 17 | + m.attr("PREFETCH_PUSH_POINTER_ABI") = py::int_(1); | ||
| 18 | + m.attr("PREFETCH_PUSH_LOCAL_ABI") = py::int_(1); | ||
| 19 | + m.attr("PREFETCH_PUSH_BARRIER_ABI") = py::int_(1); | ||
| 20 | + m.def("_prefetch_push_available", &ascend_moonep::ops::PrefetchPushPointersAvailable); | ||
| 21 | + m.def("_prefetch_push_pointers", &ascend_moonep::ops::LaunchPrefetchPushPointers, | ||
| 22 | + arg("source_ptrs"), arg("slots"), arg("plan"), arg("local_experts"), arg("aiv_barrier") = false); | ||
| 23 | + m.def("_prefetch_push_local", &ascend_moonep::ops::LaunchPrefetchPushLocal, | ||
| 24 | + arg("local_home"), arg("slots"), arg("plan"), arg("global_experts"), arg("aiv_barrier") = false); | ||
| 25 | + m.def("_prefetch_push_pointers_aiv", [](torch::Tensor p, torch::Tensor s, torch::Tensor plan, int64_t l) { | ||
| 26 | + return ascend_moonep::ops::LaunchPrefetchPushPointers(p, s, plan, l, true); | ||
| 27 | + }); | ||
| 28 | + m.def("_prefetch_push_local_aiv", [](torch::Tensor h, torch::Tensor s, torch::Tensor plan, int64_t e) { | ||
| 29 | + return ascend_moonep::ops::LaunchPrefetchPushLocal(h, s, plan, e, true); | ||
| 30 | + }); | ||
| 31 | + | ||
| 32 | + // Private MindSpeed integration. Kept out of Python __all__ and public | ||
| 33 | + // Buffer signatures so existing MoonEP callers are unaffected. | ||
| 34 | + m.attr("LPLUS_B_BUFFER_SYNC_ABI") = py::int_(3); | ||
| 35 | + m.attr("LPLUS_B_URMA_PUSH_ABI") = py::int_(1); | ||
| 36 | + m.attr("LPLUS_B_URMA_CONTIGUOUS_ABI") = py::int_(1); | ||
| 37 | + m.def("_lplusb_owner_push_urma_contiguous", &ascend_moonep::LPlusBOwnerPushUrmaContiguous, | ||
| 38 | + arg("local_home"), arg("weight_slots"), arg("experts_to_copy"), | ||
| 39 | + arg("rank"), arg("global_experts")); | ||
| 40 | + m.def("_lplusb_urma_push_available", &ascend_moonep::LPlusBUrmaAvailable); | ||
| 41 | + m.def("_lplusb_owner_push_urma", &ascend_moonep::LPlusBOwnerPushUrma, | ||
| 42 | + arg("source_ptrs"), arg("weight_slots"), arg("experts_to_copy"), | ||
| 43 | + arg("rank"), arg("local_experts")); | ||
| 44 | + m.attr("GRAD_REDUCE_DENSE_ABI") = py::int_(1); | ||
| 45 | + m.attr("LPLUS_B_OWNER_READY_ABI") = py::int_(1); | ||
| 46 | + m.def("_lplusb_owner_ready_init", &ascend_moonep::LPlusBOwnerReadyInit, arg("ready")); | ||
| 47 | + m.def("_lplusb_owner_push_ready", &ascend_moonep::LPlusBOwnerPushReady, | ||
| 48 | + arg("source_ptrs"), arg("weight_slots"), arg("experts_to_copy"), arg("ready"), | ||
| 49 | + arg("rank"), arg("local_experts"), arg("epoch")); | ||
| 50 | + m.def("_lplusb_owner_push", &ascend_moonep::LPlusBOwnerPush, | ||
| 51 | + arg("source_ptrs"), arg("weight_slots"), arg("experts_to_copy"), | ||
| 52 | + arg("rank"), arg("local_experts")); | ||
| 15 | 53 | ||
| 16 | m.def("launch_device_barrier_bench", &LaunchDeviceBarrierBench, | 54 | m.def("launch_device_barrier_bench", &LaunchDeviceBarrierBench, |
| 17 | arg("iterations"), arg("block_dim") = 32, | 55 | arg("iterations"), arg("block_dim") = 32, |
| @@ -151,4 +189,9 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { | |||
| 151 | &ascend_moonep::acl_shmem_barrier_all_on_stream, | 189 | &ascend_moonep::acl_shmem_barrier_all_on_stream, |
| 152 | arg("stream"), | 190 | arg("stream"), |
| 153 | "Global shmem barrier issued on the given aclrtStream"); | 191 | "Global shmem barrier issued on the given aclrtStream"); |
| 192 | + m.attr("ASYNC_STREAM_BARRIER_ABI") = py::int_(1); | ||
| 193 | + m.def("_acl_shmem_barrier_all_aiv_on_stream", | ||
| 194 | + &ascend_moonep::acl_shmem_barrier_all_aiv_on_stream, | ||
| 195 | + arg("stream"), | ||
| 196 | + "Same collective completion using a single AIV participant"); | ||
| 154 | } | 197 | } |
| @@ -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" |
| @@ -105,7 +106,15 @@ private: | |||
| 105 | 106 | ||
| 106 | class PrefetchWeight : public torch::jit::CustomClassHolder { | 107 | class PrefetchWeight : public torch::jit::CustomClassHolder { |
| 107 | public: | 108 | public: |
| 109 | + | ||
| 108 | explicit PrefetchWeight(int64_t /*local_mem_size*/) {} | 110 | explicit PrefetchWeight(int64_t /*local_mem_size*/) {} |
| 111 | + bool push_available() { return prefetch_weight_push_udma_available() == 1; } | ||
| 112 | + torch::Tensor compute_push(torch::Tensor home, torch::Tensor slots, torch::Tensor plan, | ||
| 113 | + int64_t num_experts, int64_t num_sms, int64_t instance_id, bool use_udma) { | ||
| 114 | + TORCH_CHECK(home.dim() == 3 && home.size(0) == num_experts, "invalid num_experts"); | ||
| 115 | + return ascend_moonep::ops::LaunchPrefetchPush( | ||
| 116 | + home, slots, plan, num_sms, instance_id, use_udma); | ||
| 117 | + } | ||
| 109 | 118 | ||
| 110 | void destroy() {} | 119 | void destroy() {} |
| 111 | 120 | ||
| @@ -146,7 +155,8 @@ public: | |||
| 146 | int64_t slots, | 155 | int64_t slots, |
| 147 | int64_t rank, | 156 | int64_t rank, |
| 148 | int64_t blocks, | 157 | int64_t blocks, |
| 149 | - bool use_udma) { | 158 | + bool use_udma, |
| 159 | + c10::optional<torch::Tensor> workspace = c10::nullopt) { | ||
| 150 | TORCH_CHECK(rank == aclshmem_my_pe(), | 160 | TORCH_CHECK(rank == aclshmem_my_pe(), |
| 151 | "rank does not match the active CANN-SHMEM PE"); | 161 | "rank does not match the active CANN-SHMEM PE"); |
| 152 | ascend_moonep::ops::GradReduce( | 162 | ascend_moonep::ops::GradReduce( |
| @@ -160,7 +170,8 @@ public: | |||
| 160 | slots, | 170 | slots, |
| 161 | rank, | 171 | rank, |
| 162 | blocks, | 172 | blocks, |
| 163 | - use_udma); | 173 | + use_udma, |
| 174 | + workspace.value_or(torch::Tensor())); | ||
| 164 | } | 175 | } |
| 165 | }; | 176 | }; |
| 166 | 177 | ||
| @@ -289,7 +300,8 @@ public: | |||
| 289 | int64_t world_size, | 300 | int64_t world_size, |
| 290 | int64_t rank, | 301 | int64_t rank, |
| 291 | bool use_udma, | 302 | bool use_udma, |
| 292 | - bool server_dedup) { | 303 | + bool server_dedup, |
| 304 | + int64_t num_sms = 32) { | ||
| 293 | TORCH_CHECK( | 305 | TORCH_CHECK( |
| 294 | rank == aclshmem_my_pe(), | 306 | rank == aclshmem_my_pe(), |
| 295 | "rank does not match the active CANN-SHMEM PE"); | 307 | "rank does not match the active CANN-SHMEM PE"); |
| @@ -309,7 +321,8 @@ public: | |||
| 309 | world_size, | 321 | world_size, |
| 310 | rank, | 322 | rank, |
| 311 | use_udma, | 323 | use_udma, |
| 312 | - server_dedup); | 324 | + server_dedup, |
| 325 | + num_sms); | ||
| 313 | } | 326 | } |
| 314 | 327 | ||
| 315 | void compute_profile( | 328 | void compute_profile( |
| @@ -372,7 +385,8 @@ public: | |||
| 372 | int64_t num_topk, | 385 | int64_t num_topk, |
| 373 | int64_t world_size, | 386 | int64_t world_size, |
| 374 | int64_t rank, | 387 | int64_t rank, |
| 375 | - bool use_udma) { | 388 | + bool use_udma, |
| 389 | + int64_t num_sms = 32) { | ||
| 376 | TORCH_CHECK( | 390 | TORCH_CHECK( |
| 377 | rank == aclshmem_my_pe(), | 391 | rank == aclshmem_my_pe(), |
| 378 | "rank does not match the active CANN-SHMEM PE"); | 392 | "rank does not match the active CANN-SHMEM PE"); |
| @@ -390,7 +404,8 @@ public: | |||
| 390 | num_topk, | 404 | num_topk, |
| 391 | world_size, | 405 | world_size, |
| 392 | rank, | 406 | rank, |
| 393 | - use_udma); | 407 | + use_udma, |
| 408 | + num_sms); | ||
| 394 | } | 409 | } |
| 395 | }; | 410 | }; |
| 396 | 411 | ||
| @@ -576,12 +591,20 @@ static auto prefetch_weight_registry = | |||
| 576 | torch::jit::class_<ascend_moonep::torch_classes::PrefetchWeight>("AscendMoonEP", "PrefetchWeight") | 591 | torch::jit::class_<ascend_moonep::torch_classes::PrefetchWeight>("AscendMoonEP", "PrefetchWeight") |
| 577 | .def(torch::jit::init<int64_t>()) | 592 | .def(torch::jit::init<int64_t>()) |
| 578 | .def("compute", &ascend_moonep::torch_classes::PrefetchWeight::compute) | 593 | .def("compute", &ascend_moonep::torch_classes::PrefetchWeight::compute) |
| 594 | + .def("compute_push", &ascend_moonep::torch_classes::PrefetchWeight::compute_push) | ||
| 595 | + .def("push_available", &ascend_moonep::torch_classes::PrefetchWeight::push_available) | ||
| 579 | .def("destroy", &ascend_moonep::torch_classes::PrefetchWeight::destroy); | 596 | .def("destroy", &ascend_moonep::torch_classes::PrefetchWeight::destroy); |
| 580 | 597 | ||
| 581 | static auto grad_reduce_registry = | 598 | static auto grad_reduce_registry = |
| 582 | torch::jit::class_<ascend_moonep::torch_classes::GradReduce>("AscendMoonEP", "GradReduce") | 599 | torch::jit::class_<ascend_moonep::torch_classes::GradReduce>("AscendMoonEP", "GradReduce") |
| 583 | .def(torch::jit::init<>()) | 600 | .def(torch::jit::init<>()) |
| 584 | - .def("compute", &ascend_moonep::torch_classes::GradReduce::compute); | 601 | + .def("compute", &ascend_moonep::torch_classes::GradReduce::compute, |
| 602 | + "", {torch::arg("expert_grads"), torch::arg("reduce_buffers"), | ||
| 603 | + torch::arg("experts_to_copy"), torch::arg("epn"), | ||
| 604 | + torch::arg("hidden"), torch::arg("projection"), | ||
| 605 | + torch::arg("ranks"), torch::arg("slots"), torch::arg("rank"), | ||
| 606 | + torch::arg("blocks"), torch::arg("use_udma"), | ||
| 607 | + torch::arg("workspace") = c10::IValue()}); | ||
| 585 | 608 | ||
| 586 | static auto planning_registry = | 609 | static auto planning_registry = |
| 587 | torch::jit::class_<ascend_moonep::torch_classes::Planning>("AscendMoonEP", "Planning") | 610 | torch::jit::class_<ascend_moonep::torch_classes::Planning>("AscendMoonEP", "Planning") |
| @@ -599,13 +622,26 @@ static auto planning_registry = | |||
| 599 | static auto dispatch_registry = | 622 | static auto dispatch_registry = |
| 600 | torch::jit::class_<ascend_moonep::torch_classes::Dispatch>("AscendMoonEP", "Dispatch") | 623 | torch::jit::class_<ascend_moonep::torch_classes::Dispatch>("AscendMoonEP", "Dispatch") |
| 601 | .def(torch::jit::init<>()) | 624 | .def(torch::jit::init<>()) |
| 602 | - .def("compute", &ascend_moonep::torch_classes::Dispatch::compute) | 625 | + .def("compute", &ascend_moonep::torch_classes::Dispatch::compute, |
| 626 | + "", {torch::arg("hidden_sh"), torch::arg("route_weights"), | ||
| 627 | + torch::arg("dst"), torch::arg("dup_groups"), torch::arg("dup_loffs"), | ||
| 628 | + torch::arg("dup_counts"), torch::arg("hidden_buf"), | ||
| 629 | + torch::arg("route_weights_buf"), torch::arg("sync_buffer"), | ||
| 630 | + torch::arg("num_tokens"), torch::arg("hidden_size"), torch::arg("num_topk"), | ||
| 631 | + torch::arg("world_size"), torch::arg("rank"), torch::arg("use_udma"), | ||
| 632 | + torch::arg("server_dedup"), torch::arg("num_sms") = 32}) | ||
| 603 | .def("compute_profile", &ascend_moonep::torch_classes::Dispatch::compute_profile); | 633 | .def("compute_profile", &ascend_moonep::torch_classes::Dispatch::compute_profile); |
| 604 | 634 | ||
| 605 | static auto combine_registry = | 635 | static auto combine_registry = |
| 606 | torch::jit::class_<ascend_moonep::torch_classes::Combine>("AscendMoonEP", "Combine") | 636 | torch::jit::class_<ascend_moonep::torch_classes::Combine>("AscendMoonEP", "Combine") |
| 607 | .def(torch::jit::init<>()) | 637 | .def(torch::jit::init<>()) |
| 608 | - .def("compute", &ascend_moonep::torch_classes::Combine::compute); | 638 | + .def("compute", &ascend_moonep::torch_classes::Combine::compute, |
| 639 | + "", {torch::arg("hidden_buf"), torch::arg("weight_buf"), | ||
| 640 | + torch::arg("dst"), torch::arg("dup_groups"), torch::arg("dup_loffs"), | ||
| 641 | + torch::arg("dup_counts"), torch::arg("hidden_sk_out"), | ||
| 642 | + torch::arg("route_weights_sk_out"), torch::arg("num_tokens"), | ||
| 643 | + torch::arg("hidden_size"), torch::arg("num_topk"), torch::arg("world_size"), | ||
| 644 | + torch::arg("rank"), torch::arg("use_udma"), torch::arg("num_sms") = 32}); | ||
| 609 | 645 | ||
| 610 | static auto combine_urma_registry = | 646 | static auto combine_urma_registry = |
| 611 | torch::jit::class_<ascend_moonep::torch_classes::CombineUrma>("AscendMoonEP", "CombineUrma") | 647 | torch::jit::class_<ascend_moonep::torch_classes::CombineUrma>("AscendMoonEP", "CombineUrma") |
| @@ -10,6 +10,9 @@ | |||
| 10 | 10 | ||
| 11 | extern "C" { | 11 | extern "C" { |
| 12 | 12 | ||
| 13 | +// Experimental native GR barrier; public tensor/SPI ABI remains unchanged. | ||
| 14 | +ASCEND_MOONEP_EXPORT int moonep_grad_reduce_native_barrier(void* stream); | ||
| 15 | + | ||
| 13 | ASCEND_MOONEP_EXPORT void device_barrier_bench_kernel_do( | 16 | ASCEND_MOONEP_EXPORT void device_barrier_bench_kernel_do( |
| 14 | void* stream, | 17 | void* stream, |
| 15 | int32_t iterations, | 18 | int32_t iterations, |
| @@ -210,4 +213,34 @@ ASCEND_MOONEP_EXPORT void prefetch_weight_kernel_udma_do( | |||
| 210 | int64_t num_slots, | 213 | int64_t num_slots, |
| 211 | int64_t block_dim); | 214 | int64_t block_dim); |
| 212 | 215 | ||
| 216 | +ASCEND_MOONEP_EXPORT int moonep_lplusb_owner_push( | ||
| 217 | + void* stream, | ||
| 218 | + const uint64_t* source_ptrs, | ||
| 219 | + void* weight_slots, | ||
| 220 | + const int32_t* experts_to_copy, | ||
| 221 | + int64_t row_elements, | ||
| 222 | + int32_t local_experts, | ||
| 223 | + int32_t ranks, | ||
| 224 | + int32_t slots, | ||
| 225 | + int32_t rank, | ||
| 226 | + int32_t blocks); | ||
| 227 | + | ||
| 228 | +ASCEND_MOONEP_EXPORT int moonep_lplusb_owner_ready( | ||
| 229 | + void* stream, int32_t* ready, const int32_t* experts_to_copy, | ||
| 230 | + int32_t local_experts, int32_t ranks, int32_t slots, int32_t rank, int32_t epoch); | ||
| 231 | + | ||
| 232 | + | ||
| 233 | + | ||
| 234 | +ASCEND_MOONEP_EXPORT int prefetch_pointer_push_udma_available(); | ||
| 235 | +ASCEND_MOONEP_EXPORT int moonep_prefetch_barrier_vec(void* stream); | ||
| 236 | +ASCEND_MOONEP_EXPORT int moonep_async_stream_barrier_vec(void* stream); | ||
| 237 | +ASCEND_MOONEP_EXPORT int moonep_prefetch_pointer_push_udma( | ||
| 238 | + void* stream, uint8_t* pointers, uint8_t* slots, uint8_t* plan, | ||
| 239 | + int64_t experts, int64_t row_elements, int64_t num_slots); | ||
| 240 | + | ||
| 241 | +ASCEND_MOONEP_EXPORT int prefetch_weight_push_udma_available(); | ||
| 242 | +ASCEND_MOONEP_EXPORT int prefetch_weight_push_udma_do( | ||
| 243 | + void* stream, uint8_t* source, uint8_t* slots, uint8_t* plan, | ||
| 244 | + int64_t experts, int64_t row_elements, int64_t num_slots); | ||
| 245 | + | ||
| 213 | } // extern "C" | 246 | } // extern "C" |
| @@ -66,7 +66,7 @@ struct alignas(8) MoonEPCombineTilingData { | |||
| 66 | uint32_t num_tokens; // S | 66 | uint32_t num_tokens; // S |
| 67 | uint32_t hidden; // H | 67 | uint32_t hidden; // H |
| 68 | uint32_t num_topk; // K | 68 | uint32_t num_topk; // K |
| 69 | - uint32_t block_dim; // fixed 32 AIV (host always writes 32) | 69 | + uint32_t block_dim; // MTE AIV launch width from num_sms |
| 70 | uint32_t with_weight; // 1: gather weights → [S,K]; 0: skip | 70 | uint32_t with_weight; // 1: gather weights → [S,K]; 0: skip |
| 71 | uint32_t reserved; | 71 | uint32_t reserved; |
| 72 | }; | 72 | }; |
| @@ -90,8 +90,12 @@ struct alignas(8) MoonEPDispatchTilingData { | |||
| 90 | uint32_t rank; | 90 | uint32_t rank; |
| 91 | uint32_t with_weights; | 91 | uint32_t with_weights; |
| 92 | uint32_t server_dedup; | 92 | uint32_t server_dedup; |
| 93 | + uint32_t block_dim; // MTE only; occupies the former tail padding | ||
| 93 | }; | 94 | }; |
| 94 | 95 | ||
| 96 | +static_assert(sizeof(MoonEPDispatchTilingData) == 32, "dispatch tiling ABI must remain 32 bytes"); | ||
| 97 | +static_assert(sizeof(MoonEPCombineTilingData) == 32, "combine tiling ABI must remain 32 bytes"); | ||
| 98 | + | ||
| 95 | // Udma dispatch profile ABI (mirrors the UBMEM template-<bool Profile> pattern | 99 | // Udma dispatch profile ABI (mirrors the UBMEM template-<bool Profile> pattern |
| 96 | // from the timing branch): moonep_dispatch_udma_profile_kernel writes each AIV's | 100 | // from the timing branch): moonep_dispatch_udma_profile_kernel writes each AIV's |
| 97 | // metrics as an int64 row into a [kMoonEPAivNum, kMoonEPDispatchUdmaProfileFields] | 101 | // metrics as an int64 row into a [kMoonEPAivNum, kMoonEPDispatchUdmaProfileFields] |
| @@ -0,0 +1,159 @@ | |||
| 1 | +// SPDX-License-Identifier: Apache-2.0 | ||
| 2 | +// Shared by the standalone contiguous-home and provider pointer-source bindings. | ||
| 3 | +// No allocations, SHMEM initialization, or custom queue protocol belong here. | ||
| 4 | +#pragma once | ||
| 5 | +#include <cstdint> | ||
| 6 | +#include "kernel_operator.h" | ||
| 7 | +#include "shmem.h" | ||
| 8 | +#include "opdev/bfloat16.h" | ||
| 9 | + | ||
| 10 | +namespace moonep_urma_push { | ||
| 11 | +using namespace AscendC; | ||
| 12 | +constexpr int32_t kUdmaCannShmemInternalUbStartBytes = 188 * 1024; | ||
| 13 | +constexpr int64_t kUdmaPrefetchUbScratchOffset = 64; | ||
| 14 | +constexpr int32_t kUdmaUbExpertTabOffset = kUdmaPrefetchUbScratchOffset; | ||
| 15 | +constexpr int32_t kUdmaUbAlignBytes = 32; | ||
| 16 | +constexpr int64_t kUdmaMaxTransferBytes = 256LL * 1024 * 1024; | ||
| 17 | +constexpr uint32_t kUdmaLocalCopyMaxBytes = 65504; | ||
| 18 | +constexpr uint32_t kUdmaWqeElements = 256; | ||
| 19 | + | ||
| 20 | +__aicore__ inline int32_t UdmaAlignUp(int32_t value, int32_t alignment) | ||
| 21 | +{ | ||
| 22 | + return (value + alignment - 1) / alignment * alignment; | ||
| 23 | +} | ||
| 24 | + | ||
| 25 | +__aicore__ inline int32_t UdmaAivWorkerIndex() | ||
| 26 | +{ | ||
| 27 | + const int32_t sub_blocks = static_cast<int32_t>(GetSubBlockNum()); | ||
| 28 | + return sub_blocks > 0 ? | ||
| 29 | + static_cast<int32_t>(GetBlockIdx()) / sub_blocks : 0; | ||
| 30 | +} | ||
| 31 | + | ||
| 32 | +__aicore__ inline void UdmaCopyLocalExpertChunk( | ||
| 33 | + __gm__ bfloat16_t* destination, | ||
| 34 | + __gm__ bfloat16_t* source, | ||
| 35 | + uint32_t elements, | ||
| 36 | + __ubuf__ bfloat16_t* ub) | ||
| 37 | +{ | ||
| 38 | + GlobalTensor<bfloat16_t> local_src; | ||
| 39 | + GlobalTensor<bfloat16_t> local_dst; | ||
| 40 | + local_src.SetGlobalBuffer(source, elements); | ||
| 41 | + local_dst.SetGlobalBuffer(destination, elements); | ||
| 42 | + | ||
| 43 | + LocalTensor<bfloat16_t> local_ub; | ||
| 44 | + local_ub.address_.logicPos = static_cast<uint8_t>(TPosition::VECIN); | ||
| 45 | + local_ub.address_.bufferAddr = reinterpret_cast<uint64_t>(ub); | ||
| 46 | + | ||
| 47 | + for (uint32_t copied = 0; copied < elements;) { | ||
| 48 | + uint32_t copy_elems = elements - copied; | ||
| 49 | + const uint32_t max_elems = kUdmaLocalCopyMaxBytes / sizeof(bfloat16_t); | ||
| 50 | + if (copy_elems > max_elems) { | ||
| 51 | + copy_elems = max_elems; | ||
| 52 | + } | ||
| 53 | + const DataCopyExtParams copy_params{ | ||
| 54 | + 1, static_cast<uint32_t>(copy_elems * sizeof(bfloat16_t)), 0, 0, 0}; | ||
| 55 | + const DataCopyPadExtParams<bfloat16_t> pad_params{false, 0, 0, 0}; | ||
| 56 | + DataCopyPad(local_ub, local_src[copied], copy_params, pad_params); | ||
| 57 | + SetFlag<HardEvent::MTE2_MTE3>(EVENT_ID1); | ||
| 58 | + WaitFlag<HardEvent::MTE2_MTE3>(EVENT_ID1); | ||
| 59 | + DataCopyPad(local_dst[copied], local_ub, copy_params); | ||
| 60 | + SetFlag<HardEvent::MTE3_MTE2>(EVENT_ID1); | ||
| 61 | + WaitFlag<HardEvent::MTE3_MTE2>(EVENT_ID1); | ||
| 62 | + copied += copy_elems; | ||
| 63 | + } | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | + | ||
| 67 | +template<bool PointerSource> | ||
| 68 | +__aicore__ inline void Run( | ||
| 69 | + GM_ADDR source_addr, GM_ADDR slots_addr, GM_ADDR plan_addr, | ||
| 70 | + int64_t experts, int64_t row_elements, int64_t slots) | ||
| 71 | +{ | ||
| 72 | + if ASCEND_IS_AIC { return; } | ||
| 73 | + if (UdmaAivWorkerIndex() != 0) { return; } | ||
| 74 | + auto* home = reinterpret_cast<__gm__ bfloat16_t*>(source_addr); | ||
| 75 | + auto* pointers = reinterpret_cast<__gm__ uint64_t*>(source_addr); | ||
| 76 | + auto* destination = reinterpret_cast<__gm__ bfloat16_t*>(slots_addr); | ||
| 77 | + auto* plan = reinterpret_cast<__gm__ int32_t*>(plan_addr); | ||
| 78 | + const int32_t ranks = aclshmem_n_pes(); | ||
| 79 | + const int32_t rank = aclshmem_my_pe(); | ||
| 80 | + const int64_t epn = (experts + ranks - 1) / ranks; | ||
| 81 | + const int32_t data_offset = UdmaAlignUp( | ||
| 82 | + kUdmaUbExpertTabOffset + UdmaAlignUp( | ||
| 83 | + static_cast<int32_t>(2 * slots * sizeof(int32_t)), 32), 32); | ||
| 84 | + TPipe pipe; | ||
| 85 | + TBuf<TPosition::VECOUT> tab_buf, wqe_buf, ub_buf; | ||
| 86 | + pipe.InitBuffer(tab_buf, data_offset); | ||
| 87 | + pipe.InitBuffer(wqe_buf, kUdmaWqeElements * sizeof(bfloat16_t)); | ||
| 88 | + pipe.InitBuffer(ub_buf, kUdmaCannShmemInternalUbStartBytes - | ||
| 89 | + data_offset - kUdmaWqeElements * sizeof(bfloat16_t)); | ||
| 90 | + auto tab = tab_buf.Get<int32_t>(); | ||
| 91 | + auto wqe = wqe_buf.Get<bfloat16_t>(); | ||
| 92 | + auto local = ub_buf.Get<bfloat16_t>(); | ||
| 93 | + auto* expert_tab = reinterpret_cast<__ubuf__ int32_t*>(tab.GetPhyAddr()); | ||
| 94 | + auto* slot_tab = expert_tab + slots; | ||
| 95 | + auto* scratch = reinterpret_cast<__ubuf__ bfloat16_t*>(wqe.GetPhyAddr()); | ||
| 96 | + auto* ub = reinterpret_cast<__ubuf__ bfloat16_t*>(local.GetPhyAddr()); | ||
| 97 | + Duplicate(wqe, static_cast<bfloat16_t>(0), kUdmaWqeElements); | ||
| 98 | + // SDK WQE construction uses scalar stores through the same raw UB pointer. | ||
| 99 | + // Order the vector clear before those stores; Tensor auto-sync cannot | ||
| 100 | + // infer this pointer handoff. SDK and local-copy events use IDs 0 and 1. | ||
| 101 | + SetFlag<HardEvent::V_S>(EVENT_ID2); | ||
| 102 | + WaitFlag<HardEvent::V_S>(EVENT_ID2); | ||
| 103 | + // Validate the complete plan before this owner submits any payload. | ||
| 104 | + for (int64_t i = 0; i < ranks * slots; ++i) { | ||
| 105 | + if (plan[i] < -1 || plan[i] >= experts) { | ||
| 106 | + AscendC::printf("URMA_PUSH_INVALID_EXPERT rank=%d entry=%ld expert=%d\n", | ||
| 107 | + rank, i, plan[i]); | ||
| 108 | + trap(); | ||
| 109 | + } | ||
| 110 | + } | ||
| 111 | + const int64_t max_elements = kUdmaMaxTransferBytes / sizeof(bfloat16_t); | ||
| 112 | + for (int32_t peer = 0; peer < ranks; ++peer) { | ||
| 113 | + int64_t active = 0; | ||
| 114 | + for (int64_t slot = 0; slot < slots; ++slot) { | ||
| 115 | + const int32_t expert = plan[peer * slots + slot]; | ||
| 116 | + if (expert >= 0 && expert / epn == rank) { | ||
| 117 | + expert_tab[active] = expert % epn; | ||
| 118 | + slot_tab[active++] = slot; | ||
| 119 | + } | ||
| 120 | + } | ||
| 121 | + for (int64_t i = 0; i < active; ++i) { | ||
| 122 | + __gm__ bfloat16_t* source; | ||
| 123 | + if constexpr (PointerSource) { | ||
| 124 | + source = reinterpret_cast<__gm__ bfloat16_t*>(pointers[expert_tab[i]]); | ||
| 125 | + if (source == nullptr) { | ||
| 126 | + AscendC::printf("URMA_PUSH_NULL_SOURCE rank=%d expert=%d\n", | ||
| 127 | + rank, expert_tab[i]); | ||
| 128 | + trap(); | ||
| 129 | + } | ||
| 130 | + } else { | ||
| 131 | + source = home + expert_tab[i] * row_elements; | ||
| 132 | + } | ||
| 133 | + for (int64_t offset = 0; offset < row_elements; offset += max_elements) { | ||
| 134 | + const uint32_t count = static_cast<uint32_t>( | ||
| 135 | + row_elements - offset < max_elements ? row_elements - offset : max_elements); | ||
| 136 | + auto* dst = destination + slot_tab[i] * row_elements + offset; | ||
| 137 | + if (peer == rank) { | ||
| 138 | + UdmaCopyLocalExpertChunk(dst, source + offset, count, ub); | ||
| 139 | + } else { | ||
| 140 | + aclshmemx_udma_put_nbi(dst, source + offset, scratch, | ||
| 141 | + count, peer, EVENT_ID0); | ||
| 142 | + } | ||
| 143 | + } | ||
| 144 | + } | ||
| 145 | + } | ||
| 146 | + // One AIV issues all peers before waiting for their payloads. The SDK has | ||
| 147 | + // finished publishing each UB-staged WQE before put_nbi returns; the WQE | ||
| 148 | + // refers to the retained GM source, not this reusable UB scratch. Queue | ||
| 149 | + // credit and any overflow drain remain owned by the default SDK path. | ||
| 150 | + // No peer-visible publication is permitted until every required quiet has | ||
| 151 | + // returned. The caller's post barrier and consumer events are unchanged. | ||
| 152 | + for (int32_t peer = 0; peer < ranks; ++peer) { | ||
| 153 | + if (peer != rank) { | ||
| 154 | + aclshmemx_udma_quiet(peer); | ||
| 155 | + } | ||
| 156 | + } | ||
| 157 | + aclshmem_quiet(); | ||
| 158 | +} | ||
| 159 | +} // namespace moonep_urma_push | ||
| @@ -0,0 +1,35 @@ | |||
| 1 | +// SPDX-License-Identifier: Apache-2.0 | ||
| 2 | + | ||
| 3 | +#include <cstdint> | ||
| 4 | +#include <cstdlib> | ||
| 5 | +#include <cstring> | ||
| 6 | + | ||
| 7 | +#include "acl/acl.h" | ||
| 8 | +#include "kernel_operator.h" | ||
| 9 | +#include "shmem.h" | ||
| 10 | + | ||
| 11 | +#include "ascend_moonep/kernels/launch.h" | ||
| 12 | + | ||
| 13 | +using namespace AscendC; | ||
| 14 | + | ||
| 15 | +// Canonical MTE and UDMA GradReduce use one AIV for their WORLD barriers in AIV mode. | ||
| 16 | +extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ | ||
| 17 | +void MoonEPGradReduceBarrierAiv(uint64_t ffts_config) | ||
| 18 | +{ | ||
| 19 | + util_set_ffts_config(ffts_config); | ||
| 20 | + aclshmemx_barrier_all_vec(); | ||
| 21 | +} | ||
| 22 | + | ||
| 23 | +extern "C" ASCEND_MOONEP_EXPORT int moonep_grad_reduce_native_barrier(void* stream) | ||
| 24 | +{ | ||
| 25 | + if (stream == nullptr) return ACL_ERROR_INVALID_PARAM; | ||
| 26 | + const char* mode = std::getenv("MOONEP_GRAD_REDUCE_NATIVE_BARRIER_MODE"); | ||
| 27 | + if (mode == nullptr || std::strcmp(mode, "mixed") == 0) { | ||
| 28 | + aclshmemx_barrier_all_on_stream(stream); | ||
| 29 | + } else if (std::strcmp(mode, "aiv") == 0) { | ||
| 30 | + MoonEPGradReduceBarrierAiv<<<1, nullptr, stream>>>(shmemx_get_ffts_config()); | ||
| 31 | + } else { | ||
| 32 | + return ACL_ERROR_INVALID_PARAM; | ||
| 33 | + } | ||
| 34 | + return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL); | ||
| 35 | +} | ||
| @@ -0,0 +1,167 @@ | |||
| 1 | +// Private L+B provider kernels. These symbols are deliberately absent from | ||
| 2 | +// npu_patch.__all__; MindSpeed reaches them through the private extension. | ||
| 3 | + | ||
| 4 | +#include <cstdint> | ||
| 5 | + | ||
| 6 | +#include "acl/acl.h" | ||
| 7 | +#include "kernel_operator.h" | ||
| 8 | +#include "shmem.h" | ||
| 9 | + | ||
| 10 | +#include "ascend_moonep/kernels/launch.h" | ||
| 11 | +#include "opdev/bfloat16.h" | ||
| 12 | + | ||
| 13 | +using namespace AscendC; | ||
| 14 | + | ||
| 15 | +namespace { | ||
| 16 | + | ||
| 17 | +constexpr int32_t kLPlusBUbBytes = 188 * 1024; | ||
| 18 | +constexpr uint64_t kLPlusBUbOffset = 64; | ||
| 19 | + | ||
| 20 | +__aicore__ inline int32_t LPlusBWorkerIndex() | ||
| 21 | +{ | ||
| 22 | + const int32_t sub_blocks = static_cast<int32_t>(GetSubBlockNum()); | ||
| 23 | + return sub_blocks > 0 ? static_cast<int32_t>(GetBlockIdx()) / sub_blocks : 0; | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +__aicore__ inline int64_t LPlusBCeilDiv(int64_t value, int64_t divisor) | ||
| 27 | +{ | ||
| 28 | + return (value + divisor - 1) / divisor; | ||
| 29 | +} | ||
| 30 | + | ||
| 31 | +} // namespace | ||
| 32 | + | ||
| 33 | +extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ | ||
| 34 | +void MoonEPLPlusBOwnerPush( | ||
| 35 | + GM_ADDR source_ptrs_addr, | ||
| 36 | + GM_ADDR weight_slots_addr, | ||
| 37 | + GM_ADDR experts_to_copy_addr, | ||
| 38 | + int64_t row_elements, | ||
| 39 | + int32_t local_experts, | ||
| 40 | + int32_t ranks, | ||
| 41 | + int32_t slots, | ||
| 42 | + int32_t rank) | ||
| 43 | +{ | ||
| 44 | + if ASCEND_IS_AIC { | ||
| 45 | + return; | ||
| 46 | + } | ||
| 47 | + auto* source_ptrs = reinterpret_cast<__gm__ uint64_t*>(source_ptrs_addr); | ||
| 48 | + auto* weight_slots = reinterpret_cast<__gm__ bfloat16_t*>(weight_slots_addr); | ||
| 49 | + auto* plan = reinterpret_cast<__gm__ int32_t*>(experts_to_copy_addr); | ||
| 50 | + const int32_t block = LPlusBWorkerIndex(); | ||
| 51 | + const int32_t block_count = GetBlockNum(); | ||
| 52 | + const int32_t tile_elements = (kLPlusBUbBytes - static_cast<int32_t>(kLPlusBUbOffset)) / | ||
| 53 | + static_cast<int32_t>(sizeof(bfloat16_t)) / 2; | ||
| 54 | + const int64_t chunks = LPlusBCeilDiv(row_elements, tile_elements); | ||
| 55 | + const int64_t entries = static_cast<int64_t>(ranks) * slots; | ||
| 56 | + const int32_t local_begin = rank * local_experts; | ||
| 57 | + auto* ping = reinterpret_cast<__ubuf__ bfloat16_t*>(kLPlusBUbOffset); | ||
| 58 | + auto* pong = ping + tile_elements; | ||
| 59 | + int32_t buffer = 0; | ||
| 60 | + SetFlag<HardEvent::MTE3_MTE2>(EVENT_ID0); | ||
| 61 | + SetFlag<HardEvent::MTE3_MTE2>(EVENT_ID1); | ||
| 62 | + for (int64_t task = block; task < entries * chunks; task += block_count) { | ||
| 63 | + const int64_t entry = task / chunks; | ||
| 64 | + const int64_t chunk = task % chunks; | ||
| 65 | + const int32_t expert = plan[entry]; | ||
| 66 | + if (expert < local_begin || expert >= local_begin + local_experts) { | ||
| 67 | + continue; | ||
| 68 | + } | ||
| 69 | + const int32_t local_expert = expert - local_begin; | ||
| 70 | + const int32_t destination_pe = static_cast<int32_t>(entry / slots); | ||
| 71 | + const int32_t destination_slot = static_cast<int32_t>(entry % slots); | ||
| 72 | + const int64_t begin = chunk * tile_elements; | ||
| 73 | + const int32_t elements = static_cast<int32_t>( | ||
| 74 | + row_elements - begin < tile_elements ? row_elements - begin : tile_elements); | ||
| 75 | + const TEventID event = buffer == 0 ? EVENT_ID0 : EVENT_ID1; | ||
| 76 | + auto* ub = buffer == 0 ? ping : pong; | ||
| 77 | + WaitFlag<HardEvent::MTE3_MTE2>(event); | ||
| 78 | + auto* src = reinterpret_cast<__gm__ bfloat16_t*>(source_ptrs[local_expert]) + begin; | ||
| 79 | + auto* dst = weight_slots + static_cast<int64_t>(destination_slot) * row_elements + begin; | ||
| 80 | + aclshmemx_mte_put_nbi( | ||
| 81 | + dst, src, ub, | ||
| 82 | + static_cast<uint32_t>(tile_elements * sizeof(bfloat16_t)), | ||
| 83 | + static_cast<uint32_t>(elements), destination_pe, event); | ||
| 84 | + SetFlag<HardEvent::MTE3_MTE2>(event); | ||
| 85 | + buffer = 1 - buffer; | ||
| 86 | + } | ||
| 87 | + WaitFlag<HardEvent::MTE3_MTE2>(EVENT_ID0); | ||
| 88 | + WaitFlag<HardEvent::MTE3_MTE2>(EVENT_ID1); | ||
| 89 | + aclshmem_quiet(); | ||
| 90 | +} | ||
| 91 | + | ||
| 92 | +extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ | ||
| 93 | +void MoonEPLPlusBOwnerReady( | ||
| 94 | + GM_ADDR ready_addr, GM_ADDR experts_to_copy_addr, | ||
| 95 | + int32_t local_experts, int32_t ranks, int32_t slots, int32_t rank, int32_t epoch) | ||
| 96 | +{ | ||
| 97 | + if ASCEND_IS_AIC { | ||
| 98 | + return; | ||
| 99 | + } | ||
| 100 | + // One publisher, launched AFTER every worker of OwnerPush has completed. | ||
| 101 | + // Publishing from one worker inside OwnerPush would race the other workers. | ||
| 102 | + if (GetBlockIdx() != 0) { | ||
| 103 | + return; | ||
| 104 | + } | ||
| 105 | + constexpr int32_t stride = 64 / sizeof(int32_t); | ||
| 106 | + static_assert(SCALAR_DATA_CACHELINE_SIZE == 64, "owner-ready signal ABI needs 64-byte lines"); | ||
| 107 | + auto* ready = reinterpret_cast<__gm__ int32_t*>(ready_addr); | ||
| 108 | + auto* plan = reinterpret_cast<__gm__ int32_t*>(experts_to_copy_addr); | ||
| 109 | + // Publish before ANY wait, even for an empty/local-only receiver. Each | ||
| 110 | + // owner has its own cache line so peer SET/flush cannot clobber another. | ||
| 111 | + for (int32_t pe = 0; pe < ranks; ++pe) { | ||
| 112 | + if (pe != rank) { | ||
| 113 | + aclshmemx_signal_op(ready + rank * stride, epoch, ACLSHMEM_SIGNAL_SET, pe); | ||
| 114 | + } | ||
| 115 | + } | ||
| 116 | + aclshmem_quiet(); | ||
| 117 | + for (int32_t owner = 0; owner < ranks; ++owner) { | ||
| 118 | + if (owner == rank) { | ||
| 119 | + continue; | ||
| 120 | + } | ||
| 121 | + for (int32_t slot = 0; slot < slots; ++slot) { | ||
| 122 | + const int32_t expert = plan[static_cast<int64_t>(rank) * slots + slot]; | ||
| 123 | + if (expert >= 0 && expert / local_experts == owner) { | ||
| 124 | + aclshmem_signal_wait_until(ready + owner * stride, ACLSHMEM_CMP_EQ, epoch); | ||
| 125 | + break; | ||
| 126 | + } | ||
| 127 | + } | ||
| 128 | + } | ||
| 129 | + aclshmem_quiet(); | ||
| 130 | +} | ||
| 131 | + | ||
| 132 | +extern "C" ASCEND_MOONEP_EXPORT int moonep_lplusb_owner_push( | ||
| 133 | + void* stream, const uint64_t* source_ptrs, void* weight_slots, | ||
| 134 | + const int32_t* experts_to_copy, int64_t row_elements, int32_t local_experts, | ||
| 135 | + int32_t ranks, int32_t slots, int32_t rank, int32_t blocks) | ||
| 136 | +{ | ||
| 137 | + if (stream == nullptr || source_ptrs == nullptr || weight_slots == nullptr || | ||
| 138 | + experts_to_copy == nullptr || row_elements <= 0 || local_experts <= 0 || | ||
| 139 | + ranks <= 0 || slots <= 0 || rank < 0 || rank >= ranks || blocks <= 0 || | ||
| 140 | + ranks != aclshmem_n_pes()) { | ||
| 141 | + return ACL_ERROR_INVALID_PARAM; | ||
| 142 | + } | ||
| 143 | + (void)aclrtGetLastError(ACL_RT_THREAD_LEVEL); | ||
| 144 | + MoonEPLPlusBOwnerPush<<<blocks, nullptr, stream>>>( | ||
| 145 | + reinterpret_cast<uint8_t*>(const_cast<uint64_t*>(source_ptrs)), | ||
| 146 | + reinterpret_cast<uint8_t*>(weight_slots), | ||
| 147 | + reinterpret_cast<uint8_t*>(const_cast<int32_t*>(experts_to_copy)), | ||
| 148 | + row_elements, local_experts, ranks, slots, rank); | ||
| 149 | + return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL); | ||
| 150 | +} | ||
| 151 | + | ||
| 152 | +extern "C" ASCEND_MOONEP_EXPORT int moonep_lplusb_owner_ready( | ||
| 153 | + void* stream, int32_t* ready, const int32_t* experts_to_copy, | ||
| 154 | + int32_t local_experts, int32_t ranks, int32_t slots, int32_t rank, int32_t epoch) | ||
| 155 | +{ | ||
| 156 | + if (stream == nullptr || ready == nullptr || experts_to_copy == nullptr || | ||
| 157 | + local_experts <= 0 || ranks <= 0 || slots <= 0 || rank < 0 || rank >= ranks || | ||
| 158 | + epoch <= 0 || ranks != aclshmem_n_pes()) { | ||
| 159 | + return ACL_ERROR_INVALID_PARAM; | ||
| 160 | + } | ||
| 161 | + (void)aclrtGetLastError(ACL_RT_THREAD_LEVEL); | ||
| 162 | + MoonEPLPlusBOwnerReady<<<1, nullptr, stream>>>( | ||
| 163 | + reinterpret_cast<uint8_t*>(ready), | ||
| 164 | + reinterpret_cast<uint8_t*>(const_cast<int32_t*>(experts_to_copy)), | ||
| 165 | + local_experts, ranks, slots, rank, epoch); | ||
| 166 | + return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL); | ||
| 167 | +} | ||
| @@ -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). |
| @@ -618,6 +617,7 @@ extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ void moonep_dispa | |||
| 618 | uint32_t with_weights = tiling.with_weights; | 617 | uint32_t with_weights = tiling.with_weights; |
| 619 | 618 | ||
| 620 | uint32_t core_idx = get_block_idx(); | 619 | uint32_t core_idx = get_block_idx(); |
| 620 | + uint32_t core_count = get_block_num(); | ||
| 621 | 621 | ||
| 622 | LocalTensor<uint8_t> ub_base; | 622 | LocalTensor<uint8_t> ub_base; |
| 623 | ub_base.address_.logicPos = static_cast<uint8_t>(TPosition::VECIN); | 623 | ub_base.address_.logicPos = static_cast<uint8_t>(TPosition::VECIN); |
| @@ -635,7 +635,7 @@ extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ void moonep_dispa | |||
| 635 | hidden_buf_gm, route_weights_buf_gm, | 635 | hidden_buf_gm, route_weights_buf_gm, |
| 636 | S, H, K, tiling.R, NvS, | 636 | S, H, K, tiling.R, NvS, |
| 637 | with_weights != 0, | 637 | with_weights != 0, |
| 638 | - core_idx, kMoonEPAivNum); | 638 | + core_idx, core_count); |
| 639 | 639 | ||
| 640 | aclshmem_quiet(); | 640 | aclshmem_quiet(); |
| 641 | aclshmemx_barrier_all_vec(); | 641 | aclshmemx_barrier_all_vec(); |
| @@ -644,7 +644,7 @@ extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ void moonep_dispa | |||
| 644 | 644 | ||
| 645 | PlanEpiloguePhase<bf16_t>( | 645 | PlanEpiloguePhase<bf16_t>( |
| 646 | ub_base, hbuf, dgrp, dloff, dcnt, | 646 | ub_base, hbuf, dgrp, dloff, dcnt, |
| 647 | - H, NvS, core_idx, kMoonEPAivNum); | 647 | + H, NvS, core_idx, core_count); |
| 648 | } | 648 | } |
| 649 | 649 | ||
| 650 | 650 | ||
| @@ -667,7 +667,7 @@ void moonep_dispatch_kernel_do( | |||
| 667 | { | 667 | { |
| 668 | auto* td = reinterpret_cast<ascend_moonep::MoonEPDispatchTilingData*>(tiling_host); | 668 | auto* td = reinterpret_cast<ascend_moonep::MoonEPDispatchTilingData*>(tiling_host); |
| 669 | 669 | ||
| 670 | - moonep_dispatch_kernel<<<kMoonEPAivNum, nullptr, stream>>>( | 670 | + moonep_dispatch_kernel<<<td->block_dim, nullptr, stream>>>( |
| 671 | hidden_sh, | 671 | hidden_sh, |
| 672 | route_weights, | 672 | route_weights, |
| 673 | dst, | 673 | dst, |
| @@ -347,27 +347,28 @@ void MoonEPShmemGradReduceFused( | |||
| 347 | } | 347 | } |
| 348 | } | 348 | } |
| 349 | 349 | ||
| 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(); | 350 | aclshmem_quiet(); |
| 353 | - // This kernel is [[core_ratio(0, 1)]] and launches AIV workers only. | ||
| 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(); | ||
| 358 | - | ||
| 359 | - ClearLocalSlots( | ||
| 360 | - reduce, | ||
| 361 | - plan, | ||
| 362 | - accum_ub, | ||
| 363 | - matrix, | ||
| 364 | - slots, | ||
| 365 | - rank, | ||
| 366 | - block, | ||
| 367 | - block_count); | ||
| 368 | } | 351 | } |
| 369 | 352 | ||
| 370 | -extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce( | 353 | +// The host stream barrier separates all peer reads from local slot reuse. |
| 354 | +// Keep the collective outside these vector-only compute kernels. | ||
| 355 | +extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ | ||
| 356 | +void MoonEPShmemGradReduceClearValidSlots( | ||
| 357 | + uint64_t ffts_addr, GM_ADDR reduce_buffers_addr, | ||
| 358 | + GM_ADDR experts_to_copy_addr, int64_t matrix, int32_t slots, int32_t rank) | ||
| 359 | +{ | ||
| 360 | + util_set_ffts_config(ffts_addr); | ||
| 361 | + if ASCEND_IS_AIC { | ||
| 362 | + return; | ||
| 363 | + } | ||
| 364 | + auto* reduce = reinterpret_cast<__gm__ float*>(reduce_buffers_addr); | ||
| 365 | + auto* plan = reinterpret_cast<__gm__ int32_t*>(experts_to_copy_addr); | ||
| 366 | + auto* zero_ub = reinterpret_cast<__ubuf__ float*>(kUbScratchOffset); | ||
| 367 | + ClearLocalSlots(reduce, plan, zero_ub, matrix, slots, rank, | ||
| 368 | + GetWorkerIndex(), GetBlockNum()); | ||
| 369 | +} | ||
| 370 | + | ||
| 371 | +static int LaunchGradReduce( | ||
| 371 | void* stream, | 372 | void* stream, |
| 372 | void* expert_grads, | 373 | void* expert_grads, |
| 373 | void* reduce_buffers, | 374 | void* reduce_buffers, |
| @@ -405,5 +406,28 @@ extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce( | |||
| 405 | ranks, | 406 | ranks, |
| 406 | slots, | 407 | slots, |
| 407 | rank); | 408 | rank); |
| 409 | + auto status = aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL); | ||
| 410 | + if (status != ACL_SUCCESS) { | ||
| 411 | + return status; | ||
| 412 | + } | ||
| 413 | + status = moonep_grad_reduce_native_barrier(stream); | ||
| 414 | + if (status != ACL_SUCCESS) { | ||
| 415 | + return status; | ||
| 416 | + } | ||
| 417 | + MoonEPShmemGradReduceClearValidSlots<<<blocks, nullptr, stream>>>( | ||
| 418 | + shmemx_get_ffts_config(), | ||
| 419 | + reinterpret_cast<std::uint8_t*>(reduce_buffers), | ||
| 420 | + reinterpret_cast<std::uint8_t*>(const_cast<int32_t*>(experts_to_copy)), | ||
| 421 | + static_cast<int64_t>(hidden) * projection, slots, rank); | ||
| 408 | return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL); | 422 | return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL); |
| 409 | } | 423 | } |
| 424 | + | ||
| 425 | +extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce( | ||
| 426 | + void* stream, void* expert_grads, void* reduce_buffers, | ||
| 427 | + const int32_t* experts_to_copy, int32_t epn, int32_t hidden, | ||
| 428 | + int32_t projection, int32_t ranks, int32_t slots, int32_t rank, | ||
| 429 | + int32_t blocks) | ||
| 430 | +{ | ||
| 431 | + return LaunchGradReduce(stream, expert_grads, reduce_buffers, experts_to_copy, | ||
| 432 | + epn, hidden, projection, ranks, slots, rank, blocks); | ||
| 433 | +} | ||
| @@ -53,6 +53,21 @@ __aicore__ inline void ComputeSingle( | |||
| 53 | 53 | ||
| 54 | using namespace moonEP::gradReduce; | 54 | using namespace moonEP::gradReduce; |
| 55 | 55 | ||
| 56 | +extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ | ||
| 57 | +void MoonEPShmemClearValidGradSlots( | ||
| 58 | + GM_ADDR reduce_addr, GM_ADDR plan_addr, int64_t matrix, int32_t slots, int32_t rank) | ||
| 59 | +{ | ||
| 60 | + AscendC::TPipe pipe; // experimental explicit InitOutput resource lifetime | ||
| 61 | + auto* plan = reinterpret_cast<__gm__ int32_t*>(plan_addr); | ||
| 62 | + GlobalTensor<float> reduce; | ||
| 63 | + reduce.SetGlobalBuffer(reinterpret_cast<__gm__ float*>(reduce_addr)); | ||
| 64 | + for (int32_t slot = 0; slot < slots; ++slot) { | ||
| 65 | + if (plan[static_cast<int64_t>(rank) * slots + slot] >= 0) { | ||
| 66 | + InitOutput(reduce[static_cast<int64_t>(slot) * matrix], matrix, 0.0f); | ||
| 67 | + } | ||
| 68 | + } | ||
| 69 | +} | ||
| 70 | + | ||
| 56 | extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ | 71 | extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ |
| 57 | void MoonEPShmemGradReduceUdmaFused( | 72 | void MoonEPShmemGradReduceUdmaFused( |
| 58 | uint64_t ffts_addr, | 73 | uint64_t ffts_addr, |
| @@ -101,7 +116,6 @@ void MoonEPShmemGradReduceUdmaFused( | |||
| 101 | if (dstRankIdx != rank) { | 116 | if (dstRankIdx != rank) { |
| 102 | continue; | 117 | continue; |
| 103 | } | 118 | } |
| 104 | - | ||
| 105 | for (int64_t slotOffset = 0; slotOffset < matrix; slotOffset += OUTER_LOOP_SIZE) | 119 | for (int64_t slotOffset = 0; slotOffset < matrix; slotOffset += OUTER_LOOP_SIZE) |
| 106 | { | 120 | { |
| 107 | int64_t loopSize = min(matrix - slotOffset, OUTER_LOOP_SIZE); | 121 | int64_t loopSize = min(matrix - slotOffset, OUTER_LOOP_SIZE); |
| @@ -116,21 +130,11 @@ void MoonEPShmemGradReduceUdmaFused( | |||
| 116 | } | 130 | } |
| 117 | } | 131 | } |
| 118 | 132 | ||
| 133 | + // Cross-rank completion and slot clearing are submitted by the host. | ||
| 119 | aclshmem_quiet(); | 134 | aclshmem_quiet(); |
| 120 | - aclshmemx_barrier_all_vec(); | ||
| 121 | - | ||
| 122 | - if (coreIdx == 0) { | ||
| 123 | - GlobalTensor<float> reduceGm_; | ||
| 124 | - reduceGm_.SetGlobalBuffer(reduce); | ||
| 125 | - for (int32_t localIdx = 0; localIdx < slots; localIdx++) { | ||
| 126 | - if (plan[rank * slots + localIdx] >= 0) { | ||
| 127 | - InitOutput(reduceGm_[localIdx * matrix], matrix, 0.0f); | ||
| 128 | - } | ||
| 129 | - } | ||
| 130 | - } | ||
| 131 | } | 135 | } |
| 132 | 136 | ||
| 133 | -extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_udma( | 137 | +static int LaunchGradReduceUdma( |
| 134 | void* stream, | 138 | void* stream, |
| 135 | void* expert_grads, | 139 | void* expert_grads, |
| 136 | void* reduce_buffers, | 140 | void* reduce_buffers, |
| @@ -152,7 +156,10 @@ extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_udma( | |||
| 152 | return ACL_ERROR_INVALID_PARAM; | 156 | return ACL_ERROR_INVALID_PARAM; |
| 153 | } | 157 | } |
| 154 | 158 | ||
| 155 | - (void)aclrtGetLastError(ACL_RT_THREAD_LEVEL); | 159 | + const auto prior_status = aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL); |
| 160 | + if (prior_status != ACL_SUCCESS) { | ||
| 161 | + return prior_status; | ||
| 162 | + } | ||
| 156 | const int32_t shmem_ranks = aclshmem_n_pes(); | 163 | const int32_t shmem_ranks = aclshmem_n_pes(); |
| 157 | if (shmem_ranks <= 0 || ranks != shmem_ranks) { | 164 | if (shmem_ranks <= 0 || ranks != shmem_ranks) { |
| 158 | return ACL_ERROR_INVALID_PARAM; | 165 | return ACL_ERROR_INVALID_PARAM; |
| @@ -160,15 +167,34 @@ extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_udma( | |||
| 160 | 167 | ||
| 161 | MoonEPShmemGradReduceUdmaFused<<<blocks, nullptr, stream>>>( | 168 | MoonEPShmemGradReduceUdmaFused<<<blocks, nullptr, stream>>>( |
| 162 | shmemx_get_ffts_config(), | 169 | shmemx_get_ffts_config(), |
| 163 | - reinterpret_cast<std::uint8_t*>(expert_grads), | 170 | + reinterpret_cast<uint8_t*>(expert_grads), |
| 164 | - reinterpret_cast<std::uint8_t*>(reduce_buffers), | 171 | + reinterpret_cast<uint8_t*>(reduce_buffers), |
| 165 | - reinterpret_cast<std::uint8_t*>(workspace), | 172 | + reinterpret_cast<uint8_t*>(workspace), |
| 166 | - reinterpret_cast<std::uint8_t*>(const_cast<int32_t*>(experts_to_copy)), | 173 | + reinterpret_cast<uint8_t*>(const_cast<int32_t*>(experts_to_copy)), |
| 167 | - epn, | 174 | + epn, hidden, projection, ranks, slots, rank); |
| 168 | - hidden, | 175 | + |
| 169 | - projection, | 176 | + auto status = aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL); |
| 170 | - ranks, | 177 | + if (status != ACL_SUCCESS) { |
| 171 | - slots, | 178 | + return status; |
| 172 | - rank); | 179 | + } |
| 180 | + // Every peer must finish reading before any rank clears its source slots. | ||
| 181 | + status = moonep_grad_reduce_native_barrier(stream); | ||
| 182 | + if (status != ACL_SUCCESS) { | ||
| 183 | + return status; | ||
| 184 | + } | ||
| 185 | + MoonEPShmemClearValidGradSlots<<<1, nullptr, stream>>>( | ||
| 186 | + reinterpret_cast<uint8_t*>(reduce_buffers), | ||
| 187 | + reinterpret_cast<uint8_t*>(const_cast<int32_t*>(experts_to_copy)), | ||
| 188 | + static_cast<int64_t>(hidden) * projection, slots, rank); | ||
| 173 | return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL); | 189 | return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL); |
| 174 | } | 190 | } |
| 191 | + | ||
| 192 | +extern "C" ASCEND_MOONEP_EXPORT int moonep_shmem_grad_reduce_udma( | ||
| 193 | + void* stream, void* expert_grads, void* reduce_buffers, void* workspace, | ||
| 194 | + const int32_t* experts_to_copy, int32_t epn, int32_t hidden, | ||
| 195 | + int32_t projection, int32_t ranks, int32_t slots, int32_t rank, | ||
| 196 | + int32_t blocks) | ||
| 197 | +{ | ||
| 198 | + return LaunchGradReduceUdma(stream, expert_grads, reduce_buffers, workspace, | ||
| 199 | + experts_to_copy, epn, hidden, projection, ranks, slots, rank, blocks); | ||
| 200 | +} | ||
| @@ -0,0 +1,50 @@ | |||
| 1 | +// SPDX-License-Identifier: Apache-2.0 | ||
| 2 | +#include "ascend_moonep/kernels/launch.h" | ||
| 3 | +#include "acl/acl.h" | ||
| 4 | +#if defined(CATLASS_ARCH) && CATLASS_ARCH == 3510 | ||
| 5 | +#include "ascend_moonep/kernels/urma_push_core.h" | ||
| 6 | +extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ | ||
| 7 | +void prefetch_barrier_vec(uint64_t ffts_config) { | ||
| 8 | + util_set_ffts_config(ffts_config); | ||
| 9 | + aclshmemx_barrier_all_vec(); | ||
| 10 | +} | ||
| 11 | +extern "C" ASCEND_MOONEP_EXPORT int moonep_prefetch_barrier_vec(void* stream) { | ||
| 12 | + if (stream == nullptr) return ACL_ERROR_INVALID_PARAM; | ||
| 13 | + prefetch_barrier_vec<<<1,nullptr,stream>>>(shmemx_get_ffts_config()); | ||
| 14 | + return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL); | ||
| 15 | +} | ||
| 16 | +// Separate name makes the async-lane domain distinguishable from prefetch | ||
| 17 | +// completion and ordered GradReduce in the device trace. Same SDK team/state. | ||
| 18 | +extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ | ||
| 19 | +void async_stream_barrier_vec(uint64_t ffts_config) { | ||
| 20 | + util_set_ffts_config(ffts_config); | ||
| 21 | + aclshmemx_barrier_all_vec(); | ||
| 22 | +} | ||
| 23 | +extern "C" ASCEND_MOONEP_EXPORT int moonep_async_stream_barrier_vec(void* stream) { | ||
| 24 | + if (stream == nullptr) return ACL_ERROR_INVALID_PARAM; | ||
| 25 | + async_stream_barrier_vec<<<1,nullptr,stream>>>(shmemx_get_ffts_config()); | ||
| 26 | + return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL); | ||
| 27 | +} | ||
| 28 | +extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ | ||
| 29 | +void prefetch_pointer_push_udma(GM_ADDR pointers, GM_ADDR slots, GM_ADDR plan, | ||
| 30 | + int64_t experts, int64_t row_elements, int64_t num_slots) { | ||
| 31 | + moonep_urma_push::Run<true>(pointers,slots,plan,experts,row_elements,num_slots); | ||
| 32 | +} | ||
| 33 | +extern "C" ASCEND_MOONEP_EXPORT int prefetch_pointer_push_udma_available() { return 1; } | ||
| 34 | +extern "C" ASCEND_MOONEP_EXPORT int moonep_prefetch_pointer_push_udma( | ||
| 35 | + void* stream, uint8_t* pointers, uint8_t* slots, uint8_t* plan, | ||
| 36 | + int64_t experts, int64_t row_elements, int64_t num_slots) { | ||
| 37 | + const auto status = aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL); | ||
| 38 | + if (status != ACL_SUCCESS) { | ||
| 39 | + return status; | ||
| 40 | + } | ||
| 41 | + prefetch_pointer_push_udma<<<1,nullptr,stream>>>(pointers,slots,plan,experts,row_elements,num_slots); | ||
| 42 | + return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL); | ||
| 43 | +} | ||
| 44 | +#else | ||
| 45 | +extern "C" ASCEND_MOONEP_EXPORT int moonep_prefetch_barrier_vec(void*) { return -1; } | ||
| 46 | +extern "C" ASCEND_MOONEP_EXPORT int moonep_async_stream_barrier_vec(void*) { return -1; } | ||
| 47 | +extern "C" ASCEND_MOONEP_EXPORT int prefetch_pointer_push_udma_available() { return 0; } | ||
| 48 | +extern "C" ASCEND_MOONEP_EXPORT int moonep_prefetch_pointer_push_udma( | ||
| 49 | + void*,uint8_t*,uint8_t*,uint8_t*,int64_t,int64_t,int64_t) { return -1; } | ||
| 50 | +#endif | ||
| @@ -0,0 +1,27 @@ | |||
| 1 | +// SPDX-License-Identifier: Apache-2.0 | ||
| 2 | +#include "ascend_moonep/kernels/launch.h" | ||
| 3 | +#include "acl/acl.h" | ||
| 4 | +#if defined(CATLASS_ARCH) && CATLASS_ARCH == 3510 | ||
| 5 | +#include "ascend_moonep/kernels/urma_push_core.h" | ||
| 6 | +extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ | ||
| 7 | +void prefetch_weight_push_udma(GM_ADDR source, GM_ADDR slots, GM_ADDR plan, | ||
| 8 | + int64_t experts, int64_t row_elements, int64_t num_slots) { | ||
| 9 | + moonep_urma_push::Run<false>(source, slots, plan, experts, row_elements, num_slots); | ||
| 10 | +} | ||
| 11 | +extern "C" ASCEND_MOONEP_EXPORT int prefetch_weight_push_udma_available() { return 1; } | ||
| 12 | +extern "C" ASCEND_MOONEP_EXPORT int prefetch_weight_push_udma_do( | ||
| 13 | + void* stream, uint8_t* source, uint8_t* slots, uint8_t* plan, | ||
| 14 | + int64_t experts, int64_t row_elements, int64_t num_slots) { | ||
| 15 | + const auto status = aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL); | ||
| 16 | + if (status != ACL_SUCCESS) { | ||
| 17 | + return status; | ||
| 18 | + } | ||
| 19 | + prefetch_weight_push_udma<<<1, nullptr, stream>>>( | ||
| 20 | + source, slots, plan, experts, row_elements, num_slots); | ||
| 21 | + return aclrtPeekAtLastError(ACL_RT_THREAD_LEVEL); | ||
| 22 | +} | ||
| 23 | +#else | ||
| 24 | +extern "C" ASCEND_MOONEP_EXPORT int prefetch_weight_push_udma_available() { return 0; } | ||
| 25 | +extern "C" ASCEND_MOONEP_EXPORT int prefetch_weight_push_udma_do( | ||
| 26 | + void*, uint8_t*, uint8_t*, uint8_t*, int64_t, int64_t, int64_t) { return -1; } | ||
| 27 | +#endif | ||
| @@ -8,7 +8,7 @@ | |||
| 8 | 8 | ||
| 9 | using namespace AscendC; | 9 | using namespace AscendC; |
| 10 | 10 | ||
| 11 | -#if defined(__NPU_ARCH__) && (__NPU_ARCH__ == 3510) | 11 | +#if defined(CATLASS_ARCH) && (CATLASS_ARCH == 3510) |
| 12 | 12 | ||
| 13 | namespace { | 13 | namespace { |
| 14 | 14 | ||
| @@ -123,6 +123,9 @@ extern "C" [[bisheng::core_ratio(0, 1)]] __global__ __aicore__ void prefetch_wei | |||
| 123 | __ubuf__ bfloat16_t* ub = | 123 | __ubuf__ bfloat16_t* ub = |
| 124 | reinterpret_cast<__ubuf__ bfloat16_t*>(ub_local.GetPhyAddr()); | 124 | reinterpret_cast<__ubuf__ bfloat16_t*>(ub_local.GetPhyAddr()); |
| 125 | Duplicate(wqe_local, static_cast<bfloat16_t>(0), kUdmaWqeElements); | 125 | Duplicate(wqe_local, static_cast<bfloat16_t>(0), kUdmaWqeElements); |
| 126 | + // Complete the vector clear before SDK scalar stores reuse its raw UB. | ||
| 127 | + SetFlag<HardEvent::V_S>(EVENT_ID2); | ||
| 128 | + WaitFlag<HardEvent::V_S>(EVENT_ID2); | ||
| 126 | 129 | ||
| 127 | int64_t active_experts = 0; | 130 | int64_t active_experts = 0; |
| 128 | for (int64_t slot = 0; slot < B; ++slot) { | 131 | for (int64_t slot = 0; slot < B; ++slot) { |
| @@ -0,0 +1,116 @@ | |||
| 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 | +""" | ||
| 6 | + | ||
| 7 | +from dataclasses import dataclass | ||
| 8 | + | ||
| 9 | +import torch | ||
| 10 | + | ||
| 11 | +from .buffer_c import sym_tensor | ||
| 12 | +from .shmem_runtime import ShmemRuntime | ||
| 13 | + | ||
| 14 | + | ||
| 15 | +def tensor_signature(tensor): | ||
| 16 | + """Metadata only: detect rebinding without reading device data/versions.""" | ||
| 17 | + storage = tensor.untyped_storage() | ||
| 18 | + return (tensor.data_ptr(), tuple(tensor.shape), tuple(tensor.stride()), | ||
| 19 | + tensor.storage_offset(), tensor.dtype, tensor.device, | ||
| 20 | + storage._cdata, storage.nbytes()) | ||
| 21 | + | ||
| 22 | + | ||
| 23 | +def symmetric_source(source): | ||
| 24 | + if not ShmemRuntime.is_initialized(): | ||
| 25 | + raise RuntimeError("initialize buffer-backed SHMEM before preparing bindings") | ||
| 26 | + if getattr(source, '_vmm_allocation', None) is None: | ||
| 27 | + raise ValueError("expected a registered VMM source tensor") | ||
| 28 | + return sym_tensor(source) | ||
| 29 | + | ||
| 30 | + | ||
| 31 | +def overlaps(left, right): | ||
| 32 | + if left.device != right.device: | ||
| 33 | + return False | ||
| 34 | + a, b = left.data_ptr(), right.data_ptr() | ||
| 35 | + return (a < b + right.numel() * right.element_size() and | ||
| 36 | + b < a + left.numel() * left.element_size()) | ||
| 37 | + | ||
| 38 | + | ||
| 39 | +@dataclass(frozen=True, eq=False, repr=False) | ||
| 40 | +class CommBuffers: | ||
| 41 | + """Prepared hidden/route views. Obtain with Buffer.prepare_comm_buffers. | ||
| 42 | + | ||
| 43 | + No allocation, lease, generation or completion state is owned by this value. | ||
| 44 | + Backing references keep the original source metadata/physical owners alive; | ||
| 45 | + callers must keep the tensors' storage and layout fixed while bound. | ||
| 46 | + """ | ||
| 47 | + | ||
| 48 | + hidden: torch.Tensor | ||
| 49 | + route: torch.Tensor | ||
| 50 | + sources: tuple | ||
| 51 | + owner: object | ||
| 52 | + | ||
| 53 | + | ||
| 54 | +@dataclass(frozen=True, eq=False, repr=False) | ||
| 55 | +class LPlusBBinding: | ||
| 56 | + """L canonical matrices plus one symmetric B-slot projection. | ||
| 57 | + | ||
| 58 | + BF16 weights use a pointer table; FP32 gradients use a dense home view. | ||
| 59 | + Metadata is prepared once. Retain this value and the Buffer until | ||
| 60 | + completion, and order all slot consumers before reusing the destination. | ||
| 61 | + """ | ||
| 62 | + | ||
| 63 | + refs: tuple | ||
| 64 | + sources: tuple | ||
| 65 | + slot: torch.Tensor | ||
| 66 | + slot_source: torch.Tensor | ||
| 67 | + table: torch.Tensor | None | ||
| 68 | + home: torch.Tensor | None | ||
| 69 | + ref_signatures: tuple | ||
| 70 | + owner: object | ||
| 71 | + | ||
| 72 | + def validate_refs(self, refs): | ||
| 73 | + """Reject a caller that switched canonical matrices after setup.""" | ||
| 74 | + validate_unchanged(tuple(refs), self.ref_signatures) | ||
| 75 | + | ||
| 76 | + | ||
| 77 | +def dense_grad_home(refs): | ||
| 78 | + """View already validated FP32 rows in expert order, without copying. | ||
| 79 | + | ||
| 80 | + The framework must create every main_grad row from one storage covering | ||
| 81 | + the entire local L projection. Adjacent independent allocations do not | ||
| 82 | + establish a safe Tensor view, even when their addresses happen to touch. | ||
| 83 | + """ | ||
| 84 | + first = refs[0] | ||
| 85 | + row_elements = first.numel() | ||
| 86 | + row_bytes = row_elements * first.element_size() | ||
| 87 | + storage = first.untyped_storage()._cdata | ||
| 88 | + if any(ref.untyped_storage()._cdata != storage or | ||
| 89 | + ref.data_ptr() != first.data_ptr() + i * row_bytes | ||
| 90 | + for i, ref in enumerate(refs)): | ||
| 91 | + raise ValueError('gradient refs must be consecutive expert-order rows of one storage') | ||
| 92 | + return first.detach().as_strided( | ||
| 93 | + (len(refs), *first.shape), (row_elements, *first.stride())) | ||
| 94 | + | ||
| 95 | + | ||
| 96 | +def validate_unchanged(refs, signatures): | ||
| 97 | + if tuple(tensor_signature(ref) for ref in refs) != signatures: | ||
| 98 | + raise ValueError("prepared storage was rebound or its layout changed") | ||
| 99 | + | ||
| 100 | + | ||
| 101 | +def comm_context(ctx, buffers, owner, carrier): | ||
| 102 | + """Select the symmetric data banks for one call, sharing control and workspace. | ||
| 103 | + | ||
| 104 | + Each EP rank must select the corresponding banks for the collective. | ||
| 105 | + The caller orders submissions that share the workspace. | ||
| 106 | + """ | ||
| 107 | + if not ShmemRuntime.is_initialized() or getattr(ShmemRuntime, '_poisoned', False): | ||
| 108 | + raise RuntimeError('explicit communication storage requires initialized healthy SHMEM') | ||
| 109 | + if not isinstance(buffers, CommBuffers) or buffers.owner is not owner: | ||
| 110 | + raise ValueError("comm_buffers must be prepared by this Buffer") | ||
| 111 | + n, h = int(ctx['NvS']), int(ctx['H']) | ||
| 112 | + local = dict(ctx) | ||
| 113 | + local['_native_comm_buffers'] = True | ||
| 114 | + local['hidden_buf'] = local['hidden_buf_local'] = carrier(buffers.hidden, (n, h), torch.bfloat16) | ||
| 115 | + local['weights_buf'] = local['weights_buf_local'] = carrier(buffers.route, (n,), torch.int32) | ||
| 116 | + return local | ||
| @@ -153,6 +153,7 @@ class DispatchOp(KernelOp): | |||
| 153 | (dest = aclshmem_ptr(ctx['hidden_buf'].data_ptr(), drank) + loff*H*2), | 153 | (dest = aclshmem_ptr(ctx['hidden_buf'].data_ptr(), drank) + loff*H*2), |
| 154 | writes weights into ctx['weights_buf'] (remote rank's symmetric chunk). | 154 | writes weights into ctx['weights_buf'] (remote rank's symmetric chunk). |
| 155 | - build_dedup_map True only right after fresh planning. | 155 | - build_dedup_map True only right after fresh planning. |
| 156 | + - MTE launch width follows self.num_sms; UDMA keeps its fixed schedule. | ||
| 156 | - shmem_instance_id: shmem runtime instance to operate on (default 0; the | 157 | - shmem_instance_id: shmem runtime instance to operate on (default 0; the |
| 157 | shmem Python API currently supports a single instance). | 158 | shmem Python API currently supports a single instance). |
| 158 | v1 degrade: host put segment scatter per plan.dst ranges. | 159 | v1 degrade: host put segment scatter per plan.dst ranges. |
| @@ -180,6 +181,7 @@ class DispatchOp(KernelOp): | |||
| 180 | int(ctx["R"]), | 181 | int(ctx["R"]), |
| 181 | int(ctx["rank"]), | 182 | int(ctx["rank"]), |
| 182 | plan.dedup_mode == "server", | 183 | plan.dedup_mode == "server", |
| 184 | + num_sms=self.num_sms, | ||
| 183 | ) | 185 | ) |
| 184 | 186 | ||
| 185 | def compute_profile(self, ctx, hidden_sh, route_weights_sk, plan, | 187 | def compute_profile(self, ctx, hidden_sh, route_weights_sk, plan, |
| @@ -220,6 +222,7 @@ class CombineOp(KernelOp): | |||
| 220 | output_sk [S, K] fp32 | 222 | output_sk [S, K] fp32 |
| 221 | - launcher selects native / legacy-rank UDMA / server-dedup UDMA | 223 | - launcher selects native / legacy-rank UDMA / server-dedup UDMA |
| 222 | from the environment and the plan's dedup mode | 224 | from the environment and the plan's dedup mode |
| 225 | + - MTE launch width follows self.num_sms; UDMA keeps its fixed schedule | ||
| 223 | """ | 226 | """ |
| 224 | 227 | ||
| 225 | def compute(self, ctx, output_sh, plan, output_sk=None, | 228 | def compute(self, ctx, output_sh, plan, output_sk=None, |
| @@ -252,6 +255,7 @@ class CombineOp(KernelOp): | |||
| 252 | int(ctx["R"]), | 255 | int(ctx["R"]), |
| 253 | int(ctx["rank"]), | 256 | int(ctx["rank"]), |
| 254 | server_dedup=server_dedup, | 257 | server_dedup=server_dedup, |
| 258 | + num_sms=self.num_sms, | ||
| 255 | ) | 259 | ) |
| 256 | 260 | ||
| 257 | class PrefetchOp(KernelOp): | 261 | class PrefetchOp(KernelOp): |
| @@ -317,6 +321,7 @@ class GradReduceOp(KernelOp): | |||
| 317 | - shmem_instance_id: shmem runtime instance to operate on (default 0; the | 321 | - shmem_instance_id: shmem runtime instance to operate on (default 0; the |
| 318 | shmem Python API currently supports a single instance). | 322 | shmem Python API currently supports a single instance). |
| 319 | Cross-rank: home rank gets each peer's reduce-buffer rows (host get / RMA). | 323 | Cross-rank: home rank gets each peer's reduce-buffer rows (host get / RMA). |
| 324 | + | ||
| 320 | """ | 325 | """ |
| 321 | 326 | ||
| 322 | def compute(self, ctx, full_grad_home, reduce_buffer, experts_to_copy, | 327 | def compute(self, ctx, full_grad_home, reduce_buffer, experts_to_copy, |
| @@ -368,4 +373,6 @@ class GradReduceOp(KernelOp): | |||
| 368 | meta_stride=0, | 373 | meta_stride=0, |
| 369 | barrier_off=0, | 374 | barrier_off=0, |
| 370 | grid_sync_bar=None, | 375 | grid_sync_bar=None, |
| 376 | + use_udma=ctx.get('_grad_reduce_use_udma'), | ||
| 377 | + udma_workspace=ctx.get('_grad_reduce_workspace'), | ||
| 371 | ) | 378 | ) |
| @@ -43,7 +43,12 @@ class MoonEPCommPlan: | |||
| 43 | # so rebuilding a different plan does not invalidate independent snapshots. | 43 | # so rebuilding a different plan does not invalidate independent snapshots. |
| 44 | _planning_generation: int = field(default=0, repr=False, compare=False) | 44 | _planning_generation: int = field(default=0, repr=False, compare=False) |
| 45 | 45 | ||
| 46 | + cu_seqlens: torch.Tensor | None = None | ||
| 47 | + | ||
| 46 | def __post_init__(self) -> None: | 48 | def __post_init__(self) -> None: |
| 49 | + if self.cu_seqlens is not None: | ||
| 50 | + assert self.cu_seqlens.dtype == torch.int32 and self.cu_seqlens.is_contiguous() | ||
| 51 | + assert tuple(self.cu_seqlens.shape) == (int(self.E) + int(self.B),) | ||
| 47 | N = int(self.N) | 52 | N = int(self.N) |
| 48 | R = int(self.R) | 53 | R = int(self.R) |
| 49 | E = int(self.E) | 54 | E = int(self.E) |
| @@ -90,6 +95,7 @@ class MoonEPCommPlan: | |||
| 90 | stream.wait_event(execution.ready) | 95 | stream.wait_event(execution.ready) |
| 91 | snapshot = type(self)( | 96 | snapshot = type(self)( |
| 92 | dst=self.dst.clone(), | 97 | dst=self.dst.clone(), |
| 98 | + cu_seqlens=self.cu_seqlens.clone() if self.cu_seqlens is not None else None, | ||
| 93 | experts_to_copy=self.experts_to_copy.clone(), | 99 | experts_to_copy=self.experts_to_copy.clone(), |
| 94 | zero_fill_ranges=self.zero_fill_ranges.clone(), | 100 | zero_fill_ranges=self.zero_fill_ranges.clone(), |
| 95 | remote_stats=self.remote_stats.clone(), | 101 | remote_stats=self.remote_stats.clone(), |
| @@ -109,10 +115,11 @@ class MoonEPCommPlan: | |||
| 109 | ready = torch_npu.npu.Event() | 115 | ready = torch_npu.npu.Event() |
| 110 | ready.record(stream) | 116 | ready.record(stream) |
| 111 | for plan in (self, snapshot): | 117 | for plan in (self, snapshot): |
| 112 | - for tensor in (plan.dst, plan.experts_to_copy, plan.zero_fill_ranges, | 118 | + for tensor in (plan.dst, plan.cu_seqlens, plan.experts_to_copy, |
| 113 | - plan.remote_stats, plan.dup_groups, plan.dup_loffs, | 119 | + plan.zero_fill_ranges, plan.remote_stats, plan.dup_groups, |
| 114 | - plan.dup_counts): | 120 | + plan.dup_loffs, plan.dup_counts): |
| 115 | - tensor.record_stream(stream) | 121 | + if tensor is not None: |
| 122 | + tensor.record_stream(stream) | ||
| 116 | execution.storage.record_stream(stream) | 123 | execution.storage.record_stream(stream) |
| 117 | storage.record_stream(stream) | 124 | storage.record_stream(stream) |
| 118 | copied_execution = CombineExecutionPlan( | 125 | copied_execution = CombineExecutionPlan( |
| @@ -146,6 +153,10 @@ def _key(ctx): | |||
| 146 | return tuple(int(ctx[name]) for name in ('S', 'H', 'K', 'R', 'rank')) | 153 | return tuple(int(ctx[name]) for name in ('S', 'H', 'K', 'R', 'rank')) |
| 147 | 154 | ||
| 148 | 155 | ||
| 156 | +def _combine_workspace_layout(ctx): | ||
| 157 | + return (int(ctx['NvS']), int(ctx['H']), int(ctx['R'])) | ||
| 158 | + | ||
| 159 | + | ||
| 149 | def _execution_key(ctx): | 160 | def _execution_key(ctx): |
| 150 | # Keep the five native launch arguments stable. The local cached-plan key | 161 | # Keep the five native launch arguments stable. The local cached-plan key |
| 151 | # also binds the private ring ABI and workspace geometry. | 162 | # also binds the private ring ABI and workspace geometry. |
| @@ -172,12 +183,18 @@ class CombineExecutionPlan: | |||
| 172 | fused: bool = False | 183 | fused: bool = False |
| 173 | 184 | ||
| 174 | def validate(self, ctx, plan): | 185 | def validate(self, ctx, plan): |
| 175 | - if ctx is not self.owner_ctx or _execution_key(ctx) != self.key: | 186 | + # Buffer launches use fresh logical views over the same capacity owner. |
| 187 | + # Activation banks may change between dispatch, forward and backward | ||
| 188 | + # combine; the immutable routing snapshot contains no bank addresses. | ||
| 189 | + owner = self.owner_ctx.get('_capacity_ctx', self.owner_ctx) | ||
| 190 | + if ctx.get('_capacity_ctx', ctx) is not owner or _execution_key(ctx) != self.key: | ||
| 176 | raise ValueError('execution plan belongs to a different Buffer/topology/shape') | 191 | raise ValueError('execution plan belongs to a different Buffer/topology/shape') |
| 177 | if ctx['combine_workspace'].data_ptr() != self.workspace.data_ptr(): | 192 | if ctx['combine_workspace'].data_ptr() != self.workspace.data_ptr(): |
| 178 | raise ValueError('combine workspace changed; collectively prepare a new plan') | 193 | raise ValueError('combine workspace changed; collectively prepare a new plan') |
| 179 | if id(plan) != self.routing_id or tuple(map(_stamp, _routes(plan))) != self.route_stamps: | 194 | if id(plan) != self.routing_id or tuple(map(_stamp, _routes(plan))) != self.route_stamps: |
| 180 | raise ValueError('routing changed; all ranks must prepare a new execution plan') | 195 | raise ValueError('routing changed; all ranks must prepare a new execution plan') |
| 196 | + if plan.combine_execution_plan is not self: | ||
| 197 | + raise ValueError('execution plan was replaced; collectively prepare a new plan') | ||
| 181 | if plan._planning_generation != self.generation: | 198 | if plan._planning_generation != self.generation: |
| 182 | raise ValueError('planning was rerun; all ranks must prepare a new execution plan') | 199 | raise ValueError('planning was rerun; all ranks must prepare a new execution plan') |
| 183 | if _stamp(self.storage) != self.storage_stamp: | 200 | if _stamp(self.storage) != self.storage_stamp: |
| @@ -243,6 +260,10 @@ def prepare_combine_plan(ctx, plan, *, storage=None, fused_timing=None): | |||
| 243 | plan._planning_generation, end, ctx, begin, end) | 260 | plan._planning_generation, end, ctx, begin, end) |
| 244 | execution.fused = fused | 261 | execution.fused = fused |
| 245 | object.__setattr__(plan, 'combine_execution_plan', execution) | 262 | object.__setattr__(plan, 'combine_execution_plan', execution) |
| 263 | + # Ready flags live in the shared workspace, unlike immutable route tables. | ||
| 264 | + # A different logical size places payload and flags at different offsets. | ||
| 265 | + owner = ctx.get('_capacity_ctx', ctx) | ||
| 266 | + owner['_combine_workspace_layout'] = _combine_workspace_layout(ctx) | ||
| 246 | return execution | 267 | return execution |
| 247 | 268 | ||
| 248 | 269 | ||
| @@ -315,6 +336,7 @@ def allocate_planning_outputs(ctx: dict): | |||
| 315 | 336 | ||
| 316 | plan = MoonEPCommPlan( | 337 | plan = MoonEPCommPlan( |
| 317 | dst=dst, | 338 | dst=dst, |
| 339 | + cu_seqlens=cu_seqlens, | ||
| 318 | experts_to_copy=experts_to_copy, | 340 | experts_to_copy=experts_to_copy, |
| 319 | zero_fill_ranges=zero_fill_ranges, | 341 | zero_fill_ranges=zero_fill_ranges, |
| 320 | remote_stats=remote_stats, | 342 | remote_stats=remote_stats, |
| @@ -0,0 +1,127 @@ | |||
| 1 | +"""Independent pointer-source PUSH; Buffer integrations own their own leases.""" | ||
| 2 | + | ||
| 3 | + | ||
| 4 | +class _PendingPushes: | ||
| 5 | + """Retain submitted storage until transfer completion, including failures. | ||
| 6 | + | ||
| 7 | + This owner is used only by the standalone launcher. Buffer/lane callers | ||
| 8 | + use the stateless native operation and their existing lease instead. | ||
| 9 | + """ | ||
| 10 | + def __init__(self): | ||
| 11 | + self.pending = [] | ||
| 12 | + self.poisoned = False | ||
| 13 | + | ||
| 14 | + def collect(self): | ||
| 15 | + if self.poisoned: | ||
| 16 | + raise RuntimeError("standalone PUSH is poisoned; backing remains retained") | ||
| 17 | + try: | ||
| 18 | + remaining = [row for row in self.pending if row[0] is None or not row[0].query()] | ||
| 19 | + except BaseException: | ||
| 20 | + self.poisoned = True | ||
| 21 | + raise | ||
| 22 | + self.pending = remaining | ||
| 23 | + | ||
| 24 | + def submit(self, resources, launch, make_event): | ||
| 25 | + self.collect() | ||
| 26 | + row = [None, resources] | ||
| 27 | + self.pending.append(row) # before the first potentially partial submission | ||
| 28 | + try: | ||
| 29 | + result = launch() | ||
| 30 | + event = make_event() | ||
| 31 | + event.record() | ||
| 32 | + row[0] = event | ||
| 33 | + return result | ||
| 34 | + except BaseException: | ||
| 35 | + self.poisoned = True | ||
| 36 | + raise | ||
| 37 | + | ||
| 38 | + def drain(self): | ||
| 39 | + if self.poisoned: | ||
| 40 | + raise RuntimeError("standalone PUSH is poisoned; cannot release or finalize") | ||
| 41 | + try: | ||
| 42 | + for event, _ in self.pending: | ||
| 43 | + if event is None: | ||
| 44 | + raise RuntimeError("PUSH has no proven completion event") | ||
| 45 | + event.synchronize() | ||
| 46 | + except BaseException: | ||
| 47 | + self.poisoned = True | ||
| 48 | + raise | ||
| 49 | + self.pending.clear() | ||
| 50 | + | ||
| 51 | + | ||
| 52 | +_pending = _PendingPushes() | ||
| 53 | + | ||
| 54 | + | ||
| 55 | +def validate_pointer_sources(refs, slots, plan, num_sms, *, bf16, int32): | ||
| 56 | + """Validate Tensor metadata only; expert order is the input sequence order.""" | ||
| 57 | + refs = tuple(refs) | ||
| 58 | + if type(num_sms) is not int or num_sms <= 0: | ||
| 59 | + raise ValueError("num_sms must be a positive integer") | ||
| 60 | + if (slots.device.type != 'npu' or plan.device != slots.device or | ||
| 61 | + slots.dtype != bf16 or plan.dtype != int32): | ||
| 62 | + raise ValueError("expected BF16 slots and INT32 plan on one NPU") | ||
| 63 | + if (slots.ndim != 3 or plan.ndim != 2 or not slots.is_contiguous() or | ||
| 64 | + not plan.is_contiguous() or plan.shape[1] != slots.shape[0]): | ||
| 65 | + raise ValueError("expected contiguous slots[B,M,N] and plan[EP,B]") | ||
| 66 | + if (not 0 < plan.shape[0] <= 2147483647 or not refs or | ||
| 67 | + len(refs) > 2147483647 // plan.shape[0] or | ||
| 68 | + slots.shape[0] > 15736 or min(slots.shape[1:]) <= 0): | ||
| 69 | + raise ValueError("invalid L/EP/projection or URMA UB extent") | ||
| 70 | + begin = slots.data_ptr() | ||
| 71 | + end = begin + slots.numel() * slots.element_size() | ||
| 72 | + for ref in refs: | ||
| 73 | + if (ref.device != slots.device or ref.dtype != bf16 or ref.ndim != 2 or | ||
| 74 | + tuple(ref.shape) != tuple(slots.shape[1:]) or not ref.is_contiguous()): | ||
| 75 | + raise ValueError("each expert must be a matching contiguous BF16 [M,N] Tensor") | ||
| 76 | + left = ref.data_ptr() | ||
| 77 | + right = left + ref.numel() * ref.element_size() | ||
| 78 | + if left == 0 or (begin < end and left < end and begin < right): | ||
| 79 | + raise ValueError("PUSH source must not alias destination slots") | ||
| 80 | + return refs | ||
| 81 | + | ||
| 82 | + | ||
| 83 | +def launch_prefetch_push_ptrs(expert_weights, prefetch_buffers, experts_to_copy, num_sms): | ||
| 84 | + """Push L ordinary local BF16 expert Tensors into symmetric [B,M,N] slots. | ||
| 85 | + | ||
| 86 | + Each rank calls collectively with the same INT32 [EP,B] plan (-1=empty). | ||
| 87 | + E=L*EP; global expert g belongs to g//L with local index g%L. Distinct | ||
| 88 | + allocations and reverse expert addresses are legal; each matrix is dense. | ||
| 89 | + No raw addresses are accepted by this public API and no weights are copied. | ||
| 90 | + | ||
| 91 | + Submission uses the current NPU stream, including pre/post barriers. The | ||
| 92 | + original destination Tensor is returned; host return is not completion. | ||
| 93 | + Order producer writes and previous slot users before calling; on another | ||
| 94 | + stream wait an event recorded after this call. Do not mutate source/plan, | ||
| 95 | + overwrite slots, unmap backing or finalize before the corresponding uses | ||
| 96 | + complete. Transfer backing is internally retained through its completion; | ||
| 97 | + final consumer use and manual VMM ownership remain the caller's duty. | ||
| 98 | + """ | ||
| 99 | + import torch | ||
| 100 | + import torch_npu | ||
| 101 | + from . import _C | ||
| 102 | + from .shmem_runtime import ShmemRuntime | ||
| 103 | + refs = validate_pointer_sources(expert_weights, prefetch_buffers, experts_to_copy, | ||
| 104 | + num_sms, bf16=torch.bfloat16, int32=torch.int32) | ||
| 105 | + if (getattr(_C, 'PREFETCH_PUSH_POINTER_ABI', None) != 1 or | ||
| 106 | + not _C._prefetch_push_available()): | ||
| 107 | + raise RuntimeError("native pointer PUSH is unavailable; no MTE fallback") | ||
| 108 | + if (getattr(ShmemRuntime, '_poisoned', False) or | ||
| 109 | + not ShmemRuntime.is_initialized() or not ShmemRuntime._udma_enabled): | ||
| 110 | + raise RuntimeError("pointer PUSH requires initialized URMA SHMEM") | ||
| 111 | + if '950' not in torch.npu.get_device_name(prefetch_buffers.device): | ||
| 112 | + raise RuntimeError("URMA PUSH requires Ascend950") | ||
| 113 | + # Immutable Tensor metadata retains the real backing if Parameter.data moves. | ||
| 114 | + sources = tuple(ref.detach() for ref in refs) | ||
| 115 | + table = torch.tensor([ref.data_ptr() for ref in sources], dtype=torch.int64, | ||
| 116 | + device=prefetch_buffers.device) | ||
| 117 | + plan = experts_to_copy.detach() | ||
| 118 | + slots = prefetch_buffers.detach() | ||
| 119 | + _pending.submit((sources, table, slots, plan), | ||
| 120 | + lambda: _C._prefetch_push_pointers(table, slots, plan, len(sources)), | ||
| 121 | + torch_npu.npu.Event) | ||
| 122 | + return prefetch_buffers | ||
| 123 | + | ||
| 124 | + | ||
| 125 | +def drain_prefetch_push(): | ||
| 126 | + """Wait standalone transfers, retaining backing on failure; not consumer drain.""" | ||
| 127 | + _pending.drain() | ||
| @@ -43,10 +43,12 @@ def audit_loaded_shmem_library( | |||
| 43 | ) -> dict[str, object]: | 43 | ) -> dict[str, object]: |
| 44 | """Return identity evidence for the one loaded ``libshmem.so`` image. | 44 | """Return identity evidence for the one loaded ``libshmem.so`` image. |
| 45 | 45 | ||
| 46 | - Mappings are deduplicated by the resolved file's ``(st_dev, st_ino)``; | 46 | + Mappings are deduplicated by procfs ``(device, inode)`` so repeated ELF |
| 47 | - repeated ELF segments are therefore one library. The procfs device/inode | 47 | + segments are one library. The procfs inode must match ``stat(2)``. The |
| 48 | - fields must also match ``stat(2)``. Any missing, deleted, inconsistent, or | 48 | + device numbers are both reported but may differ when a container path is |
| 49 | - multiple runtime images fail closed before ACLSHMEM initialization. | 49 | + an overlay/bind-mount view of the mapped host file. Any missing, deleted, |
| 50 | + inode-inconsistent, or multiple runtime images fail closed before ACLSHMEM | ||
| 51 | + initialization. | ||
| 50 | """ | 52 | """ |
| 51 | current_platform = sys.platform if platform is None else platform | 53 | current_platform = sys.platform if platform is None else platform |
| 52 | if current_platform != "linux": | 54 | if current_platform != "linux": |
| @@ -92,20 +94,30 @@ def audit_loaded_shmem_library( | |||
| 92 | raise RuntimeError( | 94 | raise RuntimeError( |
| 93 | f"cannot resolve loaded libshmem mapping identity: {mapped_path}") from exc | 95 | f"cannot resolve loaded libshmem mapping identity: {mapped_path}") from exc |
| 94 | 96 | ||
| 95 | - if maps_device_number != stat_result.st_dev or maps_inode != stat_result.st_ino: | 97 | + # /proc/<pid>/maps can expose the backing filesystem's device number |
| 98 | + # while stat(2) of the same absolute path reports the device number of | ||
| 99 | + # the container's overlay/bind-mount view. In that case the pathname | ||
| 100 | + # and inode still identify the same file, but st_dev legitimately | ||
| 101 | + # differs (for example maps=fd:00 and stat=0:33). An inode mismatch is | ||
| 102 | + # still a replacement/identity failure and must remain fail-closed. | ||
| 103 | + if maps_inode != stat_result.st_ino: | ||
| 96 | raise RuntimeError( | 104 | raise RuntimeError( |
| 97 | "loaded libshmem mapping metadata changed during audit: " | 105 | "loaded libshmem mapping metadata changed during audit: " |
| 98 | f"{mapped_path} maps dev/inode={maps_device}/{maps_inode}, " | 106 | f"{mapped_path} maps dev/inode={maps_device}/{maps_inode}, " |
| 99 | f"stat dev/inode={os.major(stat_result.st_dev):x}:" | 107 | f"stat dev/inode={os.major(stat_result.st_dev):x}:" |
| 100 | f"{os.minor(stat_result.st_dev):x}/{stat_result.st_ino}") | 108 | f"{os.minor(stat_result.st_dev):x}/{stat_result.st_ino}") |
| 101 | 109 | ||
| 102 | - identity = (stat_result.st_dev, stat_result.st_ino) | 110 | + identity = (maps_device_number, maps_inode) |
| 103 | identities.setdefault(identity, { | 111 | identities.setdefault(identity, { |
| 104 | "realpath": str(realpath), | 112 | "realpath": str(realpath), |
| 105 | "device": int(stat_result.st_dev), | 113 | "device": int(stat_result.st_dev), |
| 106 | "device_major": int(os.major(stat_result.st_dev)), | 114 | "device_major": int(os.major(stat_result.st_dev)), |
| 107 | "device_minor": int(os.minor(stat_result.st_dev)), | 115 | "device_minor": int(os.minor(stat_result.st_dev)), |
| 108 | "inode": int(stat_result.st_ino), | 116 | "inode": int(stat_result.st_ino), |
| 117 | + "maps_device": int(maps_device_number), | ||
| 118 | + "maps_device_major": int(os.major(maps_device_number)), | ||
| 119 | + "maps_device_minor": int(os.minor(maps_device_number)), | ||
| 120 | + "device_alias": bool(maps_device_number != stat_result.st_dev), | ||
| 109 | }) | 121 | }) |
| 110 | 122 | ||
| 111 | if len(identities) != 1: | 123 | if len(identities) != 1: |
| @@ -115,9 +127,10 @@ def audit_loaded_shmem_library( | |||
| 115 | f"{len(identities)}: {paths}") | 127 | f"{len(identities)}: {paths}") |
| 116 | 128 | ||
| 117 | info = next(iter(identities.values())) | 129 | info = next(iter(identities.values())) |
| 118 | - identity = (int(info["device"]), int(info["inode"])) | 130 | + path_identity = (int(info["device"]), int(info["inode"])) |
| 119 | try: | 131 | try: |
| 120 | - info["sha256"] = _sha256_file(Path(str(info["realpath"])), identity) | 132 | + info["sha256"] = _sha256_file( |
| 133 | + Path(str(info["realpath"])), path_identity) | ||
| 121 | except OSError as exc: | 134 | except OSError as exc: |
| 122 | raise RuntimeError( | 135 | raise RuntimeError( |
| 123 | f"cannot hash loaded libshmem runtime: {info['realpath']}") from exc | 136 | f"cannot hash loaded libshmem runtime: {info['realpath']}") from exc |
| @@ -148,6 +148,7 @@ def _npu_extension(): | |||
| 148 | os.path.join("native", "csrc", "acl_shared_buffer.cpp"), | 148 | os.path.join("native", "csrc", "acl_shared_buffer.cpp"), |
| 149 | os.path.join("native", "csrc", "torch_classes.cpp"), | 149 | os.path.join("native", "csrc", "torch_classes.cpp"), |
| 150 | os.path.join("native", "csrc", "launcher.cpp"), | 150 | os.path.join("native", "csrc", "launcher.cpp"), |
| 151 | + os.path.join("native", "csrc", "lplusb_runtime.cpp"), | ||
| 151 | os.path.join("native", "csrc", "ops", "moonep_combine.cpp"), | 152 | os.path.join("native", "csrc", "ops", "moonep_combine.cpp"), |
| 152 | os.path.join("native", "csrc", "ops", "moonep_combine_udma.cpp"), | 153 | os.path.join("native", "csrc", "ops", "moonep_combine_udma.cpp"), |
| 153 | os.path.join("native", "csrc", "ops", "moonep_dispatch.cpp"), | 154 | os.path.join("native", "csrc", "ops", "moonep_dispatch.cpp"), |
| @@ -239,7 +240,7 @@ def _package_data(): | |||
| 239 | if BACKEND != "npu": | 240 | if BACKEND != "npu": |
| 240 | return {} | 241 | return {} |
| 241 | # Globs are relative to the `npu_patch` package directory. | 242 | # Globs are relative to the `npu_patch` package directory. |
| 242 | - libs = ["lib/*.so", "lib/*.so.*"] | 243 | + libs = ["lib/*.so", "lib/*.so.*", "_integration_capabilities.json"] |
| 243 | return {"npu_patch": libs} | 244 | return {"npu_patch": libs} |
| 244 | 245 | ||
| 245 | 246 | ||
| @@ -197,6 +197,7 @@ class ShmemRuntime: | |||
| 197 | """Thin facade over the shmem symmetric-memory runtime lifecycle.""" | 197 | """Thin facade over the shmem symmetric-memory runtime lifecycle.""" |
| 198 | 198 | ||
| 199 | _initialized = False | 199 | _initialized = False |
| 200 | + _udma_enabled = False | ||
| 200 | _poisoned = False | 201 | _poisoned = False |
| 201 | _runtime_library_record = None | 202 | _runtime_library_record = None |
| 202 | 203 | ||
| @@ -286,7 +287,7 @@ class ShmemRuntime: | |||
| 286 | # Fail closed before any SHMEM-native call (including UID generation). | 287 | # Fail closed before any SHMEM-native call (including UID generation). |
| 287 | # Loading two libshmem images creates independent process-global | 288 | # Loading two libshmem images creates independent process-global |
| 288 | # PE/heap state. | 289 | # PE/heap state. |
| 289 | - # cls._runtime_library_record = audit_loaded_shmem_library() | 290 | + cls._runtime_library_record = audit_loaded_shmem_library() |
| 290 | rank = dist.get_rank(group=group) | 291 | rank = dist.get_rank(group=group) |
| 291 | world_size = dist.get_world_size(group=group) | 292 | world_size = dist.get_world_size(group=group) |
| 292 | if uid_bytes is None: | 293 | if uid_bytes is None: |
| @@ -327,6 +328,7 @@ class ShmemRuntime: | |||
| 327 | else ACLSHMEM_DATA_OP_MTE), | 328 | else ACLSHMEM_DATA_OP_MTE), |
| 328 | device_id=int(torch.npu.current_device()), | 329 | device_id=int(torch.npu.current_device()), |
| 329 | enable_udma=enable_udma, qp_count=qp_count) | 330 | enable_udma=enable_udma, qp_count=qp_count) |
| 331 | + cls._udma_enabled = bool(enable_udma) | ||
| 330 | cls._initialized = True | 332 | cls._initialized = True |
| 331 | 333 | ||
| 332 | @classmethod | 334 | @classmethod |
| @@ -367,7 +369,7 @@ class ShmemRuntime: | |||
| 367 | return | 369 | return |
| 368 | # The IP/port path owns the same process-global runtime and backing as | 370 | # The IP/port path owns the same process-global runtime and backing as |
| 369 | # the UID path, so it must pass the identical pre-native audit. | 371 | # the UID path, so it must pass the identical pre-native audit. |
| 370 | - # cls._runtime_library_record = audit_loaded_shmem_library() | 372 | + cls._runtime_library_record = audit_loaded_shmem_library() |
| 371 | if ip_port is None: | 373 | if ip_port is None: |
| 372 | ip_port = _env_shmem_ip_port() | 374 | ip_port = _env_shmem_ip_port() |
| 373 | if ip_port is None: | 375 | if ip_port is None: |
| @@ -400,6 +402,7 @@ class ShmemRuntime: | |||
| 400 | else ACLSHMEM_DATA_OP_MTE), | 402 | else ACLSHMEM_DATA_OP_MTE), |
| 401 | device_id=int(torch.npu.current_device()), | 403 | device_id=int(torch.npu.current_device()), |
| 402 | enable_udma=enable_udma, qp_count=qp_count) | 404 | enable_udma=enable_udma, qp_count=qp_count) |
| 405 | + cls._udma_enabled = bool(enable_udma) | ||
| 403 | cls._initialized = True | 406 | cls._initialized = True |
| 404 | 407 | ||
| 405 | @classmethod | 408 | @classmethod |
| @@ -412,6 +415,13 @@ class ShmemRuntime: | |||
| 412 | only after diagnostics are captured. | 415 | only after diagnostics are captured. |
| 413 | """ | 416 | """ |
| 414 | if cls._initialized: | 417 | if cls._initialized: |
| 418 | + # Standalone PUSH owns only transfer backing, never Buffer leases. | ||
| 419 | + from .prefetch_pointer import drain_prefetch_push | ||
| 420 | + try: | ||
| 421 | + drain_prefetch_push() | ||
| 422 | + except BaseException: | ||
| 423 | + cls._poisoned = True | ||
| 424 | + raise | ||
| 415 | # Plan B: reuse the buffer_c wrapper. | 425 | # Plan B: reuse the buffer_c wrapper. |
| 416 | rc = int(shmem_finalize()) | 426 | rc = int(shmem_finalize()) |
| 417 | if rc != 0: | 427 | if rc != 0: |
| @@ -422,6 +432,7 @@ class ShmemRuntime: | |||
| 422 | # --- Original implementation (plan A) --- | 432 | # --- Original implementation (plan A) --- |
| 423 | # core.finalize() | 433 | # core.finalize() |
| 424 | cls._initialized = False | 434 | cls._initialized = False |
| 435 | + cls._udma_enabled = False | ||
| 425 | cls._poisoned = False | 436 | cls._poisoned = False |
| 426 | return rc | 437 | return rc |
| 427 | return 0 | 438 | return 0 |
| @@ -0,0 +1,214 @@ | |||
| 1 | +"""Real CPU tensors and production Buffer; NPU streams/transport are explicit doubles.""" | ||
| 2 | +import contextlib | ||
| 3 | +import importlib | ||
| 4 | +import sys | ||
| 5 | +from types import ModuleType, SimpleNamespace | ||
| 6 | + | ||
| 7 | +from pathlib import Path | ||
| 8 | +MOONEP_ROOT = Path(__file__).resolve().parents[1] | ||
| 9 | + | ||
| 10 | +import pytest | ||
| 11 | +import torch | ||
| 12 | + | ||
| 13 | + | ||
| 14 | +PACKAGE = MOONEP_ROOT / 'npu_patch' | ||
| 15 | + | ||
| 16 | + | ||
| 17 | +@pytest.fixture | ||
| 18 | +def provider(monkeypatch): | ||
| 19 | + # Load the actual Python provider without loading its NPU package initializer. | ||
| 20 | + package = ModuleType('npu_patch') | ||
| 21 | + package.__path__ = [str(PACKAGE)] | ||
| 22 | + for name in tuple(sys.modules): | ||
| 23 | + if name == 'npu_patch' or name.startswith('npu_patch.'): | ||
| 24 | + monkeypatch.delitem(sys.modules, name) | ||
| 25 | + monkeypatch.setitem(sys.modules, 'npu_patch', package) | ||
| 26 | + calls, owners = [], {} | ||
| 27 | + | ||
| 28 | + class Stream: | ||
| 29 | + npu_stream = 7 | ||
| 30 | + def wait_stream(self, other): | ||
| 31 | + calls.append(('wait_stream', other)) | ||
| 32 | + def record_event(self): | ||
| 33 | + calls.append(('event',)) | ||
| 34 | + return object() | ||
| 35 | + def synchronize(self): | ||
| 36 | + calls.append(('synchronize',)) | ||
| 37 | + | ||
| 38 | + current = Stream() | ||
| 39 | + class Event: | ||
| 40 | + def record(self, stream): pass | ||
| 41 | + def query(self): return True | ||
| 42 | + npu = ModuleType('torch_npu') | ||
| 43 | + npu.npu = SimpleNamespace(Stream=Stream, Event=Event, current_stream=lambda: current, | ||
| 44 | + stream=lambda stream: contextlib.nullcontext(), synchronize=lambda: calls.append(('sync_device',))) | ||
| 45 | + monkeypatch.setitem(sys.modules, 'torch_npu', npu) | ||
| 46 | + native = ModuleType('npu_patch._C') | ||
| 47 | + native.LPLUS_B_BUFFER_SYNC_ABI = 3 | ||
| 48 | + native.GRAD_REDUCE_DENSE_ABI = 1 | ||
| 49 | + native._lplusb_owner_push = lambda *args: calls.append(('push', args)) | ||
| 50 | + monkeypatch.setitem(sys.modules, native.__name__, native) | ||
| 51 | + package._C = native | ||
| 52 | + common = ModuleType('npu_patch._common') | ||
| 53 | + common.BARRIER_SLOTS = 1 | ||
| 54 | + common.OP_WS_BYTES_DEFAULT = 1 | ||
| 55 | + common.dispatch_sync_buffer_nbytes = lambda ranks: 1 | ||
| 56 | + def barrier(ctx, stream): | ||
| 57 | + ctx['_barrier_round'] += 1 | ||
| 58 | + calls.append(('barrier', stream)) | ||
| 59 | + common.cross_rank_barrier = barrier | ||
| 60 | + common.record_streams = lambda tensors, stream: calls.append(('record_streams',)) | ||
| 61 | + monkeypatch.setitem(sys.modules, common.__name__, common) | ||
| 62 | + backing = ModuleType('npu_patch.buffer_c') | ||
| 63 | + backing._OWNER_SOURCE_VA_ATTR = '_moonep_owner_source_va' | ||
| 64 | + backing._SLOT_SOURCE_VA_ATTR = '_moonep_slot_source_va' | ||
| 65 | + backing.VMM_PAGE_SIZE_1G = '1g' | ||
| 66 | + backing.VMM_PAGE_SIZE_2M = '2m' | ||
| 67 | + backing.VMM_PAGE_SIZE_DEFAULT = 'default' | ||
| 68 | + backing.VMM_SCOPE_MOONEP = 'moonep' | ||
| 69 | + backing.normalize_vmm_page_size = lambda size: size or 'default' | ||
| 70 | + backing.resolve_vmm_page_size = lambda size, *, scope, default: default if size == 'default' else size | ||
| 71 | + backing.translate_tensor = lambda tensor, name: tensor | ||
| 72 | + backing.create_vmm_arena = lambda *args, **kwargs: None | ||
| 73 | + def from_pointer(pointer, shape, dtype, device): | ||
| 74 | + owner = owners[pointer] | ||
| 75 | + # Independent Tensor metadata over the same CPU storage, no copy. | ||
| 76 | + return torch.empty(0, dtype=dtype).set_(owner.untyped_storage(), 0, tuple(shape)) | ||
| 77 | + backing.create_sym_tensor_from_ptr = from_pointer | ||
| 78 | + backing.sym_tensor = lambda tensor: tensor | ||
| 79 | + for name in ('create_sym_tensor_from_source', 'create_vmm_physical', 'map_to_sym_ptr', 'acl_vmm_granularity'): | ||
| 80 | + setattr(backing, name, lambda *args, **kwargs: None) | ||
| 81 | + def granularity(device): | ||
| 82 | + calls.append(('granularity', device)) | ||
| 83 | + return 64 | ||
| 84 | + backing.acl_vmm_granularity = granularity | ||
| 85 | + monkeypatch.setitem(sys.modules, backing.__name__, backing) | ||
| 86 | + kernel_op = ModuleType('npu_patch.kernel_op') | ||
| 87 | + kernel_op.KernelOp = object | ||
| 88 | + monkeypatch.setitem(sys.modules, kernel_op.__name__, kernel_op) | ||
| 89 | + launchers = ModuleType('npu_patch.launchers') | ||
| 90 | + launchers.planning_workspace_sizes = lambda *args: (1, 1) | ||
| 91 | + launchers._env_use_udma = lambda name: False | ||
| 92 | + for name in ('launch_combine_op', 'launch_dispatch_op', 'launch_dispatch_profile_op', | ||
| 93 | + 'launch_planning_op', 'launch_prefetch'): | ||
| 94 | + setattr(launchers, name, lambda *args, **kwargs: None) | ||
| 95 | + launchers.launch_grad_reduce = lambda *args, **kwargs: calls.append(('grad_reduce', args, kwargs)) | ||
| 96 | + monkeypatch.setitem(sys.modules, launchers.__name__, launchers) | ||
| 97 | + runtime = ModuleType('npu_patch.shmem_runtime') | ||
| 98 | + runtime.ShmemRuntime = SimpleNamespace(is_initialized=lambda: False) | ||
| 99 | + runtime.publish_dedup_env = lambda mode: None | ||
| 100 | + monkeypatch.setitem(sys.modules, runtime.__name__, runtime) | ||
| 101 | + api = importlib.import_module('npu_patch.api') | ||
| 102 | + yield SimpleNamespace(api=api, calls=calls, owners=owners, native=native, runtime=runtime) | ||
| 103 | + for name in ('npu_patch.api', 'npu_patch.planning'): | ||
| 104 | + sys.modules.pop(name, None) | ||
| 105 | + | ||
| 106 | + | ||
| 107 | +def buffer_for(provider, capacity=8): | ||
| 108 | + api = provider.api | ||
| 109 | + ctx = dict(S=capacity, K=2, H=16, R=2, E=4, B=2, rank=0, | ||
| 110 | + _shmem_views_ready=True, _barrier_round=0, | ||
| 111 | + hidden_buf=torch.full((capacity * 2, 16), 9, dtype=torch.bfloat16), | ||
| 112 | + weights_buf=torch.empty(capacity * 2, dtype=torch.int32), | ||
| 113 | + carrier_row_ids=torch.arange(capacity * 2, dtype=torch.int32), | ||
| 114 | + carrier_unused=torch.empty(capacity * 2, dtype=torch.bool), | ||
| 115 | + dispatch_sync_buffer=torch.empty(1, dtype=torch.uint8), | ||
| 116 | + combine_sync_buffer=torch.empty(1, dtype=torch.uint8)) | ||
| 117 | + ctx.update(N=capacity * 2, NvS=capacity * 2, group=None, num_sms=32) | ||
| 118 | + ctx['hidden_buf_local'] = ctx['hidden_buf'][:] | ||
| 119 | + ctx['weights_buf_local'] = ctx['weights_buf'][:] | ||
| 120 | + provider.owners[ctx['hidden_buf'].data_ptr()] = ctx['hidden_buf'] | ||
| 121 | + provider.owners[ctx['weights_buf'].data_ptr()] = ctx['weights_buf'] | ||
| 122 | + def planning(context, topk, tpe, cu, plan, **kwargs): | ||
| 123 | + provider.calls.append(('planning',)) | ||
| 124 | + plan.experts_to_copy.fill_(-1) | ||
| 125 | + cu.fill_(int(context['NvS']) - 1) | ||
| 126 | + def dispatch(context, hidden, route, plan, **kwargs): | ||
| 127 | + provider.calls.append(('dispatch',)) | ||
| 128 | + n = int(context['NvS']) | ||
| 129 | + context['hidden_buf'][:n].copy_(hidden.repeat_interleave(2, 0)) | ||
| 130 | + if route is not None: | ||
| 131 | + context['weights_buf'].view(torch.float32)[:n].copy_(route.flatten()) | ||
| 132 | + def combine(context, output, plan, output_sk=None, **kwargs): | ||
| 133 | + provider.calls.append(('combine',)) | ||
| 134 | + n = int(context['NvS']) | ||
| 135 | + output.copy_(context['hidden_buf'][:n].reshape(context['S'], 2, 16).sum(1)) | ||
| 136 | + if output_sk is not None: | ||
| 137 | + output_sk.copy_(context['weights_buf'].view(torch.float32)[:n].reshape(context['S'], 2)) | ||
| 138 | + ctx['kernels'] = dict(grad_reduce=provider.api.GradReduceOp(), | ||
| 139 | + planning=SimpleNamespace(compute=planning), dispatch=SimpleNamespace(compute=dispatch), | ||
| 140 | + combine=SimpleNamespace(compute=combine)) | ||
| 141 | + buffer = api.Buffer.__new__(api.Buffer) | ||
| 142 | + # This fixture deliberately bypasses __init__; mirror its frozen default. | ||
| 143 | + buffer._ctx, buffer._destroyed, buffer._shmem_ready = ctx, False, True | ||
| 144 | + buffer.explicitly_destroy = True | ||
| 145 | + buffer._comm_stream = SimpleNamespace(wait_stream=lambda stream: provider.calls.append(('wait_stream',)), | ||
| 146 | + record_event=lambda: object()) | ||
| 147 | + return buffer | ||
| 148 | + | ||
| 149 | + | ||
| 150 | + | ||
| 151 | + | ||
| 152 | + | ||
| 153 | +@pytest.fixture | ||
| 154 | +def native(provider, monkeypatch): | ||
| 155 | + api = provider.api | ||
| 156 | + provider.runtime.ShmemRuntime.is_initialized = lambda: True | ||
| 157 | + provider.runtime.ShmemRuntime._udma_enabled = True | ||
| 158 | + class Event: | ||
| 159 | + def __init__(self, stream): | ||
| 160 | + self.stream = stream | ||
| 161 | + def query(self): | ||
| 162 | + return True | ||
| 163 | + class Stream: | ||
| 164 | + device = torch.device('cpu') | ||
| 165 | + def __init__(self, name, handle): | ||
| 166 | + self.name, self.npu_stream = name, handle | ||
| 167 | + def wait_stream(self, other): | ||
| 168 | + provider.calls.append(('wait_stream', self.name, other.name)) | ||
| 169 | + def wait_event(self, event): | ||
| 170 | + provider.calls.append(('wait_event', self.name, event.stream.name)) | ||
| 171 | + def record_event(self): | ||
| 172 | + provider.calls.append(('event', self.name)) | ||
| 173 | + return Event(self) | ||
| 174 | + q0, q1 = Stream('q0', 17), Stream('q1', 19) | ||
| 175 | + current = [q1] | ||
| 176 | + @contextlib.contextmanager | ||
| 177 | + def stream(value): | ||
| 178 | + previous, current[0] = current[0], value | ||
| 179 | + try: | ||
| 180 | + yield | ||
| 181 | + finally: | ||
| 182 | + current[0] = previous | ||
| 183 | + monkeypatch.setattr(api.torch_npu.npu, 'stream', stream) | ||
| 184 | + monkeypatch.setattr(api.torch_npu.npu, 'current_stream', lambda device=None: current[0]) | ||
| 185 | + monkeypatch.setattr(api.torch_npu.npu, 'synchronize', | ||
| 186 | + lambda: pytest.fail('unexpected blocking device sync')) | ||
| 187 | + provider.native.acl_shmem_barrier_all_on_stream = lambda handle: provider.calls.append(('peer', handle)) | ||
| 188 | + provider.native._acl_shmem_barrier_all_aiv_on_stream = lambda handle: provider.calls.append(('peer_aiv', handle)) | ||
| 189 | + buffers = [] | ||
| 190 | + def make(): | ||
| 191 | + buffer = buffer_for(provider, capacity=4) | ||
| 192 | + buffer._comm_stream = q0 | ||
| 193 | + buffers.append(buffer) | ||
| 194 | + return buffer | ||
| 195 | + provider.make, provider.q0, provider.q1 = make, q0, q1 | ||
| 196 | + yield provider | ||
| 197 | + for buffer in buffers: | ||
| 198 | + buffer._destroyed = True | ||
| 199 | + api.Buffer._failed_buffer_quarantine.clear() | ||
| 200 | + | ||
| 201 | + | ||
| 202 | +def source(native, shape, dtype): | ||
| 203 | + value = torch.zeros(shape, dtype=dtype) | ||
| 204 | + value._vmm_allocation = SimpleNamespace( | ||
| 205 | + source_va=value.data_ptr(), size=value.numel() * value.element_size(), _destroyed=False) | ||
| 206 | + native.owners[value.data_ptr()] = value | ||
| 207 | + return value | ||
| 208 | + | ||
| 209 | + | ||
| 210 | +def plan_for(provider, buffer): | ||
| 211 | + ctx = provider.api._logical_context(buffer._ctx, 3) | ||
| 212 | + plan, _ = provider.api.allocate_planning_outputs(ctx) | ||
| 213 | + plan.experts_to_copy.fill_(-1) | ||
| 214 | + return plan | ||
| @@ -0,0 +1,174 @@ | |||
| 1 | +"""CPU storage and submission tests; transport is explicitly a test double.""" | ||
| 2 | +import ast | ||
| 3 | +from pathlib import Path | ||
| 4 | +from types import SimpleNamespace | ||
| 5 | + | ||
| 6 | +import pytest | ||
| 7 | +import torch | ||
| 8 | + | ||
| 9 | +from conftest import plan_for, source | ||
| 10 | + | ||
| 11 | + | ||
| 12 | +def binding_for(native, *, slots=2): | ||
| 13 | + buffer = native.make() | ||
| 14 | + buffer._ctx['B'] = slots | ||
| 15 | + full = source(native, (2 + slots, 3, 5), torch.float32) | ||
| 16 | + bank = full[2:] | ||
| 17 | + bank._vmm_allocation = full._vmm_allocation | ||
| 18 | + refs = tuple(full[:2]) | ||
| 19 | + return buffer, refs, bank, full | ||
| 20 | + | ||
| 21 | + | ||
| 22 | +@pytest.mark.parametrize('slots', [1, 2, 3]) | ||
| 23 | +def test_prepare_has_no_gradient_table_or_copy(native, monkeypatch, slots): | ||
| 24 | + buffer, refs, bank, full = binding_for(native, slots=slots) | ||
| 25 | + monkeypatch.setattr(torch, 'tensor', lambda *a, **k: pytest.fail('allocated gradient table')) | ||
| 26 | + monkeypatch.setattr(torch, 'stack', lambda *a, **k: pytest.fail('copied gradient rows')) | ||
| 27 | + binding = buffer.prepare_lplusb(refs, bank) | ||
| 28 | + assert binding.table is None | ||
| 29 | + assert binding.home.shape == (2, 3, 5) | ||
| 30 | + assert binding.home.untyped_storage()._cdata == full.untyped_storage()._cdata | ||
| 31 | + binding.home[1].fill_(17) | ||
| 32 | + assert torch.all(refs[1] == 17) | ||
| 33 | + refs[0].fill_(23) | ||
| 34 | + assert torch.all(binding.home[0] == 23) | ||
| 35 | + | ||
| 36 | + | ||
| 37 | +@pytest.mark.parametrize('bad', ['reverse', 'gap', 'independent', 'duplicate']) | ||
| 38 | +def test_prepare_rejects_non_dense_refs(native, bad): | ||
| 39 | + buffer, refs, bank, full = binding_for(native) | ||
| 40 | + refs = {'reverse': refs[::-1], 'gap': (refs[0], full[3]), | ||
| 41 | + 'independent': (refs[0].clone(), refs[1].clone()), | ||
| 42 | + 'duplicate': (refs[0], refs[0])}[bad] | ||
| 43 | + with pytest.raises(ValueError, match='consecutive|alias'): | ||
| 44 | + buffer.prepare_lplusb(refs, bank) | ||
| 45 | + | ||
| 46 | + | ||
| 47 | +def test_dense_home_preserves_nonzero_storage_offset(native): | ||
| 48 | + buffer, _, bank, full = binding_for(native) | ||
| 49 | + larger = torch.zeros(6, 3, 5) | ||
| 50 | + refs = tuple(larger[2:4]) | ||
| 51 | + binding = buffer.prepare_lplusb(refs, bank) | ||
| 52 | + binding.home.fill_(31) | ||
| 53 | + assert binding.home.storage_offset() == 30 | ||
| 54 | + assert torch.all(larger[2:4] == 31) | ||
| 55 | + assert torch.count_nonzero(larger[:2]) == 0 | ||
| 56 | + assert torch.count_nonzero(larger[4:]) == 0 | ||
| 57 | + | ||
| 58 | + | ||
| 59 | +def test_bf16_prefetch_still_uses_weight_table(native): | ||
| 60 | + buffer = native.make() | ||
| 61 | + weights = tuple(torch.ones(3, 5, dtype=torch.bfloat16) for _ in range(2)) | ||
| 62 | + bank = source(native, (2, 3, 5), torch.bfloat16) | ||
| 63 | + binding = buffer.prepare_lplusb(weights, bank) | ||
| 64 | + assert binding.home is None | ||
| 65 | + assert binding.table.tolist() == [w.data_ptr() for w in weights] | ||
| 66 | + native.calls.clear() | ||
| 67 | + buffer.prefetch_lplusb(plan_for(native, buffer), binding) | ||
| 68 | + assert native.calls[-1][0] == 'push' | ||
| 69 | + | ||
| 70 | + | ||
| 71 | +@pytest.mark.parametrize('async_finish', [False, True]) | ||
| 72 | +@pytest.mark.parametrize('use_udma', [False, True]) | ||
| 73 | +def test_reduce_reuses_dense_op_and_real_canonical_storage(native, monkeypatch, async_finish, use_udma): | ||
| 74 | + buffer, refs, bank, full = binding_for(native) | ||
| 75 | + binding = buffer.prepare_lplusb(refs, bank) | ||
| 76 | + ctx = buffer._ctx | ||
| 77 | + ctx.update(_grad_reduce_use_udma=use_udma, grad_reduce_num_sms=8) | ||
| 78 | + scratch = torch.empty(1) | ||
| 79 | + ctx['_grad_reduce_workspace'] = scratch | ||
| 80 | + plan = plan_for(native, buffer) | ||
| 81 | + plan.experts_to_copy.copy_(torch.tensor([[0, -1], [1, -1]], dtype=torch.int32)) | ||
| 82 | + bank[0].fill_(3) | ||
| 83 | + bank[1].fill_(99) | ||
| 84 | + globals_ = ctx['kernels']['grad_reduce'].compute.__globals__ | ||
| 85 | + | ||
| 86 | + def launch(home, slots, experts, **kwargs): | ||
| 87 | + assert home is binding.home and slots is binding.slot | ||
| 88 | + assert kwargs['use_udma'] is use_udma | ||
| 89 | + assert kwargs['udma_workspace'] is scratch | ||
| 90 | + assert kwargs['num_sms'] == 8 | ||
| 91 | + native.calls.append(('payload',)) | ||
| 92 | + home[0].add_(slots[0]) | ||
| 93 | + slots[0].zero_() | ||
| 94 | + | ||
| 95 | + monkeypatch.setitem(globals_, 'launch_grad_reduce', launch) | ||
| 96 | + monkeypatch.setattr(torch, 'tensor', lambda *a, **k: pytest.fail('hot pointer table')) | ||
| 97 | + native.calls.clear() | ||
| 98 | + result = buffer.reduce_grad(plan, async_finish=async_finish, lplusb=binding) | ||
| 99 | + assert (result is not None) is async_finish | ||
| 100 | + assert torch.all(refs[0] == 3) and torch.count_nonzero(refs[1]) == 0 | ||
| 101 | + assert torch.count_nonzero(bank[0]) == 0 and torch.all(bank[1] == 99) | ||
| 102 | + if async_finish: | ||
| 103 | + assert native.calls[0] == ('wait_stream', 'q0', 'q1') | ||
| 104 | + assert native.calls.index(('payload',)) > 0 | ||
| 105 | + assert native.calls[-1] == ('event', 'q0') | ||
| 106 | + else: | ||
| 107 | + assert native.calls == [('payload',)] | ||
| 108 | + | ||
| 109 | + | ||
| 110 | +def test_ref_signature_guard_is_retained(native): | ||
| 111 | + buffer, refs, bank, full = binding_for(native) | ||
| 112 | + binding = buffer.prepare_lplusb(refs, bank) | ||
| 113 | + refs[0].data = refs[0].clone() | ||
| 114 | + with pytest.raises(ValueError, match='rebound'): | ||
| 115 | + buffer.reduce_grad(plan_for(native, buffer), lplusb=binding) | ||
| 116 | + | ||
| 117 | + | ||
| 118 | +@pytest.mark.parametrize('blocks,expected', [(32, 128 << 20), (4, 96 << 20)]) | ||
| 119 | +def test_setup_workspace_is_allocated_once(native, monkeypatch, blocks, expected): | ||
| 120 | + buffer = native.make() | ||
| 121 | + buffer._ctx.update(E=48, R=8, B=6, _grad_reduce_use_udma=True, grad_reduce_num_sms=blocks) | ||
| 122 | + full = source(native, (12, 3, 5), torch.float32) | ||
| 123 | + bank = full[6:] | ||
| 124 | + bank._vmm_allocation = full._vmm_allocation | ||
| 125 | + refs = tuple(full[:6]) | ||
| 126 | + allocations = [] | ||
| 127 | + empty = torch.empty | ||
| 128 | + def allocate(size, **kwargs): | ||
| 129 | + allocations.append(size) | ||
| 130 | + return empty(1, **kwargs) | ||
| 131 | + monkeypatch.setattr(torch, 'empty', allocate) | ||
| 132 | + first = buffer.prepare_lplusb(refs, bank) | ||
| 133 | + scratch = buffer._ctx['_grad_reduce_workspace'] | ||
| 134 | + second = buffer.prepare_lplusb(refs, bank) | ||
| 135 | + assert allocations == [expected // 4] | ||
| 136 | + assert buffer._ctx['_grad_reduce_workspace'] is scratch | ||
| 137 | + assert first.table is second.table is None | ||
| 138 | + | ||
| 139 | + | ||
| 140 | +def test_private_sync_reduce_also_uses_dense_entry(native, monkeypatch): | ||
| 141 | + buffer, refs, bank, full = binding_for(native) | ||
| 142 | + seen = [] | ||
| 143 | + op = buffer._ctx['kernels']['grad_reduce'] | ||
| 144 | + monkeypatch.setitem(op.compute.__globals__, 'launch_grad_reduce', lambda *a, **k: seen.append(a)) | ||
| 145 | + buffer._reduce_expert_grads(plan_for(native, buffer), refs, bank) | ||
| 146 | + assert seen[0][0].data_ptr() == refs[0].data_ptr() | ||
| 147 | + assert seen[0][0].shape == (2, 3, 5) | ||
| 148 | + | ||
| 149 | + | ||
| 150 | +@pytest.mark.parametrize('use_udma', [False, True]) | ||
| 151 | +@pytest.mark.parametrize('override', [None, False, True]) | ||
| 152 | +def test_launcher_packs_dense_backend_workspace(native, use_udma, override): | ||
| 153 | + root = Path(__file__).resolve().parents[1] | ||
| 154 | + path = root / 'npu_patch/launchers.py' | ||
| 155 | + tree = ast.parse(path.read_text(encoding='utf-8')) | ||
| 156 | + fn = next(n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == 'launch_grad_reduce') | ||
| 157 | + calls = [] | ||
| 158 | + ns = dict(__package__='npu_patch', torch=torch, _env_use_udma=lambda _: use_udma, | ||
| 159 | + _GRAD_REDUCE=SimpleNamespace(compute=lambda *a: calls.append(a))) | ||
| 160 | + exec(compile(ast.Module(body=[fn], type_ignores=[]), str(path), 'exec'), ns) | ||
| 161 | + class Tensor: | ||
| 162 | + device = SimpleNamespace(type='npu') | ||
| 163 | + def __init__(self, shape, dtype): | ||
| 164 | + self.shape, self.dtype, self.ndim = shape, dtype, len(shape) | ||
| 165 | + def is_contiguous(self): return True | ||
| 166 | + def numel(self): return 1 | ||
| 167 | + home, bank, plan = Tensor((6, 3, 5), torch.float32), Tensor((6, 3, 5), torch.float32), Tensor((8, 6), torch.int32) | ||
| 168 | + scratch = object() | ||
| 169 | + ns['launch_grad_reduce'](home, bank, plan, 5, 128, None, 0, 0, None, | ||
| 170 | + use_udma=override, udma_workspace=scratch) | ||
| 171 | + backend = use_udma if override is None else override | ||
| 172 | + assert calls[0][:3] == (home, bank, plan) | ||
| 173 | + assert calls[0][3:11] == (6, 3, 5, 8, 6, 5, 64, backend) | ||
| 174 | + assert calls[0][11] is (scratch if backend else None) | ||
| @@ -0,0 +1,133 @@ | |||
| 1 | +"""Compile the production C++ operator with CPU tensor/runtime metadata doubles. | ||
| 2 | + | ||
| 3 | +This checks validation and submission order, without claiming NPU arithmetic. | ||
| 4 | +""" | ||
| 5 | +from pathlib import Path | ||
| 6 | +import shutil | ||
| 7 | +import subprocess | ||
| 8 | + | ||
| 9 | +import pytest | ||
| 10 | + | ||
| 11 | + | ||
| 12 | +@pytest.fixture(scope='module') | ||
| 13 | +def native_op(tmp_path_factory): | ||
| 14 | + compiler = shutil.which('g++') or shutil.which('c++') | ||
| 15 | + if compiler is None: | ||
| 16 | + pytest.skip('CPU C++ compiler required') | ||
| 17 | + root = Path(__file__).resolve().parents[1] | ||
| 18 | + path = root / 'npu_patch/native/csrc/ops/grad_reduce.cpp' | ||
| 19 | + production = '\n'.join(line for line in path.read_text(encoding='utf-8').splitlines() | ||
| 20 | + if not line.startswith('#include')) | ||
| 21 | + prelude = r''' | ||
| 22 | +#include <algorithm> | ||
| 23 | +#include <cstdint> | ||
| 24 | +#include <cstdlib> | ||
| 25 | +#include <iostream> | ||
| 26 | +#include <limits> | ||
| 27 | +#include <memory> | ||
| 28 | +#include <stdexcept> | ||
| 29 | +#include <string> | ||
| 30 | +#include <vector> | ||
| 31 | +int allocations = 0, barriers = 0, scenario = 0; | ||
| 32 | +std::vector<std::string> events; | ||
| 33 | +#define TORCH_CHECK(condition, ...) if (!(condition)) throw std::runtime_error("metadata") | ||
| 34 | +namespace c10 { enum class DeviceType { PrivateUse1, CPU }; } | ||
| 35 | +struct Device { | ||
| 36 | + c10::DeviceType value = c10::DeviceType::PrivateUse1; | ||
| 37 | + c10::DeviceType type() const { return value; } | ||
| 38 | + bool operator==(const Device& other) const { return value == other.value; } | ||
| 39 | +}; | ||
| 40 | +namespace torch { | ||
| 41 | +constexpr int kFloat32 = 1, kInt32 = 2, kInt64 = 3; | ||
| 42 | +struct State { std::vector<int64_t> shape; int dtype; }; | ||
| 43 | +class Tensor { | ||
| 44 | + std::shared_ptr<State> data; | ||
| 45 | +public: | ||
| 46 | + Tensor() = default; | ||
| 47 | + Tensor(std::vector<int64_t> shape, int dtype): data(std::make_shared<State>(State{shape, dtype})) {} | ||
| 48 | + bool defined() const { return bool(data); } | ||
| 49 | + Device device() const { return {}; } | ||
| 50 | + bool is_contiguous() const { return true; } | ||
| 51 | + int scalar_type() const { return data->dtype; } | ||
| 52 | + int64_t dim() const { return data->shape.size(); } | ||
| 53 | + int64_t size(int i) const { return data->shape.at(i); } | ||
| 54 | + int64_t numel() const { int64_t n=1; for (auto s:data->shape) n*=s; return n; } | ||
| 55 | + int options() const { return data->dtype; } | ||
| 56 | + template<class T=void> T* data_ptr() const { return reinterpret_cast<T*>(data.get()); } | ||
| 57 | +}; | ||
| 58 | +Tensor empty(int64_t size, int dtype) { ++allocations; return Tensor({size}, dtype); } | ||
| 59 | +} | ||
| 60 | +using aclrtStream = void*; | ||
| 61 | +namespace c10_npu { | ||
| 62 | +struct Stream { void* stream() const { return reinterpret_cast<void*>(1); } }; | ||
| 63 | +Stream getCurrentNPUStream() { return {}; } | ||
| 64 | +} | ||
| 65 | +constexpr int ACL_SUCCESS = 0; | ||
| 66 | +int moonep_grad_reduce_native_barrier(void*) { | ||
| 67 | + ++barriers; | ||
| 68 | + events.push_back("barrier"); | ||
| 69 | + return (scenario == 4 && barriers == 1) || (scenario == 6 && barriers == 2) ? 9 : 0; | ||
| 70 | +} | ||
| 71 | +int payload(const char* name, int32_t epn, int32_t hidden, int32_t projection, | ||
| 72 | + int32_t ranks, int32_t slots, int32_t rank, int32_t blocks) { | ||
| 73 | + if (epn!=2 || hidden!=3 || projection!=5 || ranks!=2 || slots!=2 || rank!=0 || blocks!=8) | ||
| 74 | + throw std::runtime_error("arguments"); | ||
| 75 | + events.push_back(name); | ||
| 76 | + return scenario == 5 ? 11 : 0; | ||
| 77 | +} | ||
| 78 | +int moonep_shmem_grad_reduce(void*, void*, void*, const int32_t*, | ||
| 79 | + int32_t e, int32_t h, int32_t p, int32_t r, int32_t b, int32_t rank, int32_t blocks) { | ||
| 80 | + return payload("mte", e,h,p,r,b,rank,blocks); | ||
| 81 | +} | ||
| 82 | +int moonep_shmem_grad_reduce_udma(void*, void*, void*, void*, const int32_t*, | ||
| 83 | + int32_t e, int32_t h, int32_t p, int32_t r, int32_t b, int32_t rank, int32_t blocks) { | ||
| 84 | + return payload("udma", e,h,p,r,b,rank,blocks); | ||
| 85 | +} | ||
| 86 | +''' | ||
| 87 | + main = r''' | ||
| 88 | +int main(int argc, char** argv) { | ||
| 89 | + if(argc!=3) return 2; | ||
| 90 | + scenario=std::atoi(argv[1]); | ||
| 91 | + bool udma=std::atoi(argv[2]); | ||
| 92 | + torch::Tensor home({2,3,5}, torch::kFloat32), slots({2,3,5}, torch::kFloat32), | ||
| 93 | + plan({2,2}, torch::kInt32), workspace({512*1024*16}, torch::kFloat32); | ||
| 94 | + if (scenario==1) workspace=torch::Tensor(); | ||
| 95 | + if (scenario==2) workspace=torch::Tensor({1}, torch::kFloat32); | ||
| 96 | + if (scenario==3) workspace=torch::Tensor({512*1024*16}, torch::kInt64); | ||
| 97 | + if (scenario==7) home=torch::Tensor({3,3,5}, torch::kFloat32); | ||
| 98 | + try { | ||
| 99 | + ascend_moonep::ops::GradReduce(home, slots, plan, 2,3,5,2,2,0,8,udma,workspace); | ||
| 100 | + std::cout << "ok"; | ||
| 101 | + } catch(const std::exception&) { std::cout << "error"; } | ||
| 102 | + std::cout << " allocations=" << allocations; | ||
| 103 | + for (const auto& e:events) std::cout << " " << e; | ||
| 104 | + std::cout << "\n"; | ||
| 105 | +} | ||
| 106 | +''' | ||
| 107 | + directory = tmp_path_factory.mktemp('dense_native_op') | ||
| 108 | + src, binary = directory / 'op.cpp', directory / 'op' | ||
| 109 | + src.write_text(prelude + production + main, encoding='utf-8') | ||
| 110 | + result = subprocess.run([compiler, '-std=c++17', str(src), '-o', str(binary)], | ||
| 111 | + capture_output=True, text=True, timeout=60) | ||
| 112 | + assert result.returncode == 0, result.stderr | ||
| 113 | + return binary | ||
| 114 | + | ||
| 115 | + | ||
| 116 | +@pytest.mark.parametrize('backend', [0, 1]) | ||
| 117 | +@pytest.mark.parametrize('scenario', range(8)) | ||
| 118 | +def test_dense_native_validation_workspace_and_barriers(native_op, backend, scenario): | ||
| 119 | + run = subprocess.run([str(native_op), str(scenario), str(backend)], | ||
| 120 | + capture_output=True, text=True, timeout=5) | ||
| 121 | + assert run.returncode == 0, run.stderr | ||
| 122 | + payload = 'udma' if backend else 'mte' | ||
| 123 | + allocation = int(backend == 1 and scenario == 1) | ||
| 124 | + if scenario == 7 or (backend and scenario in (2, 3)): | ||
| 125 | + expected = 'error allocations=0' | ||
| 126 | + elif scenario == 4: | ||
| 127 | + expected = f'error allocations={allocation} barrier' | ||
| 128 | + elif scenario == 5: | ||
| 129 | + expected = f'error allocations={allocation} barrier {payload}' | ||
| 130 | + else: | ||
| 131 | + status = 'error' if scenario == 6 else 'ok' | ||
| 132 | + expected = f'{status} allocations={allocation} barrier {payload} barrier' | ||
| 133 | + assert run.stdout.strip() == expected | ||
| @@ -0,0 +1,207 @@ | |||
| 1 | +"""Execute the fused UDMA and MTE host launchers with CPU fault-injection stubs. | ||
| 2 | + | ||
| 3 | +Only <<<...>>> launch syntax is lowered; the host conditions and return paths | ||
| 4 | +are compiled unchanged. This tests submission order/error propagation, not | ||
| 5 | +device execution, FP32 arithmetic, or remote completion. | ||
| 6 | +""" | ||
| 7 | +import os | ||
| 8 | +import shutil | ||
| 9 | +import subprocess | ||
| 10 | + | ||
| 11 | +from pathlib import Path | ||
| 12 | +MOONEP_ROOT = Path(__file__).resolve().parents[1] | ||
| 13 | + | ||
| 14 | +import pytest | ||
| 15 | + | ||
| 16 | + | ||
| 17 | +SOURCE = (MOONEP_ROOT / | ||
| 18 | + 'npu_patch/native/kernels/moonep_grad_reduce_udma.cpp') | ||
| 19 | +BARRIER_SOURCE = SOURCE.with_name('barrier.cpp') | ||
| 20 | + | ||
| 21 | + | ||
| 22 | +@pytest.fixture(scope='module', params=('udma_dense', 'mte_dense')) | ||
| 23 | +def launch_binary(request, tmp_path_factory): | ||
| 24 | + compiler = shutil.which('g++') or shutil.which('c++') | ||
| 25 | + if compiler is None: | ||
| 26 | + pytest.skip('CPU C++ compiler required for native host fault injection') | ||
| 27 | + entry = request.param | ||
| 28 | + source_path = SOURCE if entry.startswith('udma_') else SOURCE.with_name('moonep_grad_reduce.cpp') | ||
| 29 | + text = source_path.read_text(encoding='utf-8') | ||
| 30 | + launch = 'LaunchGradReduceUdma' if entry.startswith('udma_') else 'LaunchGradReduce' | ||
| 31 | + begin = text.index('static int ' + launch + '(') | ||
| 32 | + end = text.index('\nextern "C"', begin) | ||
| 33 | + host = text[begin:end] | ||
| 34 | + # Exactly one site for each kernel: unexpected source changes fail closed. | ||
| 35 | + kernels = ([ | ||
| 36 | + ('MoonEPShmemClearValidGradSlots', 'clear', '1', 1), | ||
| 37 | + ('MoonEPShmemGradReduceUdmaFused', 'fused', 'blocks', 1), | ||
| 38 | + ] if entry.startswith('udma_') else [ | ||
| 39 | + ('MoonEPShmemGradReduceFused', 'ordered', 'blocks', 1), | ||
| 40 | + ('MoonEPShmemGradReduceClearValidSlots', 'clear', 'blocks', 1), | ||
| 41 | + ]) | ||
| 42 | + for name, stub, blocks, count in kernels: | ||
| 43 | + token = f'{name}<<<{blocks}, nullptr, stream>>>' | ||
| 44 | + assert host.count(token) == count | ||
| 45 | + host = host.replace(token, stub) | ||
| 46 | + assert '<<<' not in host | ||
| 47 | + # Compile the shared barrier selector for both engines. Dense | ||
| 48 | + # launchers use the same shared selector. | ||
| 49 | + barrier_source = BARRIER_SOURCE.read_text(encoding='utf-8') | ||
| 50 | + begin = barrier_source.index('extern "C" ASCEND_MOONEP_EXPORT int moonep_grad_reduce_native_barrier(') | ||
| 51 | + barrier = barrier_source[begin:] | ||
| 52 | + barrier = barrier.replace( | ||
| 53 | + 'MoonEPGradReduceBarrierAiv<<<1, nullptr, stream>>>(', 'aiv_barrier(1, ') | ||
| 54 | + assert '<<<' not in barrier | ||
| 55 | + host = barrier + host | ||
| 56 | + prelude = r''' | ||
| 57 | +#include <cstdint> | ||
| 58 | +#include <cstdlib> | ||
| 59 | +#include <cstring> | ||
| 60 | +#include <iostream> | ||
| 61 | +#include <string> | ||
| 62 | +#include <vector> | ||
| 63 | +constexpr int ACL_SUCCESS = 0; | ||
| 64 | +constexpr int ACL_ERROR_INVALID_PARAM = 7; | ||
| 65 | +constexpr int ACL_RT_THREAD_LEVEL = 0; | ||
| 66 | +#define ASCEND_MOONEP_EXPORT | ||
| 67 | +int scenario, last_error; | ||
| 68 | +std::vector<std::string> events; | ||
| 69 | +int aclrtPeekAtLastError(int) { return last_error; } | ||
| 70 | +int aclrtGetLastError(int) { | ||
| 71 | + const int previous = last_error; last_error = 0; return previous; | ||
| 72 | +} | ||
| 73 | +int aclshmem_n_pes() { return scenario == 6 ? 3 : 2; } | ||
| 74 | +uint64_t shmemx_get_ffts_config() { return 0; } | ||
| 75 | +template<class... T> void ordered(T...) { | ||
| 76 | + events.push_back("ordered"); | ||
| 77 | + last_error = scenario == 2 ? 43 : 0; | ||
| 78 | +} | ||
| 79 | +void fused(uint64_t, uint8_t*, uint8_t*, uint8_t*, uint8_t*, | ||
| 80 | + int32_t, int32_t, int32_t, int32_t, int32_t, int32_t) { | ||
| 81 | + events.push_back("fused"); | ||
| 82 | + last_error = scenario == 2 ? 43 : 0; | ||
| 83 | +} | ||
| 84 | +void aclshmemx_barrier_all_on_stream(void*) { | ||
| 85 | + events.push_back("stream_barrier"); | ||
| 86 | + last_error = scenario == 3 ? 47 : 0; | ||
| 87 | +} | ||
| 88 | +void aiv_barrier(int blocks, uint64_t) { | ||
| 89 | + events.push_back("aiv" + std::to_string(blocks)); | ||
| 90 | + last_error = scenario == 3 ? 47 : 0; | ||
| 91 | +} | ||
| 92 | +template<class... T> void clear(T...) { | ||
| 93 | + events.push_back("clear"); | ||
| 94 | + last_error = scenario == 4 ? 53 : 0; | ||
| 95 | +} | ||
| 96 | +''' | ||
| 97 | + inputs = '&data, &data, &data, &data' if entry.startswith('udma_') else '&data, &data, &data' | ||
| 98 | + main = r''' | ||
| 99 | +int main(int argc, char** argv) { | ||
| 100 | + if (argc != 2) return 2; | ||
| 101 | + scenario = std::atoi(argv[1]); | ||
| 102 | + last_error = scenario == 1 ? 41 : 0; | ||
| 103 | + int data = 0; | ||
| 104 | + auto* stream = scenario == 5 ? nullptr : static_cast<void*>(&data); | ||
| 105 | + int status = LAUNCH_FUNCTION(stream, INPUT_ARGUMENTS, | ||
| 106 | + 1, 3, 5, 2, 1, 0, 8); | ||
| 107 | + std::cout << status; | ||
| 108 | + for (auto const& event : events) std::cout << " " << event; | ||
| 109 | + std::cout << "\n"; | ||
| 110 | +} | ||
| 111 | +''' | ||
| 112 | + main = main.replace('LAUNCH_FUNCTION', launch).replace('INPUT_ARGUMENTS', inputs) | ||
| 113 | + directory = tmp_path_factory.mktemp('ordered_host_launch_' + entry) | ||
| 114 | + source = directory / 'host.cpp' | ||
| 115 | + binary = directory / 'host' | ||
| 116 | + source.write_text(prelude + host + main, encoding='utf-8') | ||
| 117 | + result = subprocess.run([compiler, '-std=c++17', '-Wall', '-Wextra', | ||
| 118 | + str(source), '-o', str(binary)], | ||
| 119 | + capture_output=True, text=True, timeout=60) | ||
| 120 | + assert result.returncode == 0, result.stderr | ||
| 121 | + return binary, entry | ||
| 122 | + | ||
| 123 | + | ||
| 124 | +@pytest.mark.parametrize('scenario,expected', [ | ||
| 125 | + (0, '0 ordered stream_barrier clear'), | ||
| 126 | + (1, '41'), # Preserve a pre-existing ACL error. | ||
| 127 | + (2, '43 ordered'), # Failed GET/reduce launch: no barrier. | ||
| 128 | + (3, '47 ordered stream_barrier'), # Failed barrier: must not clear slots. | ||
| 129 | + (4, '53 ordered stream_barrier clear'), | ||
| 130 | + (5, '7'), # Invalid stream: no launch. | ||
| 131 | + (6, '7'), # SHMEM world mismatch: no launch. | ||
| 132 | +]) | ||
| 133 | +def test_submission_fails_closed(launch_binary, scenario, expected): | ||
| 134 | + binary, entry = launch_binary | ||
| 135 | + if scenario == 1 and entry != 'udma_dense': | ||
| 136 | + # MTE retains its original error reset; UDMA preserves the first failure. | ||
| 137 | + expected = '0 ordered stream_barrier clear' | ||
| 138 | + if entry.startswith('udma_'): | ||
| 139 | + expected = expected.replace('ordered', 'fused') | ||
| 140 | + result = subprocess.run([str(binary), str(scenario)], env=barrier_env(), | ||
| 141 | + capture_output=True, text=True, timeout=5) | ||
| 142 | + assert result.returncode == 0, result.stderr | ||
| 143 | + assert result.stdout.strip() == expected | ||
| 144 | + | ||
| 145 | + | ||
| 146 | +def barrier_env(mode=None, blocks=None): | ||
| 147 | + env = dict(os.environ) | ||
| 148 | + for key, value in [('MOONEP_GRAD_REDUCE_NATIVE_BARRIER_MODE', mode), | ||
| 149 | + ('MOONEP_GRAD_REDUCE_NATIVE_AIV_BLOCKS', blocks)]: | ||
| 150 | + env.pop(key, None) | ||
| 151 | + if value is not None: | ||
| 152 | + env[key] = value | ||
| 153 | + return env | ||
| 154 | + | ||
| 155 | + | ||
| 156 | +@pytest.mark.parametrize('mode,blocks,expected', [ | ||
| 157 | + (None, None, '0 ordered stream_barrier clear'), | ||
| 158 | + ('mixed', None, '0 ordered stream_barrier clear'), | ||
| 159 | + ('aiv', None, '0 ordered aiv1 clear'), | ||
| 160 | + ('aiv', '2', '0 ordered aiv1 clear'), | ||
| 161 | + ('invalid', None, '7 ordered'), | ||
| 162 | +]) | ||
| 163 | +def test_barrier_selection_preserves_read_barrier_clear_order(launch_binary, mode, blocks, expected): | ||
| 164 | + binary, entry = launch_binary | ||
| 165 | + if entry.startswith('udma_'): | ||
| 166 | + expected = expected.replace('ordered', 'fused') | ||
| 167 | + result = subprocess.run([str(binary), '0'], env=barrier_env(mode, blocks), | ||
| 168 | + capture_output=True, text=True, timeout=5) | ||
| 169 | + assert result.returncode == 0, result.stderr | ||
| 170 | + assert result.stdout.strip() == expected | ||
| 171 | + | ||
| 172 | + | ||
| 173 | +def test_aiv_barrier_failure_prevents_slot_clear(launch_binary): | ||
| 174 | + binary, entry = launch_binary | ||
| 175 | + expected = '47 ordered ' + 'aiv1' | ||
| 176 | + if entry.startswith('udma_'): | ||
| 177 | + expected = expected.replace('ordered', 'fused') | ||
| 178 | + result = subprocess.run([str(binary), '3'], env=barrier_env('aiv'), | ||
| 179 | + capture_output=True, text=True, timeout=5) | ||
| 180 | + assert result.returncode == 0, result.stderr | ||
| 181 | + assert result.stdout.strip() == expected | ||
| 182 | + | ||
| 183 | + | ||
| 184 | +def test_only_fused_udma_payload_remains(): | ||
| 185 | + text = SOURCE.read_text(encoding='utf-8') | ||
| 186 | + assert 'MoonEPShmemGradReduceUdmaOrderedTargets' not in text | ||
| 187 | + assert 'MOONEP_GRAD_REDUCE_UDMA_IMPL' not in text | ||
| 188 | + assert text.count('MoonEPShmemGradReduceUdmaFused<<<') == 1 | ||
| 189 | + | ||
| 190 | + | ||
| 191 | +@pytest.mark.parametrize('name', ('moonep_grad_reduce.cpp', 'moonep_grad_reduce_udma.cpp')) | ||
| 192 | +def test_world_barrier_is_submitted_between_work_and_clear(name): | ||
| 193 | + text = SOURCE.with_name(name).read_text(encoding='utf-8') | ||
| 194 | + device, host = text.split('static int LaunchGradReduce', 1) | ||
| 195 | + assert 'moonep_prefetch_barrier_vec' not in text | ||
| 196 | + # The WORLD call lives in the shared barrier translation unit, never the | ||
| 197 | + # local payload kernels. | ||
| 198 | + assert 'barrier_all' not in device | ||
| 199 | + assert 'aclshmemx_barrier_all_vec' not in text | ||
| 200 | + assert 'void MoonEPGradReduceBarrierAiv(' in BARRIER_SOURCE.read_text(encoding='utf-8') | ||
| 201 | + cmake = BARRIER_SOURCE.parents[1] / 'CMakeLists.txt' | ||
| 202 | + assert 'kernels/barrier.cpp' in cmake.read_text(encoding='utf-8') | ||
| 203 | + token = 'status = moonep_grad_reduce_native_barrier(stream);' | ||
| 204 | + # Synchronization is still before clearing, with a submission error gate. | ||
| 205 | + barrier = host.index(token) | ||
| 206 | + clear = host.index('Slots<<<', barrier) | ||
| 207 | + assert 'if (status != ACL_SUCCESS)' in host[barrier:clear] | ||
| @@ -0,0 +1,121 @@ | |||
| 1 | +"""Device acceptance for the additive native APIs; run with fresh workers. | ||
| 2 | + | ||
| 3 | +MOONEP_NATIVE_TEST_UDMA=0 torchrun --nproc-per-node=2 -m pytest -s -x \ | ||
| 4 | + test_npu/buffer_test/test_buffer_native_async_extensions.py | ||
| 5 | + | ||
| 6 | +Repeat with world=8, then UDMA=1 on Ascend950 with matching native ABIs. | ||
| 7 | +No profiling/performance claim is made by this correctness test. | ||
| 8 | +""" | ||
| 9 | +import os | ||
| 10 | + | ||
| 11 | +import pytest | ||
| 12 | +import torch | ||
| 13 | +import torch.distributed as dist | ||
| 14 | +import torch_npu | ||
| 15 | + | ||
| 16 | +from npu_patch import Buffer, ShmemRuntime | ||
| 17 | +from npu_patch.buffer_c import create_vmm_physical, reset_symmetric_descriptors | ||
| 18 | + | ||
| 19 | + | ||
| 20 | +def test_native_async_storage_and_lplusb(dist_env): | ||
| 21 | + rank, world = dist_env | ||
| 22 | + if world not in (2, 8): | ||
| 23 | + pytest.skip('acceptance recipe is EP2 or EP8') | ||
| 24 | + raw = os.environ.get('MOONEP_NATIVE_TEST_UDMA', '0') | ||
| 25 | + if raw not in ('0', '1'): | ||
| 26 | + raise ValueError('MOONEP_NATIVE_TEST_UDMA must be 0 or 1') | ||
| 27 | + udma = raw == '1' | ||
| 28 | + if ShmemRuntime.is_initialized(): | ||
| 29 | + raise RuntimeError('run this acceptance test alone in fresh workers') | ||
| 30 | + s, h, k, local, b = 16, 128, 1, 2, 2 | ||
| 31 | + device = torch.device('npu', torch.npu.current_device()) | ||
| 32 | + buffer = Buffer(S=s, H=h, K=k, E=world * local, B=b, num_ep_ranks=world, | ||
| 33 | + group=dist.group.WORLD, explicitly_destroy=True, | ||
| 34 | + prefetch_use_udma=udma, grad_reduce_use_udma=udma) | ||
| 35 | + sources = [] | ||
| 36 | + def allocate(shape, dtype): | ||
| 37 | + value, _, _ = create_vmm_physical(shape, dtype, device.index) | ||
| 38 | + sources.append(value) | ||
| 39 | + return value | ||
| 40 | + # Every rank registers the same inventory/order before one-shot SHMEM init. | ||
| 41 | + activation_sources = [(allocate((s * k, h), torch.bfloat16), | ||
| 42 | + allocate((s * k,), torch.int32)) for _ in range(3)] | ||
| 43 | + weight_slots = allocate((b, h, h), torch.bfloat16) | ||
| 44 | + full_grad = allocate((local + b, h, h), torch.float32) | ||
| 45 | + grad_slots = full_grad[local:] | ||
| 46 | + grad_slots._vmm_allocation = full_grad._vmm_allocation | ||
| 47 | + weights = tuple(torch.full((h, h), rank * local + i + 1, | ||
| 48 | + dtype=torch.bfloat16, device=device) for i in range(local)) | ||
| 49 | + targets = tuple(full_grad[i] for i in range(local)) | ||
| 50 | + for i, target in enumerate(targets): | ||
| 51 | + target.fill_(10 + rank * local + i) | ||
| 52 | + ShmemRuntime.init_with_buffer(group=dist.group.WORLD, enable_udma=udma, | ||
| 53 | + qp_count=2 if udma else 0) | ||
| 54 | + banks = [buffer.prepare_comm_buffers(*pair) for pair in activation_sources] | ||
| 55 | + wbind = buffer.prepare_lplusb(weights, weight_slots) | ||
| 56 | + gbind = buffer.prepare_lplusb(targets, grad_slots) | ||
| 57 | + q1 = torch_npu.npu.current_stream() | ||
| 58 | + routes = torch.zeros(s, k, dtype=torch.int32, device=device) | ||
| 59 | + counts = torch.bincount(routes.flatten().long(), minlength=world * local).int() | ||
| 60 | + probabilities = torch.ones(s, k, dtype=torch.float32, device=device) | ||
| 61 | + saved = [] | ||
| 62 | + # Three live Z3/R1/Z1-like outputs must survive later communication calls. | ||
| 63 | + for value, bank in zip((1, 2, 3), banks): | ||
| 64 | + hidden = torch.full((s, h), rank * 4 + value, dtype=torch.bfloat16, device=device) | ||
| 65 | + out, probs, cu, plan, done = buffer.dispatch(hidden, probabilities, routes, counts, | ||
| 66 | + async_finish=True, zero_copy=True, router_weights_zero_copy=True, comm_buffers=bank) | ||
| 67 | + saved.append((hidden, out, probs, plan, done, bank)) | ||
| 68 | + for hidden, out, probs, plan, done, bank in saved: | ||
| 69 | + q1.wait_event(done) | ||
| 70 | + combined, _, event = buffer.combine(plan, out, async_finish=True, | ||
| 71 | + zero_copy=True, comm_buffers=bank) | ||
| 72 | + q1.wait_event(event) | ||
| 73 | + torch.npu.synchronize() | ||
| 74 | + torch.testing.assert_close(combined, hidden, atol=0, rtol=0) | ||
| 75 | + # Default copying path uses no bank argument and preserves each result. | ||
| 76 | + copied = [] | ||
| 77 | + for value in (5, 6): | ||
| 78 | + hidden = torch.full((s, h), value, dtype=torch.bfloat16, device=device) | ||
| 79 | + out, _, _, plan, event = buffer.dispatch(hidden, probabilities, routes, counts, | ||
| 80 | + async_finish=True) | ||
| 81 | + copied.append((hidden, out, plan, event)) | ||
| 82 | + for hidden, out, plan, event in copied: | ||
| 83 | + q1.wait_event(event) | ||
| 84 | + result, _, event = buffer.combine(plan, out, async_finish=True) | ||
| 85 | + q1.wait_event(event) | ||
| 86 | + torch.npu.synchronize() | ||
| 87 | + torch.testing.assert_close(result, hidden, atol=0, rtol=0) | ||
| 88 | + | ||
| 89 | + # Use an explicit replicated ring plan to exercise nonempty and empty slots | ||
| 90 | + # on all ranks, independently of the token planner's load distribution. | ||
| 91 | + plan = saved[-1][3].clone() | ||
| 92 | + ring = torch.full((world, b), -1, dtype=torch.int32) | ||
| 93 | + for peer in range(world): | ||
| 94 | + ring[peer, 0] = ((peer + 1) % world) * local | ||
| 95 | + plan.experts_to_copy.copy_(ring.to(device)) | ||
| 96 | + done = buffer.prefetch_lplusb(plan, wbind, async_finish=True) | ||
| 97 | + q1.wait_event(done) | ||
| 98 | + torch.npu.synchronize() | ||
| 99 | + torch.testing.assert_close(wbind.slot[0], torch.full_like(wbind.slot[0], | ||
| 100 | + int(ring[rank, 0]) + 1), atol=0, rtol=0) | ||
| 101 | + for round_id in range(2): | ||
| 102 | + gbind.slot.fill_(99) | ||
| 103 | + gbind.slot[0].fill_(rank + 1) | ||
| 104 | + done = buffer.reduce_grad(plan, async_finish=True, lplusb=gbind) | ||
| 105 | + q1.wait_event(done) | ||
| 106 | + torch.npu.synchronize() | ||
| 107 | + for i, target in enumerate(targets): | ||
| 108 | + contribution = sum(peer + 1 for peer in range(world) | ||
| 109 | + if int(ring[peer, 0]) == rank * local + i) | ||
| 110 | + expected = 10 + rank * local + i + (round_id + 1) * contribution | ||
| 111 | + torch.testing.assert_close(target, torch.full_like(target, expected), atol=0, rtol=0) | ||
| 112 | + assert torch.count_nonzero(gbind.slot[0]).item() == 0 | ||
| 113 | + assert torch.all(gbind.slot[1] == 99).item() | ||
| 114 | + # Only successful, globally drained execution may reach teardown. | ||
| 115 | + torch.npu.synchronize() | ||
| 116 | + dist.barrier() | ||
| 117 | + ShmemRuntime.finalize() | ||
| 118 | + buffer.destroy() | ||
| 119 | + for source in sources: | ||
| 120 | + source._vmm_allocation.destroy() | ||
| 121 | + reset_symmetric_descriptors() | ||