已合并
feat: 为三个 DeepSeek V4.1 算子提供 JIT 和 ACLNN 入口 #1067
xuzhenghao8创建于 13 天前
feat: 为三个 DeepSeek V4.1 算子提供 JIT 和 ACLNN 入口 #1067
已合并
共 49 个文件变更+10965-4
| @@ -0,0 +1,21 @@ | |||
| 1 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 10 | +# 算子级 dispatcher: 派发算子子目录(op_host 必选, tests 等按需). | ||
| 11 | +# 算子接入契约: gym_op_discovery 锚定本文件, 缺失即 FATAL. | ||
| 12 | + | ||
| 13 | +file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*) | ||
| 14 | +if(NOT ENABLE_TESTS) | ||
| 15 | + list(REMOVE_ITEM CURRENT_DIRS tests) | ||
| 16 | +endif() | ||
| 17 | +foreach(SUB_DIR ${CURRENT_DIRS}) | ||
| 18 | + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") | ||
| 19 | + add_subdirectory(${SUB_DIR}) | ||
| 20 | + endif() | ||
| 21 | +endforeach() | ||
| @@ -0,0 +1,306 @@ | |||
| 1 | +# AttnPrologue(PyPTO Pro,KV compress 融合) | ||
| 2 | + | ||
| 3 | +本实现在 A2 KV 支路内直接完成 `kv_compress_epilog_v2` 的 FP8 E4M3 group-32 | ||
| 4 | +量化,写出 544B cache 记录,不再需要单独的 kcev2 kernel,也不再经过 | ||
| 5 | +E4M3(scale=1) → BF16 的二次量化。 | ||
| 6 | + | ||
| 7 | +- 目标芯片:Ascend 950(`ascend950`) | ||
| 8 | +- 算子入口:`AttnPrologue`(ACLNN:`aclnnAttnPrologue` / | ||
| 9 | + `aclnnAttnPrologueGetWorkspaceSize`) | ||
| 10 | +- Torch 接口:`torch.ops.pypto_gym.attn_prologue`(前端 | ||
| 11 | + `pypto_gym.attn_prologue`) | ||
| 12 | + | ||
| 13 | +本目录沿用压缩 KV 契约,每条记录包含 512 字节 FP8 数据和 32 字节分组 scale。调用原 `ops/pypto_pro` 版本且按 512 字节分配 cache 的用户,切换到本接口时需要调整 cache 的容量和读取方式。 | ||
| 14 | + | ||
| 15 | +## 功能说明 | ||
| 16 | + | ||
| 17 | +本实现完成 QA/KV 投影、QR RMSNorm+动态量化、QB 投影和尾部 RoPE;KV 支路 | ||
| 18 | +在 kernel 内直接执行 `kv_compress_epilog_v2` 的 FP8 E4M3 group-32 量化, | ||
| 19 | +写出 544B cache 记录。 | ||
| 20 | +这消除了“E4M3(scale=1) → BF16 → E4M3(group scale)”的双重量化。 | ||
| 21 | + | ||
| 22 | +记 `Deq` 为按 E8M0 scale 的逻辑反量化,`Quant32` 为每 32 元素一组的动态量化: | ||
| 23 | + | ||
| 24 | +```text | ||
| 25 | +X = Deq(x, descale_x) | ||
| 26 | +qa = X @ Deq(wqa, descale_wqa)^T # [T,R] | ||
| 27 | +kv = X @ Deq(wkv, descale_wkv)^T # [T,D] | ||
| 28 | + | ||
| 29 | +qr, descale_qr = Quant32(RMSNorm(qa, norm_weight_qr)) | ||
| 30 | +q_proj = Deq(qr, descale_qr) @ Deq(wqb, descale_wqb)^T | ||
| 31 | +q = BF16(TailRoPE(reshape(q_proj, [T,N,D]))) | ||
| 32 | + | ||
| 33 | +kv_bf16 = BF16(TailRoPE(RMSNorm(kv, norm_weight_kv))) # [T,D] | ||
| 34 | +``` | ||
| 35 | + | ||
| 36 | +KV compress(每 32 个元素一组): | ||
| 37 | + | ||
| 38 | +```text | ||
| 39 | +amax = max(abs(kv_bf16[group])) | ||
| 40 | +s0 = max(amax, 1e-4) / 448 | ||
| 41 | +s = 2^ceil(log2(s0)) # s0 恰为 2 的幂时保持不变 | ||
| 42 | +payload = E4M3FN(clamp(kv_bf16 / s, -448, 448)) | ||
| 43 | +scale = BF16(s) | ||
| 44 | + | ||
| 45 | +record = payload[512B] || scale[16 × BF16 = 32B] # 544B | ||
| 46 | +kv_cache[cache_index[t]] = record | ||
| 47 | +``` | ||
| 48 | + | ||
| 49 | +## 函数原型 | ||
| 50 | + | ||
| 51 | +```python | ||
| 52 | +q, qr, descale_qr = attn_prologue( | ||
| 53 | + x, # E4M3 [T,5120] | ||
| 54 | + wqa, wqb, wkv, # E4M3 FRACTAL_NZ | ||
| 55 | + descale_x, descale_wqa, descale_wqb, descale_wkv, | ||
| 56 | + norm_weight_qr, norm_weight_kv, | ||
| 57 | + rope_sin, rope_cos, | ||
| 58 | + cache_index, # INT64 [T] | ||
| 59 | + kv_cache, # UINT8 [P,BS,1,C>=544],原地更新 | ||
| 60 | + qr_norm=None, # 可选:BF16 [T,1280] 归一化 QR 输出 buffer | ||
| 61 | + norm_eps=1e-6, | ||
| 62 | +) | ||
| 63 | +``` | ||
| 64 | + | ||
| 65 | +`qr_norm` 是可选输出:不传时 host tiling 选择 `QrNorm=0` 变体,kernel 在编译期 | ||
| 66 | +去掉对应分支和 GM 写回;传入时选择 `QrNorm=1` 变体。`rope_sin` / `rope_cos` | ||
| 67 | +为 `[T,64]` FP32 逐元素表,GPTJ_INTERLEAVED 布局(与 V4.1 网络及 attn_epilogue | ||
| 68 | +的 inverse RoPE 一致);网络标准表每对频率重复两次(`cos[2i]=cos[2i+1]`,sin | ||
| 69 | +同理),同一 token 的表在全部 Q head 与 KV 上共享。 | ||
| 70 | + | ||
| 71 | +## 输入输出契约 | ||
| 72 | + | ||
| 73 | +`T` 为 token 数,范围 `[1, 262144]`。所有张量必须在同一个 NPU 设备上。 | ||
| 74 | + | ||
| 75 | +| 名称 | dtype | shape | 格式 | 说明 | | ||
| 76 | +|---|---|---|---|---| | ||
| 77 | +| `x` | E4M3FN | `[T, 5120]` | ND | 已由调用方完成 MXFP8 量化的激活 | | ||
| 78 | +| `wqa` | E4M3FN | `[1280, 5120]` | FRACTAL_NZ | QA 权重 | | ||
| 79 | +| `wqb` | E4M3FN | `[32768, 1280]` | FRACTAL_NZ | QB 权重 | | ||
| 80 | +| `wkv` | E4M3FN | `[512, 5120]` | FRACTAL_NZ | KV 权重 | | ||
| 81 | +| `descale_x` | E8M0 | `[T, 80, 2]` | ND | 激活的 group-32 scale | | ||
| 82 | +| `descale_wqa` | E8M0 | `[1280, 80, 2]` | ND | QA 权重 scale | | ||
| 83 | +| `descale_wqb` | E8M0 | `[32768, 20, 2]` | ND | QB 权重 scale | | ||
| 84 | +| `descale_wkv` | E8M0 | `[512, 80, 2]` | ND | KV 权重 scale | | ||
| 85 | +| `norm_weight_qr` | FP32 | `[1280]` | ND | QR RMSNorm gamma | | ||
| 86 | +| `norm_weight_kv` | FP32 | `[512]` | ND | KV RMSNorm gamma | | ||
| 87 | +| `rope_sin` | FP32 | `[T, 64]` | ND | GPTJ_INTERLEAVED sin 表 | | ||
| 88 | +| `rope_cos` | FP32 | `[T, 64]` | ND | GPTJ_INTERLEAVED cos 表 | | ||
| 89 | +| `cache_index` | INT64 | `[T]` | ND | 每个 token 的 cache slot;`< 0` 跳过写 | | ||
| 90 | +| `kv_cache` | UINT8 | `[B, S, 1, C>=544]` | ND | 原地更新;自动读取 view stride,支持页/行 padding | | ||
| 91 | +| `norm_eps` | float | 标量 | — | RMSNorm epsilon,默认 `1e-6` | | ||
| 92 | +| `qr_norm`(可选) | BF16 | `[T,1280]` | ND | 传入时额外写归一化 QR 给 Indexer;不传则跳过 | | ||
| 93 | +| `block_stride`(内部) | int | 标量 | — | ACLNN 内部 attr;Torch binding 自动取 `kv_cache.stride(0)` | | ||
| 94 | +| `row_stride`(内部) | int | 标量 | — | ACLNN 内部 attr;Torch binding 自动取 `kv_cache.stride(1)` | | ||
| 95 | + | ||
| 96 | +输出: | ||
| 97 | + | ||
| 98 | +| 名称 | dtype | shape | 说明 | | ||
| 99 | +|---|---|---|---| | ||
| 100 | +| `q` | BF16 | `[T, 64, 512]` | 经 TailRoPE 的 Q | | ||
| 101 | +| `qr` | E4M3FN | `[T, 1280]` | 量化后的低秩 Q | | ||
| 102 | +| `descale_qr` | E8M0 | `[T, 20, 2]` | QR 的 group-32 scale | | ||
| 103 | +| `qr_norm`(可选) | BF16 | `[T, 1280]` | 传入时写出的归一化 QR | | ||
| 104 | + | ||
| 105 | +KV cache 单条记录 544 字节:`[0:512]` 为 E4M3 payload,`[512:544]` 为 | ||
| 106 | +16 个 group-32 BF16 scale。四维 cache `[B,S,1,C]` 的物理记录地址为 | ||
| 107 | +`(slot//S)*page_stride + (slot%S)*row_stride`;binding 自动取 | ||
| 108 | +`page_stride=kv_cache.stride(0)`、`row_stride=kv_cache.stride(1)`。两个 stride | ||
| 109 | +必须 32 字节对齐,`row_stride>=544`、`page_stride>=S*row_stride`,底层 storage | ||
| 110 | +必须覆盖 `(B-1)*page_stride + (S-1)*row_stride + 544`。`slot < 0` 跳过;非连续 | ||
| 111 | +view 可直接传入,不能用 `.contiguous()` 副本替代。`kv_compress_epilog_v2` | ||
| 112 | +使用同一套分页协议。 | ||
| 113 | + | ||
| 114 | +约束: | ||
| 115 | + | ||
| 116 | +- 权重必须在加载期用一次 `torch_npu.npu_format_cast(w.contiguous(), 29)` 转为 | ||
| 117 | + FRACTAL_NZ;算子不会自动转换; | ||
| 118 | +- 除三个权重外,其余输入/输出必须是 ND;`kv_cache` 可以是带页/行空洞的非连续 | ||
| 119 | + view(自动读取 stride),其它张量需 contiguous; | ||
| 120 | +- 仅提供前向计算;推理时使用 `torch.no_grad()`; | ||
| 121 | +- `rope_sin/rope_cos` 为 GPTJ_INTERLEAVED 布局:相邻输入对 `(z[2i], z[2i+1])` | ||
| 122 | + 旋转后写回相邻位置;网络标准表每对频率重复两次 | ||
| 123 | + (`cos[2i]=cos[2i+1]`,sin 同理)。 | ||
| 124 | + | ||
| 125 | +## 调用方式 | ||
| 126 | + | ||
| 127 | +### 直接 `torch.ops`(推荐) | ||
| 128 | + | ||
| 129 | +```python | ||
| 130 | +import torch | ||
| 131 | +import torch_npu | ||
| 132 | +import pypto_gym | ||
| 133 | + | ||
| 134 | +pypto_gym.load() # 加载 libpypto_gym_attn_prologue.so,注册 torch.ops.pypto_gym | ||
| 135 | + | ||
| 136 | +q, qr, descale_qr, kv_cache = torch.ops.pypto_gym.attn_prologue( | ||
| 137 | + x, wqa, wqb, wkv, | ||
| 138 | + descale_x, descale_wqa, descale_wqb, descale_wkv, | ||
| 139 | + norm_weight_qr, norm_weight_kv, | ||
| 140 | + rope_sin, rope_cos, cache_index, kv_cache, | ||
| 141 | + norm_eps=1e-6, | ||
| 142 | +) | ||
| 143 | +``` | ||
| 144 | + | ||
| 145 | +直接 `torch.ops` 返回 4 个张量:`q`、`qr`、`descale_qr`、以及被原地更新的 | ||
| 146 | +`kv_cache`;`descale_qr` 的 dtype 为 E8M0。调用是异步的:在当前 NPU stream | ||
| 147 | +入队,读取结果或计时前请 `torch.npu.synchronize()`。直接用 `torch.ops` 前必须 | ||
| 148 | +先 `pypto_gym.load()`(或访问一次 `pypto_gym.attn_prologue`)。 | ||
| 149 | + | ||
| 150 | +### 前端便捷接口 | ||
| 151 | + | ||
| 152 | +```python | ||
| 153 | +q, qr, descale_qr = pypto_gym.attn_prologue( | ||
| 154 | + x, wqa, wqb, wkv, | ||
| 155 | + descale_x, descale_wqa, descale_wqb, descale_wkv, | ||
| 156 | + norm_weight_qr, norm_weight_kv, | ||
| 157 | + rope_sin, rope_cos, cache_index, kv_cache, | ||
| 158 | + norm_eps=1e-6, | ||
| 159 | +) | ||
| 160 | +``` | ||
| 161 | + | ||
| 162 | +前端返回 3 个张量,`descale_qr` 为 int8 字节视图;`kv_cache` 仍原地更新。 | ||
| 163 | + | ||
| 164 | +### JIT 方式(直接执行 `op_kernel`) | ||
| 165 | + | ||
| 166 | +```python | ||
| 167 | +import importlib.util | ||
| 168 | +import sys | ||
| 169 | +from pathlib import Path | ||
| 170 | + | ||
| 171 | +import torch | ||
| 172 | +import torch_npu | ||
| 173 | + | ||
| 174 | +kernel_path = Path("ops/pro/deepseek_v4_1/attn_prologue/op_kernel/attn_prologue.py").resolve() | ||
| 175 | +spec = importlib.util.spec_from_file_location("attn_prologue_kernel", kernel_path) | ||
| 176 | +mod = importlib.util.module_from_spec(spec) | ||
| 177 | +sys.modules["attn_prologue_kernel"] = mod | ||
| 178 | +spec.loader.exec_module(mod) | ||
| 179 | + | ||
| 180 | +torch.npu.set_device("npu:0") | ||
| 181 | +q, qr, descale_qr = mod.attn_prologue( | ||
| 182 | + x, wqa, wqb, wkv, | ||
| 183 | + descale_x, descale_wqa, descale_wqb, descale_wkv, | ||
| 184 | + norm_weight_qr, norm_weight_kv, | ||
| 185 | + rope_sin, rope_cos, cache_index, kv_cache, | ||
| 186 | + qr_norm=None, | ||
| 187 | + norm_eps=1e-6, | ||
| 188 | +) | ||
| 189 | +torch.npu.synchronize() | ||
| 190 | +``` | ||
| 191 | + | ||
| 192 | +JIT wrapper 与 `torch.ops`/ACLNN 最终执行同一份设备计算代码,返回 3 个张量 | ||
| 193 | +(`q`/`qr`/`descale_qr`),`kv_cache` 原地更新;`qr_norm` 可选。它直接使用 | ||
| 194 | +`op_kernel/attn_prologue.py`,需要 PyPTO/PyPTO-Pro 运行时和 kernel 源码; | ||
| 195 | +首次调用会编译(计入 host 时间,不是设备 `Task Duration`),计时前应先完成 | ||
| 196 | +编译并预热。 | ||
| 197 | + | ||
| 198 | +### ACLNN 接口 | ||
| 199 | + | ||
| 200 | +ACLNN 接口通过 `op_api/include/aclnnop/aclnn_attn_prologue.h` 提供: | ||
| 201 | +`aclnnAttnPrologueGetWorkspaceSize` 后调用 `aclnnAttnPrologue`。参考 | ||
| 202 | +`tests/aclnn_bridge/aclnn_bridge_attn_prologue.cpp` 的 C++ 调用方式。 | ||
| 203 | + | ||
| 204 | +## 完整示例 | ||
| 205 | + | ||
| 206 | +```python | ||
| 207 | +import torch | ||
| 208 | +import torch_npu | ||
| 209 | +import pypto_gym | ||
| 210 | + | ||
| 211 | +dev = "npu:0" | ||
| 212 | +torch.npu.set_device(dev) | ||
| 213 | +pypto_gym.load() | ||
| 214 | + | ||
| 215 | +T, H, R, D, N, DR = 96, 5120, 1280, 512, 64, 64 | ||
| 216 | +P, BS = 1, 128 | ||
| 217 | + | ||
| 218 | +def to_nz(w): | ||
| 219 | + return torch_npu.npu_format_cast(w.contiguous(), 29) | ||
| 220 | + | ||
| 221 | +x = torch.randn(T, H, device=dev).to(torch.float8_e4m3fn) | ||
| 222 | +wqa = to_nz(torch.randn(R, H, device=dev).to(torch.float8_e4m3fn)) | ||
| 223 | +wqb = to_nz(torch.randn(N * D, R, device=dev).to(torch.float8_e4m3fn)) | ||
| 224 | +wkv = to_nz(torch.randn(D, H, device=dev).to(torch.float8_e4m3fn)) | ||
| 225 | + | ||
| 226 | +unit_scale = torch.full((), 127, dtype=torch.uint8, device=dev).view(torch.float8_e8m0fnu) | ||
| 227 | +descale_x = unit_scale.expand(T, H // 64, 2).contiguous() | ||
| 228 | +descale_wqa = unit_scale.expand(R, H // 64, 2).contiguous() | ||
| 229 | +descale_wqb = unit_scale.expand(N * D, R // 64, 2).contiguous() | ||
| 230 | +descale_wkv = unit_scale.expand(D, H // 64, 2).contiguous() | ||
| 231 | + | ||
| 232 | +norm_weight_qr = torch.ones(R, device=dev) | ||
| 233 | +norm_weight_kv = torch.ones(D, device=dev) | ||
| 234 | + | ||
| 235 | +# 真实部署应使用网络侧按 token 绝对位置生成的 GPTJ_INTERLEAVED 表 | ||
| 236 | +rope_sin = torch.randn(T, DR, device=dev) | ||
| 237 | +rope_cos = torch.randn(T, DR, device=dev) | ||
| 238 | + | ||
| 239 | +cache_index = torch.arange(T, dtype=torch.int64, device=dev) | ||
| 240 | +kv_cache = torch.zeros(P, BS, 1, 544, dtype=torch.uint8, device=dev) | ||
| 241 | + | ||
| 242 | +with torch.no_grad(): | ||
| 243 | + q, qr, descale_qr, kv_cache = torch.ops.pypto_gym.attn_prologue( | ||
| 244 | + x, wqa, wqb, wkv, | ||
| 245 | + descale_x, descale_wqa, descale_wqb, descale_wkv, | ||
| 246 | + norm_weight_qr, norm_weight_kv, | ||
| 247 | + rope_sin, rope_cos, cache_index, kv_cache, | ||
| 248 | + norm_eps=1e-6, | ||
| 249 | + ) | ||
| 250 | +torch.npu.synchronize() | ||
| 251 | +``` | ||
| 252 | + | ||
| 253 | +> 示例中的 `x/descale_x` 只是占位。生产环境必须传入网络 MXFP8 量化器产出的 | ||
| 254 | +> E4M3 激活和 E8M0 scale;KV cache 的 `cache_index` 应使用 paged KV cache 的 | ||
| 255 | +> 真实 slot id。 | ||
| 256 | + | ||
| 257 | +## 结构与 Host 接入 | ||
| 258 | + | ||
| 259 | +- 在 V1 基础上新增 `kv_compress_row_vf`,`kv_row_vf` 输出 BF16。 | ||
| 260 | +- A1/A2/B/B-epi 的数值路径与原实现一致;B 段在 `n_tiles==2` 增加了 pair-major/交错 K 的权重复用路径,见下。 | ||
| 261 | +- `op_host` 完整(def / infershape / tiling / CMake),`kv_cache` 输入 / 原地写。 | ||
| 262 | +- tiling 字段:`t / cache_rows / block_size / block_stride / row_stride / | ||
| 263 | + ws_rows / norm_eps / emit_qr_norm`。 | ||
| 264 | +- tiling key 两个 1-bit 字段: | ||
| 265 | + - `Profile`(bit0):`T<=128` 用 `NotAllocKeep`,`T>128` 用默认 L2 策略。 | ||
| 266 | + - `QrNorm`(bit1):`0` 不请求 `qr_norm`,`1` 请求;host 设置 | ||
| 267 | + `key = Profile | (QrNorm << 1)`,包内变体为 `[0, 1, 2, 3]`。 | ||
| 268 | +- B 段工作分配: | ||
| 269 | + - `n_tiles == 2`(T=129–256):pair-major QR hoist + 交错 K。两个 M tile | ||
| 270 | + 共用同一份 Wqb 权重块,每个 K 只做一次 L0B 权重搬运,连续做两个 tile 的 | ||
| 271 | + MMA;QR 按 pair 提升,避免每个 unit 重读。 | ||
| 272 | + - 三个及以上 M tile 默认按 `(tile, head, block)` 分配。达到 32 个 tile 且 tile 数是核数的倍数,或达到 32 个 tile 且每个核至少分到 4 个 tile 时,启用 split-T,由同一个核处理完整 tile。 | ||
| 273 | + | ||
| 274 | +## 测试 | ||
| 275 | + | ||
| 276 | +```bash | ||
| 277 | +D=ops/pro/deepseek_v4_1/attn_prologue | ||
| 278 | +python $D/tests/test_attn_prologue_routes.py --t 1 --t 72 --t 192 --t 1024 | ||
| 279 | +pytest $D/tests -q | ||
| 280 | +``` | ||
| 281 | + | ||
| 282 | +当前 T=1/72/192/1024 与 binary/ACLNN、qr_norm 可选输出用例均通过。 | ||
| 283 | +KV 记录与独立 `kv_compress_epilog_v2` 的逐字节对比:T=1/72 完全一致; | ||
| 284 | +T=1024 仅有 2 个 FP32 累加导致的 tie-break payload 字节(`kv_hard=0`)。 | ||
| 285 | + | ||
| 286 | +## 参考实现的历史性能(msprof,冷 L2,64M flush,5+20 中位数) | ||
| 287 | + | ||
| 288 | +采集口径:每次预热/正式调用前用 64M BF16 元素(128 MiB/缓冲)的 | ||
| 289 | +`torch.neg(src, out=dst)` 读写冲刷 L2(256 MiB/次),5 次预热 + 20 次正式调用取 | ||
| 290 | +中位数;指标为 `Task Duration(us)`,不含 host workspace、分配和 H2D/D2H。 | ||
| 291 | +设备为 Ascend950PR(28 Cube / 56 Vector),包为 hybrid + `QrNorm` tiling key 版本。 | ||
| 292 | + | ||
| 293 | +| T | 中位 µs | MFU | 模型 MBU(1.6 TB/s) | | ||
| 294 | +|---:|---:|---:|---:| | ||
| 295 | +| 5 | 43.43 | 1.56% | 81.68% | | ||
| 296 | +| 72 | 49.54 | 19.63% | 77.91% | | ||
| 297 | +| 96 | 51.78 | 25.04% | 76.70% | | ||
| 298 | +| 144 | 84.86 | 22.92% | 48.25% | | ||
| 299 | +| 192 | 87.86 | 29.52% | 49.64% | | ||
| 300 | +| 240 | 92.95 | 34.87% | 49.79% | | ||
| 301 | +| 576 | 152.18 | 51.12% | 42.67% | | ||
| 302 | +| 1152 | 250.23 | 62.18% | 38.73% | | ||
| 303 | + | ||
| 304 | +> T=128→129 有 host tiling 台阶(约 57.01→83.72 µs);这是多 tile 路径的 | ||
| 305 | +> 结构性开销,不是 `QrNorm`/`Profile` key 选择导致的。完整 24 例数据见交付 | ||
| 306 | +> 测试报告;warm-L2 数字不作为本文口径。 | ||
| @@ -0,0 +1,20 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +# coding: utf-8 | ||
| 3 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 11 | +"""PyPTO Pro ``attn_prologue`` operator.""" | ||
| 12 | + | ||
| 13 | +from .op_kernel.attn_prologue import ( | ||
| 14 | + attn_prologue, | ||
| 15 | + attn_prologue_kernel, | ||
| 16 | +) | ||
| 17 | + | ||
| 18 | +__all__ = [ | ||
| 19 | + "attn_prologue", "attn_prologue_kernel", | ||
| 20 | +] | ||
| @@ -0,0 +1,51 @@ | |||
| 1 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 10 | +cmake_minimum_required(VERSION 3.18.4) | ||
| 11 | +require_pypto_pro(attn_prologue) | ||
| 12 | +add_op_to_compiled_list() | ||
| 13 | + | ||
| 14 | +target_sources(op_host_aclnn PRIVATE | ||
| 15 | +attn_prologue_def.cpp | ||
| 16 | +) | ||
| 17 | +add_modules_sources(OPTYPE attn_prologue ACLNNTYPE aclnn) | ||
| 18 | +enable_pypto_kernel(attn_prologue) | ||
| 19 | + | ||
| 20 | +# ascend950 条件编译——缺少此项会导致 kernel binary 未编译 | ||
| 21 | +set(CONDITION_UNIT ${ASCEND_COMPUTE_UNIT}) | ||
| 22 | +if("${CONDITION_UNIT}" STREQUAL "ascend950") | ||
| 23 | + add_ops_compile_options( | ||
| 24 | + OP_NAME AttnPrologue | ||
| 25 | + COMPUTE_UNIT Ascend950PR_9599 | ||
| 26 | + OPTIONS -DENABLE_CV_COMM_VIA_SSBUF=true | ||
| 27 | + ) | ||
| 28 | +endif() | ||
| 29 | + | ||
| 30 | +if (BUILD_OPS_RTY_KERNEL) | ||
| 31 | + add_ops_compile_options( | ||
| 32 | + OP_NAME AttnPrologue | ||
| 33 | + OPTIONS --cce-auto-sync=off | ||
| 34 | + -Wno-deprecated-declarations | ||
| 35 | + -Werror | ||
| 36 | + ) | ||
| 37 | +else() | ||
| 38 | + add_ops_compile_options( | ||
| 39 | + OP_NAME AttnPrologue | ||
| 40 | + OPTIONS --cce-auto-sync=off | ||
| 41 | + -Wno-deprecated-declarations | ||
| 42 | + ) | ||
| 43 | +endif() | ||
| 44 | + | ||
| 45 | +if(NOT BUILD_OPS_RTY_KERNEL) | ||
| 46 | + add_modules_sources(OPTYPE attn_prologue ACLNNTYPE aclnn) | ||
| 47 | +endif() | ||
| 48 | + | ||
| 49 | +if(NOT BUILD_OPS_RTY_KERNEL) | ||
| 50 | + add_tiling_modules() | ||
| 51 | +endif() | ||
| @@ -0,0 +1,83 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +/*! | ||
| 12 | + * \file attn_prologue_def.cpp | ||
| 13 | + * \brief AttnPrologue operator registration. | ||
| 14 | + * | ||
| 15 | + * Input order mirrors the delivery-form kernel signature in op_kernel/ | ||
| 16 | + * (inputs first, then outputs q/qr/descale_qr, then workspace/tiling). | ||
| 17 | + * The three projection weights are FRACTAL_NZ (caller applies to_nz once at | ||
| 18 | + * weight-load time); all other tensors are ND. | ||
| 19 | + */ | ||
| 20 | + | ||
| 21 | +#include "register/op_def_registry.h" | ||
| 22 | + | ||
| 23 | +namespace ops { | ||
| 24 | +class AttnPrologue : public OpDef { | ||
| 25 | +public: | ||
| 26 | + explicit AttnPrologue(const char *name) : OpDef(name) | ||
| 27 | + { | ||
| 28 | + RegisterInput("x", ge::DT_FLOAT8_E4M3FN, ge::FORMAT_ND, true); | ||
| 29 | + RegisterInput("wqa", ge::DT_FLOAT8_E4M3FN, ge::FORMAT_FRACTAL_NZ, true); | ||
| 30 | + RegisterInput("wqb", ge::DT_FLOAT8_E4M3FN, ge::FORMAT_FRACTAL_NZ, true); | ||
| 31 | + RegisterInput("wkv", ge::DT_FLOAT8_E4M3FN, ge::FORMAT_FRACTAL_NZ, true); | ||
| 32 | + RegisterInput("descale_x", ge::DT_FLOAT8_E8M0, ge::FORMAT_ND, true); | ||
| 33 | + RegisterInput("descale_wqa", ge::DT_FLOAT8_E8M0, ge::FORMAT_ND, true); | ||
| 34 | + RegisterInput("descale_wqb", ge::DT_FLOAT8_E8M0, ge::FORMAT_ND, true); | ||
| 35 | + RegisterInput("descale_wkv", ge::DT_FLOAT8_E8M0, ge::FORMAT_ND, true); | ||
| 36 | + RegisterInput("norm_weight_qr", ge::DT_FLOAT, ge::FORMAT_ND, true); | ||
| 37 | + RegisterInput("norm_weight_kv", ge::DT_FLOAT, ge::FORMAT_ND, true); | ||
| 38 | + RegisterInput("rope_sin", ge::DT_FLOAT, ge::FORMAT_ND, true); | ||
| 39 | + RegisterInput("rope_cos", ge::DT_FLOAT, ge::FORMAT_ND, true); | ||
| 40 | + RegisterInput("cache_index", ge::DT_INT64, ge::FORMAT_ND, true); | ||
| 41 | + RegisterInput("kv_cache", ge::DT_UINT8, ge::FORMAT_ND, false); | ||
| 42 | + RegisterInput("qr_norm", ge::DT_BF16, ge::FORMAT_ND, false); | ||
| 43 | + | ||
| 44 | + RegisterOutput("q", ge::DT_BF16); | ||
| 45 | + RegisterOutput("qr", ge::DT_FLOAT8_E4M3FN); | ||
| 46 | + RegisterOutput("descale_qr", ge::DT_FLOAT8_E8M0); | ||
| 47 | + | ||
| 48 | + this->Attr("norm_eps").AttrType(OPTIONAL).Float(1e-6f); | ||
| 49 | + this->Attr("block_stride").AttrType(OPTIONAL).Int(0); | ||
| 50 | + this->Attr("row_stride").AttrType(OPTIONAL).Int(0); | ||
| 51 | + this->Attr("storage_bytes").AttrType(OPTIONAL).Int(0); | ||
| 52 | + this->Attr("emit_qr_norm").AttrType(OPTIONAL).Int(0); | ||
| 53 | + | ||
| 54 | + OpAICoreConfig aicore_config; | ||
| 55 | + aicore_config.DynamicCompileStaticFlag(true) | ||
| 56 | + .DynamicFormatFlag(true) | ||
| 57 | + .DynamicRankSupportFlag(true) | ||
| 58 | + .DynamicShapeSupportFlag(true) | ||
| 59 | + .NeedCheckSupportFlag(false) | ||
| 60 | + .PrecisionReduceFlag(true) | ||
| 61 | + .ExtendCfgInfo("opFile.value", "attn_prologue") | ||
| 62 | + .ExtendCfgInfo("aclnnSupport.value", "support_aclnn"); | ||
| 63 | + this->AICore().AddConfig("ascend950", aicore_config); | ||
| 64 | + } | ||
| 65 | + | ||
| 66 | +private: | ||
| 67 | + void RegisterInput(const char *name, ge::DataType dtype, ge::Format format, bool contiguous) | ||
| 68 | + { | ||
| 69 | + auto ¶m = this->Input(name).ParamType(REQUIRED).DataType({dtype}).Format({format}); | ||
| 70 | + if (contiguous) { | ||
| 71 | + param.AutoContiguous(); | ||
| 72 | + } else { | ||
| 73 | + param.IgnoreContiguous(); | ||
| 74 | + } | ||
| 75 | + } | ||
| 76 | + | ||
| 77 | + void RegisterOutput(const char *name, ge::DataType dtype) | ||
| 78 | + { | ||
| 79 | + this->Output(name).ParamType(REQUIRED).DataType({dtype}).Format({ge::FORMAT_ND}); | ||
| 80 | + } | ||
| 81 | +}; | ||
| 82 | +OP_ADD(AttnPrologue); | ||
| 83 | +} // namespace ops | ||
| @@ -0,0 +1,85 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +/*! | ||
| 12 | + * \file attn_prologue_infershape.cpp | ||
| 13 | + * \brief AttnPrologue InferShape / InferDataType. | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#include <register/op_impl_registry.h> | ||
| 17 | +#include "op_common/log/log.h" | ||
| 18 | + | ||
| 19 | +using namespace ge; | ||
| 20 | + | ||
| 21 | +namespace ops { | ||
| 22 | +constexpr uint32_t X_INDEX = 0; | ||
| 23 | +constexpr uint32_t Q_INDEX = 0; | ||
| 24 | +constexpr uint32_t QR_INDEX = 1; | ||
| 25 | +constexpr uint32_t DESCALE_QR_INDEX = 2; | ||
| 26 | +constexpr int64_t N_HEADS = 64; | ||
| 27 | +constexpr int64_t HEAD_DIM = 512; | ||
| 28 | +constexpr int64_t RANK = 1280; | ||
| 29 | +constexpr int64_t RANK_GROUPS = 20; | ||
| 30 | + | ||
| 31 | +static ge::graphStatus InferShapeAttnPrologue(gert::InferShapeContext *context) | ||
| 32 | +{ | ||
| 33 | + OP_CHECK_IF(context == nullptr, | ||
| 34 | + OP_LOGE("AttnPrologue", "InferShapeContext is nullptr!"), | ||
| 35 | + return ge::GRAPH_FAILED); | ||
| 36 | + const gert::Shape *xShape = context->GetInputShape(X_INDEX); | ||
| 37 | + OP_CHECK_NULL_WITH_CONTEXT(context, xShape); | ||
| 38 | + OP_CHECK_IF(xShape->GetDimNum() != 2, | ||
| 39 | + OP_LOGE(context->GetNodeName(), | ||
| 40 | + "attn_prologue: x must be rank 2 [T,H], got rank %zu.", | ||
| 41 | + xShape->GetDimNum()), | ||
| 42 | + return ge::GRAPH_FAILED); | ||
| 43 | + const int64_t t = xShape->GetDim(0); | ||
| 44 | + OP_CHECK_IF(t < 1, | ||
| 45 | + OP_LOGE(context->GetNodeName(), | ||
| 46 | + "attn_prologue: T must be positive, got %ld.", t), | ||
| 47 | + return ge::GRAPH_FAILED); | ||
| 48 | + | ||
| 49 | + gert::Shape *qShape = context->GetOutputShape(Q_INDEX); | ||
| 50 | + OP_CHECK_NULL_WITH_CONTEXT(context, qShape); | ||
| 51 | + qShape->SetDimNum(3); | ||
| 52 | + qShape->SetDim(0, t); | ||
| 53 | + qShape->SetDim(1, N_HEADS); | ||
| 54 | + qShape->SetDim(2, HEAD_DIM); | ||
| 55 | + | ||
| 56 | + gert::Shape *qrShape = context->GetOutputShape(QR_INDEX); | ||
| 57 | + OP_CHECK_NULL_WITH_CONTEXT(context, qrShape); | ||
| 58 | + qrShape->SetDimNum(2); | ||
| 59 | + qrShape->SetDim(0, t); | ||
| 60 | + qrShape->SetDim(1, RANK); | ||
| 61 | + | ||
| 62 | + gert::Shape *scaleShape = context->GetOutputShape(DESCALE_QR_INDEX); | ||
| 63 | + OP_CHECK_NULL_WITH_CONTEXT(context, scaleShape); | ||
| 64 | + scaleShape->SetDimNum(3); | ||
| 65 | + scaleShape->SetDim(0, t); | ||
| 66 | + scaleShape->SetDim(1, RANK_GROUPS); | ||
| 67 | + scaleShape->SetDim(2, 2); | ||
| 68 | + return GRAPH_SUCCESS; | ||
| 69 | +} | ||
| 70 | + | ||
| 71 | +static ge::graphStatus InferDataTypeAttnPrologue(gert::InferDataTypeContext *context) | ||
| 72 | +{ | ||
| 73 | + OP_CHECK_IF(context == nullptr, | ||
| 74 | + OP_LOGE("AttnPrologue", "InferDataTypeContext is nullptr!"), | ||
| 75 | + return ge::GRAPH_FAILED); | ||
| 76 | + context->SetOutputDataType(Q_INDEX, ge::DT_BF16); | ||
| 77 | + context->SetOutputDataType(QR_INDEX, ge::DT_FLOAT8_E4M3FN); | ||
| 78 | + context->SetOutputDataType(DESCALE_QR_INDEX, ge::DT_FLOAT8_E8M0); | ||
| 79 | + return GRAPH_SUCCESS; | ||
| 80 | +} | ||
| 81 | + | ||
| 82 | +IMPL_OP_INFERSHAPE(AttnPrologue) | ||
| 83 | + .InferShape(InferShapeAttnPrologue) | ||
| 84 | + .InferDataType(InferDataTypeAttnPrologue); | ||
| 85 | +} // namespace ops | ||
| @@ -0,0 +1,379 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +/*! | ||
| 12 | + * \file attn_prologue_tiling.cpp | ||
| 13 | + * \brief AttnPrologue host tiling. | ||
| 14 | + * | ||
| 15 | + * C++ port of the Python host wrapper | ||
| 16 | + * (``op_kernel/attn_prologue.py::attn_prologue``). The two must stay | ||
| 17 | + * equivalent: | ||
| 18 | + * - T is x.dim(0); n_slots is kv_cache.dim(0) * dim(1); | ||
| 19 | + * - grid = max(1, min(cube_num, vector_num / 2)); | ||
| 20 | + * - decode split-K workspace bands use the same gate as the kernel: | ||
| 21 | + * n_tiles * NA1 * 2 <= grid -> 2 bands, else 1 band; | ||
| 22 | + * - workspace holds ws_qa [ws_rows, R] followed by ws_kv [ws_rows, D] fp32; | ||
| 23 | + * - tiling key selects the weight L2 policy: 0 (T <= BASE_M, NotAllocKeep) | ||
| 24 | + * or 1 (T > BASE_M, default) — matches AttnPrologueTilingKey.Profile. | ||
| 25 | + */ | ||
| 26 | + | ||
| 27 | +#include "attn_prologue_tiling.h" | ||
| 28 | +#include "register/op_def_registry.h" | ||
| 29 | +#include "tiling/platform/platform_ascendc.h" | ||
| 30 | + | ||
| 31 | +#include <algorithm> | ||
| 32 | +#include <cmath> | ||
| 33 | +#include <cstdint> | ||
| 34 | +#include <initializer_list> | ||
| 35 | + | ||
| 36 | +#ifndef OP_LOGE | ||
| 37 | +#include <cstdio> | ||
| 38 | +#define OP_LOGE(nodeName, fmt, ...) \ | ||
| 39 | + do { \ | ||
| 40 | + (void)(nodeName); \ | ||
| 41 | + std::printf(fmt "\n", ##__VA_ARGS__); \ | ||
| 42 | + } while (0) | ||
| 43 | +#endif | ||
| 44 | + | ||
| 45 | +namespace optiling { | ||
| 46 | + | ||
| 47 | +constexpr int64_t H = 5120; | ||
| 48 | +constexpr int64_t R = 1280; | ||
| 49 | +constexpr int64_t N_HEADS = 64; | ||
| 50 | +constexpr int64_t D = 512; | ||
| 51 | +constexpr int64_t DR = 64; | ||
| 52 | +constexpr int64_t BASE_M = 128; | ||
| 53 | +constexpr int64_t NA1 = 14; | ||
| 54 | +constexpr int64_t KV_RECORD_BYTES = 544; | ||
| 55 | +constexpr int64_t T_MAX = 262144; | ||
| 56 | + | ||
| 57 | +enum InputIndex { | ||
| 58 | + X = 0, | ||
| 59 | + WQA, | ||
| 60 | + WQB, | ||
| 61 | + WKV, | ||
| 62 | + DESCALE_X, | ||
| 63 | + DESCALE_WQA, | ||
| 64 | + DESCALE_WQB, | ||
| 65 | + DESCALE_WKV, | ||
| 66 | + NORM_WEIGHT_QR, | ||
| 67 | + NORM_WEIGHT_KV, | ||
| 68 | + ROPE_SIN, | ||
| 69 | + ROPE_COS, | ||
| 70 | + CACHE_INDEX, | ||
| 71 | + KV_CACHE, | ||
| 72 | +}; | ||
| 73 | + | ||
| 74 | +inline int64_t CeilDiv(int64_t a, int64_t b) | ||
| 75 | +{ | ||
| 76 | + return b > 0 ? (a + b - 1) / b : 0; | ||
| 77 | +} | ||
| 78 | + | ||
| 79 | +class TilingAttnPrologueFunc { | ||
| 80 | +public: | ||
| 81 | + explicit TilingAttnPrologueFunc(gert::TilingContext *context) : context_(context) {} | ||
| 82 | + ge::graphStatus RunTiling(); | ||
| 83 | + | ||
| 84 | +private: | ||
| 85 | + ge::graphStatus ParseShapesAndAttrs(); | ||
| 86 | + ge::graphStatus ReadTokens(); | ||
| 87 | + ge::graphStatus CheckWeights(); | ||
| 88 | + ge::graphStatus CheckScales(); | ||
| 89 | + ge::graphStatus CheckRopeAndNorm(); | ||
| 90 | + ge::graphStatus ReadCache(); | ||
| 91 | + ge::graphStatus ReadModeAttrs(); | ||
| 92 | + ge::graphStatus ReadStrides(); | ||
| 93 | + static bool CheckShape(const gert::StorageShape *shape, | ||
| 94 | + std::initializer_list<int64_t> dims); | ||
| 95 | + static ge::DataType GetInputDtype(gert::TilingContext *context, size_t index); | ||
| 96 | + | ||
| 97 | + gert::TilingContext *context_ = nullptr; | ||
| 98 | + AttnPrologueTilingData tiling_data_; | ||
| 99 | + int64_t t_ = 0; | ||
| 100 | + int64_t pages_ = 0; | ||
| 101 | + int64_t cache_rows_ = 0; | ||
| 102 | + int64_t block_size_ = 0; | ||
| 103 | + int64_t block_stride_ = 0; | ||
| 104 | + int64_t row_stride_ = 0; | ||
| 105 | + int64_t storage_bytes_ = 0; | ||
| 106 | + int64_t grid_ = 1; | ||
| 107 | + float norm_eps_ = 1e-6f; | ||
| 108 | + int64_t emit_qr_norm_ = 0; | ||
| 109 | +}; | ||
| 110 | + | ||
| 111 | +ge::DataType TilingAttnPrologueFunc::GetInputDtype( | ||
| 112 | + gert::TilingContext *context, size_t index) | ||
| 113 | +{ | ||
| 114 | + const auto *desc = context->GetInputDesc(index); | ||
| 115 | + return desc == nullptr ? ge::DT_UNDEFINED : desc->GetDataType(); | ||
| 116 | +} | ||
| 117 | + | ||
| 118 | +bool TilingAttnPrologueFunc::CheckShape( | ||
| 119 | + const gert::StorageShape *shape, std::initializer_list<int64_t> dims) | ||
| 120 | +{ | ||
| 121 | + if (shape == nullptr) { | ||
| 122 | + return false; | ||
| 123 | + } | ||
| 124 | + const auto &storage = shape->GetStorageShape(); | ||
| 125 | + if (dims.size() != storage.GetDimNum()) { | ||
| 126 | + return false; | ||
| 127 | + } | ||
| 128 | + int64_t i = 0; | ||
| 129 | + for (int64_t dim : dims) { | ||
| 130 | + if (storage.GetDim(static_cast<size_t>(i)) != dim) { | ||
| 131 | + return false; | ||
| 132 | + } | ||
| 133 | + ++i; | ||
| 134 | + } | ||
| 135 | + return true; | ||
| 136 | +} | ||
| 137 | + | ||
| 138 | +ge::graphStatus TilingAttnPrologueFunc::ReadTokens() | ||
| 139 | +{ | ||
| 140 | + const auto *xShape = context_->GetInputShape(X); | ||
| 141 | + if (xShape == nullptr) { | ||
| 142 | + OP_LOGE(context_->GetNodeName(), | ||
| 143 | + "attn_prologue: x shape is null."); | ||
| 144 | + return ge::GRAPH_FAILED; | ||
| 145 | + } | ||
| 146 | + const auto &xs = xShape->GetStorageShape(); | ||
| 147 | + if (xs.GetDimNum() != 2 || xs.GetDim(1) != H) { | ||
| 148 | + OP_LOGE(context_->GetNodeName(), | ||
| 149 | + "attn_prologue: x must be [T,%ld], got rank %zu.", H, | ||
| 150 | + xs.GetDimNum()); | ||
| 151 | + return ge::GRAPH_FAILED; | ||
| 152 | + } | ||
| 153 | + t_ = xs.GetDim(0); | ||
| 154 | + if (t_ < 1 || t_ > T_MAX) { | ||
| 155 | + OP_LOGE(context_->GetNodeName(), | ||
| 156 | + "attn_prologue: T=%ld outside [1,%ld].", t_, T_MAX); | ||
| 157 | + return ge::GRAPH_FAILED; | ||
| 158 | + } | ||
| 159 | + if (GetInputDtype(context_, X) != ge::DT_FLOAT8_E4M3FN) { | ||
| 160 | + OP_LOGE(context_->GetNodeName(), | ||
| 161 | + "attn_prologue: x must be FLOAT8_E4M3FN."); | ||
| 162 | + return ge::GRAPH_FAILED; | ||
| 163 | + } | ||
| 164 | + return ge::GRAPH_SUCCESS; | ||
| 165 | +} | ||
| 166 | + | ||
| 167 | +ge::graphStatus TilingAttnPrologueFunc::CheckWeights() | ||
| 168 | +{ | ||
| 169 | + if (!CheckShape(context_->GetInputShape(WQA), {R, H}) || | ||
| 170 | + !CheckShape(context_->GetInputShape(WQB), {N_HEADS * D, R}) || | ||
| 171 | + !CheckShape(context_->GetInputShape(WKV), {D, H})) { | ||
| 172 | + OP_LOGE(context_->GetNodeName(), | ||
| 173 | + "attn_prologue: wqa/wqb/wkv shape mismatch."); | ||
| 174 | + return ge::GRAPH_FAILED; | ||
| 175 | + } | ||
| 176 | + for (uint32_t index : {static_cast<uint32_t>(WQA), static_cast<uint32_t>(WQB), | ||
| 177 | + static_cast<uint32_t>(WKV)}) { | ||
| 178 | + if (GetInputDtype(context_, index) != ge::DT_FLOAT8_E4M3FN) { | ||
| 179 | + OP_LOGE(context_->GetNodeName(), | ||
| 180 | + "attn_prologue: weights must be FLOAT8_E4M3FN."); | ||
| 181 | + return ge::GRAPH_FAILED; | ||
| 182 | + } | ||
| 183 | + } | ||
| 184 | + return ge::GRAPH_SUCCESS; | ||
| 185 | +} | ||
| 186 | + | ||
| 187 | +ge::graphStatus TilingAttnPrologueFunc::CheckScales() | ||
| 188 | +{ | ||
| 189 | + if (!CheckShape(context_->GetInputShape(DESCALE_X), {t_, H / 64, 2}) || | ||
| 190 | + !CheckShape(context_->GetInputShape(DESCALE_WQA), {R, H / 64, 2}) || | ||
| 191 | + !CheckShape(context_->GetInputShape(DESCALE_WQB), {N_HEADS * D, R / 64, 2}) || | ||
| 192 | + !CheckShape(context_->GetInputShape(DESCALE_WKV), {D, H / 64, 2})) { | ||
| 193 | + OP_LOGE(context_->GetNodeName(), | ||
| 194 | + "attn_prologue: descale shape mismatch."); | ||
| 195 | + return ge::GRAPH_FAILED; | ||
| 196 | + } | ||
| 197 | + for (uint32_t index : {static_cast<uint32_t>(DESCALE_X), | ||
| 198 | + static_cast<uint32_t>(DESCALE_WQA), | ||
| 199 | + static_cast<uint32_t>(DESCALE_WQB), | ||
| 200 | + static_cast<uint32_t>(DESCALE_WKV)}) { | ||
| 201 | + if (GetInputDtype(context_, index) != ge::DT_FLOAT8_E8M0) { | ||
| 202 | + OP_LOGE(context_->GetNodeName(), | ||
| 203 | + "attn_prologue: descale tensors must be FLOAT8_E8M0."); | ||
| 204 | + return ge::GRAPH_FAILED; | ||
| 205 | + } | ||
| 206 | + } | ||
| 207 | + return ge::GRAPH_SUCCESS; | ||
| 208 | +} | ||
| 209 | + | ||
| 210 | +ge::graphStatus TilingAttnPrologueFunc::CheckRopeAndNorm() | ||
| 211 | +{ | ||
| 212 | + if (!CheckShape(context_->GetInputShape(NORM_WEIGHT_QR), {R}) || | ||
| 213 | + !CheckShape(context_->GetInputShape(NORM_WEIGHT_KV), {D}) || | ||
| 214 | + GetInputDtype(context_, NORM_WEIGHT_QR) != ge::DT_FLOAT || | ||
| 215 | + GetInputDtype(context_, NORM_WEIGHT_KV) != ge::DT_FLOAT) { | ||
| 216 | + OP_LOGE(context_->GetNodeName(), | ||
| 217 | + "attn_prologue: norm weight shape/dtype mismatch."); | ||
| 218 | + return ge::GRAPH_FAILED; | ||
| 219 | + } | ||
| 220 | + if (!CheckShape(context_->GetInputShape(ROPE_SIN), {t_, DR}) || | ||
| 221 | + !CheckShape(context_->GetInputShape(ROPE_COS), {t_, DR}) || | ||
| 222 | + GetInputDtype(context_, ROPE_SIN) != ge::DT_FLOAT || | ||
| 223 | + GetInputDtype(context_, ROPE_COS) != ge::DT_FLOAT) { | ||
| 224 | + OP_LOGE(context_->GetNodeName(), | ||
| 225 | + "attn_prologue: rope table shape/dtype mismatch."); | ||
| 226 | + return ge::GRAPH_FAILED; | ||
| 227 | + } | ||
| 228 | + if (!CheckShape(context_->GetInputShape(CACHE_INDEX), {t_}) || | ||
| 229 | + GetInputDtype(context_, CACHE_INDEX) != ge::DT_INT64) { | ||
| 230 | + OP_LOGE(context_->GetNodeName(), | ||
| 231 | + "attn_prologue: cache_index must be [T] INT64."); | ||
| 232 | + return ge::GRAPH_FAILED; | ||
| 233 | + } | ||
| 234 | + return ge::GRAPH_SUCCESS; | ||
| 235 | +} | ||
| 236 | + | ||
| 237 | +ge::graphStatus TilingAttnPrologueFunc::ReadCache() | ||
| 238 | +{ | ||
| 239 | + const auto *kvShape = context_->GetInputShape(KV_CACHE); | ||
| 240 | + if (kvShape == nullptr) return ge::GRAPH_FAILED; | ||
| 241 | + const auto &ks = kvShape->GetStorageShape(); | ||
| 242 | + if (ks.GetDimNum() != 4 || ks.GetDim(2) != 1 || | ||
| 243 | + ks.GetDim(3) < KV_RECORD_BYTES || ks.GetDim(0) <= 0 || ks.GetDim(1) <= 0) { | ||
| 244 | + OP_LOGE(context_->GetNodeName(), | ||
| 245 | + "attn_prologue: kv_cache must be [P,BS,1,C>=%ld] with P,BS>0.", | ||
| 246 | + KV_RECORD_BYTES); | ||
| 247 | + return ge::GRAPH_FAILED; | ||
| 248 | + } | ||
| 249 | + if (GetInputDtype(context_, KV_CACHE) != ge::DT_UINT8) { | ||
| 250 | + OP_LOGE(context_->GetNodeName(), | ||
| 251 | + "attn_prologue: kv_cache must be UINT8."); | ||
| 252 | + return ge::GRAPH_FAILED; | ||
| 253 | + } | ||
| 254 | + pages_ = ks.GetDim(0); | ||
| 255 | + block_size_ = ks.GetDim(1); | ||
| 256 | + cache_rows_ = pages_ * block_size_; | ||
| 257 | + return ge::GRAPH_SUCCESS; | ||
| 258 | +} | ||
| 259 | + | ||
| 260 | +ge::graphStatus TilingAttnPrologueFunc::ReadModeAttrs() | ||
| 261 | +{ | ||
| 262 | + const auto *attrs = context_->GetAttrs(); | ||
| 263 | + const float *eps = (attrs == nullptr) ? nullptr : attrs->GetFloat(0); | ||
| 264 | + const int64_t *emit_attr = (attrs == nullptr) ? nullptr : attrs->GetInt(4); | ||
| 265 | + norm_eps_ = (eps == nullptr) ? 1e-6f : *eps; | ||
| 266 | + emit_qr_norm_ = (emit_attr == nullptr || *emit_attr == 0) ? 0 : 1; | ||
| 267 | + if (!std::isfinite(norm_eps_) || norm_eps_ <= 0.0f) { | ||
| 268 | + OP_LOGE(context_->GetNodeName(), | ||
| 269 | + "attn_prologue: norm_eps must be finite and positive."); | ||
| 270 | + return ge::GRAPH_FAILED; | ||
| 271 | + } | ||
| 272 | + return ge::GRAPH_SUCCESS; | ||
| 273 | +} | ||
| 274 | + | ||
| 275 | +ge::graphStatus TilingAttnPrologueFunc::ReadStrides() | ||
| 276 | +{ | ||
| 277 | + const auto *attrs = context_->GetAttrs(); | ||
| 278 | + const int64_t *page_attr = (attrs == nullptr) ? nullptr : attrs->GetInt(1); | ||
| 279 | + const int64_t *row_attr = (attrs == nullptr) ? nullptr : attrs->GetInt(2); | ||
| 280 | + const int64_t *storage_attr = (attrs == nullptr) ? nullptr : attrs->GetInt(3); | ||
| 281 | + row_stride_ = (row_attr == nullptr || *row_attr == 0) | ||
| 282 | + ? KV_RECORD_BYTES : *row_attr; | ||
| 283 | + if (row_stride_ < KV_RECORD_BYTES || row_stride_ % 32 != 0) { | ||
| 284 | + OP_LOGE(context_->GetNodeName(), | ||
| 285 | + "attn_prologue: invalid row_stride=%ld (>= %ld and 32B aligned).", | ||
| 286 | + row_stride_, KV_RECORD_BYTES); | ||
| 287 | + return ge::GRAPH_FAILED; | ||
| 288 | + } | ||
| 289 | + block_stride_ = (page_attr == nullptr || *page_attr == 0) | ||
| 290 | + ? block_size_ * row_stride_ : *page_attr; | ||
| 291 | + if (block_stride_ < block_size_ * row_stride_ || block_stride_ % 32 != 0) { | ||
| 292 | + OP_LOGE(context_->GetNodeName(), | ||
| 293 | + "attn_prologue: invalid block_stride=%ld (>= BS*row_stride=%ld and 32B aligned).", | ||
| 294 | + block_stride_, block_size_ * row_stride_); | ||
| 295 | + return ge::GRAPH_FAILED; | ||
| 296 | + } | ||
| 297 | + const int64_t needed = (pages_ - 1) * block_stride_ | ||
| 298 | + + (block_size_ - 1) * row_stride_ + KV_RECORD_BYTES; | ||
| 299 | + storage_bytes_ = (storage_attr == nullptr || *storage_attr <= 0) | ||
| 300 | + ? needed : *storage_attr; | ||
| 301 | + if (storage_bytes_ < needed) { | ||
| 302 | + OP_LOGE(context_->GetNodeName(), | ||
| 303 | + "attn_prologue: cache storage %ld < physical write range %ld.", | ||
| 304 | + storage_bytes_, needed); | ||
| 305 | + return ge::GRAPH_FAILED; | ||
| 306 | + } | ||
| 307 | + return ge::GRAPH_SUCCESS; | ||
| 308 | +} | ||
| 309 | + | ||
| 310 | +ge::graphStatus TilingAttnPrologueFunc::ParseShapesAndAttrs() | ||
| 311 | +{ | ||
| 312 | + if (ReadTokens() != ge::GRAPH_SUCCESS || CheckWeights() != ge::GRAPH_SUCCESS || | ||
| 313 | + CheckScales() != ge::GRAPH_SUCCESS || CheckRopeAndNorm() != ge::GRAPH_SUCCESS || | ||
| 314 | + ReadCache() != ge::GRAPH_SUCCESS || ReadModeAttrs() != ge::GRAPH_SUCCESS) return ge::GRAPH_FAILED; | ||
| 315 | + return ReadStrides(); | ||
| 316 | +} | ||
| 317 | + | ||
| 318 | +ge::graphStatus TilingAttnPrologueFunc::RunTiling() | ||
| 319 | +{ | ||
| 320 | + auto ret = ParseShapesAndAttrs(); | ||
| 321 | + if (ret != ge::GRAPH_SUCCESS) { | ||
| 322 | + return ret; | ||
| 323 | + } | ||
| 324 | + | ||
| 325 | + auto platform = platform_ascendc::PlatformAscendC(context_->GetPlatformInfo()); | ||
| 326 | + int64_t cube = static_cast<int64_t>(platform.GetCoreNumAic()); | ||
| 327 | + int64_t vector = static_cast<int64_t>(platform.GetCoreNumAiv()); | ||
| 328 | + if (cube <= 0 || vector < cube) { | ||
| 329 | + cube = 32; | ||
| 330 | + vector = 64; | ||
| 331 | + } | ||
| 332 | + grid_ = std::max<int64_t>(1, std::min<int64_t>(cube, vector / 2)); | ||
| 333 | + | ||
| 334 | + const int64_t n_tiles = CeilDiv(t_, BASE_M); | ||
| 335 | + const bool split_k = (n_tiles * NA1 * 2 <= grid_); | ||
| 336 | + const int64_t ws_rows = split_k ? (2 * n_tiles * BASE_M) : t_; | ||
| 337 | + | ||
| 338 | + tiling_data_.set_t(t_); | ||
| 339 | + tiling_data_.set_cache_rows(cache_rows_); | ||
| 340 | + tiling_data_.set_block_size(block_size_); | ||
| 341 | + tiling_data_.set_block_stride(block_stride_); | ||
| 342 | + tiling_data_.set_row_stride(row_stride_); | ||
| 343 | + tiling_data_.set_ws_rows(ws_rows); | ||
| 344 | + tiling_data_.set_norm_eps(norm_eps_); | ||
| 345 | + tiling_data_.set_emit_qr_norm(emit_qr_norm_); | ||
| 346 | + | ||
| 347 | + size_t *workspace = context_->GetWorkspaceSizes(1); | ||
| 348 | + if (workspace == nullptr) { | ||
| 349 | + OP_LOGE(context_->GetNodeName(), | ||
| 350 | + "attn_prologue: workspace size pointer is null."); | ||
| 351 | + return ge::GRAPH_FAILED; | ||
| 352 | + } | ||
| 353 | + const size_t ws_bytes = | ||
| 354 | + static_cast<size_t>(ws_rows) * static_cast<size_t>(R + D) * sizeof(float); | ||
| 355 | + workspace[0] = (ws_bytes + 511U) & ~static_cast<size_t>(511U); | ||
| 356 | + | ||
| 357 | + context_->SetTilingKey(((t_ <= BASE_M) ? 0U : 1U) | ||
| 358 | + | (emit_qr_norm_ ? 2U : 0U)); | ||
| 359 | + tiling_data_.SaveToBuffer(context_->GetRawTilingData()->GetData(), | ||
| 360 | + context_->GetRawTilingData()->GetCapacity()); | ||
| 361 | + context_->GetRawTilingData()->SetDataSize(tiling_data_.GetDataSize()); | ||
| 362 | + context_->SetBlockDim(static_cast<uint32_t>(grid_)); | ||
| 363 | + return ge::GRAPH_SUCCESS; | ||
| 364 | +} | ||
| 365 | + | ||
| 366 | +static ge::graphStatus TilingFunc(gert::TilingContext *context) | ||
| 367 | +{ | ||
| 368 | + TilingAttnPrologueFunc tiling_object(context); | ||
| 369 | + auto ret = tiling_object.RunTiling(); | ||
| 370 | + if (ret != ge::GRAPH_SUCCESS) { | ||
| 371 | + OP_LOGE(context->GetNodeName(), "attn_prologue tiling failed."); | ||
| 372 | + return ge::GRAPH_FAILED; | ||
| 373 | + } | ||
| 374 | + return ge::GRAPH_SUCCESS; | ||
| 375 | +} | ||
| 376 | + | ||
| 377 | +IMPL_OP_OPTILING(AttnPrologue).Tiling(TilingFunc); | ||
| 378 | + | ||
| 379 | +} // namespace optiling | ||
| @@ -0,0 +1,42 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +/*! | ||
| 12 | + * \file attn_prologue_tiling.h | ||
| 13 | + * \brief AttnPrologue host tiling data. | ||
| 14 | + * | ||
| 15 | + * Field names, order and types must match the PyPTO kernel dataclass | ||
| 16 | + * ``AttnPrologueTiling`` in op_kernel/attn_prologue.py exactly. | ||
| 17 | + * This is checked at configure time by cmake/scripts/tiling_layout_check.py. | ||
| 18 | + */ | ||
| 19 | + | ||
| 20 | +#ifndef ATTN_PROLOGUE_TILING_H_ | ||
| 21 | +#define ATTN_PROLOGUE_TILING_H_ | ||
| 22 | + | ||
| 23 | +#include "register/tilingdata_base.h" | ||
| 24 | +#include "tiling/tiling_api.h" | ||
| 25 | + | ||
| 26 | +namespace optiling { | ||
| 27 | + | ||
| 28 | +BEGIN_TILING_DATA_DEF(AttnPrologueTilingData) | ||
| 29 | +TILING_DATA_FIELD_DEF(int64_t, t) | ||
| 30 | +TILING_DATA_FIELD_DEF(int64_t, cache_rows) | ||
| 31 | +TILING_DATA_FIELD_DEF(int64_t, block_size) | ||
| 32 | +TILING_DATA_FIELD_DEF(int64_t, block_stride) | ||
| 33 | +TILING_DATA_FIELD_DEF(int64_t, row_stride) | ||
| 34 | +TILING_DATA_FIELD_DEF(int64_t, ws_rows) | ||
| 35 | +TILING_DATA_FIELD_DEF(float, norm_eps) | ||
| 36 | +TILING_DATA_FIELD_DEF(int64_t, emit_qr_norm) | ||
| 37 | +END_TILING_DATA_DEF | ||
| 38 | +REGISTER_TILING_DATA_CLASS(AttnPrologue, AttnPrologueTilingData) | ||
| 39 | + | ||
| 40 | +} // namespace optiling | ||
| 41 | + | ||
| 42 | +#endif // ATTN_PROLOGUE_TILING_H_ | ||
| @@ -0,0 +1,11 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +# coding: utf-8 | ||
| 3 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 11 | +"""Kernel entry modules for the enclosing operator.""" | ||
| @@ -0,0 +1,11 @@ | |||
| 1 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 10 | +# 算子 tests 构建入口(由算子级 dispatcher 在 ENABLE_TESTS 时派发进入). | ||
| 11 | +add_subdirectory(aclnn_bridge) | ||
| @@ -0,0 +1,31 @@ | |||
| 1 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 10 | +# attn_prologue 的 aclnn 模式 pybind11 桥. 权重是 FRACTAL_NZ, 因此走 torch_npu 的 | ||
| 11 | +# ConvertType 而不是公共层的 ACL_FORMAT_ND 手工构造. | ||
| 12 | +gym_add_aclnn_bridge(attn_prologue) | ||
| 13 | + | ||
| 14 | +execute_process( | ||
| 15 | + COMMAND ${Python3_EXECUTABLE} -c "import torch_npu,os;print(os.path.dirname(torch_npu.__file__))" | ||
| 16 | + OUTPUT_VARIABLE TORCH_NPU_ROOT | ||
| 17 | + OUTPUT_STRIP_TRAILING_WHITESPACE) | ||
| 18 | +if (NOT TORCH_NPU_ROOT) | ||
| 19 | + message(FATAL_ERROR "torch_npu not importable; required for the attn_prologue NZ bridge") | ||
| 20 | +endif() | ||
| 21 | + | ||
| 22 | +execute_process( | ||
| 23 | + COMMAND ${Python3_EXECUTABLE} -c "import sysconfig;print(sysconfig.get_path('include'))" | ||
| 24 | + OUTPUT_VARIABLE PYTHON_INCLUDE_DIR | ||
| 25 | + OUTPUT_STRIP_TRAILING_WHITESPACE) | ||
| 26 | + | ||
| 27 | +target_include_directories(aclnn_bridge_attn_prologue PRIVATE | ||
| 28 | + ${TORCH_NPU_ROOT}/include | ||
| 29 | + ${TORCH_NPU_ROOT}/include/third_party/op-plugin | ||
| 30 | + ${PYTHON_INCLUDE_DIR}) | ||
| 31 | +target_link_libraries(aclnn_bridge_attn_prologue PRIVATE ${TORCH_NPU_ROOT}/lib/libtorch_npu.so) | ||
| @@ -0,0 +1,126 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +/*! | ||
| 12 | + * \file aclnn_bridge_attn_prologue.cpp | ||
| 13 | + * \brief pybind11 bridge: torch.Tensor -> aclnnAttnPrologue. | ||
| 14 | + */ | ||
| 15 | + | ||
| 16 | +#include "aclnn_bridge_common.h" | ||
| 17 | + | ||
| 18 | +#include <op_plugin/utils/op_api_common_base.h> | ||
| 19 | + | ||
| 20 | +namespace { | ||
| 21 | + | ||
| 22 | +using gym_test_bridge::destroy_acl_tensor; | ||
| 23 | +using gym_test_bridge::get_current_npu_stream; | ||
| 24 | +using gym_test_bridge::get_opapi_func; | ||
| 25 | + | ||
| 26 | +typedef aclnnStatus (*AttnPrologueGetWorkspaceSizeFunc)( | ||
| 27 | + const aclTensor *, const aclTensor *, const aclTensor *, const aclTensor *, | ||
| 28 | + const aclTensor *, const aclTensor *, const aclTensor *, const aclTensor *, | ||
| 29 | + const aclTensor *, const aclTensor *, const aclTensor *, const aclTensor *, | ||
| 30 | + const aclTensor *, const aclTensor *, const aclTensor *, double, | ||
| 31 | + int64_t, int64_t, int64_t, int64_t, | ||
| 32 | + const aclTensor *, const aclTensor *, const aclTensor *, | ||
| 33 | + uint64_t *, aclOpExecutor **); | ||
| 34 | +typedef aclnnStatus (*AttnPrologueFunc)(void *, uint64_t, aclOpExecutor *, aclrtStream); | ||
| 35 | + | ||
| 36 | +aclnnStatus ExecuteAttn(std::vector<aclTensor *> &acl_inputs, std::vector<aclTensor *> &acl_outputs, | ||
| 37 | + const c10::Device &device, double norm_eps, int64_t block_stride, | ||
| 38 | + int64_t row_stride, int64_t storage_bytes, int64_t emit_qr_norm) { | ||
| 39 | + static auto get_ws_size = reinterpret_cast<AttnPrologueGetWorkspaceSizeFunc>( | ||
| 40 | + get_opapi_func("aclnnAttnPrologueGetWorkspaceSize")); | ||
| 41 | + static auto aclnn_op = reinterpret_cast<AttnPrologueFunc>( | ||
| 42 | + get_opapi_func("aclnnAttnPrologue")); | ||
| 43 | + | ||
| 44 | + uint64_t workspace_size = 0; | ||
| 45 | + aclOpExecutor *executor = nullptr; | ||
| 46 | + aclnnStatus status = get_ws_size( | ||
| 47 | + acl_inputs[0], acl_inputs[1], acl_inputs[2], acl_inputs[3], | ||
| 48 | + acl_inputs[4], acl_inputs[5], acl_inputs[6], acl_inputs[7], | ||
| 49 | + acl_inputs[8], acl_inputs[9], acl_inputs[10], acl_inputs[11], | ||
| 50 | + acl_inputs[12], acl_inputs[13], acl_inputs[14], | ||
| 51 | + norm_eps, block_stride, row_stride, storage_bytes, | ||
| 52 | + emit_qr_norm, | ||
| 53 | + acl_outputs[0], acl_outputs[1], acl_outputs[2], | ||
| 54 | + &workspace_size, &executor); | ||
| 55 | + | ||
| 56 | + if (status == 0) { | ||
| 57 | + at::Tensor workspace; | ||
| 58 | + void *workspace_addr = nullptr; | ||
| 59 | + if (workspace_size != 0) { | ||
| 60 | + workspace = at::empty( | ||
| 61 | + {static_cast<int64_t>(workspace_size)}, | ||
| 62 | + at::TensorOptions().dtype(at::kByte).device(device)); | ||
| 63 | + workspace_addr = workspace.data_ptr(); | ||
| 64 | + } | ||
| 65 | + aclrtStream stream = get_current_npu_stream(); | ||
| 66 | + status = aclnn_op(workspace_addr, workspace_size, executor, stream); | ||
| 67 | + } | ||
| 68 | + | ||
| 69 | + for (auto *tensor : acl_inputs) { | ||
| 70 | + destroy_acl_tensor(tensor); | ||
| 71 | + } | ||
| 72 | + for (auto *tensor : acl_outputs) { | ||
| 73 | + destroy_acl_tensor(tensor); | ||
| 74 | + } | ||
| 75 | + return status; | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +} // namespace | ||
| 79 | + | ||
| 80 | +PYBIND11_MODULE(aclnn_bridge_attn_prologue, m) { | ||
| 81 | + m.doc() = "pypto-gym pybind11 test bridge: aclnn C++ -> Python"; | ||
| 82 | + | ||
| 83 | + m.def("attn_prologue", | ||
| 84 | + [](torch::Tensor x, torch::Tensor wqa, torch::Tensor wqb, torch::Tensor wkv, | ||
| 85 | + torch::Tensor descale_x, torch::Tensor descale_wqa, torch::Tensor descale_wqb, | ||
| 86 | + torch::Tensor descale_wkv, torch::Tensor norm_weight_qr, | ||
| 87 | + torch::Tensor norm_weight_kv, torch::Tensor rope_sin, torch::Tensor rope_cos, | ||
| 88 | + torch::Tensor cache_index, torch::Tensor kv_cache, | ||
| 89 | + torch::Tensor qr_norm, | ||
| 90 | + torch::Tensor q, torch::Tensor qr, torch::Tensor descale_qr, double norm_eps, | ||
| 91 | + int64_t block_stride, int64_t row_stride, int64_t storage_bytes) { | ||
| 92 | + if (block_stride == 0) { | ||
| 93 | + block_stride = kv_cache.stride(0) * kv_cache.element_size(); | ||
| 94 | + } | ||
| 95 | + if (row_stride == 0) { | ||
| 96 | + row_stride = kv_cache.stride(1) * kv_cache.element_size(); | ||
| 97 | + } | ||
| 98 | + std::vector<aclTensor *> acl_inputs = { | ||
| 99 | + ConvertType(x), ConvertType(wqa), ConvertType(wqb), ConvertType(wkv), | ||
| 100 | + ConvertType(descale_x), ConvertType(descale_wqa), ConvertType(descale_wqb), | ||
| 101 | + ConvertType(descale_wkv), ConvertType(norm_weight_qr), | ||
| 102 | + ConvertType(norm_weight_kv), ConvertType(rope_sin), ConvertType(rope_cos), | ||
| 103 | + ConvertType(cache_index), ConvertType(kv_cache), | ||
| 104 | + ConvertType(qr_norm)}; | ||
| 105 | + std::vector<aclTensor *> acl_outputs = { | ||
| 106 | + ConvertType(q), ConvertType(qr), ConvertType(descale_qr)}; | ||
| 107 | + | ||
| 108 | + const auto status = ExecuteAttn(acl_inputs, acl_outputs, x.device(), norm_eps, | ||
| 109 | + block_stride, row_stride, storage_bytes, qr_norm.numel() != 0); | ||
| 110 | + TORCH_CHECK(status == 0, "aclnnAttnPrologue call failed, status=", status); | ||
| 111 | + return std::make_tuple(q, qr, descale_qr); | ||
| 112 | + }, | ||
| 113 | + pybind11::arg("x"), pybind11::arg("wqa"), pybind11::arg("wqb"), pybind11::arg("wkv"), | ||
| 114 | + pybind11::arg("descale_x"), pybind11::arg("descale_wqa"), | ||
| 115 | + pybind11::arg("descale_wqb"), pybind11::arg("descale_wkv"), | ||
| 116 | + pybind11::arg("norm_weight_qr"), pybind11::arg("norm_weight_kv"), | ||
| 117 | + pybind11::arg("rope_sin"), pybind11::arg("rope_cos"), | ||
| 118 | + pybind11::arg("cache_index"), pybind11::arg("kv_cache"), | ||
| 119 | + pybind11::arg("qr_norm"), | ||
| 120 | + pybind11::arg("q"), pybind11::arg("qr"), pybind11::arg("descale_qr"), | ||
| 121 | + pybind11::arg("norm_eps") = 1e-6, | ||
| 122 | + pybind11::arg("block_stride") = 0, | ||
| 123 | + pybind11::arg("row_stride") = 0, | ||
| 124 | + pybind11::arg("storage_bytes") = 0, | ||
| 125 | + "aclnnAttnPrologue wrapper (torch.Tensor interface)"); | ||
| 126 | +} | ||
| @@ -0,0 +1,525 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +# coding: utf-8 | ||
| 3 | +# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd. | ||
| 4 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 11 | +"""attn_prologue PyPTO-Pro 测试入口(精度 + 可选性能)。 | ||
| 12 | + | ||
| 13 | +职责 | ||
| 14 | +---- | ||
| 15 | +唯一执行入口:构造 CPU 输入(复用独立 golden 的 fixture)→ 搬到 NPU(权重 ``to_nz``、 | ||
| 16 | +FP8 字节重解释)→ 调用公开 wrapper ``attn_prologue(...)`` → 用 FP64 值域判据 | ||
| 17 | +(``attn_prologue_precision``)逐 case 比较 → 写 ``reports/pro_pypto/validation.json``。 | ||
| 18 | + | ||
| 19 | +精度判据(冻结) | ||
| 20 | +-------------------------------------- | ||
| 21 | +* Q:全有限,且 ``|got-ref| > 0.02 + 0.02*|ref|`` 比例 ≤ 0.1%。 | ||
| 22 | +* QR/descale/KV 字节:FP32 首过提名整行 → 独立 FP64 复核,``hard`` 必须为 0。 | ||
| 23 | +* 未命中 cache slot:逐字节不变。 | ||
| 24 | + | ||
| 25 | +运行 | ||
| 26 | +---- | ||
| 27 | + D=ops/pro/deepseek_v4_1/attn_prologue | ||
| 28 | + python $D/tests/test_attn_prologue_routes.py # 全 32 case 精度(默认 1 卡) | ||
| 29 | + python $D/tests/test_attn_prologue_routes.py --t 1,72,1024 # 子集 | ||
| 30 | + python $D/tests/test_attn_prologue_routes.py --case-id decode-b12-s6-t72 | ||
| 31 | + python $D/tests/test_attn_prologue_routes.py --list # 列出 case(不碰 NPU) | ||
| 32 | + pytest $D/tests -q # 4 个冒烟 case | ||
| 33 | + | ||
| 34 | +CPU golden 与判据自检不需要 NPU;只有 NPU 路径才 import torch_npu / 算子。 | ||
| 35 | +""" | ||
| 36 | +from __future__ import annotations | ||
| 37 | + | ||
| 38 | +import argparse | ||
| 39 | +import dataclasses | ||
| 40 | +import gc | ||
| 41 | +import importlib.util | ||
| 42 | +import json | ||
| 43 | +import logging | ||
| 44 | +import os | ||
| 45 | +import sys | ||
| 46 | +import time | ||
| 47 | +from pathlib import Path | ||
| 48 | + | ||
| 49 | +import torch | ||
| 50 | + | ||
| 51 | +HERE = Path(__file__).resolve().parent | ||
| 52 | +OP_ROOT = HERE.parent | ||
| 53 | +for _p in (str(HERE), str(HERE / "assets"), str(OP_ROOT / "op_kernel")): | ||
| 54 | + if _p not in sys.path: | ||
| 55 | + sys.path.insert(0, _p) | ||
| 56 | + | ||
| 57 | + | ||
| 58 | +def _assert_paged_cache(ref, flat, prefix, cache_index, block, page_stride, row_stride, cols, sentinel): | ||
| 59 | + torch.npu.synchronize() | ||
| 60 | + ref_flat = ref.reshape(-1).cpu() | ||
| 61 | + paged_flat = flat[prefix:].cpu() | ||
| 62 | + written = torch.zeros(paged_flat.numel(), dtype=torch.bool) | ||
| 63 | + for slot in cache_index.cpu().tolist(): | ||
| 64 | + base = (slot // block) * page_stride + (slot % block) * row_stride | ||
| 65 | + assert torch.equal(paged_flat[base:base + cols], | ||
| 66 | + ref_flat[slot * cols:(slot + 1) * cols]) | ||
| 67 | + written[base:base + cols] = True | ||
| 68 | + assert (paged_flat[~written] == sentinel).all() | ||
| 69 | + assert (flat[:prefix] == sentinel).all() | ||
| 70 | + | ||
| 71 | + | ||
| 72 | +def _load_asset(module_name, filename): | ||
| 73 | + """Load one asset by path so renamed operators cannot collide on module names.""" | ||
| 74 | + spec = importlib.util.spec_from_file_location(module_name, HERE / "assets" / filename) | ||
| 75 | + module = importlib.util.module_from_spec(spec) | ||
| 76 | + sys.modules[module_name] = module | ||
| 77 | + spec.loader.exec_module(module) | ||
| 78 | + return module | ||
| 79 | + | ||
| 80 | + | ||
| 81 | +golden = _load_asset("attn_prologue_gym_golden_cpu", "attn_prologue_golden_cpu.py") | ||
| 82 | +verify = _load_asset("attn_prologue_gym_precision", "attn_prologue_precision.py") | ||
| 83 | + | ||
| 84 | +LOG = logging.getLogger("attn_prologue.test") | ||
| 85 | + | ||
| 86 | +_FRACTAL_NZ = 29 | ||
| 87 | +_E4M3 = torch.float8_e4m3fn | ||
| 88 | +_E8M0 = torch.float8_e8m0fnu | ||
| 89 | +_WEIGHT_FIELDS = ("wqa", "wqb", "wkv", "descale_wqa", "descale_wqb", "descale_wkv", | ||
| 90 | + "norm_weight_qr", "norm_weight_kv") | ||
| 91 | +_PER_TOKEN_FIELDS = ("x", "descale_x", "rope_sin", "rope_cos", "cache_index") | ||
| 92 | + | ||
| 93 | + | ||
| 94 | +def _default_device() -> str: | ||
| 95 | + return os.environ.get("TILE_FWK_DEVICE_ID", "0") | ||
| 96 | + | ||
| 97 | + | ||
| 98 | +def _resolve_device(spec: str) -> str: | ||
| 99 | + LOG.info("============ device: %s", spec) | ||
| 100 | + if spec.startswith("npu"): | ||
| @@ -0,0 +1,12 @@ | |||
| 1 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 10 | +if(ENABLE_TORCH_BINDINGS AND NOT PREPARE_BUILD) | ||
| 11 | + gym_add_torch_binding(attn_prologue) | ||
| 12 | +endif() | ||
| @@ -0,0 +1,277 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +/*! | ||
| 12 | + * \file attn_prologue.cpp | ||
| 13 | + * \brief Precompiled Torch binding for aclnnAttnPrologue. | ||
| 14 | + * | ||
| 15 | + * The three projection weights use FRACTAL_NZ storage; gym_aclnn.h now carries | ||
| 16 | + * the tensor's real NPU format and physical storage shape, while all other | ||
| 17 | + * operands stay ND. | ||
| 18 | + */ | ||
| 19 | + | ||
| 20 | +#include "gym_aclnn.h" | ||
| 21 | + | ||
| 22 | +#include <ATen/ATen.h> | ||
| 23 | +#include <ATen/core/grad_mode.h> | ||
| 24 | +#include <c10/core/DeviceGuard.h> | ||
| 25 | +#include <cmath> | ||
| 26 | +#include <limits> | ||
| 27 | +#include <torch/library.h> | ||
| 28 | +#include <tuple> | ||
| 29 | + | ||
| 30 | +namespace { | ||
| 31 | + | ||
| 32 | +using Result = | ||
| 33 | + std::tuple<at::Tensor, at::Tensor, at::Tensor, at::Tensor>; | ||
| 34 | + | ||
| 35 | +constexpr int64_t H = 5120; | ||
| 36 | +constexpr int64_t R = 1280; | ||
| 37 | +constexpr int64_t N = 64; | ||
| 38 | +constexpr int64_t D = 512; | ||
| 39 | +constexpr int64_t DR = 64; | ||
| 40 | +constexpr int64_t KV_RECORD_BYTES = 544; | ||
| 41 | +constexpr int64_t FRACTAL_NZ = 29; | ||
| 42 | + | ||
| 43 | +void CheckND(const at::Tensor &tensor, at::ScalarType dtype, | ||
| 44 | + const std::vector<int64_t> &shape, const char *name) { | ||
| 45 | + TORCH_CHECK(tensor.device().is_privateuseone(), name, " must be an NPU tensor"); | ||
| 46 | + TORCH_CHECK(tensor.scalar_type() == dtype, name, " has an invalid dtype"); | ||
| 47 | + TORCH_CHECK(tensor.is_contiguous(), name, " must be contiguous"); | ||
| 48 | + TORCH_CHECK(tensor.sizes().vec() == shape, name, " has an invalid shape"); | ||
| 49 | + gym_torch::CheckNDStorage(tensor, name); | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +void CheckNZ(const at::Tensor &tensor, const std::vector<int64_t> &shape, | ||
| 53 | + const char *name) { | ||
| 54 | + TORCH_CHECK(tensor.device().is_privateuseone(), name, " must be an NPU tensor"); | ||
| 55 | + TORCH_CHECK(tensor.scalar_type() == at::ScalarType::Float8_e4m3fn, | ||
| 56 | + name, " must be E4M3"); | ||
| 57 | + TORCH_CHECK(tensor.sizes().vec() == shape, name, " has an invalid shape"); | ||
| 58 | + const auto format = at_npu::native::get_npu_format(tensor); | ||
| 59 | + TORCH_CHECK(format == FRACTAL_NZ, name, | ||
| 60 | + " must use FRACTAL_NZ storage; got NPU format ", format); | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +void CheckNoGrad(const std::vector<at::Tensor> &inputs) { | ||
| 64 | + for (const auto &value : inputs) | ||
| 65 | + TORCH_CHECK(!at::GradMode::is_enabled() || !value.requires_grad(), | ||
| 66 | + "AttnPrologue provides forward computation only; use " | ||
| 67 | + "torch.no_grad() for inference"); | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +void EnqueueAttnPrologue(const std::vector<at::Tensor> &inputs, | ||
| 71 | + const std::vector<at::Tensor> &outputs, | ||
| 72 | + double norm_eps, int64_t block_stride, | ||
| 73 | + int64_t row_stride, int64_t storage_bytes, | ||
| 74 | + int64_t emit_qr_norm) { | ||
| 75 | + using GetWorkspace = aclnnStatus (*)( | ||
| 76 | + const aclTensor *, const aclTensor *, const aclTensor *, const aclTensor *, | ||
| 77 | + const aclTensor *, const aclTensor *, const aclTensor *, const aclTensor *, | ||
| 78 | + const aclTensor *, const aclTensor *, const aclTensor *, const aclTensor *, | ||
| 79 | + const aclTensor *, const aclTensor *, const aclTensor *, double, | ||
| 80 | + int64_t, int64_t, int64_t, int64_t, | ||
| 81 | + const aclTensor *, const aclTensor *, const aclTensor *, | ||
| 82 | + uint64_t *, aclOpExecutor **); | ||
| 83 | + static const auto get_workspace = | ||
| 84 | + gym_torch::Symbol<GetWorkspace>("aclnnAttnPrologueGetWorkspaceSize"); | ||
| 85 | + static const auto execute = | ||
| 86 | + gym_torch::Symbol<gym_torch::Execute>("aclnnAttnPrologue"); | ||
| 87 | + | ||
| 88 | + auto tensors = inputs; | ||
| 89 | + tensors.insert(tensors.end(), outputs.begin(), outputs.end()); | ||
| 90 | + gym_torch::Enqueue( | ||
| 91 | + "aclnnAttnPrologue", tensors, | ||
| 92 | + [norm_eps, block_stride, row_stride, | ||
| 93 | + storage_bytes, emit_qr_norm](const auto &values, auto stream) { | ||
| 94 | + std::vector<gym_torch::TensorHandle> handles; | ||
| 95 | + handles.reserve(values.size()); | ||
| 96 | + for (const auto &value : values) | ||
| 97 | + handles.push_back(gym_torch::Tensor(value)); | ||
| 98 | + uint64_t bytes = 0; | ||
| 99 | + aclOpExecutor *executor = nullptr; | ||
| 100 | + const auto status = get_workspace( | ||
| 101 | + handles[0].get(), handles[1].get(), handles[2].get(), | ||
| 102 | + handles[3].get(), handles[4].get(), handles[5].get(), | ||
| 103 | + handles[6].get(), handles[7].get(), handles[8].get(), | ||
| 104 | + handles[9].get(), handles[10].get(), handles[11].get(), | ||
| 105 | + handles[12].get(), handles[13].get(), handles[14].get(), norm_eps, | ||
| 106 | + block_stride, row_stride, storage_bytes, emit_qr_norm, | ||
| 107 | + handles[15].get(), handles[16].get(), handles[17].get(), &bytes, | ||
| 108 | + &executor); | ||
| 109 | + TORCH_CHECK(status == 0, | ||
| 110 | + "aclnnAttnPrologueGetWorkspaceSize failed, status=", status, | ||
| 111 | + ": ", aclGetRecentErrMsg()); | ||
| 112 | + gym_torch::ExecuteOp(execute, bytes, executor, stream); | ||
| 113 | + return 0; | ||
| 114 | + }); | ||
| 115 | +} | ||
| 116 | + | ||
| 117 | +struct CacheLayout { | ||
| 118 | + int64_t pageStride; | ||
| 119 | + int64_t rowStride; | ||
| 120 | + int64_t bytes; | ||
| 121 | +}; | ||
| 122 | + | ||
| 123 | +static CacheLayout CheckCache(const at::Tensor &kv_cache) { | ||
| 124 | + TORCH_CHECK(kv_cache.device().is_privateuseone() && | ||
| 125 | + kv_cache.scalar_type() == at::ScalarType::Byte && | ||
| 126 | + kv_cache.dim() == 4 && kv_cache.size(2) == 1 && | ||
| 127 | + kv_cache.size(3) >= KV_RECORD_BYTES, | ||
| 128 | + "kv_cache must be UINT8 [P,BS,1,C>=544]"); | ||
| 129 | + // torch_npu reports a plain 4-D uint8 buffer as NCHW (0) rather than ND (2). | ||
| 130 | + // The ACLNN kernel treats kv_cache as a flat record buffer, so both are valid. | ||
| 131 | + const auto kv_format = at_npu::native::get_npu_format(kv_cache); | ||
| 132 | + TORCH_CHECK(kv_format == ACL_FORMAT_ND || kv_format == ACL_FORMAT_NCHW, | ||
| 133 | + "kv_cache must use ND/NCHW storage; got NPU format ", kv_format); | ||
| 134 | + const int64_t pages = kv_cache.size(0); | ||
| 135 | + const int64_t block_size = kv_cache.size(1); | ||
| 136 | + TORCH_CHECK(pages > 0 && block_size > 0, | ||
| 137 | + "kv_cache P/BS must be positive"); | ||
| 138 | + TORCH_CHECK(kv_cache.stride(3) == 1, | ||
| 139 | + "kv_cache records must be contiguous on the last dim"); | ||
| 140 | + const int64_t row_stride_resolved = | ||
| 141 | + kv_cache.stride(1) * kv_cache.element_size(); | ||
| 142 | + const int64_t page_stride_resolved = | ||
| 143 | + kv_cache.stride(0) * kv_cache.element_size(); | ||
| 144 | + TORCH_CHECK(row_stride_resolved >= KV_RECORD_BYTES && | ||
| 145 | + row_stride_resolved % 32 == 0, | ||
| 146 | + "row_stride must be >= 544 and 32B aligned"); | ||
| 147 | + TORCH_CHECK(page_stride_resolved >= block_size * row_stride_resolved && | ||
| 148 | + page_stride_resolved % 32 == 0, | ||
| 149 | + "page stride must be >= BS*row_stride and 32B aligned"); | ||
| 150 | + const int64_t needed = (pages - 1) * page_stride_resolved + | ||
| 151 | + (block_size - 1) * row_stride_resolved + | ||
| 152 | + KV_RECORD_BYTES; | ||
| 153 | + const int64_t storage_bytes = static_cast<int64_t>( | ||
| 154 | + kv_cache.storage().nbytes() - | ||
| 155 | + kv_cache.storage_offset() * kv_cache.element_size()); | ||
| 156 | + TORCH_CHECK(storage_bytes >= needed, | ||
| 157 | + "kv_cache backing storage ", storage_bytes, | ||
| 158 | + " < physical write range ", needed); | ||
| 159 | + return {page_stride_resolved, row_stride_resolved, storage_bytes}; | ||
| 160 | +} | ||
| 161 | + | ||
| 162 | +static void CheckScales(int64_t t, const at::Tensor &descale_x, const at::Tensor &descale_wqa, | ||
| 163 | + const at::Tensor &descale_wqb, const at::Tensor &descale_wkv) { | ||
| 164 | + CheckND(descale_x, at::ScalarType::Float8_e8m0fnu, {t, H / 64, 2}, | ||
| 165 | + "descale_x"); | ||
| 166 | + CheckND(descale_wqa, at::ScalarType::Float8_e8m0fnu, {R, H / 64, 2}, | ||
| 167 | + "descale_wqa"); | ||
| 168 | + CheckND(descale_wqb, at::ScalarType::Float8_e8m0fnu, {N * D, R / 64, 2}, | ||
| 169 | + "descale_wqb"); | ||
| 170 | + CheckND(descale_wkv, at::ScalarType::Float8_e8m0fnu, {D, H / 64, 2}, | ||
| 171 | + "descale_wkv"); | ||
| 172 | +} | ||
| 173 | + | ||
| 174 | +static at::Tensor QrNormBuffer(const c10::optional<at::Tensor> &qr_norm, const at::Tensor &x, int64_t t) { | ||
| 175 | + if (qr_norm.has_value()) { | ||
| 176 | + TORCH_CHECK(qr_norm->device() == x.device() && | ||
| 177 | + qr_norm->scalar_type() == at::ScalarType::BFloat16 && | ||
| 178 | + qr_norm->dim() == 2 && qr_norm->size(0) == t && | ||
| 179 | + qr_norm->size(1) == R && qr_norm->is_contiguous(), | ||
| 180 | + "qr_norm must be contiguous BF16 [T,1280] on the same NPU"); | ||
| 181 | + gym_torch::CheckNDStorage(*qr_norm, "qr_norm"); | ||
| 182 | + return *qr_norm; | ||
| 183 | + } | ||
| 184 | + return at::empty({0, R}, x.options().dtype(at::ScalarType::BFloat16)); | ||
| 185 | +} | ||
| 186 | + | ||
| 187 | +static Result Run(const at::Tensor &x, const at::Tensor &wqa, | ||
| 188 | + const at::Tensor &wqb, const at::Tensor &wkv, | ||
| 189 | + const at::Tensor &descale_x, const at::Tensor &descale_wqa, | ||
| 190 | + const at::Tensor &descale_wqb, const at::Tensor &descale_wkv, | ||
| 191 | + const at::Tensor &norm_weight_qr, | ||
| 192 | + const at::Tensor &norm_weight_kv, | ||
| 193 | + const at::Tensor &rope_sin, const at::Tensor &rope_cos, | ||
| 194 | + const at::Tensor &cache_index, const at::Tensor &kv_cache, | ||
| 195 | + const c10::optional<at::Tensor> &qr_norm, double norm_eps) { | ||
| 196 | + TORCH_CHECK(x.dim() == 2 && x.size(1) == H && | ||
| 197 | + x.scalar_type() == at::ScalarType::Float8_e4m3fn && | ||
| 198 | + x.device().is_privateuseone(), | ||
| 199 | + "x must be a [T,5120] E4M3 NPU tensor"); | ||
| 200 | + const c10::OptionalDeviceGuard guard(x.device()); | ||
| 201 | + const int64_t t = x.size(0); | ||
| 202 | + TORCH_CHECK(t >= 1 && t <= 262144, "T outside [1,262144]"); | ||
| 203 | + TORCH_CHECK(std::isfinite(norm_eps) && norm_eps > 0 && | ||
| 204 | + norm_eps <= std::numeric_limits<float>::max(), | ||
| 205 | + "norm_eps must be finite and positive"); | ||
| 206 | + | ||
| 207 | + CheckND(x, at::ScalarType::Float8_e4m3fn, {t, H}, "x"); | ||
| 208 | + CheckNZ(wqa, {R, H}, "wqa"); | ||
| 209 | + CheckNZ(wqb, {N * D, R}, "wqb"); | ||
| 210 | + CheckNZ(wkv, {D, H}, "wkv"); | ||
| 211 | + CheckScales(t, descale_x, descale_wqa, descale_wqb, descale_wkv); | ||
| 212 | + CheckND(norm_weight_qr, at::ScalarType::Float, {R}, "norm_weight_qr"); | ||
| 213 | + CheckND(norm_weight_kv, at::ScalarType::Float, {D}, "norm_weight_kv"); | ||
| 214 | + CheckND(rope_sin, at::ScalarType::Float, {t, DR}, "rope_sin"); | ||
| 215 | + CheckND(rope_cos, at::ScalarType::Float, {t, DR}, "rope_cos"); | ||
| 216 | + CheckND(cache_index, at::ScalarType::Long, {t}, "cache_index"); | ||
| 217 | + const auto cache = CheckCache(kv_cache); | ||
| 218 | + const auto qr_norm_buf = QrNormBuffer(qr_norm, x, t); | ||
| 219 | + const int64_t emit_qr_norm = qr_norm_buf.numel() != 0; | ||
| 220 | + std::vector<at::Tensor> inputs = { | ||
| 221 | + x, wqa, wqb, wkv, descale_x, descale_wqa, descale_wqb, descale_wkv, | ||
| 222 | + norm_weight_qr, norm_weight_kv, rope_sin, rope_cos, cache_index, | ||
| 223 | + kv_cache, qr_norm_buf}; | ||
| 224 | + CheckNoGrad(inputs); | ||
| 225 | + | ||
| 226 | + auto q = at::empty({t, N, D}, x.options().dtype(at::ScalarType::BFloat16)); | ||
| 227 | + auto qr = at::empty({t, R}, x.options().dtype(at::ScalarType::Float8_e4m3fn)); | ||
| 228 | + auto descale_qr = | ||
| 229 | + at::empty({t, R / 64, 2}, x.options().dtype(at::ScalarType::Float8_e8m0fnu)); | ||
| 230 | + gym_torch::CheckNDStorage(q, "q"); | ||
| 231 | + gym_torch::CheckNDStorage(qr, "qr"); | ||
| 232 | + gym_torch::CheckNDStorage(descale_qr, "descale_qr"); | ||
| 233 | + std::vector<at::Tensor> outputs = {q, qr, descale_qr}; | ||
| 234 | + | ||
| 235 | + EnqueueAttnPrologue(inputs, outputs, norm_eps, cache.pageStride, cache.rowStride, | ||
| 236 | + cache.bytes, emit_qr_norm); | ||
| 237 | + return {q, qr, descale_qr, kv_cache}; | ||
| 238 | +} | ||
| 239 | + | ||
| 240 | +static Result Meta(const at::Tensor &x, const at::Tensor &wqa, | ||
| 241 | + const at::Tensor &wqb, const at::Tensor &wkv, | ||
| 242 | + const at::Tensor &descale_x, const at::Tensor &descale_wqa, | ||
| 243 | + const at::Tensor &descale_wqb, const at::Tensor &descale_wkv, | ||
| 244 | + const at::Tensor &norm_weight_qr, | ||
| 245 | + const at::Tensor &norm_weight_kv, | ||
| 246 | + const at::Tensor &rope_sin, const at::Tensor &rope_cos, | ||
| 247 | + const at::Tensor &cache_index, const at::Tensor &kv_cache, | ||
| 248 | + const c10::optional<at::Tensor> &qr_norm, double norm_eps) { | ||
| 249 | + TORCH_CHECK(x.dim() == 2, "x must be rank-2"); | ||
| 250 | + (void)wqa; (void)wqb; (void)wkv; (void)descale_x; (void)descale_wqa; | ||
| 251 | + (void)descale_wqb; (void)descale_wkv; (void)norm_weight_qr; | ||
| 252 | + (void)norm_weight_kv; (void)rope_sin; (void)rope_cos; (void)cache_index; | ||
| 253 | + (void)norm_eps; (void)qr_norm; | ||
| 254 | + const auto t = x.sym_size(0); | ||
| 255 | + return {at::empty_symint({t, N, D}, x.options().dtype(at::ScalarType::BFloat16)), | ||
| 256 | + at::empty_symint({t, R}, x.options().dtype(at::ScalarType::Float8_e4m3fn)), | ||
| 257 | + at::empty_symint({t, R / 64, 2}, | ||
| 258 | + x.options().dtype(at::ScalarType::Float8_e8m0fnu)), | ||
| 259 | + kv_cache}; | ||
| 260 | +} | ||
| 261 | + | ||
| 262 | +} // namespace | ||
| 263 | + | ||
| 264 | +TORCH_LIBRARY_FRAGMENT(pypto_gym, m) { | ||
| 265 | + m.def("attn_prologue(Tensor x, Tensor wqa, Tensor wqb, Tensor wkv, " | ||
| 266 | + "Tensor descale_x, Tensor descale_wqa, Tensor descale_wqb, " | ||
| 267 | + "Tensor descale_wkv, Tensor norm_weight_qr, Tensor norm_weight_kv, " | ||
| 268 | + "Tensor rope_sin, Tensor rope_cos, Tensor cache_index, " | ||
| 269 | + "Tensor(a!) kv_cache, Tensor(b!)? qr_norm=None, *, float norm_eps=1e-6) -> " | ||
| 270 | + "(Tensor, Tensor, Tensor, Tensor(a!))"); | ||
| 271 | +} | ||
| 272 | +TORCH_LIBRARY_IMPL(pypto_gym, PrivateUse1, m) { | ||
| 273 | + m.impl("attn_prologue", TORCH_FN(Run)); | ||
| 274 | +} | ||
| 275 | +TORCH_LIBRARY_IMPL(pypto_gym, Meta, m) { | ||
| 276 | + m.impl("attn_prologue", TORCH_FN(Meta)); | ||
| 277 | +} | ||
| @@ -0,0 +1,35 @@ | |||
| 1 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 10 | +"""Public Torch frontend for the precompiled AttnPrologue operator.""" | ||
| 11 | +import math | ||
| 12 | + | ||
| 13 | +import torch | ||
| 14 | + | ||
| 15 | + | ||
| 16 | +def attn_prologue(x, wqa, wqb, wkv, | ||
| 17 | + descale_x, descale_wqa, descale_wqb, descale_wkv, | ||
| 18 | + norm_weight_qr, norm_weight_kv, | ||
| 19 | + rope_sin, rope_cos, cache_index, kv_cache, | ||
| 20 | + qr_norm=None, norm_eps=1e-6): | ||
| 21 | + """Return (q, qr, descale_qr); kv_cache is updated in place. | ||
| 22 | + | ||
| 23 | + Runs the installed ACLNN binary on the current NPU stream. Inputs follow the | ||
| 24 | + operator contract: x/weights are E4M3 (weights FRACTAL_NZ), descales E8M0, | ||
| 25 | + rope/norm weights FP32, cache_index INT64 and kv_cache UINT8 [P,BS,1,544]. | ||
| 26 | + The operator provides forward computation only. | ||
| 27 | + """ | ||
| 28 | + scalar = isinstance(norm_eps, (int, float)) and not isinstance(norm_eps, bool) | ||
| 29 | + if not scalar or not math.isfinite(norm_eps) or norm_eps <= 0: | ||
| 30 | + raise ValueError('norm_eps must be a finite positive scalar') | ||
| 31 | + q, qr, descale_qr, _ = torch.ops.pypto_gym.attn_prologue.default( | ||
| 32 | + x, wqa, wqb, wkv, descale_x, descale_wqa, descale_wqb, descale_wkv, | ||
| 33 | + norm_weight_qr, norm_weight_kv, rope_sin, rope_cos, cache_index, | ||
| 34 | + kv_cache, qr_norm=qr_norm, norm_eps=float(norm_eps)) | ||
| 35 | + return q, qr, descale_qr.view(torch.int8) | ||
| @@ -0,0 +1,9 @@ | |||
| 1 | +file(GLOB CURRENT_DIRS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*) | ||
| 2 | +if(NOT ENABLE_TESTS) | ||
| 3 | + list(REMOVE_ITEM CURRENT_DIRS tests) | ||
| 4 | +endif() | ||
| 5 | +foreach(SUB_DIR ${CURRENT_DIRS}) | ||
| 6 | + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${SUB_DIR}/CMakeLists.txt") | ||
| 7 | + add_subdirectory(${SUB_DIR}) | ||
| 8 | + endif() | ||
| 9 | +endforeach() | ||
| @@ -0,0 +1,99 @@ | |||
| 1 | +# engram_hash(PyPTO-Pro) | ||
| 2 | + | ||
| 3 | +- 实现:`op_kernel/engram_hash.py` | ||
| 4 | +- 测试:`tests/test_engram_hash_routes.py`;golden:`tests/assets/engram_hash_golden.py` | ||
| 5 | + | ||
| 6 | +## 1. 算子介绍 | ||
| 7 | + | ||
| 8 | +engram_hash 是 Engram n-gram 哈希算子:输入每个 token 的 n-gram token id,按层与 n-gram | ||
| 9 | +位置做 XOR 哈希,再按每张 embedding 表的词表大小取模、叠加桶偏移,得到记忆表的行号; | ||
| 10 | +图像 token 的输出行填充为 -1。基于 `pypto_pro` DSL 在昇腾 NPU 上实现,运行于 | ||
| 11 | +Ascend 950(arch 3510)。 | ||
| 12 | + | ||
| 13 | +DeepSeek V4.1 的规格为 `L=2`、`Tb=8`、`G=4`,输出 `[2, T, 24]`;层数、头数与 `G` 均可配置。 | ||
| 14 | + | ||
| 15 | +## 2. 计算公式 | ||
| 16 | + | ||
| 17 | +对每个 token `t`、每个 n-gram layer: | ||
| 18 | + | ||
| 19 | +```text | ||
| 20 | +hash_0 = int64(ngram_token_ids[t, 0]) * multipliers[layer, 0] | ||
| 21 | +hash_i = hash_{i-1} XOR (int64(ngram_token_ids[t, i]) * multipliers[layer, i]), i = 1..G-1 | ||
| 22 | + | ||
| 23 | +out[layer, t, (i-1)*Tb + tb] = hash_i % vocab_sizes[layer, i-1, tb] | ||
| 24 | + + offsets[layer, (i-1)*Tb + tb] | ||
| 25 | +out[layer, t, :] = -1 当 image_token_mask[t] 为真 | ||
| 26 | +``` | ||
| 27 | + | ||
| 28 | +哈希为 int64 环绕语义:token id 由 int32 提升到 int64 后与 int64 乘子相乘,再逐级 XOR。 | ||
| 29 | +取模采用向下取整语义(与 torch 的 `%` 一致);设备侧的截断取模由负余数加一次除数修正, | ||
| 30 | +对任意 int64 输入与参考实现逐位一致。 | ||
| 31 | + | ||
| 32 | +## 3. 计算流程 | ||
| 33 | + | ||
| 34 | +```mermaid | ||
| 35 | +flowchart TD | ||
| 36 | + A["输入 ngram_token_ids / multipliers / vocab_sizes / offsets / image_token_mask"] --> B["逐 token 求 hash_0 = int64(id_0) × mult[layer, 0]"] | ||
| 37 | + B --> C["逐级 XOR:hash_i = hash_(i-1) XOR (int64(id_i) × mult[layer, i])"] | ||
| 38 | + C --> D["按 vocab 取模并叠加桶偏移 offsets"] | ||
| 39 | + D --> E{"image_token_mask[t] 为真?"} | ||
| 40 | + E -- "是" --> F["整行输出 -1"] | ||
| 41 | + E -- "否" --> G["输出 hash 行号"] | ||
| 42 | + F --> H["输出 out [L, T, (G-1)×Tb] int32"] | ||
| 43 | + G --> H | ||
| 44 | +``` | ||
| 45 | + | ||
| 46 | +## 4. 入参说明 | ||
| 47 | + | ||
| 48 | +```python | ||
| 49 | +import sys | ||
| 50 | +sys.path.insert(0, "<...>/engram_hash/op_kernel") | ||
| 51 | +from engram_hash import ( | ||
| 52 | + engram_hash, | ||
| 53 | + make_offsets, | ||
| 54 | +) | ||
| 55 | + | ||
| 56 | +offsets = make_offsets(vocab_sizes) # [L, (G-1)*Tb] int32,exclusive prefix-sum | ||
| 57 | +out = engram_hash(ngram_token_ids, multipliers, vocab_sizes, offsets, image_token_mask=None) | ||
| 58 | +``` | ||
| 59 | + | ||
| 60 | +输入: | ||
| 61 | + | ||
| 62 | +| 名称 | 必选 | shape | dtype | 说明 | | ||
| 63 | +|---|---|---|---|---| | ||
| 64 | +| `ngram_token_ids` | 是 | `[T, G]` | int32 | 每个 token 的 n-gram token id | | ||
| 65 | +| `multipliers` | 是 | `[L, G]` | int64 | 每层、每个 n-gram 位置的哈希乘子 | | ||
| 66 | +| `vocab_sizes` | 是 | `[L, G-1, Tb]` | int32 | 每层、每个 n-gram 位置、每张表的词表大小 | | ||
| 67 | +| `offsets` | 是 | `[L, (G-1)*Tb]` | int32 | 由 `make_offsets` 生成,也可由调用方自备 | | ||
| 68 | +| `image_token_mask` | 否 | `[T]` | bool / uint8 | `True` 的 token 输出整行为 -1;`None` 等价全 False | | ||
| 69 | + | ||
| 70 | +输出: | ||
| 71 | + | ||
| 72 | +| 名称 | shape | dtype | 说明 | | ||
| 73 | +|---|---|---|---| | ||
| 74 | +| `out` | `[L, T, (G-1)*Tb]` | int32 | embedding 行号 | | ||
| 75 | + | ||
| 76 | +## 5. 约束 | ||
| 77 | + | ||
| 78 | +- `T ≥ 0`;`L > 0`;`G ≥ 2`;`Tb > 0`。 | ||
| 79 | +- 所有输入张量位于同一 NPU,使用 ND 存储格式。 | ||
| 80 | +- `image_token_mask` 长度必须等于 `T`。 | ||
| 81 | +- 参数 rank、dtype、shape 或 device 不符合契约时直接报错,不进行隐式类型转换。 | ||
| 82 | +- 调用方需保证 `token_id × multiplier` 不溢出 int64(与参考实现契约一致)。 | ||
| 83 | +- host 按 mask 是否存在和 n-gram 规格选择 tiling key。T、L 等运行时参数写入 TilingData。 | ||
| 84 | +- `output` 为 int32:`hash % vocab` 小于 `vocab ≤ 2^31`,叠加 int32 偏移后仍在 int32 范围内。 | ||
| 85 | + | ||
| 86 | +## 6. 测试 | ||
| 87 | + | ||
| 88 | +```bash | ||
| 89 | +python3 -m pytest -q --mode=jit ops/pro/deepseek_v4_1/engram_hash/tests/test_engram_hash_routes.py | ||
| 90 | +python3 -m pytest -q --mode=torch ops/pro/deepseek_v4_1/engram_hash/tests/test_engram_hash_routes.py | ||
| 91 | +``` | ||
| 92 | + | ||
| 93 | +用例标记 `@pytest.mark.soc("950")`;无 NPU 环境下 NPU 用例自动跳过(`make_offsets` 的 CPU 用例 | ||
| 94 | +始终运行)。输出为整型,与 `tests/assets/engram_hash_golden.py`(纯 torch 参考)用 `torch.equal` | ||
| 95 | +逐位比较,不设容差;覆盖尾块、整块、多块、mask 三态、负乘子、`T=0` 与非法输入等路径。 | ||
| 96 | + | ||
| 97 | +## 调用方式 | ||
| 98 | + | ||
| 99 | +JIT 使用 `from op_kernel.engram_hash import engram_hash`。安装算子包后,使用 `pypto_gym.engram_hash(ids, multipliers, vocab_sizes, offsets, image_token_mask)` 调用预编译的 `aclnnEngramHash`。两条路径返回相同形状的 int32 张量。 | ||
| @@ -0,0 +1,10 @@ | |||
| 1 | +require_pypto_pro(engram_hash) | ||
| 2 | +add_op_to_compiled_list() | ||
| 3 | +target_sources(op_host_aclnn PRIVATE engram_hash_def.cpp) | ||
| 4 | +add_modules_sources(OPTYPE engram_hash ACLNNTYPE aclnn) | ||
| 5 | +enable_pypto_kernel(engram_hash) | ||
| 6 | +add_ops_compile_options(OP_NAME EngramHash | ||
| 7 | + OPTIONS -DENABLE_CV_COMM_VIA_SSBUF=true --cce-auto-sync=off -Wno-deprecated-declarations) | ||
| 8 | +if(NOT BUILD_OPS_RTY_KERNEL) | ||
| 9 | + add_tiling_modules() | ||
| 10 | +endif() | ||
| @@ -0,0 +1,42 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | +#include "register/op_def_registry.h" | ||
| 11 | + | ||
| 12 | +namespace ops { | ||
| 13 | +class EngramHash : public OpDef { | ||
| 14 | +public: | ||
| 15 | + explicit EngramHash(const char *name) : OpDef(name) | ||
| 16 | + { | ||
| 17 | + this->Input("ngram_token_ids").ParamType(REQUIRED) | ||
| 18 | + .DataType({ge::DT_INT32}).Format({ge::FORMAT_ND}).AutoContiguous(); | ||
| 19 | + this->Input("multipliers").ParamType(REQUIRED) | ||
| 20 | + .DataType({ge::DT_INT64}).Format({ge::FORMAT_ND}).AutoContiguous(); | ||
| 21 | + this->Input("vocab_sizes").ParamType(REQUIRED) | ||
| 22 | + .DataType({ge::DT_INT32}).Format({ge::FORMAT_ND}).AutoContiguous(); | ||
| 23 | + this->Input("offsets").ParamType(REQUIRED) | ||
| 24 | + .DataType({ge::DT_INT32}).Format({ge::FORMAT_ND}).AutoContiguous(); | ||
| 25 | + this->Input("image_token_mask").ParamType(OPTIONAL) | ||
| 26 | + .DataType({ge::DT_UINT8}).Format({ge::FORMAT_ND}).AutoContiguous(); | ||
| 27 | + this->Output("output").ParamType(REQUIRED) | ||
| 28 | + .DataType({ge::DT_INT32}).Format({ge::FORMAT_ND}); | ||
| 29 | + OpAICoreConfig aicore_config; | ||
| 30 | + aicore_config.DynamicCompileStaticFlag(true) | ||
| 31 | + .DynamicFormatFlag(true) | ||
| 32 | + .DynamicRankSupportFlag(true) | ||
| 33 | + .DynamicShapeSupportFlag(true) | ||
| 34 | + .NeedCheckSupportFlag(false) | ||
| 35 | + .PrecisionReduceFlag(true) | ||
| 36 | + .ExtendCfgInfo("opFile.value", "engram_hash") | ||
| 37 | + .ExtendCfgInfo("aclnnSupport.value", "support_aclnn"); | ||
| 38 | + this->AICore().AddConfig("ascend950", aicore_config); | ||
| 39 | + } | ||
| 40 | +}; | ||
| 41 | +OP_ADD(EngramHash); | ||
| 42 | +} // namespace ops | ||
| @@ -0,0 +1,31 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | +#include <limits> | ||
| 11 | +#include "register/op_impl_registry.h" | ||
| 12 | +namespace ops { | ||
| 13 | +static ge::graphStatus Infer(gert::InferShapeContext *ctx) | ||
| 14 | +{ | ||
| 15 | + if (!ctx) return ge::GRAPH_FAILED; | ||
| 16 | + const auto *ids=ctx->GetInputShape(0), *mult=ctx->GetInputShape(1), *offs=ctx->GetInputShape(3); | ||
| 17 | + auto *out=ctx->GetOutputShape(0); | ||
| 18 | + if (!ids || !mult || !offs || !out || ids->GetDimNum()!=2 || | ||
| 19 | + mult->GetDimNum()!=2 || offs->GetDimNum()!=2) return ge::GRAPH_FAILED; | ||
| 20 | + out->SetDimNum(3); | ||
| 21 | + out->SetDim(0,mult->GetDim(0)); out->SetDim(1,ids->GetDim(0)); out->SetDim(2,offs->GetDim(1)); | ||
| 22 | + return ge::GRAPH_SUCCESS; | ||
| 23 | +} | ||
| 24 | +static ge::graphStatus Dtype(gert::InferDataTypeContext *ctx) | ||
| 25 | +{ | ||
| 26 | + if (!ctx) return ge::GRAPH_FAILED; | ||
| 27 | + ctx->SetOutputDataType(0,ge::DT_INT32); | ||
| 28 | + return ge::GRAPH_SUCCESS; | ||
| 29 | +} | ||
| 30 | +IMPL_OP_INFERSHAPE(EngramHash).InferShape(Infer).InferDataType(Dtype); | ||
| 31 | +} | ||
| @@ -0,0 +1,82 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | +#include <algorithm> | ||
| 11 | +#include <limits> | ||
| 12 | +#include "engram_hash_tiling.h" | ||
| 13 | +#include "register/op_impl_registry.h" | ||
| 14 | +#include "tiling/platform/platform_ascendc.h" | ||
| 15 | + | ||
| 16 | +namespace optiling { | ||
| 17 | +struct CompileInfo {}; | ||
| 18 | +static bool ValidDimensions(int64_t t, int64_t g, int64_t l, int64_t n) { | ||
| 19 | + return t >= 0 && g >= 2 && l > 0 && n > 0 && n <= std::numeric_limits<int64_t>::max() / (g - 1); | ||
| 20 | +} | ||
| 21 | + | ||
| 22 | +static ge::graphStatus ReadDimensions(gert::TilingContext *ctx, int64_t &t, int64_t &g, int64_t &l, int64_t &n) { | ||
| 23 | + const auto *ids = ctx->GetRequiredInputShape(0); | ||
| 24 | + const auto *mult = ctx->GetRequiredInputShape(1); | ||
| 25 | + const auto *vocab = ctx->GetRequiredInputShape(2); | ||
| 26 | + const auto *offs = ctx->GetRequiredInputShape(3); | ||
| 27 | + if (!ids || !mult || !vocab || !offs) return ge::GRAPH_FAILED; | ||
| 28 | + const auto &x = ids->GetStorageShape(); | ||
| 29 | + const auto &m = mult->GetStorageShape(); | ||
| 30 | + const auto &v = vocab->GetStorageShape(); | ||
| 31 | + const auto &o = offs->GetStorageShape(); | ||
| 32 | + if (x.GetDimNum()!=2 || m.GetDimNum()!=2 || v.GetDimNum()!=3 || o.GetDimNum()!=2) | ||
| 33 | + return ge::GRAPH_FAILED; | ||
| 34 | + t=x.GetDim(0); g=x.GetDim(1); l=m.GetDim(0); n=v.GetDim(2); | ||
| 35 | + if (!ValidDimensions(t, g, l, n) | ||
| 36 | + || m.GetDim(1)!=g || v.GetDim(0)!=l || v.GetDim(1)!=g-1 | ||
| 37 | + || o.GetDim(0)!=l || o.GetDim(1)!=(g-1)*n) return ge::GRAPH_FAILED; | ||
| 38 | + return ge::GRAPH_SUCCESS; | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +static ge::graphStatus Tiling(gert::TilingContext *ctx) | ||
| 42 | +{ | ||
| 43 | + if (!ctx || !ctx->GetPlatformInfo()) return ge::GRAPH_FAILED; | ||
| 44 | + int64_t t, g, l, n; | ||
| 45 | + if (ReadDimensions(ctx, t, g, l, n) != ge::GRAPH_SUCCESS) return ge::GRAPH_FAILED; | ||
| 46 | + const auto *mask=ctx->GetOptionalInputShape(4); | ||
| 47 | + if (mask && (mask->GetStorageShape().GetDimNum()!=1 || mask->GetStorageShape().GetDim(0)!=t)) | ||
| 48 | + return ge::GRAPH_FAILED; | ||
| 49 | + auto *td=ctx->GetTilingData<EngramHashTiling>(); | ||
| 50 | + auto *ws=ctx->GetWorkspaceSizes(1); | ||
| 51 | + if (!td || !ws) return ge::GRAPH_FAILED; | ||
| 52 | + td->tokens=t; td->layers=l; td->ngram=g; td->tables=n; | ||
| 53 | + ctx->GetRawTilingData()->SetDataSize(sizeof(*td)); | ||
| 54 | + const auto cores=platform_ascendc::PlatformAscendC(ctx->GetPlatformInfo()).GetCoreNumAiv(); | ||
| 55 | + if (!cores) return ge::GRAPH_FAILED; | ||
| 56 | + constexpr int64_t lanes = 128; | ||
| 57 | + const int64_t rowTiles = t / lanes + (t % lanes != 0); | ||
| 58 | + const bool standardTables = n == 8 && (g == 3 || g == 4); | ||
| 59 | + constexpr int64_t singleTokenKeyOffset = 2; | ||
| 60 | + int64_t geometry = 0; | ||
| 61 | + int64_t jobs = t; | ||
| 62 | + if (standardTables && mask != nullptr && t == 1 && l == 2) { | ||
| 63 | + geometry = g + singleTokenKeyOffset; | ||
| 64 | + jobs = 1; | ||
| 65 | + } else if (standardTables && rowTiles * 4 >= cores) { | ||
| 66 | + geometry = g; | ||
| 67 | + jobs = rowTiles; | ||
| 68 | + } else if (g <= 16 && n <= 32) { | ||
| 69 | + // Match the SIMT dispatch in engram_hash.py. Clamp before multiplying | ||
| 70 | + // by the layer count; only the physical launch width is needed here. | ||
| 71 | + const int64_t tiles = (t / lanes) * n + ((t % lanes) * n + lanes - 1) / lanes; | ||
| 72 | + jobs = std::min<int64_t>(tiles, cores) * std::min<int64_t>(l, cores); | ||
| 73 | + } | ||
| 74 | + ctx->SetBlockDim(std::clamp<int64_t>(jobs, 1, cores)); | ||
| 75 | + ctx->SetTilingKey(GET_TPL_TILING_KEY(static_cast<uint64_t>(mask != nullptr), | ||
| 76 | + static_cast<uint64_t>(geometry))); | ||
| 77 | + ws[0]=0; | ||
| 78 | + return ge::GRAPH_SUCCESS; | ||
| 79 | +} | ||
| 80 | +static ge::graphStatus Parse(gert::TilingParseContext *) { return ge::GRAPH_SUCCESS; } | ||
| 81 | +IMPL_OP_OPTILING(EngramHash).Tiling(Tiling).TilingParse<CompileInfo>(Parse); | ||
| 82 | +} | ||
| @@ -0,0 +1,20 @@ | |||
| 1 | +/** | ||
| 2 | + * Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 3 | + * This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 4 | + * CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 5 | + * Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 6 | + * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 7 | + * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 8 | + * See LICENSE in the root of the software repository for the full text of the License. | ||
| 9 | + */ | ||
| 10 | +#pragma once | ||
| 11 | +#include "register/tilingdata_base.h" | ||
| 12 | +namespace optiling { | ||
| 13 | +BEGIN_TILING_DATA_DEF(EngramHashTilingData) | ||
| 14 | +TILING_DATA_FIELD_DEF(int64_t, tokens) | ||
| 15 | +TILING_DATA_FIELD_DEF(int64_t, layers) | ||
| 16 | +TILING_DATA_FIELD_DEF(int64_t, ngram) | ||
| 17 | +TILING_DATA_FIELD_DEF(int64_t, tables) | ||
| 18 | +END_TILING_DATA_DEF | ||
| 19 | +REGISTER_TILING_DATA_CLASS(EngramHash, EngramHashTilingData) | ||
| 20 | +} | ||
| @@ -0,0 +1,380 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 9 | +"""SIMT n-gram hashing with a common JIT and offline launch ABI.""" | ||
| 10 | +from dataclasses import dataclass | ||
| 11 | + | ||
| 12 | +import torch | ||
| 13 | +import pypto_pro.language as pl | ||
| 14 | +from pypto_pro.runtime.tilingkey import TilingKeyField | ||
| 15 | + | ||
| 16 | +TILE = 128 | ||
| 17 | +SMALL_GRAMS = 16 | ||
| 18 | +SMALL_TABLES = 32 | ||
| 19 | +SMALL_COLS = (SMALL_GRAMS - 1) * SMALL_TABLES | ||
| 20 | +# For two-layer, eight-table decode, keys 5 and 6 specialize a masked | ||
| 21 | +# single token. Keys 3 and 4 retain their original row-tile meaning. | ||
| 22 | +SINGLE_TOKEN_KEY_OFFSET = 2 | ||
| 23 | +PREFIX_GRAMS = 64 | ||
| 24 | +PREFIX_TABLES = 8 | ||
| 25 | +PREFIX_COLS = (PREFIX_GRAMS - 1) * PREFIX_TABLES | ||
| 26 | + | ||
| 27 | + | ||
| 28 | +class EngramHashKey: | ||
| 29 | + HasMask = TilingKeyField(bits=1, values=[0, 1]) | ||
| 30 | + Geometry = TilingKeyField(bits=3, values=[0, 3, 4, 5, 6]) | ||
| 31 | + | ||
| 32 | + | ||
| 33 | +@dataclass | ||
| 34 | +class EngramHashTiling: | ||
| 35 | + tokens: int | ||
| 36 | + layers: int | ||
| 37 | + ngram: int | ||
| 38 | + tables: int | ||
| 39 | + | ||
| 40 | + | ||
| 41 | +def _bucket(h, divisor, offset): | ||
| 42 | + d = pl.simt.cast(divisor, pl.DT_INT64) | ||
| 43 | + r = h % d | ||
| 44 | + if r < 0: | ||
| 45 | + r = r + d | ||
| 46 | + return pl.simt.cast(r, pl.DT_INT32) + offset | ||
| 47 | + | ||
| 48 | + | ||
| 49 | +def _hash_row(ids, mult, vocab, offs, out, tid, ngram): | ||
| 50 | + h = pl.simt.cast(ids[tid, 0], pl.DT_INT64) * mult[0] | ||
| 51 | + for i in pl.range(1, ngram): | ||
| 52 | + h = h ^ (pl.simt.cast(ids[tid, i], pl.DT_INT64) * mult[i]) | ||
| 53 | + for table in pl.range(0, 8): | ||
| 54 | + col = (i - 1) * 8 + table | ||
| 55 | + out[tid, col] = _bucket(h, vocab[col], offs[col]) | ||
| 56 | + | ||
| 57 | + | ||
| 58 | +@pl.vector_function(mode="simt", max_threads=TILE) | ||
| 59 | +def hash_tile(ids, mult, vocab, offs, mask, out, valid, ngram, has_mask): | ||
| 60 | + tid = pl.simt.linear_thread_idx() | ||
| 61 | + if tid < valid: | ||
| 62 | + masked = False | ||
| 63 | + if has_mask: | ||
| 64 | + masked = mask[tid] != 0 | ||
| 65 | + if masked: | ||
| 66 | + for col in pl.range(0, (ngram - 1) * 8): | ||
| 67 | + out[tid, col] = -1 | ||
| 68 | + else: | ||
| 69 | + _hash_row(ids, mult, vocab, offs, out, tid, ngram) | ||
| 70 | + | ||
| 71 | + | ||
| 72 | +@pl.vector_function(mode="simt", max_threads=TILE) | ||
| 73 | +def hash_token_tables(ids, mult, vocab, offs, mask, out, first, count, grams, tables): | ||
| 74 | + lane = pl.simt.linear_thread_idx() | ||
| 75 | + if lane < count: | ||
| 76 | + flat = first + lane | ||
| 77 | + row = flat // tables | ||
| 78 | + table = flat % tables | ||
| 79 | + width = (grams - 1) * tables | ||
| 80 | + masked = False | ||
| 81 | + if HasMask: | ||
| 82 | + masked = mask[row] != 0 | ||
| 83 | + if masked: | ||
| 84 | + for i in pl.range(1, grams): | ||
| 85 | + out[row * width + (i - 1) * tables + table] = -1 | ||
| 86 | + else: | ||
| 87 | + h = pl.simt.cast(ids[row * grams], pl.DT_INT64) * mult[0] | ||
| 88 | + for i in pl.range(1, grams): | ||
| 89 | + h = h ^ (pl.simt.cast(ids[row * grams + i], pl.DT_INT64) * mult[i]) | ||
| 90 | + col = (i - 1) * tables + table | ||
| 91 | + out[row * width + col] = _bucket(h, vocab[col], offs[col]) | ||
| 92 | + | ||
| 93 | + | ||
| 94 | +@pl.vector_function(mode="simt", max_threads=TILE) | ||
| 95 | +def emit_tables(vocab, offsets, output, count, h, masked): | ||
| 96 | + table = pl.simt.linear_thread_idx() | ||
| 97 | + if table < count: | ||
| 98 | + if masked: | ||
| 99 | + output[table] = -1 | ||
| 100 | + else: | ||
| 101 | + d = pl.simt.cast(vocab[table], pl.DT_INT64) | ||
| 102 | + r = h % d | ||
| 103 | + if r < 0: | ||
| 104 | + r = r + d | ||
| 105 | + output[table] = pl.simt.cast(r, pl.DT_INT32) + offsets[table] | ||
| 106 | + | ||
| 107 | + | ||
| 108 | +def _write_prefixes(x, m, buffers, shape, row, layer, h, masked): | ||
| 109 | + vocab, offs, out = buffers | ||
| 110 | + t, g, n, cols = shape | ||
| 111 | + for i in pl.range(1, g): | ||
| 112 | + h = h ^ (pl.astype(x[row, i], pl.DT_INT64) * m[layer, i]) | ||
| 113 | + for start in pl.range(0, n, TILE): | ||
| 114 | + col = (i - 1) * n + start | ||
| 115 | + v = pl.make_tensor(pl.addptr(vocab, layer * cols + col), [TILE]) | ||
| 116 | + o = pl.make_tensor(pl.addptr(offs, layer * cols + col), [TILE]) | ||
| 117 | + y = pl.make_tensor(pl.addptr(out, (layer * t + row) * cols + col), [TILE]) | ||
| 118 | + emit_tables[TILE](v, o, y, pl.min(TILE, n - start), h, masked) | ||
| 119 | + | ||
| 120 | + | ||
| 121 | +def _hash_general(ids, mult, buffers, mask, shape): | ||
| 122 | + t, l, g, n, cols = shape | ||
| 123 | + x = pl.make_tensor(ids, [t, g]) | ||
| 124 | + m = pl.make_tensor(mult, [l, g]) | ||
| 125 | + image = pl.make_tensor(mask, [t]) | ||
| 126 | + for row in pl.range(pl.get_block_idx(), t, pl.get_block_num()): | ||
| 127 | + masked = 0 | ||
| 128 | + if HasMask: | ||
| 129 | + masked = image[row] | ||
| 130 | + for layer in pl.range(0, l): | ||
| 131 | + h = pl.astype(x[row, 0], pl.DT_INT64) * m[layer, 0] | ||
| 132 | + _write_prefixes(x, m, buffers, (t, g, n, cols), row, layer, h, masked) | ||
| 133 | + | ||
| 134 | + | ||
| 135 | +def _hash_compact(ids, mult, vocab, offs, mask, out, shape): | ||
| 136 | + t, l, g, n, cols = shape | ||
| 137 | + # One SIMT lane owns one (token, table) for all n-gram prefixes. | ||
| 138 | + # Static views bound a tile; count and the runtime strides limit every access | ||
| 139 | + # to the actual input/output extent, including the final partial tile. | ||
| 140 | + cells = t * n | ||
| 141 | + tiles = (cells + TILE - 1) // TILE | ||
| 142 | + for job in pl.range(pl.get_block_idx(), tiles * l, pl.get_block_num()): | ||
| 143 | + layer = job // tiles | ||
| 144 | + start = (job % tiles) * TILE | ||
| 145 | + row = start // n | ||
| 146 | + x = pl.make_tensor(pl.addptr(ids, row * g), [TILE * SMALL_GRAMS]) | ||
| 147 | + m = pl.make_tensor(pl.addptr(mult, layer * g), [SMALL_GRAMS]) | ||
| 148 | + v = pl.make_tensor(pl.addptr(vocab, layer * cols), [SMALL_COLS]) | ||
| 149 | + o = pl.make_tensor(pl.addptr(offs, layer * cols), [SMALL_COLS]) | ||
| 150 | + image = pl.make_tensor(pl.addptr(mask, row * HasMask), [TILE]) | ||
| 151 | + y = pl.make_tensor(pl.addptr(out, (layer * t + row) * cols), [TILE * SMALL_COLS]) | ||
| 152 | + hash_token_tables[TILE](x, m, v, o, image, y, start % n, pl.min(TILE, cells - start), g, n) | ||
| 153 | + | ||
| 154 | + | ||
| 155 | +def _hash_tiles(ids, mult, vocab, offs, mask, out, t, l, cols): | ||
| 156 | + # SIMT accepts statically shaped views. Limit the last tile to live lanes. | ||
| 157 | + for tile in pl.range(pl.get_block_idx(), (t + TILE - 1) // TILE, pl.get_block_num()): | ||
| 158 | + row = tile * TILE | ||
| 159 | + valid = pl.min(TILE, t - row) | ||
| 160 | + x = pl.make_tensor(pl.addptr(ids, row * Geometry), [TILE, Geometry]) | ||
| 161 | + image = pl.make_tensor(pl.addptr(mask, row * HasMask), [TILE]) | ||
| 162 | + for layer in pl.range(0, l): | ||
| 163 | + m = pl.make_tensor(pl.addptr(mult, layer * Geometry), [Geometry]) | ||
| 164 | + v = pl.make_tensor(pl.addptr(vocab, layer * cols), [(Geometry - 1) * 8]) | ||
| 165 | + o = pl.make_tensor(pl.addptr(offs, layer * cols), [(Geometry - 1) * 8]) | ||
| 166 | + y = pl.make_tensor(pl.addptr(out, (layer * t + row) * cols), [TILE, (Geometry - 1) * 8]) | ||
| 167 | + hash_tile[TILE](x, m, v, o, image, y, valid, Geometry, HasMask) | ||
| 168 | + | ||
| 169 | + | ||
| 170 | +def _prefix_hash(ids, mult, start, prefix): | ||
| 171 | + h = pl.simt.cast(ids[0], pl.DT_INT64) * mult[start] | ||
| 172 | + for i in pl.range(1, prefix + 1): | ||
| 173 | + h = h ^ (pl.simt.cast(ids[i], pl.DT_INT64) * mult[start + i]) | ||
| 174 | + return h | ||
| 175 | + | ||
| 176 | + | ||
| 177 | +@pl.vector_function(mode="simt", max_threads=TILE) | ||
| 178 | +def _single_token(ids, mult, vocab, offs, mask, out): | ||
| 179 | + lane = pl.simt.linear_thread_idx() | ||
| 180 | + g = Geometry - SINGLE_TOKEN_KEY_OFFSET | ||
| 181 | + width = (g - 1) * 8 | ||
| 182 | + if lane < 2 * width: | ||
| 183 | + if mask[0] != 0: | ||
| 184 | + out[lane] = -1 | ||
| 185 | + else: | ||
| 186 | + layer = lane // width | ||
| 187 | + prefix = (lane % width) // 8 + 1 | ||
| 188 | + h = _prefix_hash(ids, mult, layer * g, prefix) | ||
| 189 | + out[lane] = _bucket(h, vocab[lane], offs[lane]) | ||
| 190 | + | ||
| 191 | + | ||
| 192 | +@pl.vector_function(mode="simt", max_threads=TILE) | ||
| 193 | +def _hash_prefix_group(ids, mult, vocab, offs, mask, out, first, width, tables): | ||
| 194 | + col = first + pl.simt.linear_thread_idx() | ||
| 195 | + if col < width: | ||
| 196 | + masked = False | ||
| 197 | + if HasMask: | ||
| 198 | + masked = mask[0] != 0 | ||
| 199 | + if masked: | ||
| 200 | + out[col] = -1 | ||
| 201 | + else: | ||
| 202 | + prefix = col // tables + 1 | ||
| 203 | + h = _prefix_hash(ids, mult, 0, prefix) | ||
| 204 | + out[col] = _bucket(h, vocab[col], offs[col]) | ||
| 205 | + | ||
| 206 | + | ||
| 207 | +def _hash_short_rows(ids, mult, vocab, offs, mask, out, shape): | ||
| 208 | + # With few tables, distribute independent prefix outputs across lanes. | ||
| 209 | + tokens, layers, grams, tables, width = shape | ||
| 210 | + for job in pl.range(pl.get_block_idx(), tokens * layers, pl.get_block_num()): | ||
| 211 | + layer = job // tokens | ||
| 212 | + row = job % tokens | ||
| 213 | + x = pl.make_tensor(pl.addptr(ids, row * grams), [PREFIX_GRAMS]) | ||
| 214 | + m = pl.make_tensor(pl.addptr(mult, layer * grams), [PREFIX_GRAMS]) | ||
| 215 | + v = pl.make_tensor(pl.addptr(vocab, layer * width), [PREFIX_COLS]) | ||
| 216 | + o = pl.make_tensor(pl.addptr(offs, layer * width), [PREFIX_COLS]) | ||
| 217 | + image = pl.make_tensor(pl.addptr(mask, row * HasMask), [1]) | ||
| 218 | + y = pl.make_tensor(pl.addptr(out, job * width), [PREFIX_COLS]) | ||
| 219 | + for first in pl.range(0, width, TILE): | ||
| 220 | + _hash_prefix_group[TILE](x, m, v, o, image, y, first, width, tables) | ||
| 221 | + | ||
| 222 | + | ||
| 223 | +@pl.jit(arch="3510", auto_mutex=True, tiling_key=EngramHashKey) | ||
| 224 | +def engram_hash_kernel(ids: pl.Ptr[pl.DT_INT32], mult: pl.Ptr[pl.DT_INT64], | ||
| 225 | + vocab: pl.Ptr[pl.DT_INT32], offs: pl.Ptr[pl.DT_INT32], | ||
| 226 | + mask: pl.Ptr[pl.DT_UINT8], out: pl.Ptr[pl.DT_INT32], | ||
| 227 | + workspace: pl.Ptr[pl.DT_UINT8], tiling: EngramHashTiling): | ||
| 228 | + with pl.section_vector(): | ||
| 229 | + if Geometry == 5 or Geometry == 6: | ||
| 230 | + # Static views cover both supported geometries. Only the live | ||
| 231 | + # 2 * (g - 1) * 8 output lanes access memory. | ||
| 232 | + x = pl.make_tensor(ids, [4]) | ||
| 233 | + m = pl.make_tensor(mult, [8]) | ||
| 234 | + v = pl.make_tensor(vocab, [48]) | ||
| 235 | + o = pl.make_tensor(offs, [48]) | ||
| 236 | + image = pl.make_tensor(mask, [1]) | ||
| 237 | + y = pl.make_tensor(out, [48]) | ||
| 238 | + _single_token[TILE](x, m, v, o, image, y) | ||
| 239 | + else: | ||
| 240 | + t = tiling.tokens | ||
| 241 | + l = tiling.layers | ||
| 242 | + g = tiling.ngram | ||
| 243 | + n = tiling.tables | ||
| 244 | + cols = (g - 1) * n | ||
| 245 | + if Geometry != 0: | ||
| 246 | + _hash_tiles(ids, mult, vocab, offs, mask, out, t, l, cols) | ||
| 247 | + elif g <= SMALL_GRAMS and n <= SMALL_TABLES: | ||
| 248 | + _hash_compact(ids, mult, vocab, offs, mask, out, (t, l, g, n, cols)) | ||
| 249 | + elif g > SMALL_GRAMS and g <= PREFIX_GRAMS and n <= PREFIX_TABLES and t <= TILE: | ||
| 250 | + _hash_short_rows(ids, mult, vocab, offs, mask, out, (t, l, g, n, cols)) | ||
| 251 | + else: | ||
| 252 | + # Keep the full input contract for other n-gram and table dimensions. | ||
| 253 | + _hash_general(ids, mult, (vocab, offs, out), mask, (t, l, g, n, cols)) | ||
| 254 | + | ||
| 255 | + | ||
| 256 | +def make_offsets(vocab_sizes): | ||
| 257 | + """由 vocab_sizes 求每层的 exclusive prefix-sum(与参考实现一致,int32)。""" | ||
| 258 | + rows = [] | ||
| 259 | + for layer in range(vocab_sizes.shape[0]): | ||
| 260 | + flat = vocab_sizes[layer].reshape(-1) | ||
| 261 | + rows.append(torch.cat([torch.zeros(1, dtype=torch.int32, device=flat.device), | ||
| 262 | + flat[:-1].cumsum(0, dtype=torch.int32)])) | ||
| 263 | + return torch.stack(rows, dim=0) | ||
| 264 | + | ||
| 265 | + | ||
| 266 | +def _check_nd(name, tensor): | ||
| 267 | + import torch_npu | ||
| 268 | + | ||
| 269 | + if tensor.device.type != "npu" or torch_npu.get_npu_format(tensor) != 2: | ||
| 270 | + raise ValueError(f"engram_hash: {name} must use ND storage on NPU") | ||
| 271 | + | ||
| 272 | + | ||
| 273 | +def _input_dimensions(ngram_token_ids, multipliers, vocab_sizes, offsets): | ||
| 274 | + for name, tensor, rank in (("ngram_token_ids", ngram_token_ids, 2), | ||
| 275 | + ("multipliers", multipliers, 2), | ||
| 276 | + ("vocab_sizes", vocab_sizes, 3), | ||
| 277 | + ("offsets", offsets, 2)): | ||
| 278 | + if tensor.dim() != rank: | ||
| 279 | + raise ValueError(f"engram_hash: {name} must be {rank}-D, got shape {tuple(tensor.shape)}") | ||
| 280 | + devices = {t.device for t in (ngram_token_ids, multipliers, vocab_sizes, offsets)} | ||
| 281 | + if len(devices) != 1: | ||
| 282 | + raise ValueError(f"engram_hash: all inputs must share one device, got {sorted(map(str, devices))}") | ||
| 283 | + | ||
| 284 | + num_tokens, max_ngram = ngram_token_ids.shape | ||
| 285 | + num_layers = multipliers.shape[0] | ||
| 286 | + tables = vocab_sizes.shape[2] | ||
| 287 | + num_cols = (max_ngram - 1) * tables | ||
| 288 | + | ||
| 289 | + expected = ( | ||
| 290 | + ("ngram_token_ids", ngram_token_ids, torch.int32, (num_tokens, max_ngram)), | ||
| 291 | + ("multipliers", multipliers, torch.int64, (num_layers, max_ngram)), | ||
| 292 | + ("vocab_sizes", vocab_sizes, torch.int32, (num_layers, max_ngram - 1, tables)), | ||
| 293 | + ("offsets", offsets, torch.int32, (num_layers, num_cols)), | ||
| 294 | + ) | ||
| 295 | + for name, tensor, want_dtype, want_shape in expected: | ||
| 296 | + if tensor.dtype != want_dtype: | ||
| 297 | + raise ValueError(f"engram_hash: {name} must be {want_dtype}, got {tensor.dtype}") | ||
| 298 | + if tuple(tensor.shape) != want_shape: | ||
| 299 | + raise ValueError(f"engram_hash: {name} must be {want_shape}, got {tuple(tensor.shape)}") | ||
| 300 | + _check_nd(name, tensor) | ||
| 301 | + if num_layers <= 0 or max_ngram < 2 or tables <= 0: | ||
| 302 | + raise ValueError("engram_hash: require num_layers > 0, max_ngram >= 2, tables > 0") | ||
| 303 | + | ||
| 304 | + return num_tokens, max_ngram, num_layers, tables | ||
| 305 | + | ||
| 306 | + | ||
| 307 | +def engram_hash( | ||
| 308 | + ngram_token_ids: torch.Tensor, | ||
| 309 | + multipliers: torch.Tensor, | ||
| 310 | + vocab_sizes: torch.Tensor, | ||
| 311 | + offsets: torch.Tensor, | ||
| 312 | + image_token_mask: torch.Tensor = None, | ||
| 313 | +) -> torch.Tensor: | ||
| 314 | + """Engram hash indices。 | ||
| 315 | + | ||
| 316 | + Args: | ||
| 317 | + ngram_token_ids: ``[num_tokens, max_ngram]`` int32。 | ||
| 318 | + multipliers: ``[num_layers, max_ngram]`` int64。 | ||
| 319 | + vocab_sizes: ``[num_layers, max_ngram - 1, tables]`` int32。 | ||
| 320 | + offsets: ``[num_layers, (max_ngram - 1) * tables]`` int32, | ||
| 321 | + 由 :func:`make_offsets` 生成。 | ||
| 322 | + image_token_mask: 可选,``[num_tokens]`` bool/uint8,True 表示 image token, | ||
| 323 | + 其整行输出为 -1。None 等价于全 False。 | ||
| 324 | + | ||
| 325 | + Returns: | ||
| 326 | + ``[num_layers, num_tokens, (max_ngram - 1) * tables]`` int32。 | ||
| 327 | + | ||
| 328 | + 所有张量必须在同一 NPU 设备上。dtype 不符会 fail closed(不做隐式转换, | ||
| 329 | + 因为 ids/vocab/offsets 的整型宽度决定计算结果)。 | ||
| 330 | + """ | ||
| 331 | + # 先查 rank,再按 rank 取维度;混设备的张量必须在 launch 前拦掉。 | ||
| 332 | + num_tokens, max_ngram, num_layers, tables = _input_dimensions(ngram_token_ids, multipliers, vocab_sizes, offsets) | ||
| 333 | + num_cols = (max_ngram - 1) * tables | ||
| 334 | + | ||
| 335 | + if image_token_mask is None: | ||
| 336 | + mask = None | ||
| 337 | + else: | ||
| 338 | + if image_token_mask.shape != (num_tokens,): | ||
| 339 | + raise ValueError( | ||
| 340 | + f"engram_hash: image_token_mask must be [{num_tokens}], got {tuple(image_token_mask.shape)}") | ||
| 341 | + if image_token_mask.device != ngram_token_ids.device: | ||
| 342 | + raise ValueError( | ||
| 343 | + f"engram_hash: image_token_mask must be on {ngram_token_ids.device}, " | ||
| 344 | + f"got {image_token_mask.device}") | ||
| 345 | + if image_token_mask.dtype not in (torch.bool, torch.uint8): | ||
| 346 | + raise ValueError("engram_hash: image_token_mask must be bool or uint8") | ||
| 347 | + _check_nd("image_token_mask", image_token_mask) | ||
| 348 | + mask = image_token_mask.to(torch.uint8).reshape(num_tokens, 1) | ||
| 349 | + | ||
| 350 | + output = torch.empty((num_layers, num_tokens, num_cols), dtype=torch.int32, | ||
| 351 | + device=ngram_token_ids.device) | ||
| 352 | + if num_tokens == 0: | ||
| 353 | + return output | ||
| 354 | + | ||
| 355 | + tiling = EngramHashTiling(num_tokens, num_layers, max_ngram, tables) | ||
| 356 | + has_mask = int(mask is not None) | ||
| 357 | + cores = torch.npu.get_device_properties(output.device.index).vector_core_num | ||
| 358 | + row_tiles = (num_tokens + TILE - 1) // TILE | ||
| 359 | + # Short inputs leave most vector cores idle with a row-only split. | ||
| 360 | + # Distribute their tables across cores even for the standard geometry. | ||
| 361 | + standard_tables = tables == 8 and max_ngram in (3, 4) | ||
| 362 | + use_row_tiles = standard_tables and row_tiles * 4 >= cores | ||
| 363 | + geometry = max_ngram if use_row_tiles else 0 | ||
| 364 | + if has_mask and num_tokens == 1 and num_layers == 2 and standard_tables: | ||
| 365 | + geometry = max_ngram + SINGLE_TOKEN_KEY_OFFSET | ||
| 366 | + jobs = 1 | ||
| 367 | + elif use_row_tiles: | ||
| 368 | + jobs = row_tiles | ||
| 369 | + elif max_ngram <= SMALL_GRAMS and tables <= SMALL_TABLES: | ||
| 370 | + jobs = num_layers * ((num_tokens * tables + TILE - 1) // TILE) | ||
| 371 | + else: | ||
| 372 | + jobs = num_tokens | ||
| 373 | + grid = min(jobs, cores) | ||
| 374 | + workspace = torch.empty(1, dtype=torch.uint8, device=output.device) | ||
| 375 | + engram_hash_kernel[None, grid, {"HasMask": has_mask, "Geometry": geometry}]( | ||
| 376 | + ngram_token_ids.contiguous(), multipliers.contiguous(), | ||
| 377 | + vocab_sizes.contiguous(), offsets.contiguous(), | ||
| 378 | + mask.contiguous() if has_mask else workspace, output, workspace, tiling, | ||
| 379 | + ) | ||
| 380 | + return output | ||
| @@ -0,0 +1,44 @@ | |||
| 1 | +#!/usr/bin/env python3 | ||
| 2 | +# coding: utf-8 | ||
| 3 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 4 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 5 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 6 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 7 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 8 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 9 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 10 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 11 | +"""Engram hash 的 torch 参考(CPU / 任意设备,纯 FP32 无关的整型运算,逐位一致)。 | ||
| 12 | + | ||
| 13 | +本文件为 engram_hash 的 torch 参考实现(整型运算,与设备实现逐位一致),只保留 | ||
| 14 | +hash 部分以便本目录自包含: | ||
| 15 | + | ||
| 16 | + prod = ids[None].to(int64) * multipliers[:, None] | ||
| 17 | + hash = XOR_i prod[:, :, i] | ||
| 18 | + out[layer, :, (i-1)*Tb + t] = hash % vocab[layer, i-1, t] + offsets[layer, col] | ||
| 19 | + out[mask, :] = -1 | ||
| 20 | +""" | ||
| 21 | +import torch | ||
| 22 | + | ||
| 23 | + | ||
| 24 | +def engram_hash_ref(ngram_token_ids, multipliers, vocab_sizes, offsets, image_token_mask=None): | ||
| 25 | + """参考实现:输入输出布局与 ``engram_hash`` 的 wrapper 一致。""" | ||
| 26 | + num_layers = multipliers.shape[0] | ||
| 27 | + max_ngram_size = multipliers.shape[1] | ||
| 28 | + | ||
| 29 | + prod = ngram_token_ids.to(torch.int64).unsqueeze(0) * multipliers.unsqueeze(1) | ||
| 30 | + | ||
| 31 | + pieces = [[] for _ in range(num_layers)] | ||
| 32 | + hashes = prod[:, :, 0].clone() | ||
| 33 | + for i in range(1, max_ngram_size): | ||
| 34 | + hashes.bitwise_xor_(prod[:, :, i]) | ||
| 35 | + for layer in range(num_layers): | ||
| 36 | + pieces[layer].append( | ||
| 37 | + (hashes[layer].unsqueeze(-1) | ||
| 38 | + % vocab_sizes[layer, i - 1].to(torch.int64).unsqueeze(0)).to(torch.int32)) | ||
| 39 | + | ||
| 40 | + stacked = torch.stack([torch.cat(p, dim=-1) for p in pieces], dim=0) | ||
| 41 | + output = stacked + offsets.unsqueeze(1) | ||
| 42 | + if image_token_mask is not None: | ||
| 43 | + output = output.masked_fill(image_token_mask.view(1, -1, 1).bool(), -1) | ||
| 44 | + return output | ||
| @@ -0,0 +1,195 @@ | |||
| 1 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 9 | +"""engram_hash(PyPTO-Pro)测试套件。 | ||
| 10 | + | ||
| 11 | +纯 CPU 的 ``make_offsets`` 校验,以及 NPU 校验(无 NPU 时自动跳过):输出为整型, | ||
| 12 | +与 ``tests/assets/engram_hash_golden.py`` 逐位比较(``torch.equal``),不做容差。 | ||
| 13 | +用例规格:L=2、Tb=8、G∈{3,4}、mask 开关,T 覆盖 1 / 尾块 / 多块;并额外覆盖负 | ||
| 14 | +multiplier(floor-mod 分支)、mask 三态与 T=0。 | ||
| 15 | + | ||
| 16 | +运行: | ||
| 17 | + python3 -m pytest ops/pro/deepseek_v4_1/engram_hash/tests/test_engram_hash_routes.py -q | ||
| 18 | + | ||
| 19 | +kernel 位于 ``op_kernel/engram_hash.py``,golden 位于 ``tests/assets/``。 | ||
| 20 | +""" | ||
| 21 | + | ||
| 22 | +import importlib.util | ||
| 23 | +import os | ||
| 24 | +import sys | ||
| 25 | + | ||
| 26 | +import pytest | ||
| 27 | +import torch | ||
| 28 | + | ||
| 29 | +_THIS_DIR = os.path.dirname(os.path.abspath(__file__)) | ||
| 30 | +_OP_DIR = os.path.dirname(_THIS_DIR) | ||
| 31 | + | ||
| 32 | + | ||
| 33 | +def _load_module(name, path): | ||
| 34 | + spec = importlib.util.spec_from_file_location(name, path) | ||
| 35 | + module = importlib.util.module_from_spec(spec) | ||
| 36 | + sys.modules[spec.name] = module | ||
| 37 | + spec.loader.exec_module(module) | ||
| 38 | + return module | ||
| 39 | + | ||
| 40 | + | ||
| 41 | +def _jit_module(): | ||
| 42 | + name = "gym_pro_engram_hash" | ||
| 43 | + if name in sys.modules: | ||
| 44 | + return sys.modules[name] | ||
| 45 | + return _load_module(name, os.path.join(_OP_DIR, "op_kernel", "engram_hash.py")) | ||
| 46 | + | ||
| 47 | + | ||
| 48 | +if os.environ.get("GYM_TEST_MODE", "jit") == "jit": | ||
| 49 | + _jit_module() | ||
| 50 | +golden = _load_module("gym_pro_engram_hash_golden", os.path.join(_THIS_DIR, "assets", "engram_hash_golden.py")) | ||
| 51 | +pytestmark = pytest.mark.soc("950") | ||
| 52 | + | ||
| 53 | + | ||
| 54 | +def entry(*args): | ||
| 55 | + from op_caller import get_op_caller | ||
| 56 | + return get_op_caller("engram_hash", jit_module="gym_pro_engram_hash", aclnn_module="pypto_gym")(*args) | ||
| 57 | + | ||
| 58 | + | ||
| 59 | +def _npu_available(): | ||
| 60 | + try: | ||
| 61 | + import torch_npu # noqa: F401 | ||
| 62 | + return torch.npu.is_available() | ||
| 63 | + except Exception: # noqa: BLE001 | ||
| 64 | + return False | ||
| 65 | + | ||
| 66 | + | ||
| 67 | +requires_npu = pytest.mark.skipif( | ||
| 68 | + not _npu_available(), reason="torch_npu / NPU not available" | ||
| 69 | +) | ||
| 70 | + | ||
| 71 | + | ||
| 72 | +def _set_device(): | ||
| 73 | + device_id = int(os.environ.get("TILE_FWK_DEVICE_ID", 0)) | ||
| 74 | + torch.npu.set_device(device_id) | ||
| 75 | + return f"npu:{device_id}" | ||
| 76 | + | ||
| 77 | + | ||
| 78 | +def _make_inputs(num_tokens, max_ngram, num_layers, tables, seed=0, with_mask=False, | ||
| 79 | + signed_multipliers=False): | ||
| 80 | + g = torch.Generator().manual_seed(seed) | ||
| 81 | + ids = torch.randint(0, 100000, (num_tokens, max_ngram), generator=g, dtype=torch.int32) | ||
| 82 | + if signed_multipliers: | ||
| 83 | + mult = torch.randint(-100000, 100000, (num_layers, max_ngram), generator=g, | ||
| 84 | + dtype=torch.int64) | ||
| 85 | + else: | ||
| 86 | + mult = torch.randint(0, 100000, (num_layers, max_ngram), generator=g, dtype=torch.int64) | ||
| 87 | + vocab = torch.randint(100000, 1000000, (num_layers, max_ngram - 1, tables), | ||
| 88 | + generator=g, dtype=torch.int32) | ||
| 89 | + sizes = vocab.flatten(1) | ||
| 90 | + offsets = torch.cat((torch.zeros_like(sizes[:, :1]), sizes[:, :-1].cumsum(1, dtype=torch.int32)), dim=1) | ||
| 91 | + mask = ((torch.rand(num_tokens, generator=g) < 0.5).to(torch.uint8) | ||
| 92 | + if with_mask else None) | ||
| 93 | + return ids, mult, vocab, offsets, mask | ||
| 94 | + | ||
| 95 | + | ||
| 96 | +def _run_case(dev, num_tokens, max_ngram, num_layers=2, tables=8, seed=0, | ||
| 97 | + with_mask=False, signed_multipliers=False): | ||
| 98 | + ids, mult, vocab, offsets, mask = _make_inputs( | ||
| 99 | + num_tokens, max_ngram, num_layers, tables, seed, with_mask, signed_multipliers) | ||
| 100 | + args = tuple(t.to(dev) for t in (ids, mult, vocab, offsets)) | ||
| 101 | + mask_dev = mask.to(dev) if mask is not None else None | ||
| 102 | + got = entry(*args, mask_dev) | ||
| 103 | + | ||
| 104 | + want = golden.engram_hash_ref(ids, mult, vocab, offsets, mask) | ||
| 105 | + assert torch.equal(got.cpu(), want), (got.flatten()[:8], want.flatten()[:8]) | ||
| 106 | + | ||
| 107 | + | ||
| 108 | +def test_make_offsets(): | ||
| 109 | + vocab = torch.tensor([[[3, 5], [7, 11]], [[13, 17], [19, 23]]], dtype=torch.int32) | ||
| 110 | + want = torch.tensor([[0, 3, 8, 15], [0, 13, 30, 49]], dtype=torch.int32) | ||
| 111 | + pytest.importorskip("pypto_pro", reason="make_offsets belongs to the source JIT module") | ||
| 112 | + got = _jit_module().make_offsets(vocab) | ||
| 113 | + assert got.dtype == torch.int32 and torch.equal(got, want) | ||
| 114 | + | ||
| 115 | + | ||
| 116 | +@requires_npu | ||
| 117 | +def test_contract_errors(): | ||
| 118 | + dev = _set_device() | ||
| 119 | + ids, mult, vocab, offsets, _ = _make_inputs(8, 3, 2, 8) | ||
| 120 | + ids, mult, vocab, offsets = (x.to(dev) for x in (ids, mult, vocab, offsets)) | ||
| 121 | + with pytest.raises((ValueError, RuntimeError), match="multipliers"): | ||
| 122 | + entry(ids, mult.to(torch.int32), vocab, offsets) | ||
| 123 | + with pytest.raises((ValueError, RuntimeError), match="offsets"): | ||
| 124 | + entry(ids, mult, vocab, offsets[:1]) | ||
| 125 | + with pytest.raises((ValueError, RuntimeError), match="vocab_sizes"): | ||
| 126 | + entry(ids, mult, vocab.reshape(-1), offsets) | ||
| 127 | + with pytest.raises((ValueError, RuntimeError), match="device"): | ||
| 128 | + entry(ids.cpu(), mult.to(dev), vocab.to(dev), offsets.to(dev)) | ||
| 129 | + | ||
| 130 | + | ||
| 131 | +@requires_npu | ||
| 132 | +def test_rejects_blocked_ids_and_invalid_mask(): | ||
| 133 | + import torch_npu | ||
| 134 | + | ||
| 135 | + device = _set_device() | ||
| 136 | + args = tuple(t.to(device) for t in _make_inputs(32, 32, 2, 8)[:4]) | ||
| 137 | + blocked = torch_npu.npu_format_cast(args[0], 29) | ||
| 138 | + with pytest.raises((ValueError, RuntimeError), match="ngram_token_ids.*ND"): | ||
| 139 | + entry(blocked, *args[1:]) | ||
| 140 | + mask = torch.full((32,), 256, dtype=torch.int32, device=device) | ||
| 141 | + with pytest.raises((ValueError, RuntimeError), match="image_token_mask.*bool or uint8"): | ||
| 142 | + entry(*args, mask) | ||
| 143 | + | ||
| 144 | + | ||
| 145 | +@requires_npu | ||
| 146 | +@pytest.mark.parametrize("num_tokens", [1, 127, 128, 129, 300, 1024]) | ||
| 147 | +@pytest.mark.parametrize("max_ngram", [3, 4]) | ||
| 148 | +@pytest.mark.parametrize("with_mask", [False, True]) | ||
| 149 | +def test_correctness(num_tokens, max_ngram, with_mask): | ||
| 150 | + dev = _set_device() | ||
| 151 | + _run_case(dev, num_tokens, max_ngram, with_mask=with_mask, | ||
| 152 | + seed=num_tokens + max_ngram) | ||
| 153 | + | ||
| 154 | + | ||
| 155 | +@requires_npu | ||
| 156 | +@pytest.mark.parametrize("num_tokens,max_ngram,with_mask", [(300, 4, True), (128, 3, False)]) | ||
| 157 | +def test_correctness_signed_multipliers(num_tokens, max_ngram, with_mask): | ||
| 158 | + """负 multiplier 让 xor hash 落到负数区间,压 floor-mod 修正。""" | ||
| 159 | + dev = _set_device() | ||
| 160 | + _run_case(dev, num_tokens, max_ngram, with_mask=with_mask, | ||
| 161 | + signed_multipliers=True, seed=7) | ||
| 162 | + | ||
| 163 | + | ||
| 164 | +@requires_npu | ||
| 165 | +@pytest.mark.parametrize("with_mask", [False, True]) | ||
| 166 | +@pytest.mark.parametrize("tokens,ngram,tables", [ | ||
| 167 | + (129, 5, 3), (7, 2, 129), (137, 5, 1), (9, 16, 32), (5, 17, 33), | ||
| 168 | + (9, 17, 1), (128, 64, 8), (129, 17, 1), (2, 65, 8), (2, 17, 9), | ||
| 169 | +]) | ||
| 170 | +def test_dynamic_geometry(with_mask, tokens, ngram, tables): | ||
| 171 | + _run_case(_set_device(), tokens, ngram, num_layers=3, tables=tables, seed=7, | ||
| 172 | + signed_multipliers=True, with_mask=with_mask) | ||
| 173 | + | ||
| 174 | + | ||
| 175 | +@requires_npu | ||
| 176 | +@pytest.mark.parametrize("tokens,ngram", [(256, 4), (1, 3), (1, 4)]) | ||
| 177 | +def test_mask_dtype_states(tokens, ngram): | ||
| 178 | + """mask 的 bool / uint8 / None 三态一致。""" | ||
| 179 | + dev = _set_device() | ||
| 180 | + ids, mult, vocab, offsets, mask = _make_inputs(tokens, ngram, 2, 8, seed=3, with_mask=True) | ||
| 181 | + args = tuple(t.to(dev) for t in (ids, mult, vocab, offsets)) | ||
| 182 | + for mask_value in (mask, 1 - mask): | ||
| 183 | + want = golden.engram_hash_ref(ids, mult, vocab, offsets, mask_value) | ||
| 184 | + for dtype in (torch.bool, torch.uint8): | ||
| 185 | + assert torch.equal(entry(*args, mask_value.to(dtype).to(dev)).cpu(), want), dtype | ||
| 186 | + want_none = golden.engram_hash_ref(ids, mult, vocab, offsets, None) | ||
| 187 | + assert torch.equal(entry(*args).cpu(), want_none) | ||
| 188 | + | ||
| 189 | + | ||
| 190 | +@requires_npu | ||
| 191 | +def test_zero_tokens(): | ||
| 192 | + dev = _set_device() | ||
| 193 | + ids, mult, vocab, offsets, _ = _make_inputs(0, 3, 2, 8) | ||
| 194 | + out = entry(*(t.to(dev) for t in (ids, mult, vocab, offsets))) | ||
| 195 | + assert tuple(out.shape) == (2, 0, 16) | ||
| @@ -0,0 +1,3 @@ | |||
| 1 | +if(ENABLE_TORCH_BINDINGS AND NOT PREPARE_BUILD) | ||
| 2 | + gym_add_torch_binding(engram_hash) | ||
| 3 | +endif() | ||