Merged
refactor(ops): Remove jit-only deepseek_v4_1 tree superseded by pro delivery #1132
refactor(ops): Remove jit-only deepseek_v4_1 tree superseded by pro delivery #1132
Merged
sunhaoxuan2024Add on 3 days ago
Total: 100 files changed+6-35609
@@ -275,7 +275,7 @@ pypto-gym/
275| `spatial_ssrl_3b/` | rms_norm, rope | RMSNorm + RoPE(Vision 2D / 多模态 3D) |275| `spatial_ssrl_3b/` | rms_norm, rope | RMSNorm + RoPE(Vision 2D / 多模态 3D) |
276| `experimental/matmul/` | gmm_mxfp8 | MXFP8 GMM 算子 |276| `experimental/matmul/` | gmm_mxfp8 | MXFP8 GMM 算子 |
277| `experimental/ops_transformer/` | flash_attention_mha, flash_attention_mha_grad, flash_attention_score, flash_attention_score_grad, fused_swiglu, fused_swiglu_grad, lightning_indexer, mla_prolog, mla_prolog_mxfp_quant_v3, mla_prolog_quant_hifp8_v3, page_attention_quant, sparse_attention_antiquant_fp8, sparse_attention_antiquant_kv_split, sparse_attention_grad_tnd, sparse_attention_tnd, attention_worker_combine, engram, flash_attention_fp8, kimi_attention_residuals | Flash Attention(MHA/Score/FP8,含量化/反向)、MLA Prolog(含量化)、SwiGLU、Page Attention、稀疏注意力、Engram、Kimi Attention Residuals 等算子 |277| `experimental/ops_transformer/` | flash_attention_mha, flash_attention_mha_grad, flash_attention_score, flash_attention_score_grad, fused_swiglu, fused_swiglu_grad, lightning_indexer, mla_prolog, mla_prolog_mxfp_quant_v3, mla_prolog_quant_hifp8_v3, page_attention_quant, sparse_attention_antiquant_fp8, sparse_attention_antiquant_kv_split, sparse_attention_grad_tnd, sparse_attention_tnd, attention_worker_combine, engram, flash_attention_fp8, kimi_attention_residuals | Flash Attention(MHA/Score/FP8,含量化/反向)、MLA Prolog(含量化)、SwiGLU、Page Attention、稀疏注意力、Engram、Kimi Attention Residuals 等算子 |
278-| `pypto_pro/deepseek_v4_1/` | engram_gate, indexer_prologue_k, indexer_prologue_qw | DeepSeek V4.1 IFA Pro 算子(PyPTO Pro DSL) |278+| `pro/deepseek_v4_1/` | engram_gate, engram_hash, indexer_prologue_k, indexer_prologue_qw, mixed_quant_sparse_flash_mla 等 17 个 | DeepSeek V4.1 IFA Pro 算子(JIT 直调 + ACLNN 双路由交付形态) |
279| `pypto_pro/llada2/` | liger_cross_entropy_loss | Liger Cross Entropy Loss(Pro 实现) |279| `pypto_pro/llada2/` | liger_cross_entropy_loss | Liger Cross Entropy Loss(Pro 实现) |
280| `pypto_pro/experimental/ops_transformer/` | engram, kda 系列 | 实验性 Pro 算子(Engram、KDA 等) |280| `pypto_pro/experimental/ops_transformer/` | engram, kda 系列 | 实验性 Pro 算子(Engram、KDA 等) |
281 281 
Rops/pypto_pro/deepseek_v4_1/attn_prologue/DESIGN.md→ops/pro/deepseek_v4_1/attn_prologue/DESIGN.md+0-0
File renamed without changes.
Rops/pypto_pro/deepseek_v4_1/attn_prologue/RESULTS.md→ops/pro/deepseek_v4_1/attn_prologue/RESULTS.md+0-0
File renamed without changes.
Rops/pypto_pro/deepseek_v4_1/engram_gate/DESIGN.md→ops/pro/deepseek_v4_1/engram_gate/DESIGN.md+0-0
File renamed without changes.
Rops/pypto_pro/deepseek_v4_1/engram_gate/RESULTS.md→ops/pro/deepseek_v4_1/engram_gate/RESULTS.md+0-0
File renamed without changes.
Rops/pypto_pro/deepseek_v4_1/engram_gate_bwd/DESIGN.md→ops/pro/deepseek_v4_1/engram_gate_bwd/DESIGN.md+0-0
File renamed without changes.
Rops/pypto_pro/deepseek_v4_1/engram_gate_bwd/RESULTS.md→ops/pro/deepseek_v4_1/engram_gate_bwd/RESULTS.md+0-0
File renamed without changes.
Rops/pypto_pro/deepseek_v4_1/engram_hash/DESIGN.md→ops/pro/deepseek_v4_1/engram_hash/DESIGN.md+0-0
File renamed without changes.
Rops/pypto_pro/deepseek_v4_1/engram_hash/RESULT.md→ops/pro/deepseek_v4_1/engram_hash/RESULT.md+0-0
File renamed without changes.
Rops/pypto_pro/deepseek_v4_1/kv_compress_epilog_v2/DESIGN.md→ops/pro/deepseek_v4_1/kv_compress_epilog_v2/DESIGN.md+0-0
File renamed without changes.
Rops/pypto_pro/deepseek_v4_1/kv_compress_epilog_v2/RESULTS.md→ops/pro/deepseek_v4_1/kv_compress_epilog_v2/RESULTS.md+0-0
File renamed without changes.
Rops/pypto_pro/deepseek_v4_1/mhc_post_fwd/DESIGN.md→ops/pro/deepseek_v4_1/mhc_post_fwd/DESIGN.md+0-0
File renamed without changes.
Rops/pypto_pro/deepseek_v4_1/mhc_post_fwd/RESULTS.md→ops/pro/deepseek_v4_1/mhc_post_fwd/RESULTS.md+0-0
File renamed without changes.
Rops/pypto_pro/deepseek_v4_1/mhc_pre_fuse/DESIGN.md→ops/pro/deepseek_v4_1/mhc_pre_fuse/DESIGN.md+0-0
File renamed without changes.
Rops/pypto_pro/deepseek_v4_1/mhc_pre_fuse/RESULTS.md→ops/pro/deepseek_v4_1/mhc_pre_fuse/RESULTS.md+0-0
File renamed without changes.
Rops/pypto_pro/deepseek_v4_1/mixed_quant_sparse_flash_mla/DESIGN.md→ops/pro/deepseek_v4_1/mixed_quant_sparse_flash_mla/DESIGN.md+0-0
File renamed without changes.
@@ -5,8 +5,8 @@ PyPTO-Pro 稀疏 Flash MLA 计算,kernel 以 raw Ptr + OpTiling 形态编写
5直调(jit)、经 CANN 框架的 aclnn 接口调用(run 包 built-in),以及 whl 安装态的5直调(jit)、经 CANN 框架的 aclnn 接口调用(run 包 built-in),以及 whl 安装态的
6`torch.ops.pypto_gym.mixed_quant_sparse_flash_mla` Torch 绑定。6`torch.ops.pypto_gym.mixed_quant_sparse_flash_mla` Torch 绑定。
7 7 
8-算法设计、流水结构与性能/优化记录见原 jit 形态算子目录8+算法设计、流水结构与性能/优化记录见本目录
9-`ops/pypto_pro/deepseek_v4_1/mixed_quant_sparse_flash_mla/`(`DESIGN.md` / `RESULTS.md`);9+`DESIGN.md` / `RESULTS.md`(自原 jit 形态算子目录迁入);
10本目录只承载交付形态所需的 kernel 签名改造、host 侧(def / infershape / tiling)与测试桥。10本目录只承载交付形态所需的 kernel 签名改造、host 侧(def / infershape / tiling)与测试桥。
11 11 
12## 产品支持情况12## 产品支持情况
Rops/pypto_pro/deepseek_v4_1/mixed_quant_sparse_flash_mla/RESULTS.md→ops/pro/deepseek_v4_1/mixed_quant_sparse_flash_mla/RESULTS.md+0-0
File renamed without changes.
Rops/pypto_pro/deepseek_v4_1/quant_lightning_indexer/DESIGN.md→ops/pro/deepseek_v4_1/quant_lightning_indexer/DESIGN.md+0-0
File renamed without changes.
Rops/pypto_pro/deepseek_v4_1/quant_lightning_indexer/RESULTS.md→ops/pro/deepseek_v4_1/quant_lightning_indexer/RESULTS.md+0-0
File renamed without changes.
@@ -1,120 +0,0 @@
1-# AttnEpilogue 设计说明
2- 
3-单文件 kernel(`op_kernel/attn_epilogue.py`)每次调用只启动 **一个** `@pl.jit` kernel,核心计算全部在 kernel 内;wrapper 只做参数校验、只读元数据读取、纯 Python 整数推导与 scratch 分配。
4- 
5-## 计算阶段划分
6- 
7-| 阶段 | 执行域 | 内容 | 数据交接 |
8-|---|---|---|---|
9-| **M1** | Vector(56/64) | inverse RoPE(按 512 维 head 切片)+ 回归组为 8 group + MXFP8 量化 | 写出 GM 载荷 `aq`(FP8E4M3)与 `asc`(E8M0) |
10-| **M2** | Cube(28/32) | GEMM1:`y[t, g*1024+n] = Σ_k aq[t,g,k]·woa[g,n,k]`,K=4096,FP8×FP8→FP32 | 累加器经 C→V 通道交给 Vector |
11-| **M3** | Vector(56/64) | 对 `y` 再做 MXFP8 量化 | 写出 GM 载荷 `yq`(FP8E4M3)与 `ys`(E8M0) |
12-| **M4** | Cube(28/32) | GEMM2:`out[t,m] = Σ_k yq[t,k]·wob[m,k]`,K=8192,bf16 写回 | 直接写 `out` |
13- 
14-四个阶段同属一个 native task。M1 的 `aq/asc` 与 M3 的 `yq/ys` 经 GM 传递,M2 的累加器经 C→V 共享环交给 M3;第二级首块权重在 L1 中跨阶段保留。分段发布、共享环事件及阶段交接分别保护这些数据路径,不能仅凭一个全局 barrier 推断全部片上状态的生命周期。
15- 
16-## 核间切分策略
17- 
18-- **核配额**:按实际硬件选择 28 Cube + 56 Vector 或 32 Cube + 64 Vector,每个 Cube 固定配 2 个 Vector subblock。
19-- **第一级工作空间**:按 **M → group → N** 排列,任务数 `8 × nm × ⌈1024/BN1⌉`(`nm = ⌈padded/BM⌉`)。
20- 按 M 优先可让同一 group 的 N 分块落在相邻核上,长输入时每个 Cube 拿到互不重叠的输出 tile。
21-- **第二级工作空间**:任务数 `nm × ⌈5120/BN⌉`,每个 Cube 负责不重叠的输出 tile。
22-- **Vector 内部**:同一 Cube 的两个 Vector 按**补齐行对半**分工(各自处理该 tile 的一半行)。
23-- **量化分段发布**:32 核布局把激活量化切成两个 **2048 列**分段,每段全部 Vector 写完后再通知 Cube,
24- 使 M1 与 M2 重叠。
25-- **不切 K**:两级 GEMM 都不做 K 维跨核拆分(无 split-K/stream-K 合并),K 在核内流式消费——
26- 这避免了部分和合并的额外搬运与 cast-order 风险。
27-- **布局自适应**:`tiling_key_for(t, cube_cores)` 以 `cube_cores == 32` 区分两套布局(32 核用
28- `BN1=256/BN=160/K0=128`,少数核布局用 `BN1=160/BN=192`),tiling key schema 共 6 个合法 key,
29- 公开调用在 32 核机器上只产生 3 个编译版本,且签名不含 `T` 的静态取值。
30- 
31-## 核内切分策略
32- 
33-### 基本块选择(32 核布局)
34- 
35-| BM | BK | VSlots | K0 | BN1 | BN | 适用 T |
36-|---:|---:|---:|---:|---:|---:|---|
37-| 64 | 512 | 2 | 256 | 256 | 160 | `T ≤ 64` |
38-| 128 | 256 | 2 | 128 | 256 | 160 | `64 < T ≤ 128` |
39-| 256 | 256 | 1 | 128 | 256 | 160 | `T > 128` |
40- 
41-基本块同时受 L0C、L0B、L1 和 UB 约束。容量与布局由所选工具链的原生声明检查,采用核心 skill 的[容量契约](../../../../cannbot-skills/ops/pypto-pro-kernel/references/api/memory-limits.md),不以单个 SDK 配置文件替代当前设备校验。
42- 
43-- **L0C**:每槽预留 `4 * BM * max(BN1, BN)` 字节,深度 `min(2, 65536 // (BM * max(BN1, BN)))`;六档配置中,`BM=256` 使用一槽,其他档使用两槽。
44-- **L0B**:每槽按 `K0 * max(BN1, BN)` 字节分隔,槽数为 `256 // K0`,并为对应 scale 平面保留配对地址。
45-- **L1**:A/B 双缓冲按 `2 * (BM + max(BN1, BN)) * BK` 字节预留;随后 A-scale 区预留 `BM * 256` 字节,B-scale 区容纳两阶段中较大的声明。
46-- **UB**:C→V 共享环占 `2 * BM * BN1 * VSlots` 字节,另计量化 scratch 与偏移。inverse RoPE 以 `R_ROWS=8` 行处理,32 核布局的 `y` 量化以 `Q_ROWS=64` 行处理,使工作区峰值受行块控制。
47- 
48-### 核内 Buffer 划分
49- 
50-- **L1**:A/B 条带各双缓冲,两个投影共享每个物理槽的 mutex ID。B 槽按 `max(BN1, BN) * BK` 预留间距;A/B scale 起点也在两阶段保持一致,A-scale 区按第二级 `K=8192` 的 256 个 scale 列预留。各阶段保留自己的有效形状和布局,B 条带经 `ZN` 转置视图供 MX matmul 消费。
51-- **L0**:L0A/L0B 环各 `256 // K0` 槽。L0B 的槽距为 `max(BN1, BN) * K0`,对应 ScaleLeft/ScaleRight 地址等于数据槽地址 `>> 4`。两个阶段的对应槽保留相同 mutex ID。
52-- **L0C**:两阶段使用相同槽距 `4 * BM * max(BN1, BN)`,深度为 `min(2, 65536 // (BM * max(BN1, BN)))`。Acc 的 `phase=`/`unit_flag` 依赖仍需在阶段切换时排空;统一 mutex ID 不替代该完成协议。
53-- **UB**:C→V 共享环(`VSlots` 槽,每槽 `[BM/2, BN1]` fp32)供 `y` 交接;量化 scratch 依次为
54- bf16 中间、量化载荷、E8M0 序列、倒数表、偶/奇列展开缓冲与 scale 打包缓冲,全部落在同一个
55- 静态 UB 布局内。
56-- **GM 工作区**:4 个缓冲区(`aq/asc/yq/ys`)合计 `42240 × ceil(T/16)×16` 字节,按
57- (device, stream, padded) 键缓存复用,图捕获期间只分配一次。
58- 
59-## 接口选择
60- 
61-- **对外 API**:`attn_epilogue(o, woa, wob, descale_woa, descale_wob, rope_sin, rope_cos) -> bf16 [T,5120]`,
62- 与原生参考语义一致(ND 布局 + 独立 E8M0 scale,不做权重量化)。
63-- **kernel 入口**:单一 `@pl.jit(arch="a5", auto_mutex=True, tiling_key=EpilogueKey)`,`T` 与地址在
64- 运行期传入;`EpilogueKey` 用 `TilingKeyField` 声明 `BM/BK/VSlots/K0/BN1/BN`,`is_valid` 枚举两套
65- 硬件布局的合法组合,使编译产物数量可控且可枚举校验。
66-- **wrapper 边界**:只做 shape/dtype/device 校验、`scratch_buffers` 分配与**一次** `launch_kernel`;启动不在 host
67- 循环内,也不做任何张量运算。
68-- **精度接口**:输出与中间载荷都可与参考逐字节比较(`tests/assets/precision_compare.py`),
69- 支撑 `rtol=0, atol=0` 的验收方式。
70- 
71-## 流水设计
72- 
73-- **首块权重预取**:进入任务循环前先把 GEMM1 的首块 B tile(含 scale)搬入 L1,与 M1 的尾部 Vector
74- 工作重叠;任务循环内首个工作项跳过该块的重复加载。
75-- **K 条带双缓冲**:A/B 条带按 K 交替使用两个 L1 槽,由 `auto_mutex` 保证"载入 vs 消费"的依赖,
76- 不额外叠加手写同步。
77-- **L0 深环**:`K0=128` 时 L0A/L0B 各有 2 槽,使 L0 载入与 MMA 重叠;`K0=256` 时单槽但减少 inner 步数。
78-- **C→V 通道**:GEMM1 的 FP32 累加器经 C→V 共享环交给 Vector,环深 `VSlots` 配合自动事件
79- (0/1)实现生产者/消费者推进,`VSlots=2` 允许 drain 与下一次 MMA 重叠。
80-- **Vector↔Cube 重叠**:量化按 2048 列分段发布,全 Vector 写入完成用事件 5/6 通知,
81- Vector→Cube 用事件 3/4;由此 M1 的量化与 M2 的 GEMM1 在时间上重叠,而不是串行。
82-- **跨投影预取的一致性**:GEMM2 的首块权重在 GEMM1 最后一次读取后写入 L1 的 B 槽 0,使用 `reinterpret(bg, shape=[BN, BK])` 保持 GEMM2 的物理 NZ 行距,并继承槽 0 的 ID。容量按 `max(BN1, BN)` 预留,两个有效 N 宽度无需相等。
83-- **阶段交接**:Cube 在两级投影之间执行 `bar_all`,排空预取、操作数消费和 MMA/FIX;Vector 端须完成 `yq/ys` 的发布。28 核布局通过 MIX collective 交接,32 核布局通过 Vector 的 MTE3 全局事件 8 和向 Cube MTE2 的事件 7 交接。测试把 Cube 存储域的 `MutexMismatch` 视为错误,同时保留逐字节中间量、输出守卫及交替输入的 graph replay 验证。
84- 
85-32 核布局的 RoPE 临时区与 C→V 共享区存在串行复用,原生声明检查可能报告 `Vec` 重叠;该提示保持可见。最后一个 slab 的 MTE3 全局事件 6 完成后,事件 4 才允许 Cube 加载后半 K;GEMM1 消费全部 K 后才能写共享 UB。这个跨核完成链保护复用,不能用同一个 per-core mutex ID 替代。声明告警、编译成功和实际数值回归分别判断。
86- 
87-## 命名与符号约定
88- 
89-为便于阅读,kernel 内部函数一律用语义化命名(无 `_a`/`_b` 这类字母后缀):
90- 
91-| 函数 | 职责 |
92-|---|---|
93-| `_apply_inverse_rope` / `_apply_inverse_rope_slab` | inverse RoPE(单 head 切片 / 按行 slab) |
94-| `_compute_mx_block_scales` | 每 32 个元素的 E8M0 块 scale 与倒数 |
95-| `_quantize_to_fp8_payload` | 用倒数把 bf16 量化为 FP8E4M3 载荷 |
96-| `_cast_accumulator_to_bf16` | GEMM 累加器(FP32)按行转 bf16 |
97-| `_pack_mx_scale_bytes` | 把 per-32 scale 字节打包成 GEMM2 读取的 E8M0 形态 |
98-| `_zero_fill_quantized_tile`(+ `_tail` / `_batch` / `_batch_tail`) | 空 tile / 尾行的载荷与 scale 置零 |
99-| `_gemm1_tile` | M2:一个 (group, m, n) tile 的 GEMM1,累加器交给 C→V 环,并预取 GEMM2 首块权重 |
100-| `_quantize_gemm1_output` | M3:把 GEMM1 输出 tile 量化为 `yq`/`ys` |
101-| `_gemm2_tile` | M4:GEMM2 的一个输出 tile |
102-| `_prefetch_gemm1_weights` | 任务循环前把 GEMM1 首块 B(含 scale)搬入 L1 |
103-| `_mx_matmul_strip` / `_mx_matmul_step` | MX 矩阵乘:一个 L1 K 条带 / 其中一个 L0 子步 |
104-| `_rope_quantize_slabbed` / `_rope_quantize_whole` | M1 整体(slab 分块 / 整段两种变体) |
105-| `scratch_buffers` / `BUFFER_CACHE` | GM scratch 的取用函数 / 其按 (device, stream, padded) 的缓存 |
106-| `tiling_key_for` / `launch_kernel` | 按 `(T, cube_cores)` 选档 / 启动一次 kernel |
107- 
108-片上 Buffer 与 GM 载荷的符号:
109- 
110-| 符号 | 含义 |
111-|---|---|
112-| `aq` / `asc` | M1 输出的激活 FP8E4M3 载荷 / E8M0 scale(GM 载荷) |
113-| `yq` / `ys` | M3 输出的 `y` 载荷 / E8M0 scale(GM 载荷) |
114-| `ag` / `bg` | L1 上 A / B 操作数 tile 组(双缓冲,`Mat` 空间) |
115-| `asg` / `bsg` | A / B 的 block scale 暂存 tile(`ZZ` / `NN` 布局) |
116-| `al` / `als` | L0A 上的 A 条带 / 其 scale 条带 |
117-| `bl` / `bls` | L0B 上的 B 条带 / 其 scale 条带 |
118-| `accg` | L0C FP32 累加器组(槽数 `acc_slots`) |
119-| `shared` | C→V(L0C→UB)共享环,深度 `VSlots` |
120-| `bfg`/`qg`/`esg`/`rg`/`eg`/`og`/`spg` | 量化阶段 UB scratch:bf16 中间、FP8 载荷、E8M0 序列、倒数表、偶/奇列展开、scale 打包 |
@@ -1,87 +0,0 @@
1-# AttnEpilogue(PyPTO-Pro)
2- 
3-注意力输出端的融合算子:inverse RoPE + 回归组 + OCP MXFP8 量化 + 两级 block-scaled GEMM。
4-单次调用内完成 `o[T,64,512]`(bf16)到 `out[T,5120]`(bf16)的全部计算。
5- 
6-## 产品支持情况
7- 
8-| 产品 | 是否支持 |
9-|---|---|
10-| Ascend 950PR(`Ascend950PR_9589`,32 Cube / 64 Vector,1650 MHz) | **支持**(本机实测:精度 45/45,性能见 `RESULTS.md`) |
11-| Ascend 950PR(28 Cube 布局) | 支持(`tiling_key_for` 按 `cube_core_num` 选择布局;未在本机实测) |
12-| 其它产品 | 不支持(kernel 以 `arch="a5"` 编译,且分档依赖 A5 的 L0/L1/UB 容量) |
13- 
14-## 功能说明
15- 
16-记 `o` 为 attention 输出,按 64 个 head、每 head 512 维排列。算子执行:
17- 
18-1. **inverse RoPE**:对每 head 的 512 维向量按缓存的 `rope_sin`/`rope_cos` 做逆旋转,并回归组为
19- 8 个 group(每 group 1024 列,对应 `woa` 的分组维度);
20-2. **MXFP8 量化**:按 32 个元素一块计算 E8M0 块缩放,得到 FP8E4M3 载荷与 scale(OCP MX 格式);
21-3. **GEMM1**:分组矩阵乘 `y[t, g*1024+n] = Σ_k aq[t, g, k] · woa[g, n, k]`(K = 4096,FP8 × FP8 → FP32 累加);
22-4. **y 量化**:对 `y` 再做一次 MXFP8 量化,得到 `yq`/`ys`;
23-5. **GEMM2**:`out[t, m] = Σ_k yq[t, k] · wob[m, k]`(K = 8192),结果以 bf16 写回。
24- 
25-两级 GEMM 均为 block-scaled(MX)矩阵乘,权重 `woa`/`wob` 由调用方在初始化阶段量化好(ND 布局 + E8M0 scale)。
26- 
27-## 函数原型
28- 
29-```python
30-attn_epilogue(o, woa, wob, descale_woa, descale_wob, rope_sin, rope_cos) -> torch.Tensor
31-```
32- 
33-## 参数说明
34- 
35-| 参数 | 类型/布局 | Shape | 说明 |
36-|---|---|---|---|
37-| `o` | bf16,ND,连续 | `[T, 64, 512]` | attention 输出,64 head × 512 维 |
38-| `woa` | FP8E4M3,ND | `[8, 1024, 4096]` | GEMM1 权重(8 个 group),由调用方预先量化 |
39-| `wob` | FP8E4M3,ND | `[5120, 8192]` | GEMM2 权重,由调用方预先量化 |
40-| `descale_woa` | FP8E8M0,ND | `[8, 1024, 64, 2]` | `woa` 的块缩放(每 32 个 K 元素一个 E8M0 scale) |
41-| `descale_wob` | FP8E8M0,ND | `[5120, 128, 2]` | `wob` 的块缩放 |
42-| `rope_sin` | fp32,ND | `[T, 64]` | inverse RoPE 的 sin 表 |
43-| `rope_cos` | fp32,ND | `[T, 64]` | inverse RoPE 的 cos 表 |
44- 
45-`T` 为运行期 token 数;除 `T` 外的形状均为固定维度。
46- 
47-## 返回值说明
48- 
49-- 返回 `torch.Tensor`:bf16、连续、shape `[T, 5120]`。
50-- 内部把 `T` 补齐到 16 的倍数(并行分档需要),**返回值只包含有效行**,不暴露补齐行。
51- 
52-## 约束说明
53- 
54-- `T >= 1` 的任意正整数;`o` 必须为 3 维且后两维恰为 `(64, 512)`;所有输入须为**同一 NPU 上的连续 ND 张量**。
55-- 权重与 scale **不接受 FRACTAL_NZ**(按 ND 行连续搬入 L1,片上再做转置视图);量化由调用方完成,算子不做权重量化。
56-- 片上工作区:4 个 GM 缓冲区合计 `42240 * ceil(T/16)*16` 字节,由 wrapper 缓存复用(按 device/stream/padded 键)。
57-- 支持的分档由 tiling key schema 约束:两种硬件布局共 6 个合法 key,32 核布局下公开调度只产生 3 个编译版本,签名不含 `T` 的静态取值。
58-- 精度:与 torch_npu 原生参考**逐位一致**(`rtol=0, atol=0`),包含中间量(激活载荷/scale、`Y` 载荷/scale),见 `RESULTS.md`。
59- 
60-## 调用示例
61- 
62-```python
63-import torch
64-import torch_npu
65-from attn_epilogue import attn_epilogue
66- 
67-T = 256
68-o = torch.randn(T, 64, 512, dtype=torch.bfloat16, device="npu")
69-woa = torch.randint(-64, 64, (8, 1024, 4096), dtype=torch.int8, device="npu").view(torch.float8_e4m3fn)
70-wob = torch.randint(-64, 64, (5120, 8192), dtype=torch.int8, device="npu").view(torch.float8_e4m3fn)
71-descale_woa = torch.randint(120, 128, (8, 1024, 64, 2), dtype=torch.uint8, device="npu").view(torch.float8_e8m0fnu)
72-descale_wob = torch.randint(120, 128, (5120, 128, 2), dtype=torch.uint8, device="npu").view(torch.float8_e8m0fnu)
73-rope_sin = torch.randn(T, 64, dtype=torch.float32, device="npu")
74-rope_cos = torch.randn(T, 64, dtype=torch.float32, device="npu")
75- 
76-out = attn_epilogue(o, woa, wob, descale_woa, descale_wob, rope_sin, rope_cos) # [T, 5120] bf16
77-```
78- 
79-运行测试与基准:
80- 
81-```bash
82-python -m pytest ops/pypto_pro/deepseek_v4_1/attn_epilogue/tests/test_attn_epilogue.py -q
83-python ops/pypto_pro/deepseek_v4_1/attn_epilogue/tests/test_attn_epilogue.py --benchmark --tokens 256
84-```
85- 
86-- 详细设计(阶段划分、切分策略、Buffer 与流水)见 `DESIGN.md`;
87-- 精度标准、绝对性能与理论评估(MFU / Bound / 利用率)见 `RESULTS.md`。
@@ -1,98 +0,0 @@
1-# AttnEpilogue 结果:精度与性能
2- 
3-测试入口:`tests/test_attn_epilogue.py`(本次实测 **45/45 PASS**)。
4-性能采集与精度验收在同一交付文件上完成:`op_kernel/attn_epilogue.py`,sha256 `550910e6…`。
5- 
6-## 用例
7- 
8-| 类别 | 覆盖内容 |
9-|---|---|
10-| 给定算例(supplied) | 8 组 `(T, padding, scale)` 组合,含 `T=1/33/72`、`padding=0/16`、`scale=1.0/0.0`(全零激活) |
11-| 边界算例(token boundaries) | `T = 2, 15, 16, 17, 31, 32, 63, 64, 65, 127, 128, 129, 255, 256, 272, 511, 512, 513, 1024,
12-2048, 2049, 4096, 16384` |
13-| 动态 range | 同一编译产物覆盖运行期变长 `T`(签名不含 `T` 静态取值) |
14-| primitive-only 路径 | 不依赖 torch_npu 原生算子的纯 kernel 结果 |
15-| 分档枚举 | tiling key schema 的合法 key 集合与 `tiling_key_for` 实际产生值逐一比对 |
16-| 接口校验 | 非法 shape / dtype / device 的报错路径 |
17-| 量化交叉验证 | CPU 量化路径与原生参考一致 |
18-| 比较器自检 | 人为破坏输入时 `assert_exact` / `assert_payload` 必须抛错 |
19- 
20-## 精度标准
21- 
22-1. **输出逐位一致**:`out[T, 5120]` 与 torch_npu 原生参考 `rtol=0, atol=0` 全等(非阈值比较)。
23-2. **中间量逐字节一致**:激活 FP8 载荷与 E8M0 scale、`Y`(GEMM1 输出)FP8 载荷与 E8M0 scale
24- 四组缓冲区均与参考逐字节相等——任何一级量化或 GEMM 的偏差都会在此暴露。
25-3. **独立数学参考**:`tests/assets/attn_epilogue_golden_cpu.py` 用 FP64 点积 + 两级 BF16 舍入实现
26- 独立 CPU 参考,与 NPU 原生参考、kernel 三方互证。
27-4. **反例门**:比较器自身用故意损坏的输入验证(避免"比较器恒定通过"的假绿)。
28- 
29-## 性能结果
30- 
31-> **采集机器**:本节全部耗时、带宽与占用率数据均在本机 `Ascend950PR_9589`(32 AI Core,32 Cube / 64 Vector,L2 128 MiB)上采集。
32- 
33-### 采集协议
34- 
35-- 设备:device 0(空闲卡),核配额 `Block Num=32 / Mix Block Num=64`。
36-- `msprof --ai-core=off --l2=off --task-time=on`;预热 10 次 → 图捕获内
37- `(256 MiB FP32 ReduceSum 驱逐 L2 + kernel) ×16` → 重放 6 次 = **96 次冷 L2 调用**。
38-- 指标:`op_summary` 中匹配核名的 **末 96 条 `Task Duration(us)` 中位数**(每次采集均审计
39- "前置同流 L2 驱逐 = 96/96")。
40- 
41-### 绝对性能结果
42- 
43-| T | 本实现(µs) | min / max |
44-|---:|---:|---|
45-| 1 | **55.516** | 54.789 / 66.291 |
46-| 33 | **60.069** | 59.225 / 61.959 |
47-| 72 | 65.653 | 64.772 / 68.472 |
48-| 128 | **70.811** | 69.893 / 83.813 |
49-| 129 | 74.638 | 73.351 / 79.269 |
50-| 193 | **80.120** | 78.550 / 81.883 |
51-| 255 | **90.792** | 88.771 / 98.380 |
52-| 256 | 91.726 | 89.840 / 93.187 |
53- 
54-耗时随 T 单调上升后趋平(T=256 时 91.7 µs)。本实现的窗口间重复性约 ±2%(同一 T=256 两次为
55-91.924 / 91.726 µs),因此低于该量级的差异不应解读为性能变化;上表各档均来自同一次采集窗口。
56- 
57-### 理论评估对比(MFU / Bound / 利用率)
58- 
59-平台常量引自本机安装态 `framework/src/platform/parser/simulation_platform/platform_config/Ascend950PR_9589.ini`:
60-`cube_core_cnt=32`、`vector_core_cnt=64`、`cube_freq=1650` MHz、`l1_size=524288`、`l0_c_size=262144`、
61-`ub_size=253952`、`[DtypeMKN] DT_FLOAT8_E4M3FN=16,32,16`。
62- 
63-- **算力峰值** = `M·N·K × 2 × cube_core_cnt × cube_freq` = `16×32×16 × 2 × 32 × 1.65e9`
64- = **864.9 TFLOP/s**(FP8 dense)。
65-- **单 token 计算量** = GEMM1 `8×1024×4096` + GEMM2 `5120×8192` = 75.50 M MAC = **151.0 MFLOP**。
66- 
67-| T | 计算量(GFLOP) | 实测(µs) | 实测算力(TFLOP/s) | **MFU** | 备注 |
68-|---:|---:|---:|---:|---:|---|
69-| 1 | 0.151 | 55.516 | 2.72 | 0.3% | 延迟主导(权重填充 + 4 段 barrier) |
70-| 33 | 4.983 | 60.069 | 83.0 | 9.6% | 延迟主导 |
71-| 72 | 10.87 | 65.653 | 165.6 | 19.1% | 过渡 |
72-| 128 | 19.33 | 70.811 | 272.9 | 31.6% | 过渡 |
73-| 193 | 29.14 | 80.120 | 363.7 | 42.1% | 接近均衡 |
74-| 255 | 38.51 | 90.792 | 424.1 | 49.0% | 均衡 |
75-| 256 | 38.66 | 91.726 | 421.4 | **48.7%** | 均衡 |
76- 
77-- **口径说明**:实测算力 = `计算量 / 实测时长`,MFU = 实测算力 / 平台峰值;该口径与 msprof 的
78- `mac_fp16` 比率定义一致(同一采集上核算值与工具输出相同),可直接用于衡量算力使用程度。
79-- **Bound 情况**:T=256 的单次调用搬运量 ≈ **108 MB**(权重+scale ≈78 MB、`o` 16.8 MB、`out` 2.6 MB、
80- 激活载荷+scale 8.7 MB、`y` 载荷+scale 2.2 MB),算力强度 ≈ **358 FLOP/B**;本机 roofline 拐点约为
81- `864.9 TFLOP/s ÷ 实测可达带宽(~1.7 TB/s) ≈ 509 FLOP/B`,故大 T 位于"算力与访存接近均衡"区
82- (MFU 42–49%、访存约为可达带宽的 ~70%),小 T(≤72)则由固定开销(约 78 MB 权重的 L1 填充与
83- 四段 barrier 的串行)主导——这与"MFU 随 T 单调上升后趋平"的实测曲线一致。
84-- **利用率**:Cube 发射利用率即上表 MFU;Vector 侧(inverse RoPE + 两级 MX 量化)与 Cube 阶段
85- 通过分段发布重叠——32 核布局下激活量化被切成两个 2048 列分段,与 GEMM1 重叠执行;权重仅 78 MB,
86- 在 128 MiB L2 内被多核反复复用(实测 L2 读命中约 87%)。
87- 
88-### 复现命令
89- 
90-```bash
91-# 本实现(PyPTO-Pro)
92-export TILE_FWK_DEVICE_ID=0 PYTHONPATH=<pypto build_out>
93-msprof --ai-core=off --l2=off --task-time=on --output=<dir> \
94- --application="python3 ops/pypto_pro/deepseek_v4_1/attn_epilogue/tests/test_attn_epilogue.py --benchmark --tokens <T>"
95-python3 ops/pypto_pro/deepseek_v4_1/attn_epilogue/tests/test_attn_epilogue.py --summarize <dir>
96-```
97- 
98-> 计时必须固定在空闲设备上采集:同一份代码在繁忙设备上可慢一个数量级。
@@ -1,65 +0,0 @@
1-# Copyright (c) 2025-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-"""Independent CPU mathematics for the BF16 / OCP MXFP8 projection."""
10- 
11-import torch
12- 
13- 
14-def inverse_rope(o, sin, cos):
15- """Apply separate FP32 products/additions, then round the tail to BF16."""
16- x = o.float()
17- result = x.clone()
18- even, odd = x[..., 448::2], x[..., 449::2]
19- c, s = cos[:, None, ::2], sin[:, None, ::2]
20- result[..., 448::2] = even * c + odd * s
21- result[..., 449::2] = odd * c - even * s
22- return result.to(torch.bfloat16)
23- 
24- 
25-def quantize_mx(x):
26- """Quantize BF16 values in groups of 32; return payload and E8M0 bytes."""
27- if x.device.type != "cpu" or x.dtype != torch.bfloat16 or x.shape[-1] % 64:
28- raise ValueError("CPU BF16 input with K divisible by 64 required")
29- grouped = x.contiguous().reshape(*x.shape[:-1], -1, 32)
30- exponent = ((grouped.view(torch.int16).to(torch.int32) & 0x7F80) >> 7).amax(-1)
31- exponent = exponent.clamp_min(8)
32- scale = (exponent - 8).to(torch.uint8)
33- reciprocal_bits = torch.where(exponent == 8, 0, (262 - exponent) << 7)
34- reciprocal = reciprocal_bits.to(torch.int16).view(torch.bfloat16).float()
35- scaled = grouped.float() * reciprocal[..., None]
36- payload = scaled.clamp(-448, 448).to(torch.float8_e4m3fn).reshape(x.shape)
37- return payload, scale.reshape(*x.shape[:-1], x.shape[-1] // 64, 2)
38- 
39- 
40-def dequantize_mx(payload, scales):
41- """Decode the per-32 E8M0 scale in the public packed scale layout."""
42- code = scales.view(torch.uint8).reshape(*payload.shape[:-1], -1).int()
43- factor = torch.pow(2.0, code.double() - 127)
44- return (payload.double().reshape(*payload.shape[:-1], -1, 32) * factor[..., None]).reshape(payload.shape)
45- 
46- 
47-def attn_epilogue_golden_cpu(o, woa, wob, descale_woa, descale_wob, rope_sin, rope_cos):
48- """CPU mathematical oracle with BF16 rounding at each projection boundary.
49- 
50- FP64 dot products isolate mathematical rounding from device accumulation.
51- Device acceptance additionally uses the upstream native oracle, because its
52- FP32 accumulation order is part of the upstream zero-tolerance criterion.
53- """
54- if any(v.device.type != "cpu" for v in (o, woa, wob, descale_woa, descale_wob, rope_sin, rope_cos)):
55- raise ValueError("the CPU oracle requires CPU tensors")
56- t = o.shape[0]
57- rotated = inverse_rope(o, rope_sin, rope_cos).reshape(t, 8, 4096)
58- aq, asc = quantize_mx(rotated)
59- activation = dequantize_mx(aq, asc)
60- wa = dequantize_mx(woa, descale_woa)
61- y = torch.bmm(activation.permute(1, 0, 2), wa.transpose(1, 2)).permute(1, 0, 2)
62- y = y.contiguous().reshape(t, 8192).to(torch.bfloat16)
63- yq, ys = quantize_mx(y)
64- result = dequantize_mx(yq, ys) @ dequantize_mx(wob, descale_wob).t()
65- return result.to(torch.bfloat16)
@@ -1,28 +0,0 @@
1-# Copyright (c) 2025-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-"""Fixed upstream acceptance: exact BF16 values and exact quantization bytes."""
10- 
11-import torch
12- 
13- 
14-def assert_exact(actual, expected, label="output"):
15- """Assert bit-exact bf16 equality elementwise, reporting the first mismatch."""
16- if actual.shape != expected.shape or actual.dtype != expected.dtype:
17- raise AssertionError(f"{label}: shape/dtype mismatch")
18- a, b = actual.detach().cpu(), expected.detach().cpu()
19- if a.is_floating_point() and not bool(torch.isfinite(a.float()).all()):
20- raise AssertionError(f"{label}: nonfinite values")
21- torch.testing.assert_close(a, b, rtol=0, atol=0, msg=label)
22- if a.dtype == torch.bfloat16 and not torch.equal(a.view(torch.int16), b.view(torch.int16)):
23- raise AssertionError(f"{label}: BF16 bit patterns differ")
24- 
25- 
26-def assert_payload(actual, expected, label="payload"):
27- """Assert byte-exact equality of a payload/scale buffer, reporting the first mismatch."""
28- assert_exact(actual.view(torch.uint8), expected.view(torch.uint8), label)
@@ -1,382 +0,0 @@
1-# Copyright (c) 2025-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-"""Upstream-aligned exact tests, boundary tests and cold-L2 graph benchmark."""
10- 
11-import argparse
12-import ast
13-import csv
14-import importlib.util
15-import inspect
16-import json
17-import os
18-from pathlib import Path
19-import logging
20-import statistics
21-import sys
22- 
23-import pytest
24-import torch
25- 
26-# Support both direct execution and pytest from the repository root.
27-_HERE = Path(__file__).resolve().parent
28-_LOG = logging.getLogger(__name__)
29-sys.path.insert(0, str(_HERE))
30-sys.path.insert(0, str(_HERE / "assets"))
31-sys.path.insert(0, str(_HERE.parent / "op_kernel"))
32-sys.path.insert(0, str(_HERE.parents[4] / "tests/common"))
33- 
34-from attn_epilogue_golden_cpu import ( # noqa: E402 local test modules, path set above
35- attn_epilogue_golden_cpu,
36- inverse_rope,
37- quantize_mx,
38-)
39-from precision_compare import assert_exact, assert_payload # noqa: E402
40-from op_caller import get_op_caller # noqa: E402
41- 
42- 
43-# Slab publication orders intentional Vec reuse; keep its warning visible.
44-pytestmark = [
45- pytest.mark.soc("950"),
46- pytest.mark.filterwarnings(
47- "error:Tile buffers in (Mat|Left|Right|ScaleLeft|ScaleRight|Acc) overlap:pypto_pro._errors.MutexMismatch"
48- ),
49-]
50- 
51-SUPPLIED_CASES = [(1, 0, 1.0), (33, 0, 1.0), (72, 16, 1.0), (129, 0, 1.0),
52- (193, 0, 1.0), (255, 0, 1.0), (72, 0, 0.0), (256, 0, 1e-37)]
53-BOUNDARY_TOKENS = [2, 15, 16, 17, 31, 32, 63, 64, 65, 127, 128, 192, 256,
54- 257, 272, 511, 512, 513, 769, 1024, 1793, 2048, 2049, 4096, 16384]
55- 
56- 
57-def input_fixture(t, scale=1.0):
58- gen = torch.Generator().manual_seed(2026)
59- return (torch.randn(t, 64, 512, generator=gen) * (0.3 * scale)).to(torch.bfloat16)
60- 
61- 
62-def rope_tables(t):
63- j = torch.arange(0, 64, 2, dtype=torch.float32)
64- angles = torch.outer(torch.arange(t, dtype=torch.float32), 1.0 / (10000.0 ** (j / 64)))
65- return angles.sin().repeat_interleave(2, -1), angles.cos().repeat_interleave(2, -1)
66- 
67- 
68-def make_weights():
69- import torch_npu
70- gen = torch.Generator().manual_seed(2026)
71- wa = (torch.randn(8, 1024, 4096, generator=gen) * 0.3).to(torch.bfloat16)
72- wb = (torch.randn(5120, 8192, generator=gen) * 0.2).to(torch.bfloat16)
73- aq, asc = torch_npu.npu_dynamic_mx_quant(wa.reshape(8192, 4096).npu(), dst_type=292)
74- bq, bsc = torch_npu.npu_dynamic_mx_quant(wb.npu(), dst_type=292)
75- e8 = torch.float8_e8m0fnu
76- return aq.reshape(8, 1024, 4096), bq, asc.view(e8).reshape(8, 1024, 64, 2), bsc.view(e8)
77- 
78- 
79-def native_reference(o, woa, wob, sa, sb, sin, cos):
80- """Use the same native arithmetic and intermediate rounding as upstream."""
81- import torch_npu
82- t = o.shape[0]
83- rotated = inverse_rope(o.cpu(), sin.cpu(), cos.cpu()).reshape(t, 8, 4096)
84- aq, asc = torch_npu.npu_dynamic_mx_quant(rotated.npu(), dst_type=292)
85- y = torch_npu.npu_transpose_quant_batchmatmul(
86- aq, woa, 15, x1_scale=asc.view(torch.float8_e8m0fnu), x2_scale=sa,
87- group_sizes=[1, 1, 32], perm_x1=[1, 0, 2], perm_x2=[0, 2, 1], perm_y=[1, 0, 2],
88- ).reshape(t, 8192)
89- yq, ys = torch_npu.npu_dynamic_mx_quant(y, dst_type=292)
90- out = torch_npu.npu_quant_matmul(
91- yq, wob.t(), sb.transpose(0, 1), pertoken_scale=ys.view(torch.float8_e8m0fnu),
92- output_dtype=torch.bfloat16, group_sizes=[1, 1, 32],
93- )
94- return (out.cpu(), aq.view(torch.uint8).cpu(), asc.view(torch.uint8).reshape(t, 8, 128).cpu(),
95- yq.view(torch.uint8).cpu(), ys.view(torch.uint8).reshape(t, 256).cpu())
96- 
97- 
98-@pytest.fixture(scope="module")
99-def weights():
100- pytest.importorskip("torch_npu")
101- if not torch.npu.is_available():
102- pytest.skip("Ascend 950 NPU required")
103- torch.npu.set_device(int(os.environ.get("TILE_FWK_DEVICE_ID", 0)))
104- return make_weights()
105- 
106- 
107-def arguments(weights, t, scale=1.0):
108- x = input_fixture(t, scale)
109- sin, cos = rope_tables(t)
110- return (x.npu(), *weights, sin.npu(), cos.npu())
111- 
112- 
113-def test_comparator_rejects_corruption():
114- a = torch.ones((2, 3), dtype=torch.bfloat16)
115- b = a.clone()
116- b[1, 2] += 1
117- with pytest.raises(AssertionError):
118- assert_exact(a, b)
119- with pytest.raises(AssertionError):
120- assert_payload(torch.tensor([1, 2], dtype=torch.uint8), torch.tensor([1, 3], dtype=torch.uint8))
121- 
122- 
123-@pytest.mark.parametrize("t,padding,scale", SUPPLIED_CASES)
124-def test_supplied_native_and_replay(weights, t, padding, scale):
125- import attn_epilogue as op
126- args = arguments(weights, t, scale)
127- expected = [native_reference(*args)]
128- negative = (-args[0], *args[1:])
129- expected.append(native_reference(*negative))
130- m = (t + 15) // 16 * 16 + padding
131- buffers = op.scratch_buffers(args[0], m)
132- storage = torch.full((m * 5120 + 64,), 19.0, dtype=torch.bfloat16, device=args[0].device)
133- output = storage[32:-32].view(m, 5120)
134- op.launch_kernel(*args, buffers, output)
135- torch.npu.synchronize()
136- assert_exact(output[:t], expected[0][0])
137- assert_payload(buffers[0].view(8, m, 4096)[:, :t], expected[0][1].permute(1, 0, 2), "activation bytes")
138- assert_payload(buffers[1].view(8, m, 128)[:, :t], expected[0][2].permute(1, 0, 2), "activation scales")
139- assert_payload(buffers[2][:t], expected[0][3], "Y bytes")
140- assert_payload(buffers[3][:t], expected[0][4], "Y scales")
141- assert bool((storage[:32] == 19).all()) and bool((storage[-32:] == 19).all())
142- assert bool((output[t:] == 19).all())
143- graph = torch.npu.NPUGraph()
144- with torch.npu.graph(graph):
145- snapshots = []
146- for _ in range(2):
147- args[0].neg_()
148- op.launch_kernel(*args, buffers, output)
149- snapshots.append(output[:t].clone())
150- for _ in range(2):
151- graph.replay()
152- torch.npu.synchronize()
153- for i, snapshot in enumerate(snapshots):
154- assert_exact(snapshot, expected[(i + 1) % 2][0], "alternating replay")
155- 
156- 
157-@pytest.mark.parametrize("t", [1, 72, 256, 257, 2048])
158-def test_public_tp1(weights, t):
159- import attn_epilogue as op
160- args = arguments(weights, t)
161- expected = [native_reference(*args)[0], native_reference(-args[0], *args[1:])[0]]
162- out = op.attn_epilogue(*args)
163- assert out.shape == (t, 5120) and out.dtype == torch.bfloat16 and out.is_contiguous()
164- ids = {key: tuple(v.data_ptr() for v in values) for key, values in op.BUFFER_CACHE.items()}
165- args[0].neg_()
166- other = op.attn_epilogue(*args)
167- torch.npu.synchronize()
168- assert out.data_ptr() != other.data_ptr()
169- assert_exact(out, expected[0])
170- assert_exact(other, expected[1])
171- assert ids == {key: tuple(v.data_ptr() for v in values) for key, values in op.BUFFER_CACHE.items()}
172- graph = torch.npu.NPUGraph()
173- with torch.npu.graph(graph):
174- args[0].neg_()
175- first = op.attn_epilogue(*args)
176- args[0].neg_()
177- second = op.attn_epilogue(*args)
178- assert first.data_ptr() != second.data_ptr()
179- for _ in range(2):
180- graph.replay()
181- torch.npu.synchronize()
182- assert_exact(first, expected[0])
183- assert_exact(second, expected[1])
184- 
185- 
186-@pytest.mark.parametrize("t", BOUNDARY_TOKENS)
187-def test_token_boundaries(weights, t):
188- attn_epilogue = get_op_caller("attn_epilogue")
189- args = arguments(weights, t)
190- out = attn_epilogue(*args)
191- assert_exact(out, native_reference(*args)[0])
192- 
193- 
194-def test_dynamic_token_range(weights):
195- attn_epilogue = get_op_caller("attn_epilogue")
196- for t in range(1, 257):
197- args = arguments(weights, t)
198- assert_exact(attn_epilogue(*args), native_reference(*args)[0], f"runtime T={t}")
199- 
200- 
201-def _pl_attribute(node):
202- """Return True for `pl.<attr>` accesses in the kernel source."""
203- return (isinstance(node, ast.Attribute) and isinstance(node.value, ast.Name)
204- and node.value.id == "pl")
205- 
206- 
207-def test_primitive_only_implementation():
208- """The kernel must go through the tile/primitive API only, never raw gemm/shmem entry points."""
209- import attn_epilogue as op
210- tree = ast.parse(inspect.getsource(op))
211- accesses = {node.attr for node in ast.walk(tree) if _pl_attribute(node)}
212- assert not accesses.intersection({"gemm", "gemm_mx", "mem_space", "allocate_tile_group"})
213- assert {"make_tile_group", "matmul_mx", "matmul_mx_acc"} <= accesses
214- 
215- 
216-def test_bounded_tiling_profiles():
217- from pypto_pro.runtime.tilingkey import TilingKeySchema
218- import attn_epilogue as op
219- schema = TilingKeySchema(op.EpilogueKey)
220- profiles = set(schema.enumerate_valid())
221- assert len(profiles) == 6
222- combined = set()
223- for cores in (28, 32):
224- selected = {tuple(op.tiling_key_for(t, cores)[name] for name in schema.field_names())
225- for t in [*range(1, 257), *BOUNDARY_TOKENS]}
226- assert len(selected) == 3
227- assert selected <= profiles
228- combined.update(selected)
229- assert combined == profiles
230- 
231- 
232-def test_public_validation(weights):
233- import attn_epilogue as op
234- import torch_npu
235- args = arguments(weights, 72)
236- assert list(inspect.signature(op.attn_epilogue).parameters) == [
237- "o", "woa", "wob", "descale_woa", "descale_wob", "rope_sin", "rope_cos"]
238- faults = [(0, args[0].reshape(576, 4096)), (1, weights[0].reshape(8192, 4096)),
239- (3, weights[2].view(torch.uint8)), (6, args[6].cpu()),
240- (6, args[6][:, ::2]), (6, args[6].to(torch.float16)),
241- (6, torch.empty((72, 128), device=args[0].device)[:, ::2]),
242- (2, torch_npu.npu_format_cast(weights[1], 29))]
243- for index, value in faults:
244- bad = list(args)
245- bad[index] = value
246- with pytest.raises((ValueError, TypeError)):
247- op.attn_epilogue(*bad)
248- bad = list(args)
249- bad[0] = torch.empty((0, 64, 512), dtype=torch.bfloat16, device=args[0].device)
250- with pytest.raises(ValueError):
251- op.attn_epilogue(*bad)
252- 
253- 
254-def test_cpu_quantization_matches_native(weights):
255- import torch_npu
256- for scale in (0.0, 1e-37, 1.0, 1000.0):
257- x = input_fixture(1, scale).reshape(8, 4096)
258- q, s = quantize_mx(x)
259- nq, ns = torch_npu.npu_dynamic_mx_quant(x.npu(), dst_type=292)
260- assert_payload(q, nq.cpu())
261- assert_payload(s, ns.cpu())
262- 
263- 
264-def test_independent_cpu_projection(weights):
265- from attn_epilogue import attn_epilogue
266- x = ((torch.arange(32768).float() % 127 - 63) / 128).reshape(1, 64, 512).bfloat16()
267- sin, cos = rope_tables(1)
268- codes = torch.tensor([1.0, -1.0]).to(torch.float8_e4m3fn).view(torch.uint8)
269- wa = torch.zeros((8, 1024, 4096), dtype=torch.uint8)
270- rows = torch.arange(1024)
271- for group in range(8):
272- wa[group, rows, (rows * 3 + group * 17) % 4096] = codes[group % 2]
273- wb = torch.zeros((5120, 8192), dtype=torch.uint8)
274- rows = torch.arange(5120)
275- wb[rows, (rows * 37 + 13) % 8192] = codes[rows % 2]
276- wa = wa.view(torch.float8_e4m3fn)
277- wb = wb.view(torch.float8_e4m3fn)
278- sa = torch.full((8, 1024, 64, 2), 127, dtype=torch.uint8).view(torch.float8_e8m0fnu)
279- sb = torch.full((5120, 128, 2), 127, dtype=torch.uint8).view(torch.float8_e8m0fnu)
280- args = (x, wa, wb, sa, sb, sin, cos)
281- expected = attn_epilogue_golden_cpu(*args)
282- assert_exact(attn_epilogue(*(v.npu() for v in args)), expected, "independent CPU projection")
283- 
284- 
285-def benchmark(tokens, baseline_root=None, compare=False, scale=1.0):
286- import torch_npu # noqa: F401 required for NPU device init
287- import attn_epilogue as op
288- torch.npu.set_device(int(os.environ.get("TILE_FWK_DEVICE_ID", 0)))
289- args = arguments(make_weights(), tokens, scale)
290- expected = native_reference(*args)[0]
291- run = op.attn_epilogue
292- if baseline_root:
293- directory = Path(baseline_root).resolve() / "samples/attn_epilogue"
294- spec = importlib.util.spec_from_file_location("upstream_attn_epilogue", directory / "attn_epilogue.py")
295- module = importlib.util.module_from_spec(spec)
296- sys.path.insert(0, str(directory))
297- spec.loader.exec_module(module)
298- run = module.attn_epilogue
299- for _ in range(10):
300- out = run(*args)
301- if compare:
302- candidate = op.attn_epilogue(*args)
303- torch.npu.synchronize()
304- assert_exact(out, expected)
305- if compare:
306- assert_exact(candidate, expected)
307- eviction = torch.ones(256 * 1024 * 1024 // 4, dtype=torch.float32, device=args[0].device)
308- graph = torch.npu.NPUGraph()
309- with torch.npu.graph(graph):
310- outputs = []
311- for _ in range(8 if compare else 16):
312- for call in ((run, op.attn_epilogue, op.attn_epilogue, run) if compare else (run,)):
313- sink = eviction.sum()
314- outputs.append(call(*args))
315- for _ in range(6):
316- graph.replay()
317- torch.npu.synchronize()
318- assert sink.item() == eviction.numel()
319- for out in outputs:
320- assert_exact(out, expected)
321- implementation = "AB/BA: 48 pairs per order" if compare else ("upstream" if baseline_root else "pypto")
322- _LOG.info("PASS: T=%s, scale=%s, 96 cold-L2 calls per implementation, %s", tokens, scale,
323- implementation)
324- 
325- 
326-def summarize_benchmark(directory):
327- """Read one paired msprof capture and verify task count, order and eviction."""
328- files = list(Path(directory).rglob("op_summary_*.csv"))
329- if len(files) != 1:
330- raise ValueError("provide one capture directory containing one op_summary CSV")
331- with files[0].open() as stream:
332- rows = sorted(csv.DictReader(stream), key=lambda r: float(r["Task Start Time(us)"]))
333- custom = [(i, r) for i, r in enumerate(rows)
334- if "attn_epilogue_kernel" in r["Op Name"] or "AttnEpilogueTP1Kernel" in r["Op Name"]]
335- if len(custom) < 192:
336- raise ValueError("fewer than 96 calls per implementation; no comparison established")
337- selected = custom[-192:]
338- quota = {(r["Block Num"], r["Mix Block Num"]) for _, r in selected}
339- if len(quota) != 1:
340- raise ValueError("baseline/candidate core quotas differ")
341- for i, row in selected:
342- previous = rows[i - 1] if i else {}
343- if "ReduceSum" not in previous.get("OP Type", "") or previous.get("Stream ID") != row["Stream ID"]:
344- raise ValueError("a measured call lacks the preceding same-stream L2 eviction")
345- orders = {"AB": [], "BA": []}
346- for i in range(0, 192, 4):
347- block = [r for _, r in selected[i:i + 4]]
348- if ["AttnEpilogueTP1Kernel" in r["Op Name"] for r in block] != [True, False, False, True]:
349- raise ValueError("unexpected native-task order or number of tasks per call")
350- durations = [float(r["Task Duration(us)"]) for r in block]
351- orders["AB"].append((durations[0], durations[1]))
352- orders["BA"].append((durations[3], durations[2]))
353- 
354- def summary(values):
355- return dict(median_us=statistics.median(values), min_us=min(values), max_us=max(values))
356- pairs = orders["AB"] + orders["BA"]
357- return dict(metric="msprof Task Duration(us)", calls_per_implementation=96,
358- baseline=summary([p[0] for p in pairs]), candidate=summary([p[1] for p in pairs]),
359- orders={name: dict(pairs=len(values), median_ratio=statistics.median(b / a for a, b in values),
360- candidate_wins=sum(b < a for a, b in values)) for name, values in orders.items()})
361- 
362- 
363-if __name__ == "__main__":
364- logging.basicConfig(level=logging.INFO, format="%(message)s", stream=sys.stdout)
365- parser = argparse.ArgumentParser(description=__doc__)
366- parser.add_argument("--benchmark", action="store_true")
367- parser.add_argument("--tokens", type=int, default=72)
368- parser.add_argument("--baseline-root")
369- parser.add_argument("--compare", action="store_true")
370- parser.add_argument("--scale", type=float, default=1.0)
371- parser.add_argument("--summarize", help="paired msprof capture directory")
372- options, pytest_args = parser.parse_known_args()
373- if options.summarize:
374- _LOG.info("%s", json.dumps(summarize_benchmark(options.summarize), indent=2))
375- elif options.benchmark:
376- if options.tokens < 1:
377- parser.error("--tokens must be positive")
378- if options.compare and not options.baseline_root:
379- parser.error("--compare requires --baseline-root")
380- benchmark(options.tokens, options.baseline_root, options.compare, options.scale)
381- else:
382- raise SystemExit(pytest.main([__file__, "-q", *pytest_args]))
@@ -1,185 +0,0 @@
1-# attn_prologue(PyPTO-Pro)
2- 
3-`attn_prologue` 是使用 PyPTO-Pro 实现的 Attention 前置处理融合算子。一次设备调用完成两级 Q 投影、KV 投影、RMSNorm、QR 动态 MXFP8 量化、尾部 RoPE 和分页 KV cache 写回,返回 `(q, qr, descale_qr)`,并就地更新 `kv_cache`。
4- 
5-当前 kernel 的特征维度固定为 `(H,R,N,D,Dr)=(5120,1280,64,512,64)`,分别表示输入特征宽度、Q 中间投影宽度、Q head 数、每 head 宽度及 RoPE 处理宽度。唯一动态轴是展平后的 token 数 `T=batch*seq`,host 接受 `1 <= T <= 262144`。它不计算 QK、softmax 或 Attention 加权输出,也不读取已有 cache 做注意力计算。接口与数值行为以本目录的实现和测试为依据。
6- 
7-## 产品支持情况
8- 
9-| 项 | 取值 |
10-| :--- | :--- |
11-| 芯片 | Ascend 950PR / 950DT(目标架构 `NpuArch.DAV_3510`) |
12-| 能力依赖 | `matmul_mx/matmul_mx_acc` 联合消费 E4M3FN 数据与 E8M0 分组 scale,FP32 累加;FRACTAL_NZ 权重及 NZ/ZN 同址视图;ScaleLeft/ScaleRight 与操作数地址配对;`DualModeSplitM` 将累加结果分发给两个 AIV;VF 量化与 RoPE;MIX 全局同步和跨核事件 |
13-| 启动核数 | 正常查询路径取 `max(1, min(cube_core_num, vector_core_num//2))`;平台查询异常或返回异常核数时,`_fused_grid()` 回退到 32 Cube / 64 Vector 的配置 |
14-| 原有实测环境 | DAV_3510,32 Cube / 64 Vector;CANN 9.3.0、PyPTO-Pro、PyTorch 2.12.0+cpu、torch_npu、Python 3.12;本次文档完善未重新采集设备性能 |
15-| 测试标注 | 测试模块标注 `pytest.mark.soc("950")`,4 个 NPU 冒烟项另标注 `pytest.mark.npu`;通过 pytest 执行时由仓库 conftest 应用这些标记 |
16-| 依赖 | kernel 使用 pypto_pro、torch、torch_npu;CPU 参考与判据模块只依赖 torch,测试入口另使用 pytest |
17- 
18-host 指 CPU 侧接口代码,AIC 是 Cube 矩阵计算单元,AIV 是向量计算单元;MIX kernel 使用两者协作。一次启动中的一个核组对应 1 个 AIC 与 2 个 AIV。VF 指 `@pl.vector_function` 定义的向量函数。GM 是设备全局内存,L1/L0 用于 Cube 操作数与累加结果,UB 是 AIV 的本地缓冲区。
19- 
20-## 功能说明
21- 
22-公开函数 `attn_prologue` 只检查输入元数据、分配输出及工作区,再调用一次 `attn_prologue_kernel`。三个矩阵乘都由 Cube 使用 MXFP8 数据和分组 scale 直接完成,结果以 FP32 累加;设备上不会先构造完整的反量化 X 和权重。Vector 完成归一化、量化、RoPE 和输出处理。kernel 不使用 tiling key,T 由动态张量形状提供,内部根据 `ceil(T/128)` 选择工作分配,详见 [DESIGN.md](DESIGN.md)。
23- 
24-以下使用 CPU 参考实现中已有的函数名表示数学过程:`dequantize_mxfp8` 将 FP8 数据乘以对应分组 scale,`quantize_mxfp8` 做每 32 元素一组的动态量化,`rms_norm` 和 `apply_tail_rope` 分别执行整行归一化及尾部位置变换。它们用于说明数值顺序,不表示 kernel 实际调用 CPU 函数。
25- 
26-```text
27-x_deq = dequantize_mxfp8(x, descale_x) # [T,5120]
28-qa = x_deq @ dequantize_mxfp8(wqa, descale_wqa).T # [T,1280]
29-kv = x_deq @ dequantize_mxfp8(wkv, descale_wkv).T # [T,512]
30- 
31-qr_norm = rms_norm(qa, norm_weight_qr, norm_eps)
32-qr, descale_qr = quantize_mxfp8(qr_norm) # 另有参考诊断量,此处省略
33-q_proj = dequantize_mxfp8(qr, descale_qr) @ dequantize_mxfp8(wqb, descale_wqb).T
34-q = BF16(apply_tail_rope(reshape(q_proj, [T,64,512]), rope_sin, rope_cos))
35- 
36-kv_norm = rms_norm(kv, norm_weight_kv, norm_eps)
37-kv_rope = apply_tail_rope(kv_norm, rope_sin, rope_cos)
38-kv_bytes = E4M3FN(clamp(kv_rope, -448, 448)).view(uint8)
39-kv_cache[cache_index[t]//BS, cache_index[t]%BS, 0, :] = kv_bytes[t, :]
40-```
41- 
42-QA 与 QB 是代码对 Q 第一次、第二次投影的称呼;`qr` 是两次投影之间经过 RMSNorm 和量化的低秩表示。QB 必须消费量化后的 `qr/descale_qr`,不能直接使用 FP32 的 `qr_norm`。KV 支路先 RMSNorm、再 RoPE、最后转 E4M3FN,scale 固定为 1;返回的 QR scale 不用于解释 KV cache。
43- 
44-**RMSNorm**:对每个 token 的整行计算,不减均值。QR 沿 R=1280 归约,KV 沿 D=512 归约。实现先求 `rstd = 1/sqrt(sum(v*v)/width + norm_eps)`,再依次计算 `(v*rstd)*gamma`。QR VF 按 20 段、KV VF 按 8 段的 64 个 FP32 元素累加平方和;Cube 的分块归约和 VF 的求和顺序可能与 CPU torch 不同,精度判据对此单独处理。
45- 
46-**QR 动态量化**:每行含 40 个连续的 32 元素组。对通常的非零有限输入组,计算:
47- 
48-```text
49-amax = max(abs(group))
50-e = max(floor(log2(amax)) - 8, -127)
51-scale = 2^e
52-payload = E4M3FN(clamp(group / scale, -448, 448))
53-scale_byte = e + 127
54-```
55- 
56-kernel 通过 FP32 指数字段取得共享指数,并构造 `2^-e` 与数据相乘。CPU 参考使用 `frexp` 和 `ldexp`,另对指数上限 127 做钳位;对有限 FP32 正常数,上限不会起作用。E4M3FN 采用最近偶数舍入(`CAST_RINT`),在转换前显式饱和到 ±448。该指数规则不等于用 `amax/448` 生成连续 scale,组内部分值仍可能饱和。
57- 
58-全零组写零 payload 和编码字节 0;E8M0 字节 0 本身表示 `2^-127`,不是数值 0。最后两维 `[R/64,2]` 展平后,40 个 scale 依次对应特征 `0..31`、`32..63`、…、`1248..1279`;末维长度 2 是框架加载 scale 分形时使用的物理 phase 轴。这里的 scale 是乘法因子,名字中的 `descale` 不表示取倒数。
59- 
60-**尾部 RoPE**:沿用 CPU 参考的 `RopeConvention.INTERLEAVE_HALF`。对每个 Q head 和 KV 向量,只变换末尾 64 维;前 448 维不做位置变换,Q 最后仍需转 BF16、KV 仍需转 E4M3FN。设尾部输入为 z,对 `i=0..31`:
61- 
62-```text
63-out_tail[i] = z[2*i] * rope_cos[t,i] + z[2*i+1] * rope_sin[t,i]
64-out_tail[32 + i] = z[2*i] * rope_sin[t,32+i] + z[2*i+1] * rope_cos[t,32+i]
65-```
66- 
67-输入按相邻元素配对,输出分别放入两个连续半区。同一 token 的表在全部 64 个 Q head 上共享。代码没有额外添加负号,不能直接替换为常见的带负号 RoPE 公式;是否构成保范数的旋转取决于调用方提供的系数表。kernel 只实现上述变换,不生成或校验角度表。
68- 
69-## 函数原型
70- 
71-```python
72-from attn_prologue import attn_prologue, to_nz
73- 
74-q, qr, descale_qr = attn_prologue(
75- x, wqa, wqb, wkv,
76- descale_x, descale_wqa, descale_wqb, descale_wkv,
77- norm_weight_qr, norm_weight_kv,
78- rope_sin, rope_cos, cache_index, kv_cache,
79- norm_eps=1e-6,
80-)
81-```
82- 
83-`to_nz(weight)` 要求 NPU 张量,调用 `torch_npu.npu_format_cast(weight.contiguous(), 29)` 转为 FRACTAL_NZ。应在权重加载期一次性执行;公开计算函数只通过 `get_npu_format` 检查三份权重的 format 29,不自动转换。
84- 
85-### 参数说明
86- 
87-`T` 是 token 总数,batch 和 seq 不单独传入;`P` 是 cache 页数,`BS` 是每页 slot 数。下表权重形状均为逻辑形状,NZ 改变物理排布,不改变 `[输出宽度,输入宽度]` 的矩阵方向。
88- 
89-| 参数 | dtype | shape / 布局 | 说明 |
90-| :--- | :--- | :--- | :--- |
91-| `x` | E4M3FN | `[T,5120]` / ND | 输入的 FP8 编码数据,每字节一个元素 |
92-| `wqa` | E4M3FN | `[1280,5120]` / NZ | Q 第一次投影权重 |
93-| `wqb` | E4M3FN | `[32768,1280]` / NZ | Q 第二次投影权重,输出列按 head 连续组织 |
94-| `wkv` | E4M3FN | `[512,5120]` / NZ | KV 投影权重 |
95-| `descale_x` | E8M0 | `[T,80,2]` / ND | 每行 160 个 scale,各覆盖 32 个输入元素 |
96-| `descale_wqa` | E8M0 | `[1280,80,2]` / ND | QA 权重沿输入特征维的 scale |
97-| `descale_wqb` | E8M0 | `[32768,20,2]` / ND | QB 权重每行 40 个 scale |
98-| `descale_wkv` | E8M0 | `[512,80,2]` / ND | KV 权重每行 160 个 scale |
99-| `norm_weight_qr` | FP32 | `[1280]` / ND | QR RMSNorm 的逐特征权重,不要求全 1 |
100-| `norm_weight_kv` | FP32 | `[512]` / ND | KV RMSNorm 的逐特征权重 |
101-| `rope_sin` / `rope_cos` | FP32 | 各 `[T,64]` / ND | 每 token 的位置变换系数,不从 `cache_index` 推导 |
102-| `cache_index` | INT64 | `[T]` / ND | 扁平 cache slot,约定 `0 <= idx < P*BS`,一次调用内不重复 |
103-| `kv_cache` | UINT8 | `[P,BS,1,512]` / ND | 就地写回的 E4M3FN 编码字节,读取时按 scale=1 解释 |
104-| `norm_eps` | float | 默认 `1e-6` | 两支路共用,作为运行期 FP32 参数传入;调用方应提供有限正数 |
105- 
106-E4M3FN 和 E8M0 对应 `torch.float8_e4m3fn`、`torch.float8_e8m0fnu`。host 的 dtype 检查也接受 `int8/uint8` 形式的编码字节;测试入口 `_device_input` 会先搬运原始字节,再 `.view` 为 kernel 声明的 FP8 dtype。为保持接口与 JIT 类型一致,建议按上表传入 FP8 视图,不能用 `.to(float8)` 对编码整数做数值转换。
107- 
108-有限 E8M0 编码 b(0–254)表示 `2^(b-127)`。每组 scale 为一个字节,因此 x 的 scale 开销是每 token 160 B,而不是 80 B。测试主要使用非单位 scale 和有限随机输入;NaN、无穷或极端动态范围不属于本目录已完整验证的输入范围。
109- 
110-### 返回值说明
111- 
112-返回 `(q, qr, descale_qr)`;`kv_cache` 就地更新,不额外返回。
113- 
114-| 输出 | dtype | shape | 说明 |
115-| :--- | :--- | :--- | :--- |
116-| `q` | BF16 | `[T,64,512]` | QB 投影与尾部 RoPE 后的最终 Q |
117-| `qr` | E4M3FN | `[T,1280]` | QA 经 RMSNorm、动态量化后的中间表示,同时作为 QB 输入 |
118-| `descale_qr` | INT8 | `[T,20,2]` | E8M0 编码字节;内部按 E8M0 分配,返回 int8 视图 |
119-| `kv_cache`(就地) | UINT8 | `[P,BS,1,512]` | 仅覆盖 `cache_index` 命中的整行,每 slot 512 B |
120- 
121-解释 `descale_qr` 时应先 `.view(torch.uint8)` 或 `.view(torch.float8_e8m0fnu)`,不能直接把 int8 的负数当作有符号指数。三个返回张量和两个 FP32 工作区均由 host 用 `torch.empty` 分配;`kv_cache` 使用调用方提供的存储,未命中 slot 保留原始字节。
122- 
123-最终 Q 每 token 为 65536 B;T=262144 时单个 q 输出为 16 GiB。测试通过分块回传与比较来限制 CPU 参考内存,设备上的公开输出仍按完整 T 分配。
124- 
125-## 约束说明
126- 
127-**输入与布局**
128- 
129-1. 当前只支持固定的 H/R/N/D/Dr,上述维度不是可调接口参数。CPU 参考支持小几何自检,不代表设备 kernel 同时支持这些形状。T 必须在 `[1,262144]`。
130-2. 调用方应提供同一 NPU 上的张量,ND 输入按连续布局准备,三份权重预先转 NZ。`_validate_metadata` 显式检查 shape、dtype 集合和权重 NZ 标记,但没有统一检查所有输入的设备一致性或连续性,也不自动修正布局。
131-3. `x[t]`、位置表第 t 行与 `cache_index[t]` 必须对应同一个 token。算子不根据 T、batch 或 cache 页号推断位置。
132-4. cache 页数和页大小应为正,索引须在 `[0,P*BS)` 且唯一。kernel 对负索引有跳过写入的分支,但 CPU golden 拒绝负索引,当前公开约定不将其作为有效输入;kernel 不检查索引上界或重复项,host 也不把设备索引读回 CPU。
133- 
134-**数值与执行**
135- 
136-5. QB 消费量化后的 QR,KV 先归一化和位置变换再量化。不能交换这些步骤,也不能将 QR 的动态 scale 用在 KV 上。
137-6. E4M3FN 转换为最近偶数舍入,并先显式饱和到 ±448;QR 全零组的编码为零 payload 与 scale 字节 0。Q 的 BF16 转换在尾部 RoPE 之后执行。
138-7. host 只对 `norm_eps` 做 `float(...)` 转换,没有有限性和正数检查;调用方应保证其有效。它以运行期 FP32 标量传入,不作为 tiling key。
139-8. 一次公开调用只启动一个 kernel;CPU 侧的输入构造、NZ 权重转换、参考计算和输出比较均不在 kernel 内,也不包含于设备 task duration。
140-9. `_check_constants()` 在导入期检查列块整除、归约步数、若干地址区域的容量及相邻区域关系、MX 地址配对、跨核事件编号和预载 mutex 编号。检查通过不表示运行期输入内容已被逐项验证;这些检查通过 `RuntimeError` 保持在 `python -O` 下有效。
141-10. 调用方不需把 T 补为 128 的倍数。普通路径的 `ws_rows=T`;启用归约维二分时工作区为两个 `ceil(T/128)*128` 行带。Cube 在片上使用固定矩阵窗口,GM 读取、工作区写入、Q 存储与 cache 索引访问分别按逻辑行数限制;Q 的无效 AIV 半区仍参与必要事件握手。
142- 
143-## 调用示例
144- 
145-以下假设全部输入已按参数表准备并位于同一 NPU,FP8 字节已恢复为相应 dtype:
146- 
147-```python
148-import sys
149- 
150-sys.path.insert(0, "ops/pypto_pro/deepseek_v4_1/attn_prologue/op_kernel")
151-from attn_prologue import attn_prologue, to_nz
152- 
153-# 权重加载期执行一次,后续调用复用 NZ 权重。
154-wqa, wqb, wkv = to_nz(wqa), to_nz(wqb), to_nz(wkv)
155-q, qr, descale_qr = attn_prologue(
156- x, wqa, wqb, wkv,
157- descale_x, descale_wqa, descale_wqb, descale_wkv,
158- norm_weight_qr, norm_weight_kv,
159- rope_sin, rope_cos, cache_index, kv_cache,
160- norm_eps=1e-6,
161-)
162-```
163- 
164-运行测试时在仓库根目录加载 CANN 与 PyPTO 环境。CLI 的 `--device` 优先于 `TILE_FWK_DEVICE_ID`,环境变量未设置时使用逻辑设备 0:
165- 
166-```bash
167-D=ops/pypto_pro/deepseek_v4_1/attn_prologue
168- 
169-# 两种几何的 CPU 参考实现自检,不使用 NPU。
170-python $D/tests/assets/attn_prologue_golden_cpu.py
171-# 两组 CPU 比较器自检,内部共 12 个检查场景。
172-python $D/tests/assets/attn_prologue_precision.py
173- 
174-# 完整的 32 个设备场景,或按 T 选取子集;--t 可重复,不能传逗号列表。
175-TILE_FWK_DEVICE_ID=1 python $D/tests/test_attn_prologue.py
176-python $D/tests/test_attn_prologue.py --device 1 --t 1 --t 72 --t 1024
177-python $D/tests/test_attn_prologue.py --list
178- 
179-# pytest 收集 4 个设备冒烟项和 2 个 CPU 判据项,并非完整的 32 场景。
180-pytest $D/tests -q
181-```
182- 
183-`--list` 在加载 NPU wrapper 前输出所选场景 JSON;也可使用 `--phase`、`--case-id` 和 `--unique-t` 筛选。`expected_template` 是参考用例记录的历史标签,不是 kernel 的实际分支判定,实际调度需看 T 和平台核数。
184- 
185-精度入口每完成一个 case 就更新 `--out` 指定的 JSON,默认 `tests/reports/pro_pypto/validation.json`;`--row-chunk` 控制 CPU 分块比较,默认 256,`--norm-eps` 同时用于设备调用与参考计算。当前入口没有性能采样选项,历史 msprof 口径与结果见 [RESULTS.md](RESULTS.md)。
@@ -1,297 +0,0 @@
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/pypto_pro/deepseek_v4_1/attn_prologue
28- python $D/tests/test_attn_prologue.py # 全 32 case 精度(默认 1 卡)
29- python $D/tests/test_attn_prologue.py --t 1,72,1024 # 子集
30- python $D/tests/test_attn_prologue.py --case-id decode-b12-s6-t72
31- python $D/tests/test_attn_prologue.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 json
42-import logging
43-import os
44-import sys
45-import time
46-from pathlib import Path
47- 
48-import torch
49- 
50-HERE = Path(__file__).resolve().parent
51-OP_ROOT = HERE.parent
52-for _p in (str(HERE), str(HERE / "assets"), str(OP_ROOT / "op_kernel")):
53- if _p not in sys.path:
54- sys.path.insert(0, _p)
55- 
56-import attn_prologue_golden_cpu as golden # noqa: E402
57-import attn_prologue_precision as verify # noqa: E402
58- 
59-LOG = logging.getLogger("attn_prologue.test")
60- 
61-_FRACTAL_NZ = 29
62-_E4M3 = torch.float8_e4m3fn
63-_E8M0 = torch.float8_e8m0fnu
64-_WEIGHT_FIELDS = ("wqa", "wqb", "wkv", "descale_wqa", "descale_wqb", "descale_wkv",
65- "norm_weight_qr", "norm_weight_kv")
66-_PER_TOKEN_FIELDS = ("x", "descale_x", "rope_sin", "rope_cos", "cache_index")
67- 
68- 
69-def _default_device() -> str:
70- return os.environ.get("TILE_FWK_DEVICE_ID", "0")
71- 
72- 
73-def _resolve_device(spec: str) -> str:
74- LOG.info("============ device: %s", spec)
75- if spec.startswith("npu"):
76- return spec
77- return f"npu:{spec}"
78- 
79- 
80-def _to_nz(weight: torch.Tensor) -> torch.Tensor:
81- import torch_npu # noqa: F401
82- 
83- return torch_npu.npu_format_cast(weight.contiguous(), _FRACTAL_NZ)
84- 
85- 
86-def _device_input(name, value, device, to_nz):
87- """Move one ND fixture to the public API, preserving encoded FP8 bytes.
88- 
89- FP8/E8M0 carriers are reinterpreted (view), never numerically cast; only the
90- three weights go through ``to_nz``. Non-FP8 fields are a plain ``.to``.
91- """
92- weights = ("wqa", "wqb", "wkv")
93- if name in ("x",) + weights:
94- dtype = _E4M3
95- elif name in ("descale_x", "descale_wqa", "descale_wqb", "descale_wkv"):
96- dtype = _E8M0
97- else:
98- return value.to(device)
99- if value.dtype not in (torch.int8, torch.uint8, dtype):
100- raise TypeError(f"{name} must contain encoded {dtype} bytes, got {value.dtype}")
101- payload = value.contiguous().view(torch.int8).to(device)
102- if name in weights:
103- payload = to_nz(payload)
104- return payload.view(dtype)
105- 
106- 
107-class DeviceWeights:
108- """Cache the NZ-converted / device-moved weight fields per device."""
109- 
110- def __init__(self, weights: golden.SharedWeights, device: str):
111- self._fields = {
112- name: _device_input(name, value, device, _to_nz)
113- for name, value in weights.fields.items()
114- }
115- 
116- def as_dict(self):
117- return dict(self._fields)
118- 
119- 
120-def _load_wrapper():
121- """Lazily import the Pro public wrapper (keeps CPU collection NPU-free)."""
122- import torch_npu # noqa: F401
123- from attn_prologue import attn_prologue # op_kernel on sys.path
124- 
125- return attn_prologue
126- 
127- 
128-def _run_case(case, device, weights, shadow, wrapper, dev_weights, *,
129- row_chunk=256, norm_eps=1e-6):
130- inputs = golden.make_case_inputs(case, weights)
131- cache = inputs.kv_cache.to(device)
132- values = dev_weights.as_dict()
133- for name in _PER_TOKEN_FIELDS:
134- values[name] = _device_input(name, getattr(inputs, name), device, _to_nz)
135- values["kv_cache"] = cache
136- q, qr, descale_qr = wrapper(
137- values["x"], values["wqa"], values["wqb"], values["wkv"],
138- values["descale_x"], values["descale_wqa"], values["descale_wqb"],
139- values["descale_wkv"], values["norm_weight_qr"], values["norm_weight_kv"],
140- values["rope_sin"], values["rope_cos"], values["cache_index"], cache,
141- norm_eps=norm_eps,
142- )
143- torch.npu.synchronize()
144- outputs = (q, qr, descale_qr)
145- t0 = time.time()
146- stats = verify.validate_outputs(
147- inputs, weights, outputs, cache,
148- row_chunk=row_chunk, shadow=shadow, norm_eps=norm_eps,
149- )
150- elapsed = time.time() - t0
151- record = dict(
152- **case.record(),
153- reference_norm_eps=norm_eps, row_chunk=row_chunk,
154- compare_elapsed_s=round(elapsed, 3), **stats.output(),
155- )
156- # free device tensors before the next case
157- del q, qr, descale_qr, outputs, cache, values
158- gc.collect()
159- try:
160- torch.npu.empty_cache()
161- except Exception: # noqa: BLE001
162- pass
163- return record
164- 
165- 
166-def _select_cases(args):
167- cases = golden.all_cases()
168- if args.phase != "all":
169- cases = [c for c in cases if c.phase == args.phase]
170- if args.case_id:
171- want = set(args.case_id)
172- cases = [c for c in cases if c.case_id in want]
173- if args.t:
174- want_t = set(args.t)
175- cases = [c for c in cases if c.token_count in want_t]
176- if args.unique_t:
177- seen, kept = set(), []
178- for c in cases:
179- if c.token_count in seen:
180- continue
181- seen.add(c.token_count)
182- kept.append(c)
183- cases = kept
184- return cases
185- 
186- 
187-def main(argv=None):
188- parser = argparse.ArgumentParser(description="attn_prologue Pro accuracy/perf entry")
189- parser.add_argument("--phase", choices=["all", "decode", "prefill"], default="all")
190- parser.add_argument("--case-id", action="append")
191- parser.add_argument("--t", type=int, action="append")
192- parser.add_argument("--unique-t", action="store_true")
193- parser.add_argument("--device", default=_default_device())
194- parser.add_argument("--row-chunk", type=int, default=256)
195- parser.add_argument("--norm-eps", type=float, default=1e-6)
196- parser.add_argument("--out", default=str(OP_ROOT / "tests" / "reports" / "pro_pypto" / "validation.json"))
197- parser.add_argument("--list", action="store_true")
198- parser.add_argument("--cpu-threads", type=int, default=min(16, os.cpu_count() or 4))
199- args = parser.parse_args(argv)
200- 
201- # handler 指向 stdout:--list 的 JSON 契约走 stdout,且满足 G.LOG.02(统一用 logging)
202- logging.basicConfig(level=logging.INFO, format="%(message)s", stream=sys.stdout)
203- cases = _select_cases(args)
204- if args.list:
205- LOG.info(json.dumps([c.record() for c in cases], indent=2))
206- return 0
207- if not cases:
208- LOG.error("no cases selected")
209- return 2
210- 
211- device = _resolve_device(args.device)
212- torch.set_num_threads(args.cpu_threads)
213- wrapper = _load_wrapper()
214- import torch_npu # noqa: F401
215- 
216- torch.npu.set_device(device)
217- weights = golden.SharedWeights()
218- shadow = verify.FP64Shadow(weights)
219- dev_weights = DeviceWeights(weights, device)
220- 
221- out_path = Path(args.out)
222- out_path.parent.mkdir(parents=True, exist_ok=True)
223- results, all_pass = [], True
224- for idx, case in enumerate(cases, 1):
225- LOG.info("[%d/%d] RUN %s (T=%d, %s)", idx, len(cases), case.case_id, case.token_count, device)
226- LOG.info("%s", case)
227- try:
228- rec = _run_case(case, device, weights, shadow, wrapper, dev_weights,
229- row_chunk=args.row_chunk, norm_eps=args.norm_eps)
230- except Exception as exc: # noqa: BLE001
231- rec = dict(**case.record(), passed=False,
232- error=f"{type(exc).__name__}: {exc}")
233- LOG.exception("case %s raised", case.case_id)
234- ok = bool(rec.get("passed"))
235- all_pass = all_pass and ok
236- results.append(rec)
237- LOG.info(" -> %s q_bad_rate=%s qr_hard=%s kv_hard=%s untouched_bad=%s",
238- "PASS" if ok else "FAIL", rec.get("q_bad_rate"), rec.get("qr_hard"),
239- rec.get("kv_hard"), rec.get("untouched_bad"))
240- out_path.write_text(json.dumps(
241- {"operator": "attn_prologue", "device": device,
242- "case_count": len(results), "all_passed": all_pass, "cases": results},
243- indent=2))
244- LOG.info("=" * 60)
245- LOG.info("%d/%d cases passed", sum(1 for r in results if r.get("passed")), len(results))
246- LOG.info("report: %s", out_path)
247- return 0 if all_pass else 1
248- 
249- 
250-# ---------------------------------------------------------------------------
251-# pytest smoke path (CPU collection stays NPU-free)
252-# ---------------------------------------------------------------------------
253-try:
254- import pytest
255- 
256- pytestmark = pytest.mark.soc("950")
257- _SMOKE = ["decode-b1-s1-t1", "decode-b12-s6-t72", "prefill-b1-s1024-t1024",
258- "prefill-b1-s2048-t2048"]
259- 
260- @pytest.fixture(scope="module")
261- def runtime():
262- device = _resolve_device(_default_device())
263- wrapper = _load_wrapper()
264- import torch_npu # noqa: F401
265- 
266- torch.npu.set_device(device)
267- weights = golden.SharedWeights()
268- shadow = verify.FP64Shadow(weights)
269- dev_weights = DeviceWeights(weights, device)
270- yield device, wrapper, weights, shadow, dev_weights
271- gc.collect()
272- try:
273- torch.npu.empty_cache()
274- except Exception: # noqa: BLE001
275- pass
276- 
277- @pytest.mark.npu
278- @pytest.mark.parametrize("case_id", _SMOKE)
279- def test_attn_prologue_accuracy(case_id, runtime):
280- device, wrapper, weights, shadow, dev_weights = runtime
281- case = next(c for c in golden.all_cases() if c.case_id == case_id)
282- rec = _run_case(case, device, weights, shadow, wrapper, dev_weights)
283- assert rec["case_id"] == case_id
284- assert rec.get("passed"), rec
285- 
286- def test_fp8_value_criterion():
287- verify.test_fp8_value_criterion()
288- 
289- def test_full_output_validator():
290- verify.test_full_output_validator()
291- 
292-except ImportError: # pragma: no cover - pytest optional
293- pass
294- 
295- 
296-if __name__ == "__main__":
297- raise SystemExit(main())
@@ -1,75 +0,0 @@
1-# CompressorV2 设计说明
2- 
3-## 计算阶段划分
4- 
5-FP16 和 BF16 共用计算流程,矩阵乘以 FP32 累加,按输入类型转换输出。入口先检查输入并分配输出,再选择通用路径或片上路径;总 token 数为 `0` 时直接返回输出。
6- 
7-| 路径与阶段 | 主要工作 | 中间结果 |
8-| :--- | :--- | :--- |
9-| 通用路径,`Stage=0` | Cube 计算 KV 和分数投影;Vector 读取首组需要的调用前历史状态。 | FP32 投影工作区和历史快照。 |
10-| 通用路径,`Stage=1` | 合并 H 分区的部分和,拼接历史前缀,按组执行 softmax 加权,写出输出并更新缓存。 | 与输入同类型的输出及更新后的 FP32 缓存。 |
11-| 片上路径,`Stage=2` | Cube 将两路投影直接交给两个 Vector 子核,完成压缩与缓存写回。 | 投影无需独立的全局内存工作区。 |
12- 
13-两路投影分别为 `K = X @ wkv.T`、`G = X @ wgate.T`。每个长度为 `r = cmp_ratio` 的完整组,先求各通道的最大分数,再计算 `exp(G - max(G))`、加权和与归一化。计算加权分子前将 KV 乘以 `1 / r`,归一化后乘回 `r`。这些向量运算均使用 FP32,最后按最近值、中点取偶数转换为输入类型。
14- 
15-通用路径中的历史快照在缓存写回前完成,首组只从快照读取调用前的历史,避免长序列环形写回覆盖仍需使用的槽位。仅完整压缩组产生有效输出;缓存写回独立保留本次输入最后 `min(L_b, block_size)` 个 token 的投影。
16- 
17-## 核间切分策略
18- 
19-通用投影按“投影种类、H 分区、token 行块、输出通道块”分配工作项,Cube 核以核号为起点、核数为步长领取任务。若共享激活后工作项仍足以覆盖 Cube 核,则同一激活块先后用于 KV 和分数投影。
20- 
21-工作项较少且 H 足够大时,可沿 H 切为 `2` 至 `4` 个分区,每个分区的边界按装入面板宽度对齐。各分区分别写出 FP32 部分和,Vector 按分区顺序相加后再用于输出或缓存,不使用原子加法。分区选择依据工作轮数与搬运量估算,只有估算代价低于原路径的 `80%` 才启用。
22- 
23-历史快照按序列和 `64` 个缓存通道切分。分组压缩按压缩组与 `64` 个输出通道切分;固定长度布局且 `S <= 128` 时,先按序列和通道分配。缓存写回按投影种类和通道分配;工作项及核数满足条件时,使用压缩任务之外的 Vector 核。
24- 
25-片上路径按“token 行块、输出通道块”切分。每个 Cube 的 KV、分数累加结果经 `DualModeSplitM` 分成互不重叠的两个行半块,分别交给两个 Vector 子核。每个子核对其行半块独立完成压缩与缓存写回。
26- 
27-## 核内切分策略、基本块选择与核内 Buffer 划分
28- 
29-通用投影的列块宽度在总 token 数 `T <= 128` 时取 `64`,否则取 `128`;行块容量从 `16、32、64、96、128` 中按 Cube 核数及列块数选择。H 分区路径固定使用 `256 × 64` 输出块,并共享两路投影的激活。每次装入的 H 宽度为 `256` 或 `512`,矩阵乘的 H 方向步长为 `64` 或 `128`。
30- 
31-片上路径仅用于单序列且未显式提供 `seqused` 和 `start_pos` 的输入,从 `(行数, 列数) = (256, 128)、(128, 128)、(64, 64)、(32, 64)` 中选择。`T` 必须是行块大小的整数倍,每个行半块至少包含一个完整压缩组。行数为 `256` 时,缓存块大小还须为 `128` 的整数倍;其他候选可处理未对齐的缓存写回。
32- 
33-下表列出源码显式申请的片上 Buffer。`M`、`N` 为行、列块容量,`F` 表示是否共享两路投影的激活,取 `0` 或 `1`;`P` 为装入的 H 面板宽度,`Q` 为矩阵乘的 H 方向步长,`Parts` 为 H 分区数。Mat、Left、Right、Acc、Vec 分别对应 L1、L0A、L0B、L0C 和向量缓冲区 UB,各存储空间分别计量。Vec 容量按单个 Vector 核列出;两槽表示两块相同大小的 Buffer 交替使用,`1 KiB = 1024` 字节。
34- 
35-| 阶段 | Buffer 形状、类型及槽数 | 显式容量 |
36-| :--- | :--- | :--- |
37-| `Stage=0` 投影 | Mat:激活 `M × P`,权重共 `1 + F` 份 `N × P`,FP16 或 BF16,两槽 | `4P[M + (1 + F)N]` 字节 |
38-| `Stage=0` 投影 | Left:`M × Q`;Right:`Q × N`;均与输入同类型、两槽 | 依次为 `4MQ`、`4QN` 字节 |
39-| `Stage=0` 投影 | Acc:`M × N`,FP32,两槽 | `8MN` 字节 |
40-| `Stage=0` 历史快照 | Vec:`r × 64`,FP32,单槽 | `256r` 字节 |
41-| `Stage=1` 压缩与缓存更新 | Vec:KV、分数、临时块各 `128 × 64`,FP32;另有 `max(1, Parts - 1)` 个同形状部分和槽;输出 `(128 / r) × 64`,与输入同类型 | `98304 + 32768 × max(1, Parts - 1) + 16384 / r` 字节 |
42-| `Stage=2` 投影 | Mat:激活 `M × 256`、两路权重各 `N × 256`,与输入同类型,两槽 | `1024(M + 2N)` 字节 |
43-| `Stage=2` 投影 | Left:`M × Q`;Right:`Q × N`;均与输入同类型、两槽;Acc:`M × N`,FP32,两槽 | 依次为 `4MQ`、`4QN`、`8MN` 字节 |
44-| `Stage=2` 压缩,每个 Vector 子核 | Vec:两路投影各 `(M / 2) × N`,FP32;输出 `(M / (2r)) × N`,与输入同类型 | `4MN + MN / r` 字节 |
45-| `Stage=2` 非直接缓存写回 | Vec:额外两块 `(M / 2) × N`,FP32,单槽 | 在上一行基础上增加 `4MN` 字节 |
46- 
47-`Stage=0` 的 `P` 在共享激活或 `M=256` 时取 `256`,其他情况取 `512`;`Q` 在 `M=256` 时取 `64`,其他情况取 `128`。`Stage=2` 同样按 `M` 选择 `Q`。`M=256` 的片上路径满足缓存对齐条件,使用直接写回,无需额外缓存临时块。
48- 
49-通用路径另分配 FP32 投影 `[Parts, 2, T, D]` 和历史 `[B, r, 2D]` 工作区,分别占 `8 × Parts × T × D`、`8BrD` 字节;投影第二轴依次为 KV 和分数。片上路径无需这两块独立工作区。输出单独分配,元素类型与输入相同。以上容量由源码的形状、槽数和地址计算,不代表编译后的资源占用或硬件利用率。
50- 
51-## 接口选择
52- 
53-| 接口 | 用途 |
54-| :--- | :--- |
55-| `@pl.jit(auto_mutex=True, tiling_key=CompressorKey)` | 为三个独立阶段入口按数据类型、压缩率和分块参数编译计算变体,自动管理带显式 mutex ID 的 Buffer 槽位。 |
56-| `pl.make_tuple` | 将同一阶段的张量和 Buffer 组织为带字段名称的组合,供辅助函数使用。 |
57-| `pl.make_tile_group`、`pl.set_validshape` | 申请 Buffer 并限制末块的有效范围。 |
58-| `pl.matmul`、`pl.matmul_acc` | 初始化矩阵乘结果,并沿 H 累加 FP32 投影。 |
59-| `pl.reinterpret`、`pl.move` | 组织权重面板布局,将输入和权重搬入矩阵乘缓冲区。 |
60-| `pl.vector_function` 与 `vf` 接口 | 完成部分和合并、历史拼接、最大值、指数、归一化和输出转换。 |
61-| `pl.load`、`pl.store` | 读写投影与历史工作区,写出有效输出并更新缓存。 |
62-| `pl.move(..., acc_to_vec_mode=DualModeSplitM)` | 将 Cube 累加结果按行交给两个 Vector 子核。 |
63-| `pl.system.set_cross_core`、`pl.system.wait_cross_core` | 在 Cube 与 Vector 间通知投影就绪和共享 Buffer 释放。 |
64- 
65-投影与历史快照、分组压缩与缓存写回、片上融合分别使用独立的 JIT 入口,各入口只接收该阶段所需的设备指针。主机侧将张量形状、缓存步长和可选元数据是否存在组织为不可变配置,并据此复用相应入口实例。
66- 
67-分块选择只读取形状、数据类型、可选参数是否存在及平台核数。BSH 的固定序列长度来自形状配置;TH 的序列边界、调用方提供的 `seqused` 和 `start_pos` 数值,以及缓存物理块号,由 kernel 读取设备侧元数据张量。
68- 
69-## 流水设计
70- 
71-通用路径先完成 `Stage=0` 的全部投影和历史快照,再启动 `Stage=1`。矩阵乘沿 H 使用两槽输入与权重 Buffer;共享激活时,KV 和分数投影复用同一份 L0A 片段。各 H 分区的结果写入独立工作区,压缩和缓存写回前再合并。
72- 
73-片上路径中,Cube 计算当前工作项的两路投影后,等待上一工作项的 Vector 释放共享区,再将累加结果按行半块搬入 UB。就绪事件使用 `event_id=0`,由 FIX 流水通知 Vector 的 V 流水;Vector 接收后完成加权输出及缓存写回。
74- 
75-缓存块大小是行半块大小的整数倍时,直接从投影 Buffer 写回缓存,由 MTE3 在搬出完成后发送 `event_id=1` 释放事件。否则先复制到独立缓存临时块,再按环形边界分段写回,由 V 流水在共享区最后一次读取完成后发送释放事件。下一工作项只有收到释放事件后才能覆盖共享区;循环结束时,Cube 等待最后一次释放完成收尾。
@@ -1,112 +0,0 @@
1-# CompressorV2(PyPTO-Pro)
2- 
3-## 产品支持情况
4- 
5-本实现面向 Ascend 950PR,使用矩阵计算单元(Cube)与向量计算单元(Vector)协同执行。启动核数从平台信息读取,调用前需配置匹配的 CANN、PyPTO-Pro 和 torch_npu 运行环境。
6- 
7-## 功能说明
8- 
9-CompressorV2 将连续若干个 token 的投影结果压缩为一个向量,并原位更新历史状态缓存。记输入特征宽度为 `H`、输出特征宽度为 `D`、压缩率为 `r = cmp_ratio`。每个 token 先计算两路投影:
10- 
11-```text
12-K = X @ wkv.T
13-G = X @ wgate.T
14-```
15- 
16-两路权重均按 `[D, H]` 存储。FP16 和 BF16 输入直接参与矩阵乘,投影以 FP32 累加;沿 H 分区计算时,各分区的 FP32 部分和先合并,再用于压缩与缓存更新。
17- 
18-随后按绝对位置划分长度为 `r` 的组,在每个通道内沿 token 轴进行 softmax 加权:
19- 
20-```text
21-m[d] = max_i G[i, d]
22-a[i, d] = exp(G[i, d] - m[d])
23-Y[d] = sum_i(a[i, d] * K[i, d]) / sum_i a[i, d]
24-```
25- 
26-`i` 遍历一个完整组内的 `r` 个 token。实现先将 KV 乘以 `1 / r`,加权归一化后再乘回 `r`;指数、加权累加和除法均使用 FP32。输出转换为与 `x` 相同的类型,舍入到最近的可表示值,中点取偶数。
27- 
28-`start_pos[b]` 为第 `b` 条序列本次调用的绝对起点。若起点未对齐组边界,首组先从调用前缓存读取 `start_pos[b] % r` 个历史 token,再拼接本次新输入。仅完整组产生有效输出;末尾不足一组不产生有效输出,其投影仍参与缓存更新。
29- 
30-缓存采用环形寻址:第 `b` 条序列使用物理块 `state_block_table[b]`,绝对位置 `p` 对应槽位 `p % block_size`。前 `D` 个通道保存 `K`,后 `D` 个通道保存 `G`。每条序列仅写入本次最后 `min(L_b, block_size)` 个 token 的投影,`L_b` 为实际参与计算的新输入长度;其余槽位及未使用的物理块保持原值。
31- 
32-## 函数原型
33- 
34-公开入口位于 `op_kernel/compressor_v2.py`,同一模块包含 kernel、输入校验、输出分配和启动逻辑:
35- 
36-```python
37-def compressor(
38- x, wkv, wgate, state_cache, cmp_ratio=4, *,
39- state_block_table=None, cu_seqlens=None,
40- seqused=None, start_pos=None,
41-):
42- ...
43-```
44- 
45-`state_block_table`、`cu_seqlens`、`seqused` 和 `start_pos` 只能按关键字传入。
46- 
47-### 参数说明
48- 
49-| 参数 | 类型与形状 | 说明 |
50-| :--- | :--- | :--- |
51-| `x` | FP16 或 BF16,`[B, S, H]` 或 `[T, H]` | 输入激活。`B` 为序列数,`S` 为每条序列本次输入长度,`T` 为所有序列本次输入长度之和。 |
52-| `wkv` | 与 `x` 同类型,`[D, H]` | KV 投影权重。 |
53-| `wgate` | 与 `x` 同类型,`[D, H]` | softmax 分数的投影权重。 |
54-| `state_cache` | FP32,`[block_count, block_size, 2 * D]` | 可读写的历史状态,调用时原位更新。 |
55-| `cmp_ratio` | 整数,默认 `4` | 一个完整压缩组包含的 token 数。 |
56-| `state_block_table` | INT32,`[B]` | 序列到缓存物理块的映射,必须显式传入。 |
57-| `cu_seqlens` | INT32,`[B + 1]` 或 `None` | `[T, H]` 输入必填的序列长度前缀和;`[B, S, H]` 输入必须为 `None`。 |
58-| `seqused` | INT32,`[B]` 或 `None` | 各序列实际参与压缩和缓存更新的新输入 token 数;默认使用各序列完整长度。 |
59-| `start_pos` | INT32,`[B]` 或 `None` | 各序列非负的绝对起点,默认全为 `0`。 |
60- 
61-### 返回值说明
62- 
63-返回一个连续输出张量 `out`,设备与数据类型均与 `x` 相同:
64- 
65-| 输入布局 | 输出分配形状 |
66-| :--- | :--- |
67-| `[B, S, H]` | `[B, ceil(S / r), D]` |
68-| `[T, H]` | `[min(T, T // r + B), D]` |
69- 
70-对第 `b` 条序列,提供 `seqused` 时取 `L_b = seqused[b]`,否则取该序列完整长度。当 `L_b > 0` 时,有效输出组数为 `(start_pos[b] % r + L_b) // r`;当 `L_b = 0` 时为 `0`。省略 `start_pos` 时按 `0` 计算。
71- 
72-`[B, S, H]` 布局中,每条序列的有效结果从该序列输出区域首行开始;`[T, H]` 布局中,各序列有效结果按序列顺序紧密排列。分配容量中未使用行的数值不作规定,调用方应按有效组数读取结果。`state_cache` 的更新通过传入张量体现,不另行返回。
73- 
74-## 约束说明
75- 
76-- `H` 在 `[1024, 10240]` 内且为 `512` 的整数倍;`D` 为 `128` 或 `512`。
77-- `cmp_ratio` 为 `2、4、8、16、32、64、128` 之一。
78-- `block_count > 0`,`1 <= block_size <= 1024`。缓存最后两轴连续,第 `0` 轴步长不得小于 `block_size * 2 * D`,允许块间留有间隔。
79-- 所有张量位于同一个 NPU。除缓存第 `0` 轴外,各输入必须连续。
80-- `state_cache` 的可写区域不得与 `x`、`wkv`、`wgate` 或任一元数据张量的存储区域重叠;这些只读输入之间允许共享数据。
81-- `state_block_table` 的块号互不相同,且满足 `0 <= block_id < block_count`;块号 `0` 为有效物理块。
82-- `cu_seqlens` 单调不减,首元素为 `0`,末元素为 `T`。`seqused[b]` 在 `0` 到第 `b` 条序列实际长度之间。
83-- `start_pos` 非负。首次使用历史 token 前,调用方需保证对应缓存槽位包含所需状态。若环形容量不足以保留全部历史,首组读取的是传入槽位当前实际保存的值。
84-- 输入校验检查形状、类型、步长和设备;设备侧元数据的数值约束及存储不重叠约束由调用方保证。`B`、`S` 或 `T` 可以为 `0`,总 token 数为 `0` 时不启动 kernel。
85- 
86-## 调用示例
87- 
88-在算子目录已加入 Python 模块搜索路径的环境中,可按以下方式调用:
89- 
90-```python
91-import torch
92-import torch_npu # noqa: F401
93- 
94-from op_kernel.compressor_v2 import compressor
95- 
96-batch, sequence, hidden, dim = 1, 128, 1024, 128
97-device = "npu"
98-dtype = torch.bfloat16
99-x = torch.randn(batch, sequence, hidden, device=device, dtype=dtype)
100-wkv = torch.randn(dim, hidden, device=device, dtype=dtype)
101-wgate = torch.randn(dim, hidden, device=device, dtype=dtype)
102-state_cache = torch.zeros(2, 128, 2 * dim, device=device, dtype=torch.float32)
103-state_block_table = torch.tensor([1], device=device, dtype=torch.int32)
104- 
105-out = compressor(
106- x, wkv, wgate, state_cache,
107- cmp_ratio=4,
108- state_block_table=state_block_table,
109-)
110-torch.npu.synchronize()
111-assert out.shape == (1, 32, 128)
112-```
@@ -1,114 +0,0 @@
1-# CompressorV2 结果说明
2- 
3-## 用例
4- 
5-`tests/test_compressor_v2.py` 采用 AscendC CompressorV2 单用例入口默认启用的 20 组参数,将不同起点展开为 25 个用例。输入激活与两路权重均为 BF16,特征宽度 `H=4096`;历史缓存为 FP32。输入激活、权重和历史缓存均按默认参数的 `[-10, 10]` 范围均匀采样,激活和权重随后转换为 BF16。
6- 
7-表中 `B × S` 表示序列数与每条序列的 token 数。BSH 输入形状为 `[B, S, 4096]`,TH 输入形状为 `[B × S, 4096]`;`D` 为输出特征宽度,`r` 为压缩率。各序列使用表中相同的起点,`seqused=None`,使用完整序列长度;TH 的 `cu_seqlens` 为 `[0, S, 2S, ..., B × S]`。
8- 
9-缓存形状为 `[B, block_size, 2D]`,后两轴连续。缓存配置中的 `pad` 表示块步长额外增加的 FP32 元素数,`offset` 表示缓存起始位置相对分配区的 FP32 元素偏移,块步长为 `block_size × 2D + pad`。`Contiguous0` 使用连续缓存;其余用例保留带填充的块步长配置。
10- 
11-| 用例 | 布局;B × S | D / r | block_size | 起点 | 有效组总数 | 缓存 pad / offset |
12-| :--- | :--- | :--- | ---: | ---: | ---: | :--- |
13-| `Prefill0` | TH 1 × 8192 | 512 / 4 | 128 | 0 | 2048 | 14 / 6 |
14-| `Prefill1` | TH 1 × 8192 | 128 / 4 | 128 | 0 | 2048 | 16 / 6 |
15-| `Prefill2` | TH 1 × 8192 | 512 / 128 | 128 | 0 | 64 | 5 / 1 |
16-| `decode0_start8192` | TH 1 × 1 | 512 / 4 | 128 | 8192 | 0 | 38 / 20 |
17-| `decode0_start8195` | TH 1 × 1 | 512 / 4 | 128 | 8195 | 1 | 16 / 6 |
18-| `decode1_start8192` | TH 1 × 1 | 128 / 4 | 128 | 8192 | 0 | 23 / 0 |
19-| `decode1_start8195` | TH 1 × 1 | 128 / 4 | 128 | 8195 | 1 | 49 / 24 |
20-| `decode2_start8192` | TH 1 × 1 | 512 / 128 | 128 | 8192 | 0 | 24 / 17 |
21-| `decode2_start8195` | TH 1 × 1 | 512 / 128 | 128 | 8195 | 0 | 26 / 18 |
22-| `decode3_start8193` | TH 8 × 3 | 512 / 4 | 128 | 8193 | 8 | 10 / 0 |
23-| `decode4_start8192` | TH 8 × 3 | 128 / 4 | 128 | 8192 | 0 | 35 / 25 |
24-| `decode4_start8193` | TH 8 × 3 | 128 / 4 | 128 | 8193 | 8 | 35 / 24 |
25-| `decode4_start8191` | TH 8 × 3 | 128 / 4 | 128 | 8191 | 8 | 11 / 6 |
26-| `decode5_start8193` | TH 8 × 3 | 512 / 128 | 128 | 8193 | 0 | 5 / 1 |
27-| `FullLoad0` | BSH 1 × 4 | 512 / 4 | 128 | 0 | 1 | 31 / 8 |
28-| `FullLoad1` | BSH 1 × 4 | 128 / 4 | 128 | 0 | 1 | 29 / 0 |
29-| `FullLoad2` | BSH 1 × 4 | 512 / 128 | 131 | 0 | 0 | 3 / 0 |
30-| `FullLoad3` | BSH 64 × 4 | 512 / 4 | 128 | 0 | 64 | 18 / 11 |
31-| `FullLoad4` | BSH 64 × 4 | 128 / 4 | 128 | 0 | 64 | 38 / 31 |
32-| `FullLoad5` | BSH 8 × 2 | 512 / 4 | 128 | 0 | 0 | 47 / 11 |
33-| `FullLoad6` | BSH 1 × 1 | 512 / 4 | 128 | 100 | 0 | 23 / 2 |
34-| `FullLoad7` | BSH 1 × 1 | 128 / 4 | 128 | 100 | 0 | 21 / 12 |
35-| `FullLoad8` | BSH 1 × 1 | 512 / 128 | 128 | 100 | 0 | 22 / 14 |
36-| `Contiguous0` | TH 2 × 3 | 512 / 4 | 128 | 8193 | 2 | 0 / 0 |
37-| `NonContiguous0` | TH 2 × 3 | 512 / 4 | 128 | 8193 | 2 | 36 / 4 |
38- 
39-随机数据由固定的 CPU 生成器产生。按表中顺序编号 `i=1,...,25`,种子为 `2026102800 + i`;物理块映射与缓存视图参数也固定在测试文件中。表中 11 个用例尚未组成完整压缩组,有效组数为 0,但仍执行投影、缓存更新及缓存检查。
40- 
41-## 精度标准
42- 
43-参考计算位于 `tests/assets/compressor_v2_golden_cpu.py`:读取已经量化为 BF16 的输入和权重,在 CPU 上以 FP64 计算投影、历史拼接和压缩;有效压缩输出转为 BF16,更新缓存转为 FP32。
44- 
45-数值判据采用 [AscendC CompressorV2 默认单用例测试](https://gitcode.com/cann/ops-transformer/blob/master/experimental/attention/compressor_v2/tests/pytest/compressor_golden.py) 的 `check_result`。按该测试的调用方式,有效输出、KV 缓存更新区和分数缓存更新区都先转为 FP32 比较,并使用输出类型 BF16 选择容差:
46- 
47-| 检查项 | 通过条件 |
48-| :--- | :--- |
49-| 元素匹配率 | 至少 99.5% 的元素满足 `abs(actual-expected) <= 0.0001 + 0.0078125*abs(expected)` |
50-| 不匹配元素的归一化误差 | 先令 `b=max(abs(actual),abs(expected),2^-14/0.005)+1e-9`,再要求 `abs(actual-expected)/(b+1e-9)` 小于 10 |
51- 
52-第二项沿用官方函数检查前一千万个不匹配元素的规则;本组各比较区域的总元素数均小于一千万。NaN、Inf 的数值处理也保留该函数原有规则,不增加其他误差门槛。
53- 
54-数值检查覆盖全部有效输出及两个缓存更新区域。未更新缓存要求逐位不变,缓存视图以外的分配保护区保持原值;输出还检查形状、类型和连续布局。25 例测试全部通过,0 失败、0 错误、0 跳过;有有效输出的用例还验证整片有效输出损坏后比较器会拒绝。性能采集的两种实现各 575 次调用(每例 3 次预热和 20 次计量)均通过同一数值判据及缓存保护检查。
55- 
56-## 性能结果
57- 
58-> **采集机器**:本节全部耗时、带宽与占用率数据均在本机 `Ascend950PR_9589`(32 AI Core,32 Cube / 64 Vector,L2 128 MiB)上采集。
59- 
60-采集设备为 Ascend 950PR_9589(32 个 Cube 核、64 个 Vector 核),使用物理 0 号卡。软件为 PyPTO 0.3.0、PyTorch 2.8.0+cpu、torch_npu 2.8.0.post4;msprof 来自 CANN Toolkit 9.3.0 安装目录。采集时记录设备上的其他上下文,以下结果适用于该次共享卡测量条件。
61- 
62-双方使用相同输入与独立的初始缓存。采用 cann-bench 的预热算子,并在每次调用前执行 `CannBenchCacheClean`,读取 `[96,1024,1024]` FP16 缓冲区(192 MiB)后同步完成。双方交替先后顺序,每例各预热 3 次,再各采集 20 次,共 20 对计量样本。
63- 
64-采集遵循 [msprof AI 任务采集说明](https://www.hiascend.com/doc_center/source/en/CANNCommunityEdition/910/devaids/Profiling/atlasprofiling_16_0011.html),启用任务耗时和 PipeUtilization。每次完整调用的全部设备任务均计入,使用 `op_summary` 的 `Task Duration(us)` 求和,再对 20 个样本取中位数。[该字段](https://www.hiascend.com/doc_center/source/zh/CANNCommunityEdition/910beta2/devaids/Profiling/atlasprofiling_16_0067.html)包含调度、加速器执行和结束响应,不含任务间等待;主机耗时、输入准备、清 L2 和精度检查不计入。PyPTO-Pro 每次包含 2 个设备任务,AscendC 每次包含 1 个。
65- 
66-AscendC 基线使用官方源码提交 `637598412a4a295d02b84b1b5bb2b8d9f1154bcf` 编译的 CompressorV2,算子目录与本轮核查的 master 提交 `62884679af1b2fb6ceef3b8e9950bc89a030b254` 完全一致。
67- 
68-### 绝对性能结果
69- 
70-单位为微秒(μs)。性能占比为 AscendC 中位耗时除以 PyPTO-Pro 中位耗时,以数值比值展示:1.0 表示耗时相同,大于 1.0 表示 PyPTO-Pro 耗时更低。比值用未舍入的中位数计算,最多保留 4 位小数。
71- 
72-| 用例 | AscendC(μs) | PyPTO-Pro(μs) | 性能占比 |
73-| :--- | ---: | ---: | ---: |
74-| `Prefill0` | 181.007 | 191.241 | 0.9465 |
75-| `Prefill1` | 72.176 | 64.923 | 1.1117 |
76-| `Prefill2` | 182.121 | 192.616 | 0.9455 |
77-| `decode0_start8192` | 17.812 | 11.240 | 1.5847 |
78-| `decode0_start8195` | 19.916 | 11.152 | 1.7858 |
79-| `decode1_start8192` | 19.564 | 8.599 | 2.2751 |
80-| `decode1_start8195` | 21.822 | 8.871 | 2.4601 |
81-| `decode2_start8192` | 18.101 | 10.806 | 1.6751 |
82-| `decode2_start8195` | 18.398 | 11.311 | 1.6266 |
83-| `decode3_start8193` | 21.641 | 16.384 | 1.3209 |
84-| `decode4_start8192` | 20.255 | 12.473 | 1.6239 |
85-| `decode4_start8193` | 21.474 | 13.026 | 1.6485 |
86-| `decode4_start8191` | 20.956 | 15.748 | 1.3307 |
87-| `decode5_start8193` | 20.207 | 15.183 | 1.3309 |
88-| `FullLoad0` | 22.584 | 12.560 | 1.7981 |
89-| `FullLoad1` | 21.296 | 9.461 | 2.2509 |
90-| `FullLoad2` | 17.493 | 11.073 | 1.5799 |
91-| `FullLoad3` | 31.619 | 26.519 | 1.1923 |
92-| `FullLoad4` | 26.704 | 15.418 | 1.732 |
93-| `FullLoad5` | 18.764 | 12.161 | 1.5429 |
94-| `FullLoad6` | 17.552 | 11.070 | 1.5856 |
95-| `FullLoad7` | 16.569 | 8.375 | 1.9783 |
96-| `FullLoad8` | 17.754 | 12.294 | 1.4441 |
97-| `Contiguous0` | 20.066 | 11.354 | 1.7673 |
98-| `NonContiguous0` | 19.946 | 12.177 | 1.638 |
99- 
100-本轮 23/25 个用例的 PyPTO-Pro 中位耗时低于 AscendC,AscendC / PyPTO-Pro 耗时比范围为 0.946~2.460。 `Prefill0` 的耗时高于 AscendC 5.65%。 `Prefill2` 的耗时高于 AscendC 5.76%。
101- 
102-### 理论评估对比
103- 
104-按一次乘加计 2 次浮点运算,两路投影的数学计算量为 `4THD`,其中 `T` 为本次输入 token 总数、`H` 为输入特征宽度、`D` 为投影输出宽度。实现沿 H 切分时,各分区的 FP32 部分和再合并,不改变该矩阵乘计算量;softmax、缓存更新和数据搬运另计。
105- 
106-下表按用例的实际形状计算两路投影的数学运算量,1 GFLOP 表示十亿次浮点运算。
107- 
108-| 用例 | T | H | D | 两路投影计算量(GFLOP) |
109-| :--- | ---: | ---: | ---: | ---: |
110-| `Prefill0` | 8192 | 4096 | 512 | 68.719 |
111-| `Prefill1` | 8192 | 4096 | 128 | 17.180 |
112-| `Prefill2` | 8192 | 4096 | 512 | 68.719 |
113- 
114-性能表按完整调用的全部设备任务计量,包含投影、压缩和缓存更新;此处的数学运算量只统计两路矩阵乘。
@@ -1,150 +0,0 @@
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- 
10-"""Uniform CPU inputs and independent FP64 reference for CompressorV2."""
11- 
12-from __future__ import annotations
13- 
14-from typing import NamedTuple
15- 
16-import torch
17- 
18- 
19-class CompressorInputs(NamedTuple):
20- """Operator inputs in the public positional order."""
21- 
22- x: torch.Tensor
23- wkv: torch.Tensor
24- wgate: torch.Tensor
25- cache: torch.Tensor
26- table: torch.Tensor
27- cu_seqlens: torch.Tensor | None
28- seqused: torch.Tensor | None
29- start_pos: torch.Tensor | None
30- 
31- 
32-class _SequenceSpan(NamedTuple):
33- """Input and cache positions for a single sequence."""
34- 
35- begin: int
36- count: int
37- start: int
38- prefix: int
39- groups: int
40- block: int
41- 
42- 
43-def make_inputs(case):
44- """Generate uniform [-10, 10] inputs using the case's fixed CPU seed."""
45- b, s, h, d = (case[key] for key in ("batch", "sequence", "hidden", "dim"))
46- generator = torch.Generator().manual_seed(case["seed"])
47- dtype = getattr(torch, case["dtype"])
48- shape = (b, s, h) if case["layout"] == "BSH" else (b * s, h)
49- cache = (
50- torch.rand(
51- (b, case["block_size"], 2 * d), generator=generator, dtype=torch.float32
52- )
53- * 20
54- - 10
55- )
56- x = (torch.rand(shape, generator=generator, dtype=torch.float32) * 20 - 10).to(
57- dtype
58- )
59- wkv = (torch.rand((d, h), generator=generator, dtype=torch.float32) * 20 - 10).to(
60- dtype
61- )
62- wgate = (torch.rand((d, h), generator=generator, dtype=torch.float32) * 20 - 10).to(
63- dtype
64- )
65- table = torch.tensor(case["blocks"], dtype=torch.int32)
66- cu = (
67- (torch.arange(b + 1, dtype=torch.int32) * s) if case["layout"] == "TH" else None
68- )
69- starts = torch.tensor(case["starts"], dtype=torch.int32)
70- return CompressorInputs(x, wkv, wgate, cache, table, cu, None, starts)
71- 
72- 
73-def _sequence_span(values, batch, sequence_length, ratio):
74- """Resolve the active input range and absolute start for one sequence."""
75- _, table, cu, used, starts = values[3:]
76- begin = batch * sequence_length if cu is None else int(cu[batch])
77- count = sequence_length if cu is None else int(cu[batch + 1]) - begin
78- if used is not None:
79- count = int(used[batch])
80- start = 0 if starts is None else int(starts[batch])
81- prefix = start % ratio
82- groups = (prefix + count) // ratio if count else 0
83- return _SequenceSpan(begin, count, start, prefix, groups, int(table[batch]))
84- 
85- 
86-def _compress_group(old, projected, span, absolute, ratio, dim):
87- """Combine historical and new FP64 projections for one complete group."""
88- kvs, scores = [], []
89- for pos in range(absolute, absolute + ratio):
90- if pos < span.start:
91- row = old[span.block, pos % old.shape[1]].double()
92- kvs.append(row[:dim])
93- scores.append(row[dim:])
94- else:
95- row = span.begin + pos - span.start
96- kvs.append(projected[0][row])
97- scores.append(projected[1][row])
98- weight = torch.softmax(torch.stack(scores), dim=0)
99- return (weight * torch.stack(kvs)).sum(0)
100- 
101- 
102-def _write_sequence_output(
103- output, mask, old, projected, span, ratio, output_base, batch, is_bsh
104-):
105- """Write valid groups using the public BSH or packed TH output layout."""
106- dim = projected[0].shape[-1]
107- for group in range(span.groups):
108- absolute = span.start - span.prefix + group * ratio
109- value = _compress_group(old, projected, span, absolute, ratio, dim)
110- index = (batch, group) if is_bsh else output_base + group
111- output[index] = value
112- mask[index] = True
113- 
114- 
115-def _update_sequence_cache(cache, updated, projected, span, block_size, dim):
116- """Replace exactly the final input rows retained by the ring cache."""
117- for offset in range(max(0, span.count - block_size), span.count):
118- slot = (span.start + offset) % block_size
119- cache[span.block, slot, :dim] = projected[0][span.begin + offset].float()
120- cache[span.block, slot, dim:] = projected[1][span.begin + offset].float()
121- updated[span.block, slot] = True
122- 
123- 
124-def reference(values, ratio):
125- """Independent FP64 contraction and grouping over the pre-call cache state."""
126- x, wkv, wgate, old, _, cu, _, _ = values
127- h, d = x.shape[-1], wkv.shape[0]
128- b = x.shape[0] if x.ndim == 3 else cu.numel() - 1
129- s = x.shape[1] if x.ndim == 3 else 0
130- t = x.numel() // h
131- projected = (
132- x.double().reshape(t, h) @ wkv.double().T,
133- x.double().reshape(t, h) @ wgate.double().T,
134- )
135- shape = (
136- (b, (s + ratio - 1) // ratio, d) if x.ndim == 3 else (min(t, t // ratio + b), d)
137- )
138- output = torch.zeros(shape, dtype=torch.float64)
139- mask = torch.zeros(shape[:-1], dtype=torch.bool)
140- cache = old.clone()
141- updated = torch.zeros_like(old, dtype=torch.bool)
142- output_base = 0
143- for batch in range(b):
144- span = _sequence_span(values, batch, s, ratio)
145- _write_sequence_output(
146- output, mask, old, projected, span, ratio, output_base, batch, x.ndim == 3
147- )
148- _update_sequence_cache(cache, updated, projected, span, old.shape[1], d)
149- output_base += span.groups
150- return output.to(x.dtype), mask, cache, updated
@@ -1,344 +0,0 @@
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- 
10-"""AscendC CompressorV2 single-case precision and allocation-guard checks.
11- 
12-Numerical comparison follows ops-transformer compressor_golden.check_result.
13-All updated regions select tolerances using the operator output dtype.
14-"""
15- 
16-import logging
17- 
18-import numpy as np
19-import torch
20- 
21-_LOGGER = logging.getLogger(__name__)
22- 
23-_PRECISION = {
24- "bfloat16": {
25- "diff_thd": 0.005,
26- "max_diff_hd": 10.0,
27- "rtol": 0.0078125,
28- "atol": 0.0001,
29- },
30- "float16": {
31- "diff_thd": 0.005,
32- "max_diff_hd": 10.0,
33- "rtol": 0.005,
34- "atol": 0.000025,
35- },
36- "float32": {
37- "diff_thd": 0.005,
38- "max_diff_hd": 10.0,
39- "rtol": 0.005,
40- "atol": 0.000025,
41- },
42-}
43- 
44- 
45-def cal_relative_diff_np_isclose(real_data, expect_data, type_str="fp16"):
46- diff = abs(float(real_data) - float(expect_data))
47- result = diff / (np.abs(expect_data) + 10e-10)
48- return result
49- 
50- 
51-_ROW_DIVIDER = "-" * 87
52- 
53- 
54-_ERROR_DIVIDER = "Error Line" + "-" * 77
55- 
56- 
57-_MAX_RE_DIVIDER = "Max-RE line:" + "-" * 75
58- 
59- 
60-_LOOP_HEADER = "Loop \t ExpectOut \t RealOut \t FpDiff \t RateDiff"
61- 
62- 
63-_LOOP_HEADER_FP32 = (
64- "Loop \t ExpFP32Out \t ExpFP16Out \t NPUOut \tFpDiff(min) \t RateDiff"
65-)
66- 
67- 
68-def _format_loop_row(seq, expect_val, real_val, expect_fp32_val=None):
69- """格式化单行点位:期望值为 inf/nan 时用字符串列,否则用 7 位小数;expect_fp32 存在时输出双列。"""
70- diff_rate = cal_relative_diff_np_isclose(real_val, expect_val)
71- if "inf" in str(expect_val) or "nan" in str(expect_val):
72- diff_abs = "inf" if "inf" in str(expect_val) else "nan"
73- if expect_fp32_val is not None:
74- return (
75- f"{seq:08d} \t {expect_fp32_val:<7} \t {expect_val:<7} \t "
76- f"{real_val:<7} \t {diff_abs:<7} \t {diff_rate:<7}"
77- )
78- return f"{seq:08d} \t {expect_val:<7} \t {real_val:<7} \t {diff_abs:<7} \t {diff_rate:<7}"
79- diff_abs = abs(np.float64(expect_val) - np.float64(real_val))
80- if expect_fp32_val is not None:
81- return (
82- f"{seq:08d} \t {expect_fp32_val:.7f} \t {expect_val:.7f} \t "
83- f"{real_val:.7f} \t {diff_abs:.7f} \t {diff_rate:.7f}"
84- )
85- return f"{seq:08d} \t {expect_val:.7f} \t {real_val:.7f} \t {diff_abs:.7f} \t {diff_rate:.7f}"
86- 
87- 
88-def _format_error_row(seq, expect_val, real_val, diff_rate):
89- """格式化错误点位明细行(7 位小数定点)。"""
90- diff_abs = abs(np.float64(expect_val) - np.float64(real_val))
91- return f"{seq:08d} \t {expect_val:.7f} \t {real_val:.7f} \t {diff_abs:.7f} \t {diff_rate:.7f}"
92- 
93- 
94-def _display_row_range(real_data, expect_data, start, row_range, expect_fp32_data=None):
95- """打印 [start + lo, start + hi) 区间的点位行(绝对序号 = start + idx + 1)。"""
96- for idx in row_range:
97- seq = start + idx + 1
98- fp32 = expect_fp32_data[idx + start] if expect_fp32_data is not None else None
99- print_log(
100- _format_loop_row(
101- seq, expect_data[idx + start], real_data[idx + start], fp32
102- )
103- )
104- 
105- 
106-def print_log(data=None, level="INFO"):
107- """Send diagnostics through the standard logger with caller information."""
108- severity = getattr(logging, level.upper(), logging.INFO)
109- _LOGGER.log(severity, "%s", data, stacklevel=2)
110- 
111- 
112-def display_output_np_isclose(
113- real_data, expect_data, start, end, expect_fp32_data=None
114-):
115- """输出每个点位的对比结果(≤20 点位全显示,>20 显示首尾各 10)。"""
116- print_log(_ROW_DIVIDER)
117- print_log(_LOOP_HEADER_FP32 if expect_fp32_data is not None else _LOOP_HEADER)
118- print_log(_ROW_DIVIDER)
119- split_count = int(end - start)
120- if split_count <= 20:
121- _display_row_range(
122- real_data, expect_data, start, range(split_count + 1), expect_fp32_data
123- )
124- else:
125- _display_row_range(real_data, expect_data, start, range(10), expect_fp32_data)
126- print_log("... \t ... \t ... \t ... \t ...")
127- _display_row_range(
128- real_data,
129- expect_data,
130- start,
131- range(split_count - 10 + 1, split_count + 1),
132- expect_fp32_data,
133- )
134- 
135- 
136-def display_error_output(real_data, expect_data, err_idx, relative_diff):
137- """输出错误点位明细 + 最大相对误差点位。"""
138- print_log(_ERROR_DIVIDER)
139- print_log(_LOOP_HEADER)
140- print_log(_ROW_DIVIDER)
141- len_err = len(err_idx)
142- for count, i in enumerate(err_idx, start=1):
143- if count < 10 or (90 < count < 100):
144- print_log(
145- _format_error_row(
146- i, expect_data[i], real_data[i], relative_diff[count - 1]
147- )
148- )
149- elif count == 10 or (count == 100 and len_err > 100):
150- print_log(
151- f"{'...':>8} \t {'...':>7} \t {'...':>7} \t {'...':>7} \t {'...':>7}"
152- )
153- elif count > 100:
154- break
155- 
156- print_log(_MAX_RE_DIVIDER)
157- max_error = max(relative_diff)
158- m_idx_list = err_idx[np.where(relative_diff == max_error)]
159- for m_count, m_idx in enumerate(m_idx_list, start=1):
160- if m_count < 4:
161- print_log(
162- _format_error_row(
163- m_idx, expect_data[m_idx], real_data[m_idx], max_error
164- )
165- )
166- else:
167- break
168- print_log(_ROW_DIVIDER)
169- 
170- 
171-def _print_verdict(rtol, atol, pct_thd, fulfill_percent, result_str):
172- """打印 Rtol/Atol/PctThd/PctRlt/Result 汇总表格。"""
173- print_log(_ROW_DIVIDER)
174- print_log("Rtol \t Atol \t PctThd \t PctRlt \t Result")
175- print_log(_ROW_DIVIDER)
176- print_log(
177- f"{rtol:.4f} \t {atol:.6f} \t {pct_thd:.2f}% \t {fulfill_percent:.6f}% \t {result_str}"
178- )
179- 
180- 
181-def _log_reference_overflows(expected_data):
182- """Report non-finite reference values without changing the comparison."""
183- infinities = expected_data[np.isinf(expected_data)]
184- not_a_numbers = expected_data[np.isnan(expected_data)]
185- count = infinities.size + not_a_numbers.size
186- if count > 0:
187- print_log(
188- f"Overflow,size:{count},benchmark_output:{infinities[:10]}, {not_a_numbers[:10]}"
189- )
190- 
191- 
192-def _float8_storage(values, saturate_infinity):
193- """Preserve the upstream FP8 comparison's byte-oriented conversion."""
194- values[np.isnan(values)] = 0
195- if saturate_infinity:
196- values[np.isposinf(values)] = 57344
197- values[np.isneginf(values)] = -57344
198- return np.frombuffer(values.tobytes(), dtype="uint8")
199- 
200- 
201-def _comparison_data(real_data, expected_data):
202- """Convert FP8 arrays in the same order as the upstream checker."""
203- kind = str(real_data.dtype)
204- if kind in ("float8_e4m3fn", "float8_e5m2"):
205- saturate_infinity = kind == "float8_e5m2"
206- real_data = _float8_storage(real_data, saturate_infinity)
207- expected_data = _float8_storage(expected_data, saturate_infinity)
208- return real_data, expected_data
209- 
210- 
211-def _matching_elements(real_data, expected_data, config):
212- """Build the original element-wise tolerance mask."""
213- if str(real_data.dtype) == "bfloat16":
214- real_data = real_data.astype(np.float32)
215- expected_data = expected_data.astype(np.float32)
216- return np.isclose(
217- real_data,
218- expected_data,
219- rtol=config["rtol"],
220- atol=config["atol"],
221- equal_nan=True,
222- )
223- 
224- 
225-def _relative_errors(real_data, expected_data, error_indices, diff_threshold):
226- """Normalize only unmatched errors, retaining the two epsilon additions."""
227- if str(expected_data.dtype) == "bool":
228- expected_data = expected_data.astype(np.int8)
229- real_data = real_data.astype(np.int8)
230- absolute_diff = abs(expected_data - real_data)
231- magnitude = np.maximum(np.abs(real_data), np.abs(expected_data))
232- floor = float((1.0 / (1 << 14)) / diff_threshold)
233- denominator = np.add(np.maximum(magnitude, floor), 10e-10)
234- epsilon = 10e-10
235- relative = absolute_diff / (denominator + epsilon)
236- return real_data, expected_data, relative[error_indices]
237- 
238- 
239-def _result_verdict(fulfill_percent, relative_errors, pct_threshold, max_diff):
240- """Apply the original match-rate and abnormal-error gates."""
241- required_percent = (1 - pct_threshold) * 100.0
242- verdict = "Pass" if fulfill_percent >= required_percent else "Failed"
243- max_error = 0
244- if len(relative_errors) > 0:
245- # Python max preserves the upstream ordering semantics for NaNs.
246- max_error = max(relative_errors[:10_000_000])
247- if max_error >= max_diff:
248- verdict = "Failed"
249- return verdict, required_percent, max_error
250- 
251- 
252-def check_result(expect, result, data_type, pct_thd=0.005):
253- """Apply the AscendC CompressorV2 comparison criteria without new gates."""
254- real_data = result.cpu().numpy().flatten()
255- expected_data = expect.cpu().numpy().flatten()
256- if real_data.size == 0 and real_data.size == expected_data.size:
257- print_log("Empty actual and reference outputs: comparison Pass")
258- return 100.0, "Pass"
259- if real_data.size != expected_data.size:
260- print_log(
261- f"Output size mismatch: actual={real_data.size}, reference={expected_data.size}"
262- )
263- return 0.0, "Failed"
264- _log_reference_overflows(expected_data)
265- config = _PRECISION.get(data_type, _PRECISION["float16"])
266- end = max(real_data.size - 1, 0)
267- count = int(end + 1) if end != 0 else 1
268- print_log(f"split_count:{float(count)}; max_diff_hd:{config['max_diff_hd']};")
269- real_data, expected_data = _comparison_data(real_data, expected_data)
270- matched = _matching_elements(real_data, expected_data, config)
271- error_indices = np.where(matched != np.array((True,)))[0]
272- real_data, expected_data, relative = _relative_errors(
273- real_data, expected_data, error_indices, config["diff_thd"]
274- )
275- fulfill_percent = float(count - error_indices.size) / float(count) * 100.0
276- display_output_np_isclose(real_data, expected_data, 0, end)
277- verdict, required_percent, max_error = _result_verdict(
278- fulfill_percent, relative, pct_thd, config["max_diff_hd"]
279- )
280- _print_verdict(
281- config["rtol"], config["atol"], required_percent, fulfill_percent, verdict
282- )
283- if len(relative) > 0:
284- print_log(
285- f"Max-RelativeError is: {max_error}. Threshold is: {config['max_diff_hd']}."
286- )
287- if verdict == "Failed":
288- display_error_output(
289- real_data, expected_data, error_indices, relative[:10_000_000]
290- )
291- return fulfill_percent, verdict
292- 
293- 
294-def check(actual, cache, expected, dtype):
295- """Check specified outputs and updated cache with the AscendC criterion."""
296- output, mask, expected_cache, updated = expected
297- if not (
298- actual.shape == output.shape
299- and actual.dtype == output.dtype
300- and actual.is_contiguous()
301- ):
302- raise AssertionError("output shape, dtype or layout mismatch")
303- actual, cache = actual.cpu(), cache.cpu()
304- if cache.shape != expected_cache.shape or cache.dtype != expected_cache.dtype:
305- raise AssertionError("cache shape or dtype mismatch")
306- dim = cache.shape[-1] // 2
307- regions = [("cmp_kv", actual[mask], output[mask])]
308- for name, begin in (("kv_state_update", 0), ("score_state_update", dim)):
309- region = slice(begin, begin + dim)
310- selected = updated[..., region]
311- regions.append(
312- (name, cache[..., region][selected], expected_cache[..., region][selected])
313- )
314- # The official caller selects every region's threshold from npu_out.dtype.
315- data_type = str(actual.dtype).replace("torch.", "")
316- precision = {}
317- failures = []
318- for name, value, golden in regions:
319- percentage, verdict = check_result(
320- golden.to(torch.float32), value.to(torch.float32), data_type
321- )
322- precision[name] = {"fulfill_percent": percentage, "result": verdict}
323- if verdict != "Pass":
324- failures.append(f"{name}: fulfill_percent={percentage}, result={verdict}")
325- if failures:
326- raise AssertionError("\n".join(failures))
327- unchanged = torch.equal(
328- cache[~updated].view(torch.int32), expected_cache[~updated].view(torch.int32)
329- )
330- if not unchanged:
331- raise AssertionError("untouched cache changed")
332- return precision
333- 
334- 
335-def check_guards(backing, cache):
336- """Reject writes to the allocation outside the declared cache view."""
337- guard_mask = torch.ones(backing.numel(), dtype=torch.bool)
338- block_elements = cache.shape[1] * cache.shape[2]
339- for block in range(cache.shape[0]):
340- begin = cache.storage_offset() + block * cache.stride(0)
341- end = begin + block_elements
342- guard_mask[begin:end] = False
343- if not torch.all(backing.cpu()[guard_mask] == 7717).item():
344- raise AssertionError("allocation guard changed")
@@ -1,288 +0,0 @@
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- 
10-"""Official CompressorV2 single-test defaults with reproducible input seeds."""
11- 
12-import logging
13-import sys
14-from pathlib import Path
15- 
16-import pytest
17-import torch
18-import torch_npu # noqa: F401
19- 
20-_LOGGER = logging.getLogger(__name__)
21- 
22-_THIS_DIR = Path(__file__).resolve().parent
23-for _path in (_THIS_DIR / "assets", _THIS_DIR.parent / "op_kernel"):
24- if str(_path) not in sys.path:
25- sys.path.insert(0, str(_path))
26- 
27-from compressor_v2 import compressor
28-from compressor_v2_golden_cpu import make_inputs, reference
29-from compressor_v2_precision import check, check_guards
30- 
31-# fmt: off
32-_FULLLOAD3_BLOCKS = [
33- 17, 12, 7, 38, 44, 43, 52, 16, 56, 18, 14, 11, 35, 20, 26, 42,
34- 57, 13, 1, 62, 41, 47, 0, 3, 37, 48, 50, 49, 46, 24, 39, 36,
35- 55, 51, 29, 61, 34, 53, 8, 19, 32, 31, 30, 15, 23, 21, 25, 45,
36- 63, 54, 58, 28, 6, 5, 4, 27, 9, 2, 59, 40, 22, 60, 33, 10,
37-]
38- 
39-_FULLLOAD4_BLOCKS = [
40- 37, 5, 33, 54, 36, 41, 44, 28, 16, 7, 0, 25, 56, 18, 63, 21,
41- 52, 42, 6, 61, 58, 39, 53, 31, 55, 47, 2, 32, 34, 15, 3, 35,
42- 4, 17, 10, 20, 38, 40, 24, 46, 13, 29, 48, 19, 23, 59, 9, 22,
43- 12, 30, 27, 26, 14, 43, 60, 49, 11, 50, 1, 57, 45, 62, 8, 51,
44-]
45- 
46-# name, layout, batch, sequence, dim, ratio, block_size, start_pos, seed, pad, offset, blocks
47-_CASE_ROWS = [
48- ("Prefill0", "TH", 1, 8192, 512, 4, 128, 0, 2026102801, 14, 6, [0]),
49- ("Prefill1", "TH", 1, 8192, 128, 4, 128, 0, 2026102802, 16, 6, [0]),
50- ("Prefill2", "TH", 1, 8192, 512, 128, 128, 0, 2026102803, 5, 1, [0]),
51- ("decode0_start8192", "TH", 1, 1, 512, 4, 128, 8192, 2026102804, 38, 20, [0]),
52- ("decode0_start8195", "TH", 1, 1, 512, 4, 128, 8195, 2026102805, 16, 6, [0]),
53- ("decode1_start8192", "TH", 1, 1, 128, 4, 128, 8192, 2026102806, 23, 0, [0]),
54- ("decode1_start8195", "TH", 1, 1, 128, 4, 128, 8195, 2026102807, 49, 24, [0]),
55- ("decode2_start8192", "TH", 1, 1, 512, 128, 128, 8192, 2026102808, 24, 17, [0]),
56- ("decode2_start8195", "TH", 1, 1, 512, 128, 128, 8195, 2026102809, 26, 18, [0]),
57- ("decode3_start8193", "TH", 8, 3, 512, 4, 128, 8193, 2026102810, 10, 0, [3, 2, 0, 6, 5, 1, 4, 7]),
58- ("decode4_start8192", "TH", 8, 3, 128, 4, 128, 8192, 2026102811, 35, 25, [4, 5, 2, 1, 7, 3, 0, 6]),
59- ("decode4_start8193", "TH", 8, 3, 128, 4, 128, 8193, 2026102812, 35, 24, [4, 0, 1, 6, 7, 2, 5, 3]),
60- ("decode4_start8191", "TH", 8, 3, 128, 4, 128, 8191, 2026102813, 11, 6, [4, 1, 7, 0, 6, 3, 2, 5]),
61- ("decode5_start8193", "TH", 8, 3, 512, 128, 128, 8193, 2026102814, 5, 1, [6, 1, 5, 4, 0, 2, 7, 3]),
62- ("FullLoad0", "BSH", 1, 4, 512, 4, 128, 0, 2026102815, 31, 8, [0]),
63- ("FullLoad1", "BSH", 1, 4, 128, 4, 128, 0, 2026102816, 29, 0, [0]),
64- ("FullLoad2", "BSH", 1, 4, 512, 128, 131, 0, 2026102817, 3, 0, [0]),
65- ("FullLoad3", "BSH", 64, 4, 512, 4, 128, 0, 2026102818, 18, 11, _FULLLOAD3_BLOCKS),
66- ("FullLoad4", "BSH", 64, 4, 128, 4, 128, 0, 2026102819, 38, 31, _FULLLOAD4_BLOCKS),
67- ("FullLoad5", "BSH", 8, 2, 512, 4, 128, 0, 2026102820, 47, 11, [6, 1, 3, 7, 0, 2, 4, 5]),
68- ("FullLoad6", "BSH", 1, 1, 512, 4, 128, 100, 2026102821, 23, 2, [0]),
69- ("FullLoad7", "BSH", 1, 1, 128, 4, 128, 100, 2026102822, 21, 12, [0]),
70- ("FullLoad8", "BSH", 1, 1, 512, 128, 128, 100, 2026102823, 22, 14, [0]),
71- ("Contiguous0", "TH", 2, 3, 512, 4, 128, 8193, 2026102824, 0, 0, [0, 1]),
72- ("NonContiguous0", "TH", 2, 3, 512, 4, 128, 8193, 2026102825, 36, 4, [1, 0]),
73-]
74-# fmt: on
75- 
76-_CASES = {
77- name: {
78- "name": name,
79- "layout": layout,
80- "dtype": "bfloat16",
81- "batch": batch,
82- "sequence": sequence,
83- "hidden": 4096,
84- "dim": dim,
85- "ratio": ratio,
86- "block_size": block_size,
87- "starts": [start] * batch,
88- "seed": seed,
89- "blocks": blocks,
90- "cache_stride_extra": pad,
91- "cache_offset": offset,
92- }
93- for name, layout, batch, sequence, dim, ratio, block_size, start, seed, pad, offset, blocks in _CASE_ROWS
94-}
95- 
96- 
97-def to_device(values, case):
98- """Build the specified cache view, retaining a trailing allocation guard."""
99- device_values = [None if value is None else value.to("npu:0") for value in values]
100- old = values[3]
101- block_elements = old.shape[1] * old.shape[2]
102- block_stride = block_elements + case["cache_stride_extra"]
103- backing = torch.full(
104- (old.shape[0] * block_stride + 64,), 7717.0, device="npu:0", dtype=torch.float32
105- )
106- cache = backing.as_strided(
107- old.shape, (block_stride, old.shape[2], 1), storage_offset=case["cache_offset"]
108- )
109- cache.copy_(device_values[3])
110- device_values[3] = cache
111- return tuple(device_values), backing
112- 
113- 
114-def call(values, ratio):
115- x, kv, gate, cache, table, cu, used, starts = values
116- return compressor(
117- x,
118- kv,
119- gate,
120- cache,
121- ratio,
122- state_block_table=table,
123- cu_seqlens=cu,
124- seqused=used,
125- start_pos=starts,
126- )
127- 
128- 
129-def run_case(case):
130- """Run one public wrapper call and validate every specified result."""
131- torch.set_num_threads(8)
132- torch.npu.set_device(0)
133- cpu_values = make_inputs(case)
134- expected = reference(cpu_values, case["ratio"])
135- values, backing = to_device(cpu_values, case)
136- out = call(values, case["ratio"])
137- torch.npu.synchronize()
138- check(out, values[3], expected, values[0].dtype)
139- check_guards(backing, values[3])
140- if expected[1].any():
141- corrupted = out.cpu().clone()
142- corrupted[expected[1]] = float("nan")
143- try:
144- check(corrupted, values[3], expected, values[0].dtype)
145- except AssertionError:
146- pass
147- else:
148- raise AssertionError(
149- "the correctness criterion accepted a corrupted output"
150- )
151- return out
152- 
153- 
154-@pytest.mark.soc("950")
155-def test_prefill0():
156- run_case(_CASES["Prefill0"])
157- 
158- 
159-@pytest.mark.soc("950")
160-def test_prefill1():
161- run_case(_CASES["Prefill1"])
162- 
163- 
164-@pytest.mark.soc("950")
165-def test_prefill2():
166- run_case(_CASES["Prefill2"])
167- 
168- 
169-@pytest.mark.soc("950")
170-def test_decode0_start8192():
171- run_case(_CASES["decode0_start8192"])
172- 
173- 
174-@pytest.mark.soc("950")
175-def test_decode0_start8195():
176- run_case(_CASES["decode0_start8195"])
177- 
178- 
179-@pytest.mark.soc("950")
180-def test_decode1_start8192():
181- run_case(_CASES["decode1_start8192"])
182- 
183- 
184-@pytest.mark.soc("950")
185-def test_decode1_start8195():
186- run_case(_CASES["decode1_start8195"])
187- 
188- 
189-@pytest.mark.soc("950")
190-def test_decode2_start8192():
191- run_case(_CASES["decode2_start8192"])
192- 
193- 
194-@pytest.mark.soc("950")
195-def test_decode2_start8195():
196- run_case(_CASES["decode2_start8195"])
197- 
198- 
199-@pytest.mark.soc("950")
200-def test_decode3_start8193():
201- run_case(_CASES["decode3_start8193"])
202- 
203- 
204-@pytest.mark.soc("950")
205-def test_decode4_start8192():
206- run_case(_CASES["decode4_start8192"])
207- 
208- 
209-@pytest.mark.soc("950")
210-def test_decode4_start8193():
211- run_case(_CASES["decode4_start8193"])
212- 
213- 
214-@pytest.mark.soc("950")
215-def test_decode4_start8191():
216- run_case(_CASES["decode4_start8191"])
217- 
218- 
219-@pytest.mark.soc("950")
220-def test_decode5_start8193():
221- run_case(_CASES["decode5_start8193"])
222- 
223- 
224-@pytest.mark.soc("950")
225-def test_fullload0():
226- run_case(_CASES["FullLoad0"])
227- 
228- 
229-@pytest.mark.soc("950")
230-def test_fullload1():
231- run_case(_CASES["FullLoad1"])
232- 
233- 
234-@pytest.mark.soc("950")
235-def test_fullload2():
236- run_case(_CASES["FullLoad2"])
237- 
238- 
239-@pytest.mark.soc("950")
240-def test_fullload3():
241- run_case(_CASES["FullLoad3"])
242- 
243- 
244-@pytest.mark.soc("950")
245-def test_fullload4():
246- run_case(_CASES["FullLoad4"])
247- 
248- 
249-@pytest.mark.soc("950")
250-def test_fullload5():
251- run_case(_CASES["FullLoad5"])
252- 
253- 
254-@pytest.mark.soc("950")
255-def test_fullload6():
256- run_case(_CASES["FullLoad6"])
257- 
258- 
259-@pytest.mark.soc("950")
260-def test_fullload7():
261- run_case(_CASES["FullLoad7"])
262- 
263- 
264-@pytest.mark.soc("950")
265-def test_fullload8():
266- run_case(_CASES["FullLoad8"])
267- 
268- 
269-@pytest.mark.soc("950")
270-def test_contiguous0():
271- run_case(_CASES["Contiguous0"])
272- 
273- 
274-@pytest.mark.soc("950")
275-def test_noncontiguous0():
276- run_case(_CASES["NonContiguous0"])
277- 
278- 
279-def main():
280- for case in _CASES.values():
281- run_case(case)
282- _LOGGER.info("PASS %s", case["name"])
283- _LOGGER.info("COMPRESSOR_V2_OK %s", len(_CASES))
284- 
285- 
286-if __name__ == "__main__":
287- logging.basicConfig(level=logging.INFO, format="%(message)s")
288- main()
@@ -1,150 +0,0 @@
1-# engram_gate
2- 
3-## 产品支持情况
4- 
5-| 项目 | 说明 |
6-| :--- | :--- |
7-| 硬件平台 | Ascend 950PR(`Ascend950PR_9589`,平台信息 `soc_version = 'DAV_3510'`);cube(矩阵计算单元)32 核 / vector(向量计算单元)64 核 |
8-| 使用的计算单元 | AI Vector(AIV)核,不使用 Cube |
9-| 软件环境 | CANN 9.3.0、PyPTO-Pro DSL |
10-| 输入数据类型 | `x`、`key`、`value` 为 BF16;`weight` 为 FP32;`image_mask` 为 BOOL |
11-| 输出数据类型 | `y` 为 BF16 |
12-| 支持的形状 | `x` / `key` / `y` 为 `[t, hc, dim]`,`value` 为 `[t, dim]`,`weight` 为 `[hc, dim]`,`image_mask` 为 `[t]`;`t ≥ 1`,`hc` 为 `1 ~ 向量核数`(本平台向量核数为 64),`dim` 最大 8512 |
13-| 参考实现 | 功能说明里那条公式的独立 CPU 参考实现(FP32 计算、BF16 输出),见 `tests/assets/engram_gate_golden_cpu.py` |
14- 
15-未覆盖的情况(当前不支持):`dim > 8512`、`hc` 大于向量核数、`eps` / `clamp_value` 取默认值
16-`1e-6` 以外的值、输入含有 NaN / Inf。
17- 
18-前三种调用都会在 host 侧报错,不会静默给出错误结果:`dim` 与 `eps` / `clamp_value` 由
19-wrapper 直接拦下;`hc` 越界时,`hc = 0` 在计算起核数时除零,`hc` 大于向量核数则在起核时
20-报 `InvalidType`。含 NaN / Inf 的输入不在支持范围内,输出未定义。
21- 
22-## 功能说明
23- 
24-`engram_gate` 是 DeepSeek V4.1 Engram 的残差门控(residual gate)算子,使用 PyPTO-Pro
25-在昇腾 NPU 的向量核上实现。计算沿最后一维 `dim`、逐 `(token, head)` 行进行:
26- 
27-```text
28-rstd = rsqrt(mean(x²) + eps) · rsqrt(mean(key²) + eps) # x、key 两路均方根(RMS)的倒数之积
29-dot = Σ(x · weight · key) · rstd / √dim # 加权点积,按 dim 归约
30-gate = sigmoid(copysign(√max(|dot|, clamp_value), dot)) # |dot| 开方后贴回 dot 的符号,再过 sigmoid(1/(1+e^(-x)))
31-y = bf16(x + gate · value) # 残差更新
32-```
33- 
34-其中 `value` 按 token 共享、不随 head 变化,所以在 head 维上广播。
35- 
36-如果把这四步各写成一个 kernel,就要来回读写全局内存四趟。本算子把它们融合成**一个 kernel
37-的一趟扫描**:每个 `(token, head)` 行的 `x`、`key`、`value` 各只搬进片上一次,`y` 只写出
38-一次,两趟计算复用同一块片上数据,中间的统计量不再往返全局内存。`value` 行由同一 token 的
39-`hc` 个 head 各搬一次、`weight` 由每个核各搬自己那一行,这两处重复量在 `RESULTS.md` 的流量
40-表里单列。
41- 
42-`image_mask` 为 `True` 的 token 不做上述门控计算,直接原样返回 `x`(逐位相等,不重新取整)。
43-这类 token 在 kernel 里走一条只搬不算的分支。
44- 
45-## 函数原型
46- 
47-```python
48-# 把 op_kernel 目录加入 sys.path 后:
49-from engram_gate import engram_gate_wrapper
50- 
51-y = engram_gate_wrapper(x, key, value, weight, image_mask, eps=1e-6, clamp_value=1e-6)
52-```
53- 
54-### 参数说明
55- 
56-| 参数 | 形状 | 类型 | 说明 |
57-| :--- | :--- | :--- | :--- |
58-| `x` | `[t, hc, dim]` | BF16 | 主激活值,也是残差更新的基准项 |
59-| `key` | `[t, hc, dim]` | BF16 | key 激活值,与 `x` 同形状 |
60-| `value` | `[t, dim]` | BF16 | value 激活值,按 token 共享(在 head 维广播) |
61-| `weight` | `[hc, dim]` | FP32 | 逐 `(head, dim)` 的加权系数 |
62-| `image_mask` | `[t]` | BOOL | 为 `True` 的 token 原样返回 `x` |
63-| `eps` | 标量 | float | RMS 的稳定项,只接受默认值 `1e-6` |
64-| `clamp_value` | 标量 | float | `\|dot\|` 的软阈值,只接受默认值 `1e-6` |
65- 
66-### 返回值说明
67- 
68-| 返回值 | 形状 | 类型 | 说明 |
69-| :--- | :--- | :--- | :--- |
70-| `y` | `[t, hc, dim]` | BF16 | 门控后的残差更新结果,与 `x` 同形状;由本函数内部分配并返回 |
71- 
72-## 约束说明
73- 
74-- `dim` 最大 8512。这个上限来自 kernel 给片上数据行定的宽度 `CHUNK = 8512`:整行
75- `(token, head)` 必须一次驻留在 UB(片上统一缓冲,kernel 直接寻址的片上内存)里,才能让
76- 两趟计算复用同一块数据。超过时 wrapper 直接报错,不做静默降级。
77-- `eps` 与 `clamp_value` 被编成 kernel 内的立即数,`1e-6` 以外的取值 wrapper 会报错。
78-- `t`、`hc`、`dim` 都是运行时动态轴,同一个 kernel 服务全部形状,不需要按形状重新编译。
79-- 启动核数取 `min(向量核数, t·hc)`,再向下取整到 `hc` 的倍数——因为 token 维按
80- `hc` 分组轮转,核数必须是 `hc` 的整数倍才不会漏 token。
81-- 因此 `hc` 不能大于向量核数(本平台 64):否则取整后起核数为 0。`hc ≤ 64` 时起核数总是
82- `hc` 的整数倍且不小于 `hc`,每个核至少拿到一行。
83-- 输入张量的内存布局不做要求:连续张量与带步长的非连续视图(`token` 维、`dim` 维分别构成
84- 非连续)都得到一致的结果;`RESULTS.md` 的精度与性能数据在连续张量上采集。
85-- `x`、`key`、`value`、`weight`、`image_mask` 的形状必须互相匹配,否则 wrapper 报错;
86- dtype 必须与上表一致,不一致时运行时报 `InvalidType`,并指出是哪个入参、期望与实际分别是
87- 什么 dtype。
88-- 单次调用只下发一个 kernel,host 侧不做任何数值计算,也不做额外的同步或后处理。
89-- 输出 `y` 是新分配的张量,不原地修改 `x`。
90- 
91-## 调用示例
92- 
93-```python
94-import sys
95- 
96-import torch
97-import torch_npu # noqa: F401
98- 
99-sys.path.insert(0, "ops/pypto_pro/deepseek_v4_1/engram_gate/op_kernel")
100-from engram_gate import engram_gate_wrapper
101- 
102-torch.npu.set_device(0)
103-t, hc, dim = 5, 4, 5120
104- 
105-x = torch.randn(t, hc, dim, dtype=torch.bfloat16).npu()
106-key = torch.randn(t, hc, dim, dtype=torch.bfloat16).npu()
107-value = torch.randn(t, dim, dtype=torch.bfloat16).npu()
108-weight = torch.randn(hc, dim, dtype=torch.float32).npu()
109-image_mask = torch.arange(t) % 2 == 1
110-image_mask = image_mask.npu()
111- 
112-y = engram_gate_wrapper(x, key, value, weight, image_mask)
113-torch.npu.synchronize()
114-print(y.shape, y.dtype)
115-# torch.Size([5, 4, 5120]) torch.bfloat16
116- 
117-# image_mask == True 的行与 x 逐位相等
118-print(bool(torch.equal(y[image_mask], x[image_mask])))
119-# True
120-```
121- 
122-示例依赖的文件分布在算子目录下(`op_kernel/` 放 kernel 与公开 wrapper,`tests/assets/` 放
123-golden 与精度比较器,`tests/` 直接放测试入口):
124- 
125-```text
126-engram_gate/
127-├── README.md # 本文件:接口与用法
128-├── DESIGN.md # 设计说明:阶段划分、切分与流水
129-├── RESULTS.md # 结果说明:用例、精度与性能
130-├── op_kernel/
131-│ └── engram_gate.py # 算子本体(kernel + 公开 wrapper)
132-└── tests/
133- ├── test_engram_gate.py # 测试入口(pytest 与命令行都能跑)
134- └── assets/
135- ├── engram_gate_golden_cpu.py # 独立 CPU 参考实现
136- └── engram_gate_precision.py # 精度比较器(方案 A)
137-```
138- 
139-测试与参考实现自检都可以在仓库根目录直接运行,不需要额外的驱动脚本:
140- 
141-```bash
142-# 全部 5 个用例
143-pytest ops/pypto_pro/deepseek_v4_1/engram_gate/tests -q
144- 
145-# 只跑其中一个用例
146-pytest ops/pypto_pro/deepseek_v4_1/engram_gate/tests -q -k partial_image_mask
147- 
148-# CPU 参考实现自检
149-python ops/pypto_pro/deepseek_v4_1/engram_gate/tests/assets/engram_gate_golden_cpu.py
150-```
@@ -1,225 +0,0 @@
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.
5-# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED.
6-"""engram_gate PyPTO-Pro kernel and host wrapper (single dynamic-axis kernel).
7- 
8-One module-level ``@pl.jit(auto_mutex=True)`` kernel serves any ``t/hc/dim``
9-(dynamic axes); a fixed UB row width keeps a whole ``(token, hc)`` row resident so
10-pass 1 (the two RMS reductions and the weighted dot) and pass 2 (the residual
11-write) read the same UB tile. Every numeric step runs inside the kernel; the host
12-side only validates shapes/dtypes, allocates the output and launches once.
13-"""
14- 
15-import math
16- 
17-import torch
18- 
19-import pypto
20-import pypto_pro.language as pl
21-from pypto_pro.language import Vf as vf # noqa: N813
22-from pypto_pro.runtime.platform import get_platform_info
23- 
24-CHUNK = 8512 # fixed UB row width; exceeds the largest supported row for one scan
25- 
26-# Gate constants. They are compile-time literals inside the VF, so the wrapper
27-# can only accept these values.
28-_EPS = 1e-06
29-_CLAMP_VALUE = 1e-06
30- 
31-S_BF = CHUNK * 2
32-A_UX = 0
33-A_UK = A_UX + 3 * S_BF
34-A_UV = A_UK + 3 * S_BF
35-A_UW = A_UV + 3 * S_BF
36-A_UO = A_UW + CHUNK * 4
37- 
38- 
39-def _vector_core_count():
40- """Vector core count from the PyPTO-Pro platform info (not hard-coded)."""
41- info = get_platform_info()
42- count = int(info.vector_core_num)
43- if count <= 0:
44- raise RuntimeError(
45- "cannot determine the NPU vector core count from the PyPTO-Pro platform info"
46- )
47- return count
48- 
49- 
50-@pl.vector_function
51-def engram_gate_vf(ux, uk, uw, uv, uo, dim: pl.DT_INT64):
52- preg = vf.create_mask(pattern=pl.MaskPattern.ALL, dtype=pl.DT_FP32)
53- pall_u32 = vf.create_mask(pattern=pl.MaskPattern.ALL, dtype=pl.DT_UINT32)
54- m32 = vf.create_mask(pattern=pl.MaskPattern.ALL, dtype=pl.DT_FP32)
55- m16 = vf.create_mask(pattern=pl.MaskPattern.ALL, dtype=pl.DT_FP16)
56- 
57- a_x2 = vf.full(0.0, dtype=pl.DT_FP32)
58- a_k2 = vf.full(0.0, dtype=pl.DT_FP32)
59- a_dot = vf.full(0.0, dtype=pl.DT_FP32)
60- n_full = dim // 64
61- tail = dim - n_full * 64
62- for s in pl.range(0, n_full, 1):
63- mul = s * 64
64- xr = vf.load_align(ux, mul, dist=pl.LoadDist.UNPK_B16)
65- xf = vf.astype(xr, m32, dtype=pl.DT_FP32, round_mode=pl.VFRoundMode.CAST_RINT,
66- saturate=pl.SaturateMode.OFF)
67- kr = vf.load_align(uk, mul, dist=pl.LoadDist.UNPK_B16)
68- kf = vf.astype(kr, m32, dtype=pl.DT_FP32, round_mode=pl.VFRoundMode.CAST_RINT,
69- saturate=pl.SaturateMode.OFF)
70- wf = vf.load_align(uw, mul)
71- a_x2 = vf.mul_add_dst(xf, xf, preg)
72- a_k2 = vf.mul_add_dst(kf, kf, preg)
73- tmp = vf.mul(xf, wf, preg)
74- a_dot = vf.mul_add_dst(tmp, kf, preg)
75- if tail != 0:
76- mt = vf.update_mask(tail, dtype=pl.DT_FP32)
77- mul = n_full * 64
78- xr = vf.load_align(ux, mul, dist=pl.LoadDist.UNPK_B16)
79- xf = vf.astype(xr, m32, dtype=pl.DT_FP32, round_mode=pl.VFRoundMode.CAST_RINT,
80- saturate=pl.SaturateMode.OFF)
81- kr = vf.load_align(uk, mul, dist=pl.LoadDist.UNPK_B16)
82- kf = vf.astype(kr, m32, dtype=pl.DT_FP32, round_mode=pl.VFRoundMode.CAST_RINT,
83- saturate=pl.SaturateMode.OFF)
84- wf = vf.load_align(uw, mul)
85- px = vf.mul(xf, xf, mt)
86- a_x2 = vf.add(a_x2, px, preg)
87- pk = vf.mul(kf, kf, mt)
88- a_k2 = vf.add(a_k2, pk, preg)
89- tmp = vf.mul(xf, wf, mt)
90- pd = vf.mul(tmp, kf, mt)
91- a_dot = vf.add(a_dot, pd, preg)
92- 
93- sx2 = vf.reduce_sum(a_x2, preg)
94- sk2 = vf.reduce_sum(a_k2, preg)
95- sdot = vf.reduce_sum(a_dot, preg)
96- 
97- one = vf.full(1.0, dtype=pl.DT_FP32)
98- dimf = vf.full(dim, preg, dtype=pl.DT_FP32)
99- inv_dim = vf.div(one, dimf, preg)
100- sqrt_dim = vf.sqrt(dimf, preg)
101- inv_sqrt_dim = vf.div(one, sqrt_dim, preg)
102- xrms = vf.mul(sx2, inv_dim, preg)
103- xrms = vf.adds(xrms, _EPS, preg)
104- xrms = vf.sqrt(xrms, preg)
105- krms = vf.mul(sk2, inv_dim, preg)
106- krms = vf.adds(krms, _EPS, preg)
107- krms = vf.sqrt(krms, preg)
108- t1 = vf.mul(sdot, inv_sqrt_dim, preg)
109- t2 = vf.mul(xrms, krms, preg)
110- nd = vf.div(t1, t2, preg)
111- absr = vf.abs(nd, preg)
112- absr = vf.maxs(absr, _CLAMP_VALUE, preg)
113- mag = vf.sqrt(absr, preg)
114- neg = vf.lt(nd, 0.0, preg)
115- nmag = vf.muls(mag, -1.0, preg)
116- sr = vf.select(nmag, mag, neg)
117- nsr = vf.muls(sr, -1.0, preg)
118- ex = vf.exp(nsr, preg)
119- den = vf.add(one, ex, preg)
120- gate = vf.div(one, den, preg)
121- gate = vf.full(gate, preg)
122- 
123- for s in pl.range(0, n_full, 1):
124- mul = s * 64
125- ox = vf.load_align(ux, mul, dist=pl.LoadDist.UNPK_B16)
126- xf2 = vf.astype(ox, m32, dtype=pl.DT_FP32, round_mode=pl.VFRoundMode.CAST_RINT,
127- saturate=pl.SaturateMode.OFF)
128- ov = vf.load_align(uv, mul, dist=pl.LoadDist.UNPK_B16)
129- vf2 = vf.astype(ov, m32, dtype=pl.DT_FP32, round_mode=pl.VFRoundMode.CAST_RINT,
130- saturate=pl.SaturateMode.OFF)
131- pr = vf.mul(gate, vf2, preg)
132- res = vf.add(xf2, pr, preg)
133- ob = vf.astype(res, m16, dtype=pl.DT_BF16, round_mode=pl.VFRoundMode.CAST_RINT,
134- saturate=pl.SaturateMode.OFF)
135- ob_pk32 = vf.bit_cast(ob, dtype=pl.DT_UINT32)
136- vf.store_align(uo, ob_pk32, pall_u32, mul, dist=pl.StoreDist.PACK)
137- if tail != 0:
138- mt = vf.update_mask(tail, dtype=pl.DT_FP32)
139- mul = n_full * 64
140- ox = vf.load_align(ux, mul, dist=pl.LoadDist.UNPK_B16)
141- xf2 = vf.astype(ox, m32, dtype=pl.DT_FP32, round_mode=pl.VFRoundMode.CAST_RINT,
142- saturate=pl.SaturateMode.OFF)
143- ov = vf.load_align(uv, mul, dist=pl.LoadDist.UNPK_B16)
144- vf2 = vf.astype(ov, m32, dtype=pl.DT_FP32, round_mode=pl.VFRoundMode.CAST_RINT,
145- saturate=pl.SaturateMode.OFF)
146- pr = vf.mul(gate, vf2, mt)
147- res = vf.add(xf2, pr, mt)
148- ob = vf.astype(res, m16, dtype=pl.DT_BF16, round_mode=pl.VFRoundMode.CAST_RINT,
149- saturate=pl.SaturateMode.OFF)
150- ob_pk32 = vf.bit_cast(ob, dtype=pl.DT_UINT32)
151- vf.store_align(uo, ob_pk32, pall_u32, mul, dist=pl.StoreDist.PACK)
152- 
153- 
154-@pl.jit(auto_mutex=True)
155-def engram_gate_kernel(
156- x: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC, pl.DYNAMIC], pl.DT_BF16],
157- key: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC, pl.DYNAMIC], pl.DT_BF16],
158- value: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC], pl.DT_BF16],
159- weight: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC], pl.DT_FP32],
160- image_mask: pl.Tensor[[pl.DYNAMIC], pl.DT_BOOL],
161- y: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC, pl.DYNAMIC], pl.DT_BF16],
162-):
163- with pl.section_vector():
164- tt = pl.TileType(shape=[1, CHUNK], dtype=pl.DT_BF16, target_memory=pl.MemorySpace.Vec)
165- wt = pl.TileType(shape=[1, CHUNK], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec)
166- uw = pl.make_tile_group(type=wt, addrs=[A_UW], mutex_ids=[9], depth=1)[0]
167- ux_grp = pl.make_tile_group(type=tt, addrs=[A_UX, A_UX + S_BF, A_UX + 2 * S_BF],
168- mutex_ids=[0, 1, 2], depth=3)
169- uk_grp = pl.make_tile_group(type=tt, addrs=[A_UK, A_UK + S_BF, A_UK + 2 * S_BF],
170- mutex_ids=[3, 4, 5], depth=3)
171- uv_grp = pl.make_tile_group(type=tt, addrs=[A_UV, A_UV + S_BF, A_UV + 2 * S_BF],
172- mutex_ids=[6, 7, 8], depth=3)
173- uo_grp = pl.make_tile_group(type=tt, addrs=[A_UO, A_UO + S_BF, A_UO + 2 * S_BF],
174- mutex_ids=[10, 11, 12], depth=3)
175- 
176- hc = x.shape[1]
177- dim = x.shape[2]
178- core = pl.get_block_idx()
179- nc = pl.get_block_num()
180- wcore = core % hc
181- dtok = nc // hc
182- pl.set_validshape(uw, [1, dim])
183- pl.load(uw, weight, [wcore, 0])
184- slot = 0
185- for token in pl.range(core // hc, x.shape[0], dtok):
186- flag = pl.getval(image_mask, token)
187- si = slot % 3
188- if flag != 0:
189- pl.set_validshape(ux_grp[si], [1, dim])
190- pl.load(ux_grp[si], x, [token, wcore, 0])
191- pl.store(y, ux_grp[si], [token, wcore, 0])
192- else:
193- pl.set_validshape(ux_grp[si], [1, dim])
194- pl.load(ux_grp[si], x, [token, wcore, 0])
195- pl.set_validshape(uk_grp[si], [1, dim])
196- pl.load(uk_grp[si], key, [token, wcore, 0])
197- pl.set_validshape(uv_grp[si], [1, dim])
198- pl.load(uv_grp[si], value, [token, 0])
199- engram_gate_vf(ux_grp[si], uk_grp[si], uw, uv_grp[si], uo_grp[si], dim)
200- pl.set_validshape(uo_grp[si], [1, dim])
201- pl.store(y, uo_grp[si], [token, wcore, 0])
202- slot = slot + 1
203- 
204- 
205-def engram_gate_wrapper(x, key, value, weight, image_mask, eps=_EPS, clamp_value=_CLAMP_VALUE):
206- """Public wrapper: validate, allocate the output and launch the kernel once."""
207- t, hc, dim = x.shape
208- if list(key.shape) != [t, hc, dim] or list(weight.shape) != [hc, dim]:
209- raise ValueError("key/weight shapes do not match x")
210- if list(value.shape) != [t, dim] or list(image_mask.shape) != [t]:
211- raise ValueError("value/image_mask shapes do not match x")
212- if dim > CHUNK:
213- raise ValueError(f"dim {dim} exceeds the supported single-scan width {CHUNK}")
214- if not math.isclose(eps, _EPS) or not math.isclose(clamp_value, _CLAMP_VALUE):
215- raise ValueError(
216- f"this kernel bakes eps={_EPS} and clamp_value={_CLAMP_VALUE}, "
217- f"got eps={eps} and clamp_value={clamp_value}")
218- y = torch.empty((t, hc, dim), dtype=torch.bfloat16, device=x.device)
219- # The kernel strides tokens by nc // hc, so the launch width must be a multiple
220- # of hc; for every supported shape this leaves the launched core count unchanged.
221- block_dim = min(_vector_core_count(), t * hc)
222- block_dim -= block_dim % hc
223- with pypto.options(pass_options={"enable_slice": False}):
224- engram_gate_kernel[None, block_dim](x, key, value, weight, image_mask, y)
225- return y