Merged
feat(operator): Add ling_3_1_flash_code #1146
feat(operator): Add ling_3_1_flash_code #1146
Merged
叶凡Add on 3 days ago
Total: 8 files changed+5881-0
@@ -0,0 +1,149 @@
1+# flash_kda — Flash Kimi Delta Attention(融合两阶段 prefill)
2+ 
3+`flash_kda` 的 PyPTO-Pro 融合实现:Kimi Delta Attention prefill 融合为**单个** AICore kernel(stage1 段 + `sync_all(MIX)` 全局屏障 + stage2 段),由单入口 `flash_kda_wrapper` 启动(dense 与 TND 各一次 launch,无第二次 kernel 下发)。
4+ 
5+## 产品支持情况
6+ 
7+- Ascend 950PR / 950DT:支持。
8+ 
9+## 功能说明
10+ 
11+**stage1 段**(flat `(chunk, head)` 软件流水)完成块内预计算:门控激活与 Q/K L2 归一化 → 块内累积门控 `cs`(chunk 内 cumsum,跨 chunk 清零)→ 衰减 Query/Key 与块末衰减 → KKT / Mqk(块相对逐行归一化形式,避免 exp 上溢)→ Neumann 求逆 `(I+T)⁻¹` 与融合 `W`/`Upre`。中间量写入 GM 工作区。
12+ 
13+两段之间由一条顶层 `pl.system.sync_all(core_type=pl.SyncCoreType.MIX)` 全局屏障衔接(替代原先两次 launch 的 kernel 边界):stage1 的全部 GM 中间结果(qd/kr/gam/mqk/w/upre)对 stage2 段的 MTE2/UB 读可见;stage1 的手写核间事件在屏障前 set==wait 全部清空(kn/cs-done 两条通道各余 1 个 token,stage2 不复用 7/14),其余通道可跨段复用。
14+ 
15+块内常量(合并掩码 `sl_mask`、累积门控下三角 `L_tril`、Neumann 种子单位阵 `eye64`)全部在 kernel 内部由 INT32 lane 索引构造(`ltril_rows_vf` / `eye_rows_vf` 等),不经 GM 传入:dense 与 TND(varlen)每调用均仅 1 次 AICore kernel launch,无任何 host 侧小算子;`lower_bound`/`scale` 以 kernel 标量参数(launch host args)下发,无 per-call H2D。
16+ 
17+**stage2 段**(每个 `(batch, value head)` 按 $D_v$ 切成 `128/DV` 个 dv 切片;`DV` 由编译期 tiling key `Stage2VRows` 选择——dense ∈ {16,64,128}、TND ∈ {16,64}(仅当段数×V head 数 ≥ 2×核数的大网格时用 128),见 `_stage2_v_rows`)完成跨块递推与输出合成,状态 S 常驻 UB 不落 GM:
18+ 
19+$$
20+\Delta_c = U_{pre,c} + W_c S_{c-1}^{\top},\qquad
21+O_c = Q_{d,c} S_{c-1}^{\top} + M_{qk,c}\,\Delta_c,\qquad
22+S_c = S_{c-1}\operatorname{diag}(\mathrm{gam}_c) + \Delta_c^{\top} K^{r}_c
23+$$
24+ 
25+## 接口
26+ 
27+```python
28+flash_kda_wrapper(q, k, v, g, beta, scale, initial_state,
29+ a_log, dt_bias, lower_bound,
30+ layout_qkv="BSND", cu_seqlens=None)
31+ -> (out, final_state)
32+```
33+ 
34+### dense 模式(`cu_seqlens=None`,BSND / BNSD)
35+ 
36+> **⚠️ 长度对齐要求**:dense 路径要求 `S` 为 **64 的整倍数**(`S >= 64`)。
37+> **非 64 对齐或变长场景必须走下方 varlen 模式**——
38+> 且无需任何预 padding:单条不对齐序列只要传 `cu_seqlens=[0, S]`(或直接用 TND 3-D 形态),
39+> 补零在 kernel 片上完成,无 GM padding 拷贝,额外开销为零。
40+ 
41+| 参数 | 类型 | shape | 说明 |
42+|---|---|---|---|
43+| `q` / `k` | bf16 | `[B,S,Nk,D]`(BSND)或 `[B,Nk,S,D]`(BNSD) | 原始 query/key(核内做 L2 归一化与 scale) |
44+| `v` | bf16 | `[B,S,Nv,D]` / `[B,Nv,S,D]` | value |
45+| `g` | bf16 | `[B,S,Nv,D]` / `[B,Nv,S,D]` | 原始门控输入(核内激活) |
46+| `beta` | bf16 | `[B,S,Nv]` / `[B,Nv,S]` | beta logit(核内 sigmoid) |
47+| `scale` | float | — | query 缩放系数(一般传 `D**-0.5`) |
48+| `initial_state` | fp32 | `[B,Nv,Dv,Dk]` | 初始循环状态(无初态传全零张量) |
49+| `a_log` | fp32 | `[Nv]` | 门控系数(核内取 exp) |
50+| `dt_bias` | fp32 | `[Nv,D]` | 门控偏置 |
51+| `lower_bound` | float | `[-5, 0]` | 门控下界 |
52+| `layout_qkv` | str | — | `"BSND"` / `"BNSD"` |
53+ 
54+返回:`(out [B,S,Nv,D] bf16, final_state [B,Nv,Dv,Dk] fp32)`。
55+ 
56+### varlen 模式(`cu_seqlens` 给定或 `layout_qkv="TND"`)
57+ 
58+> **适用:一切非 64 对齐 / 变长 / 多段场景。** 段边界(`cu_seqlens` 取值)不需要 64 对齐,
59+> 单条不对齐序列传 `cu_seqlens=[0, S]` 即可;TND 与 packed BSND+cu 是同一 kernel,
60+> 结果 bit 一致、性能相同。
61+ 
62+- packed token-major 输入:4-D `[1,T,H,D]`(packed BSND)或 3-D `[T,Nk,D]`(TND);
63+- `cu_seqlens`:int32/int64 `[N+1]`,device 上,`cu[0]==0`、`cu[-1]==T`,各段非空(段长任意,含单 token);
64+- 序列按 64-token chunk 核内补零(无 GM padding 拷贝),各序列状态独立,无论序列数均只 1 次 kernel launch;
65+- 任务网格只分派真实 chunk 数($\sum_i \lceil len_i/64 \rceil \times N_{v}$,按 chunk-major 序遍历):
66+ 长度为 64 整数倍的段不再产生空 chunk 的流水槽位;同一核相邻任务的 chunk 序号单调递增,
67+ 段边界由增量游标推进(`tnd_advance_chunk`),替代逐任务全量重扫 `cu_seqlens`;
68+- 返回:`(out [1,T,Nv,D] bf16, final_state [N,Nv,Dv,Dk] fp32)`。
69+ 
70+## 使用示例
71+ 
72+```python
73+import torch, torch_npu
74+from ops.pypto_pro.ling_3_1_flash.flash_kda.flash_kda import flash_kda_wrapper
75+ 
76+B, S, Nk, Nv, D = 1, 4096, 4, 4, 128
77+dev = "npu:0"
78+q = torch.randn(B, S, Nk, D, dtype=torch.bfloat16, device=dev)
79+k = torch.randn(B, S, Nk, D, dtype=torch.bfloat16, device=dev)
80+v = torch.randn(B, S, Nv, D, dtype=torch.bfloat16, device=dev)
81+g = torch.randn(B, S, Nv, D, dtype=torch.bfloat16, device=dev)
82+beta = torch.randn(B, S, Nv, dtype=torch.bfloat16, device=dev)
83+a_log = torch.randn(Nv, dtype=torch.float32, device=dev)
84+dt_bias = torch.randn(Nv, D, dtype=torch.float32, device=dev)
85+init_s = torch.zeros(B, Nv, D, D, dtype=torch.float32, device=dev)
86+ 
87+out, final_state = flash_kda_wrapper(
88+ q, k, v, g, beta, scale=D ** -0.5, initial_state=init_s,
89+ a_log=a_log, dt_bias=dt_bias, lower_bound=-5.0, layout_qkv="BSND")
90+```
91+ 
92+varlen(两条序列打包,T=200=128+72):
93+ 
94+```python
95+T = 200
96+cu = torch.tensor([0, 128, 200], dtype=torch.int32, device=dev)
97+out, final_state = flash_kda_wrapper(
98+ q.view(1, T, Nk, D), k.view(1, T, Nk, D), v.view(1, T, Nv, D),
99+ g.view(1, T, Nv, D), beta.view(1, T, Nv), scale=D ** -0.5,
100+ initial_state=torch.zeros(2, Nv, D, D, dtype=torch.float32, device=dev),
101+ a_log=a_log, dt_bias=dt_bias, lower_bound=-5.0,
102+ layout_qkv="BSND", cu_seqlens=cu)
103+```
104+ 
105+TND(3-D token-major,无 batch 轴;与 packed BSND 走同一 TND kernel,结果逐位一致):
106+ 
107+```python
108+T = 200
109+cu = torch.tensor([0, 128, 200], dtype=torch.int32, device=dev)
110+out, final_state = flash_kda_wrapper(
111+ q[0], k[0], v[0], g[0], beta[0], # [T,Nk,D]×2 / [T,Nv,D] / [T,Nv]
112+ scale=D ** -0.5,
113+ initial_state=torch.zeros(2, Nv, D, D, dtype=torch.float32, device=dev),
114+ a_log=a_log, dt_bias=dt_bias, lower_bound=-5.0,
115+ layout_qkv="TND", cu_seqlens=cu)
116+```
117+ 
118+注意:TND 形态要求 q/k/g 为 3-D `[T,Nk(Dv),D]`、beta 为 2-D `[T,Nv]`;返回值仍带 batch 轴(`out [1,T,Nv,D]`、`final_state [N,Nv,D,D]`)。
119+ 
120+**非 64 对齐单序列**(最常见误区:以为必须补齐到 64 才能用)——传 `cu_seqlens=[0, S]` 即可,不要自行补零:
121+ 
122+```python
123+S = 100 # 非 64 对齐
124+cu = torch.tensor([0, S], dtype=torch.int32, device=dev)
125+out, final_state = flash_kda_wrapper(
126+ q.view(1, S, Nk, D), k.view(1, S, Nk, D), v.view(1, S, Nv, D),
127+ g.view(1, S, Nv, D), beta.view(1, S, Nv), scale=D ** -0.5,
128+ initial_state=torch.zeros(1, Nv, D, D, dtype=torch.float32, device=dev),
129+ a_log=a_log, dt_bias=dt_bias, lower_bound=-5.0,
130+ layout_qkv="BSND", cu_seqlens=cu) # 补零在核内完成,开销为零
131+```
132+ 
133+## 约束与限制
134+ 
135+- `Dk = Dv = D = 128`,固定;
136+- dense 模式 `S` 必须为 64 的正整数倍;**非对齐 / 变长请改用 varlen 模式**(传 `cu_seqlens` 或 `layout_qkv="TND"`,单条不对齐序列传 `cu_seqlens=[0, S]`,切勿自行预 padding);
137+- GQA:`Nv % Nk == 0`;
138+- 规格上限(冻结 SPEC 验收边界):`B <= 64`(varlen 即段数 `R <= 64`)、`Nk <= 64`、`Nv <= 96`;
139+- `lower_bound ∈ [-5, 0]`;
140+- varlen 要求 packed batch size 为 1,且仅支持 packed BSND 语义;
141+- 状态方向为 `[Dv, Dk]`(与 cannbot-dsl 参考一致;与 fla naive 的 `[K,V]` 方向互为转置);
142+- 输入 bf16、状态 fp32、输出 bf16;所有张量须在同一 NPU 上且连续。
143+ 
144+## 文件列表
145+ 
146+| 文件 | 作用 |
147+|---|---|
148+| `flash_kda_impl.py` | kernel 实现:融合主 kernel `flash_kda_kernel`(stage1 段 + sync_all + stage2 段)与 TND 变体 `flash_kda_tnd_kernel` + 公开入口 `flash_kda_wrapper` |
149+| `README.md` | 本文件:接口、约束与使用说明 |
@@ -0,0 +1,110 @@
1+# fused_recurrent_kda — 递归 KDA decode
2+ 
3+`fused_recurrent_kda` 的 PyPTO-Pro 实现:逐 token 的 gated delta-rule 递归 decode kernel(单 Vector section),面向 decode / MTP 短序列场景,与 cannbot-dsl 参考实现 bit-level 对齐。
4+ 
5+## 产品支持情况
6+ 
7+- Ascend 950PR / 950DT:支持。
8+ 
9+## 功能说明
10+ 
11+对每个 `(batch, value head)` 逐 token 执行(全部 fp32 计算):
12+ 
13+1. **L2 归一化 Q/K**(div 形式,eps=1e-6 在 sqrt 内):`q_scaled = q/sqrt(Σq²+1e-6)·scale`;k 归一化但不乘 scale;
14+2. **门控激活**:`decay = lower_bound·sigmoid(exp(A_log)·(g+dt_bias))`(per-D,128 维);`beta_act = sigmoid(beta)`(标量);
15+3. **状态递推**(状态 `[Dv,Dk]` fp32,跨 token 常驻 UB):
16+ 
17+$$
18+sk = \textstyle\sum_j S_{t-1}[dv,j]\cdot d[j]\cdot \bar k[j],\quad
19+\delta = \beta\,(v - sk),\quad
20+S_t = S_{t-1}\odot d + \delta\,\bar k^{\top},\quad
21+o_t = S_t\,\bar q
22+$$
23+ 
24+4. **输出** bf16 写 GM;状态 fp32 in-place 快照写回状态池。
25+ 
26+## 接口
27+ 
28+```python
29+fused_recurrent_kda_wrapper(query, key, value, state, beta, g,
30+ scale, A_log, dt_bias, lower_bound,
31+ layout_qkv,
32+ *, ssm_state_indices=None,
33+ num_accepted_tokens=None,
34+ cu_seqlens=None)
35+ -> (state, output)
36+```
37+ 
38+| 参数 | 类型 | shape | 说明 |
39+|---|---|---|---|
40+| `query` | bf16 | `[B,S,Nk,D]`(BSND)或 `[B,Nk,S,D]`(BNSD) | 原始 query(核内归一化 + scale) |
41+| `key` | bf16 | 同 query 布局 | 原始 key(核内归一化,不乘 scale) |
42+| `value` | bf16 | `[B,S,Nv,D]` / `[B,Nv,S,D]` | value |
43+| `state` | fp32 | `[pool, Nv, 128, 128]` | 循环状态池,**in-place 更新** |
44+| `beta` | bf16 | `[B,S,Nv]` / `[B,Nv,S]` | beta logit(核内 sigmoid) |
45+| `g` | bf16 | `[B,S,Nv,D]` / `[B,Nv,S,D]` | 原始门控输入(核内激活) |
46+| `scale` | float | — | query 缩放(一般 `D**-0.5`) |
47+| `A_log` | fp32 | `[Nv]` | 门控系数(核内取 exp) |
48+| `dt_bias` | fp32 | `[Nv,D]` | 门控偏置 |
49+| `lower_bound` | float | `[-5, 0]` | 门控下界 |
50+| `layout_qkv` | str | — | `"BSND"` / `"BNSD"` |
51+| `ssm_state_indices` | int64,可选 | `[B·S]` | 状态池槽号;缺省时按 `b·S+t` 算术槽寻址 |
52+| `num_accepted_tokens` | int64,可选 | `[B]` | 每 batch 已接受 token 数;缺省按 1 |
53+| `cu_seqlens` | int32/int64,可选 | `[N+1]` | TND varlen 累计序列长度(`cu[0]==0`、`cu[-1]==T`) |
54+ 
55+返回:`(state, output)` —— `state` 为更新后的状态池(与入参同一张量),`output` 为 bf16,布局与输入一致。
56+ 
57+### 状态池槽位语义(dense)
58+ 
59+- 初态槽:`ssm[b·S + na[b] − 1]`(最后接受 token 的快照);
60+- 快照槽:token t 写 `ssm[b·S + t]`;
61+- `ssm` / `na` 均缺省时:`ssm[b·S+t] = b·S+t`(即 pool 需 ≥ `B·S` 个槽,等价逐 batch 顺序排布)。
62+ 
63+### varlen(`cu_seqlens`)
64+ 
65+- packed batch size 为 1:`query [1,T,Nk,D]`(BSND)或 `[1,Nk,T,D]`(BNSD);
66+- 单次 launch 覆盖所有 segment,序列间状态不跨越;
67+- `state` 为 `[T, Nv, D, D]`:序列 i 从槽 `cu[i]` 读初态、原地快照更新 `[cu[i], cu[i+1])`,终态位于槽 `cu[i+1]−1`;
68+- `ssm_state_indices` / `num_accepted_tokens` 不适用于 varlen 路径。
69+ 
70+## 使用示例
71+ 
72+```python
73+import torch, torch_npu
74+from ops.pypto_pro.ling_3_1_flash.fused_recurrent_kda.fused_recurrent_kda_impl import (
75+ fused_recurrent_kda_wrapper)
76+ 
77+B, S, Nk, Nv, D = 2, 1, 4, 4, 128 # decode:每 batch 1 个 token
78+dev = "npu:0"
79+pool = 8
80+state = torch.zeros(pool, Nv, D, D, dtype=torch.float32, device=dev)
81+args = dict(
82+ query=torch.randn(B, S, Nk, D, dtype=torch.bfloat16, device=dev),
83+ key=torch.randn(B, S, Nk, D, dtype=torch.bfloat16, device=dev),
84+ value=torch.randn(B, S, Nv, D, dtype=torch.bfloat16, device=dev),
85+ beta=torch.randn(B, S, Nv, dtype=torch.bfloat16, device=dev),
86+ g=torch.randn(B, S, Nv, D, dtype=torch.bfloat16, device=dev),
87+ scale=D ** -0.5,
88+ A_log=torch.randn(Nv, dtype=torch.float32, device=dev),
89+ dt_bias=torch.randn(Nv, D, dtype=torch.float32, device=dev),
90+ lower_bound=-5.0,
91+ layout_qkv="BSND",
92+)
93+state, output = fused_recurrent_kda_wrapper(state=state, **args)
94+```
95+ 
96+## 约束与限制
97+ 
98+- `Dk = Dv = D = 128`,固定;GQA:`Nv % Nk == 0`;
99+- `state` 必须为 fp32,in-place 更新;其余输入 bf16、输出 bf16;
100+- `lower_bound ∈ [-5, 0]`;
101+- 自定义槽路径(P1):`ssm_state_indices` / `num_accepted_tokens` 必须为 int64 且连续;
102+- varlen 路径要求 packed batch size 为 1,且不支持 ssm/na 自定义槽;
103+- 所有张量须在同一 NPU 上且连续;
104+- `row_block` 由 wrapper 自动选择(`B·Nv ≤ 16 → 32`,否则 64),无需配置。
105+ 
106+## 文件列表
107+ 
108+| 文件 | 作用 |
109+|---|---|
110+| `fused_recurrent_kda_impl.py` | kernel 实现:常量、UB 布局表、vector function、`@pl.jit` kernel 与 wrapper |
@@ -0,0 +1,315 @@
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+ 
12+"""PyPTO-Pro flash_kda CPU golden reference (higher precision, pure torch).
13+ 
14+Pure-CPU FP32 reference with the same mathematical steps and the same documented bf16
15+narrow-intermediate quantization points (Qd/Kr/Mqk/W/Upre/U).
16+Properties:
17+ - pure CPU, no torch_npu, no device selection;
18+ - bf16 inputs are promoted to fp32 for computation;
19+ - outputs are returned in FP32 (out is NOT cast back to bf16; final_state is fp32);
20+ - math semantics are identical.
21+ 
22+Golden operation inventory (canonical BSND physical order (B,S,H,D); BNSD is the same
23+logical tensor with (head, seq) swapped):
24+ 1. gate[b,hv,t,d] = lower_bound * sigmoid(exp(a_log[hv]) * (g[b,t,hv,d] + dt_bias[hv,d]))
25+ 2. cs[b,hv,c,l,d] = chunk-local cumsum over l in [0,64) of gate (resets per chunk), fp32
26+ 3. qn/kn row-L2 div normalize (denom sqrt(sum x^2)+1e-6, fp32 accum, stored bf16)
27+ 4. Qd = bf16(qn*exp(cs)*scale) (key head hk = hv // (Nv//Nk))
28+ 5. Kr = bf16(kn*exp(cs[C-1]-cs))
29+ 6. gam = exp(cs[C-1]) (fp32, may underflow to 0)
30+ 7. beta_s = sigmoid(beta)
31+ 8. strictly-lower KKT T[r,l] = sum_d kn[r]*kn[l]*exp(cs[r]-cs[l]) (r>l), built with the
32+ reference block-relative per-D operands (all exp args <= 0, overflow-safe)
33+ 9. Inv = (I + T_beta)^{-1} via 64-term Neumann series, T_beta = row-beta-weighted T
34+ 10. W = bf16(Inv @ (-beta_s * kn*exp(cs))) (K side -beta)
35+ 11. Upre = bf16(Inv @ (beta_s * v)) (V side +beta)
36+ 12. Mqk = bf16(causal incl-diag scale*qn*kn*exp(cs[r]-cs[l]))
37+ 13. U = bf16(Upre + W@S) (U is (C,V))
38+ 14. O = Qd@S + Mqk@U (fp32 acc); out stays fp32 in this CPU reference
39+ 15. S <- gam*S + Kr^T@U (fp32 (K,V) rows=key cols=value; equivalent to SPEC's literal
40+ "gam*S + U^T@Kr" transposed to the canonical KDA orientation of
41+ ref_kda.naive_chunk_kda; update after output; gam per-K dim)
42+ 
43+Semantic source: SPEC machine contract + precision red lines and reference
44+ /home/daiyuwen/code/cann-recipes-infer/ops/cannbot_dsl/flash_kda.py
45+ (flash_kda() L2072, _run_stage1_body() L1306, _run_stage2_body() L1694).
46+This file is pure torch; it does NOT import cannbotdsl.
47+"""
48+ 
49+import torch
50+ 
51+# ─────────────────────────────────────────────
52+# CPU Golden 参考实现(更高精度)
53+# ─────────────────────────────────────────────
54+ 
55+_CHUNK = 64 # CHUNK_SIZE (frozen)
56+_HEAD_DIM = 128 # Dk = Dv = 128 (frozen)
57+_L2_EPS = 1e-6 # l2 eps (frozen)
58+ 
59+ 
60+def _bf16_round(x: torch.Tensor) -> torch.Tensor:
61+ """Quantize an fp32 tensor to bf16 and promote back to fp32 representation."""
62+ return x.to(torch.bfloat16).to(torch.float32)
63+ 
64+ 
65+def flash_kda_golden_cpu(
66+ q: torch.Tensor,
67+ k: torch.Tensor,
68+ v: torch.Tensor,
69+ g: torch.Tensor,
70+ beta: torch.Tensor,
71+ scale: float,
72+ initial_state: torch.Tensor,
73+ a_log: torch.Tensor,
74+ dt_bias: torch.Tensor,
75+ lower_bound: float,
76+ layout_qkv: str,
77+ cu_seqlens=None,
78+):
79+ """FlashKDA forward (Flash Kimi Delta Attention) high-precision CPU reference.
80+ 
81+ Args:
82+ q: query, bf16, BSND (B,S,Nk,D) or BNSD (B,Nk,S,D).
83+ k: key, bf16, same shape/layout as q.
84+ v: value, bf16, BSND (B,S,Nv,D) or BNSD (B,Nv,S,D).
85+ g: raw gate input, bf16, same shape/layout as v.
86+ beta: raw beta logits, bf16, BSND (B,S,Nv) or BNSD (B,Nv,S).
87+ scale: float scaling factor.
88+ initial_state: caller-owned persistent state, fp32 (B,Nv,D,D).
89+ a_log: per-value-head log-gain, fp32 (Nv,).
90+ dt_bias: per-head bias, fp32 (Nv,D).
91+ lower_bound: float in [-5, 0].
92+ layout_qkv: "BSND" or "BNSD" (physical axis order; semantics identical).
93+ cu_seqlens: must be None (variable-length not supported).
94+ 
95+ Returns:
96+ (out, final_state): out FP32 same layout as inputs (BSND (B,S,Nv,D) /
97+ BNSD (B,Nv,S,D)); final_state fp32 (B,Nv,D,D), fresh tensor.
98+ """
99+ if not (layout_qkv in ("BSND", "BNSD")):
100+ raise AssertionError(f"layout_qkv must be BSND or BNSD, got {layout_qkv!r}")
101+ 
102+ # Normalize to canonical BSND (B, S, H, D) semantics; BNSD only changes axis order.
103+ if layout_qkv == "BNSD":
104+ q = q.transpose(1, 2)
105+ k = k.transpose(1, 2)
106+ v = v.transpose(1, 2)
107+ g = g.transpose(1, 2)
108+ beta = beta.transpose(1, 2)
109+ 
110+ batch_v, seq_len_v, num_key_heads, head_dim = q.shape
111+ num_value_heads = v.shape[2]
112+ chunk_size = _CHUNK
113+ if not (head_dim == _HEAD_DIM):
114+ raise AssertionError(f"flash_kda supports only D={_HEAD_DIM}, got {head_dim}")
115+ if not (num_value_heads % num_key_heads == 0):
116+ raise AssertionError(f"GQA requires Nv % Nk == 0, got Nv={num_value_heads}, Nk={num_key_heads}")
117+ 
118+ scale = float(scale)
119+ lower_bound = float(lower_bound)
120+ 
121+ if cu_seqlens is not None:
122+ return _golden_varlen_bsnd(q, k, v, g, beta, scale, initial_state,
123+ a_log, dt_bias, lower_bound, cu_seqlens)
124+ 
125+ if not (seq_len_v % chunk_size == 0):
126+ raise AssertionError(f"S must be a multiple of {chunk_size}")
127+ 
128+ # ---- fp32 arithmetic domain (inputs may be bf16; promoted here) ----
129+ q32 = q.to(torch.float32)
130+ k32 = k.to(torch.float32)
131+ v32 = v.to(torch.float32)
132+ g32 = g.to(torch.float32)
133+ beta32 = beta.to(torch.float32)
134+ a_log32 = a_log.to(torch.float32)
135+ dt_bias32 = dt_bias.to(torch.float32)
136+ 
137+ out, final_state = _golden_fixed_core(
138+ q32, k32, v32, g32, beta32, scale, initial_state, a_log32,
139+ dt_bias32, lower_bound)
140+ if layout_qkv == "BNSD":
141+ out = out.transpose(1, 2).contiguous()
142+ return out, final_state
143+ 
144+ 
145+def _golden_varlen_bsnd(q, k, v, g, beta, scale, initial_state, a_log,
146+ dt_bias, lower_bound, cu_seqlens):
147+ """TND varlen reference: per-sequence fixed-length core over padded segments.
148+ 
149+ Mirrors the kernel varlen trick: each segment is zero-padded to a multiple
150+ of 64 except raw g, whose pad rows are set to -inf so the activated gate is
151+ exactly 0 (chunk cumsum stays flat and the state/gamma math is untouched);
152+ the padded output rows are exactly zero and are sliced away.
153+ """
154+ if cu_seqlens.dtype not in (torch.int32, torch.int64):
155+ raise TypeError(f"cu_seqlens must be int32/int64, got {cu_seqlens.dtype}")
156+ if cu_seqlens.dim() != 1 or cu_seqlens.numel() < 2:
157+ raise ValueError("cu_seqlens must be 1-D [N+1] with N >= 1")
158+ cu_list = cu_seqlens.tolist()
159+ if cu_list[0] != 0:
160+ raise ValueError("cu_seqlens[0] must be 0")
161+ if any(b < a_ for a_, b in zip(cu_list, cu_list[1:])):
162+ raise ValueError("cu_seqlens must be non-decreasing")
163+ token_count = q.shape[1]
164+ if cu_list[-1] != token_count:
165+ raise ValueError(f"cu_seqlens[-1] must equal T={token_count}, got {cu_list[-1]}")
166+ num_seqs = len(cu_list) - 1
167+ num_value_heads_v = v.shape[2]
168+ head_dim_v = q.shape[3]
169+ if initial_state is not None:
170+ if not (tuple(initial_state.shape) == (num_seqs, num_value_heads_v, head_dim_v, head_dim_v)):
171+ raise AssertionError(f"initial_state must be (N,{num_value_heads_v},{head_dim_v},{head_dim_v}) for varlen")
172+ if not (initial_state.dtype == torch.float32):
173+ raise AssertionError("")
174+ 
175+ out = torch.empty(1, token_count, num_value_heads_v, head_dim_v, dtype=torch.float32)
176+ st_in = (torch.zeros(num_seqs, num_value_heads_v, head_dim_v, head_dim_v, dtype=torch.float32)
177+ if initial_state is None else initial_state.to(torch.float32).clone())
178+ final_state = torch.empty(num_seqs, num_value_heads_v, head_dim_v, head_dim_v, dtype=torch.float32)
179+ 
180+ neg_inf = float("-inf")
181+ for n in range(num_seqs):
182+ bos, eos = cu_list[n], cu_list[n + 1]
183+ slen = eos - bos
184+ padded_len = ((slen + _CHUNK - 1) // _CHUNK) * _CHUNK
185+ 
186+ def _pad(t, fill, padded_len_v=padded_len, slen=slen, bos=bos, eos=eos):
187+ p = torch.full((1, padded_len_v) + tuple(t.shape[2:]), fill, dtype=torch.float32)
188+ p[:, :slen] = t[:, bos:eos].to(torch.float32)
189+ return p
190+ 
191+ q32 = _pad(q, 0.0)
192+ k32 = _pad(k, 0.0)
193+ v32 = _pad(v, 0.0)
194+ g32 = _pad(g, neg_inf)
195+ beta32 = _pad(beta, 0.0)
196+ o_n, fs_n = _golden_fixed_core(
197+ q32, k32, v32, g32, beta32, scale, st_in[n:n + 1],
198+ a_log.to(torch.float32), dt_bias.to(torch.float32), lower_bound)
199+ out[0, bos:eos] = o_n[0, :slen]
200+ final_state[n] = fs_n[0]
201+ return out, final_state
202+ 
203+ 
204+def _golden_fixed_core(q32, k32, v32, g32, beta32, scale, initial_state,
205+ a_log32, dt_bias32, lower_bound):
206+ """Fixed-length BSND fp32 core: q/k/v/g/beta [1,S,H,D] fp32, S % 64 == 0.
207+ 
208+ Returns (out fp32 [1,S,Nv,D], final_state fp32 [1,Nv,D,D])."""
209+ batch_v2, seq_len_v2, num_key_heads_v, head_dim_v2 = q32.shape
210+ num_value_heads_v2 = v32.shape[2]
211+ chunk_size_v = _CHUNK
212+ if not (head_dim_v2 == _HEAD_DIM):
213+ raise AssertionError(f"flash_kda supports only D={_HEAD_DIM}, got {head_dim_v2}")
214+ if not (seq_len_v2 % chunk_size_v == 0):
215+ raise AssertionError(f"S must be a multiple of {chunk_size_v}")
216+ if not (num_value_heads_v2 % num_key_heads_v == 0):
217+ raise AssertionError(f"GQA requires Nv % Nk == 0, got Nv={num_value_heads_v2}, Nk={num_key_heads_v}")
218+ nc = seq_len_v2 // chunk_size_v
219+ 
220+ scale = float(scale)
221+ lower_bound = float(lower_bound)
222+ 
223+ # (1) gate activation (fp32)
224+ gate = lower_bound * torch.sigmoid(
225+ torch.exp(a_log32.reshape(1, 1, num_value_heads_v2, 1)) * \
226+ (g32 + dt_bias32.reshape(1, 1, num_value_heads_v2, head_dim_v2))
227+ ) # (B,S,Nv,D), values in [lower_bound, 0]
228+ 
229+ # (2) chunk-local cumulative sum over l (resets every C rows), fp32
230+ # NOTE: (B,S,Nv,D) -> (B,Nv,S,D) -> (B,Nv,nc,C,D); a plain reshape would reorder
231+ # the (seq, head) axes whenever Nv > 1.
232+ gate_c = gate.permute(0, 2, 1, 3).reshape(batch_v2, num_value_heads_v2, nc, chunk_size_v, head_dim_v2)
233+ cs = torch.cumsum(gate_c, dim=3) # (B,Nv,nc,C,D)
234+ 
235+ # (3) row-L2 normalize q/k: div form, fp32 accumulate, result stored bf16
236+ qn32 = q32 / (q32.square().sum(-1, keepdim=True).sqrt() + _L2_EPS)
237+ kn32 = k32 / (k32.square().sum(-1, keepdim=True).sqrt() + _L2_EPS)
238+ qn = _bf16_round(qn32) # (B,S,Nk,D)
239+ kn = _bf16_round(kn32) # (B,S,Nk,D)
240+ 
241+ # GQA: value head hv shares key head hk = hv // (Nv//Nk)
242+ heads_per_key_head = num_value_heads_v2 // num_key_heads_v
243+ hk_idx = torch.arange(num_value_heads_v2) // heads_per_key_head
244+ qn_v = qn[:, :, hk_idx, :].permute(0, 2, 1, 3).reshape(batch_v2, num_value_heads_v2, nc, chunk_size_v, head_dim_v2)
245+ kn_v = kn[:, :, hk_idx, :].permute(0, 2, 1, 3).reshape(batch_v2, num_value_heads_v2, nc, chunk_size_v, head_dim_v2)
246+ v_c = v32.permute(0, 2, 1, 3).reshape(batch_v2, num_value_heads_v2, nc, chunk_size_v, head_dim_v2)
247+ 
248+ beta_s = torch.sigmoid(beta32).permute(0, 2, 1).reshape(
249+ batch_v2, num_value_heads_v2, nc, chunk_size_v, 1) # (B,Nv,nc,C,1)
250+ 
251+ # (4) Qd / (5) Kr / (6) gamma
252+ qd = _bf16_round(qn_v * torch.exp(cs) * scale) # (B,Nv,nc,C,D)
253+ cs_last = cs[:, :, :, -1:, :]
254+ kr = _bf16_round(kn_v * torch.exp(cs_last - cs)) # (B,Nv,nc,C,D)
255+ gam = torch.exp(cs_last).squeeze(3) # (B,Nv,nc,D)
256+ 
257+ # (8) KKT with the reference block-relative per-D operands (overflow-safe)
258+ kkt_full = torch.zeros((batch_v2, num_value_heads_v2, nc, chunk_size_v, chunk_size_v), dtype=torch.float32)
259+ mqk_full = torch.zeros_like(kkt_full)
260+ row_block = chunk_size_v // 4 # 16
261+ for rb in range(4):
262+ r0 = rb * row_block
263+ ref = cs[:, :, :, r0, :] # (B,Nv,nc,D) row-block base
264+ cmax = r0 + row_block # only lower blocks are materialized
265+ l_op = (kn_v[:, :, :, r0:r0 + row_block]
266+ * torch.exp(cs[:, :, :, r0:r0 + row_block] - ref.unsqueeze(3))) # <= |kn|
267+ r_op = (kn_v[:, :, :, :cmax]
268+ * torch.exp(ref.unsqueeze(3) - cs[:, :, :, :cmax])) # <= |kn|
269+ kkt_full[:, :, :, r0:r0 + row_block, :cmax] = torch.matmul(
270+ l_op, r_op.transpose(-1, -2))
271+ lq_op = (qn_v[:, :, :, r0:r0 + row_block]
272+ * torch.exp(cs[:, :, :, r0:r0 + row_block] - ref.unsqueeze(3))
273+ * scale)
274+ mqk_full[:, :, :, r0:r0 + row_block, :cmax] = torch.matmul(
275+ lq_op, r_op.transpose(-1, -2))
276+ strict_lower = torch.tril(torch.ones(chunk_size_v, chunk_size_v, dtype=torch.bool), diagonal=-1)
277+ t_mat = kkt_full.masked_fill(~strict_lower, 0.0)
278+ # reference realization: inverse uses the row-beta-weighted strictly-lower matrix
279+ t_beta = t_mat * beta_s
280+ 
281+ # (9) Inv = (I + T_beta)^{-1} realized as 64-term Neumann series sum_{k=0..63} (-T_beta)^k
282+ p = -t_beta
283+ inv = torch.eye(chunk_size_v, dtype=p.dtype).reshape(1, 1, 1, chunk_size_v, chunk_size_v).expand_as(p)
284+ acc = p
285+ for _ in range(63):
286+ inv = inv + acc
287+ acc = torch.matmul(acc, p)
288+ 
289+ # (10) W (K side -beta) / (11) Upre (V side +beta)
290+ d_left = kn_v * torch.exp(cs) # decayed K (forward), safe (cs <= 0)
291+ w = _bf16_round(torch.matmul(inv, (-beta_s) * d_left)) # (B,Nv,nc,C,D)
292+ upre = _bf16_round(torch.matmul(inv, beta_s * v_c)) # (B,Nv,nc,C,D)
293+ 
294+ # (12) Mqk: causal incl. diagonal, scale * qn*kn*exp(cs[r]-cs[l])
295+ causal = torch.tril(torch.ones(chunk_size_v, chunk_size_v, dtype=torch.bool), diagonal=0)
296+ mqk = _bf16_round(mqk_full.masked_fill(~causal, 0.0)) # (B,Nv,nc,C,C)
297+ 
298+ # ---- Stage-2 chunked recurrent state passing (fp32 state) ----
299+ # State orientation follows the canonical KDA reference ref_kda.naive_chunk_kda:
300+ # S <- gam*S + Kr^T @ U (SPEC's literal "U^T @ Kr" transposed to (K,V)).
301+ state = initial_state.to(torch.float32).clone() # (B,Nv,K,V) fp32
302+ out_c = torch.empty((batch_v2, num_value_heads_v2, nc, chunk_size_v, head_dim_v2), dtype=torch.float32)
303+ for c in range(nc):
304+ u = _bf16_round(upre[:, :, c] + torch.matmul(w[:, :, c], state))
305+ # (14) O = Qd@S + Mqk@U (fp32 acc); CPU golden keeps O in fp32 (no final bf16 cast)
306+ o = torch.matmul(qd[:, :, c], state) + torch.matmul(mqk[:, :, c], u)
307+ out_c[:, :, c] = o
308+ # (15) S <- gam*S + Kr^T@U (gamma per-K-dim decay, fp32; update after output)
309+ delta = torch.matmul(kr[:, :, c].transpose(-1, -2), u)
310+ state = gam[:, :, c, :, None] * state + delta
311+ 
312+ # ---- output assembly: BSND physical (B,S,Nv,D) ----
313+ out_bsnd = out_c.permute(0, 2, 3, 1, 4).reshape(batch_v2, seq_len_v2, num_value_heads_v2, head_dim_v2).contiguous()
314+ final_state = state.contiguous()
315+ return out_bsnd, final_state
@@ -0,0 +1,95 @@
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+ 
12+"""Minimal flash_kda delivery test: TND case.
13+ 
14+Compares the PyPTO-Pro flash_kda TND wrapper against the pure-torch FP32 CPU
15+golden.
16+"""
17+ 
18+import os
19+import sys
20+ 
21+import pytest
22+import torch
23+import torch_npu
24+ 
25+_THIS_DIR = os.path.dirname(os.path.abspath(__file__))
26+if _THIS_DIR not in sys.path:
27+ sys.path.insert(0, _THIS_DIR)
28+ 
29+_REPO_ROOT = _THIS_DIR
30+while not os.path.isdir(os.path.join(_REPO_ROOT, "src")):
31+ _PARENT = os.path.dirname(_REPO_ROOT)
32+ if _PARENT == _REPO_ROOT:
33+ break
34+ _REPO_ROOT = _PARENT
35+if _REPO_ROOT not in sys.path:
36+ sys.path.insert(0, _REPO_ROOT)
37+ 
38+from flash_kda_golden import flash_kda_golden_cpu
39+ 
40+from ops.pypto_pro.ling_3_1_flash.flash_kda.flash_kda_impl import (
41+ flash_kda_wrapper,
42+)
43+ 
44+_DEVICE_ID = int(os.environ.get("TILE_FWK_DEVICE_ID", 0))
45+torch.npu.set_device(_DEVICE_ID)
46+DEV = torch.device(f"npu:{_DEVICE_ID}")
47+D = 128
48+SCALE = D ** -0.5
49+LOWER_BOUND = -5.0
50+ 
51+ 
52+def _check(actual, expected, rtol, atol, name):
53+ a = actual.float().cpu()
54+ g = expected.float().cpu()
55+ if not (a.shape == g.shape):
56+ raise AssertionError(f"{name}: shape {tuple(a.shape)} != {tuple(g.shape)}")
57+ diff = (a - g).abs()
58+ ok = diff <= atol + rtol * g.abs()
59+ ratio = ok.float().mean().item()
60+ if not (ratio >= 0.99):
61+ raise AssertionError(f"{name}: matched_ratio={ratio:.6f} < 0.99 "
62+ f"(max_abs={diff.max().item():.3e}, rtol={rtol:g}, atol={atol:g})")
63+ 
64+ 
65+def _tnd_inputs(segs=(63, 65), num_key_heads_v=1, num_value_heads_v=2, seed=7):
66+ torch.manual_seed(seed)
67+ token_count = sum(segs)
68+ num_seqs = len(segs)
69+ q = (torch.randn(1, token_count, num_key_heads_v, D) * 0.1).to(torch.bfloat16)
70+ k = (torch.randn(1, token_count, num_key_heads_v, D) * 0.1).to(torch.bfloat16)
71+ v = (torch.randn(1, token_count, num_value_heads_v, D) * 0.1).to(torch.bfloat16)
72+ g = (torch.randn(1, token_count, num_value_heads_v, D) * 1.0).to(torch.bfloat16)
73+ beta = (torch.randn(1, token_count, num_value_heads_v) * 0.5).to(torch.bfloat16)
74+ cu = torch.tensor([0] + list(torch.cumsum(torch.tensor(segs), 0).tolist()),
75+ dtype=torch.int64)
76+ state = torch.randn(num_seqs, num_value_heads_v, D, D, dtype=torch.float32) * 0.1
77+ a_log = torch.randn(num_value_heads_v, dtype=torch.float32) * 0.5
78+ dt_bias = torch.randn(num_value_heads_v, D, dtype=torch.float32) * 0.1
79+ inputs = (q, k, v, g, beta, cu, state, a_log, dt_bias)
80+ return inputs
81+ 
82+ 
83+@pytest.mark.soc("950")
84+def test_flash_kda_tnd():
85+ q, k, v, g, beta, cu, state, a_log, dt_bias = _tnd_inputs()
86+ golden = flash_kda_golden_cpu(
87+ q, k, v, g, beta, SCALE, state, a_log, dt_bias, LOWER_BOUND, "BSND",
88+ cu_seqlens=cu)
89+ out = flash_kda_wrapper(
90+ q[0].to(DEV), k[0].to(DEV), v[0].to(DEV), g[0].to(DEV), beta[0].to(DEV),
91+ SCALE, state.transpose(-1, -2).to(DEV), a_log.to(DEV), dt_bias.to(DEV),
92+ LOWER_BOUND, layout_qkv="TND", cu_seqlens=cu.to(DEV))
93+ torch.npu.synchronize()
94+ _check(out[0].squeeze(0), golden[0][0], 2 ** -7, 1e-3, "flash_kda TND out")
95+ _check(out[1], golden[1].transpose(-1, -2), 1e-3, 1e-4, "flash_kda TND state")
@@ -0,0 +1,267 @@
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+ 
12+"""PyPTO-Pro fused_recurrent_kda CPU golden reference (higher precision).
13+ 
14+Pure-CPU FP32 reference for fused_recurrent_kda, with the same math as the
15+kernel and pure FP32 computation:
16+ 
17+ - No torch_npu import, no NPU device logic
18+ - bf16 inputs cast to fp32 at the start; all computation in fp32
19+ - Output cast back to bf16 at the end (matching the reference's output dtype,
20+ enabling the three-way comparison at atol=rtol=1e-5)
21+ - State stays fp32 (matching the reference's state dtype)
22+ 
23+Math is identical to the NPU golden and the cannbot-dsl reference:
24+ - L2 normalisation: q / sqrt(sum(q^2) + 1e-6) (div form, eps inside sqrt)
25+ - sigmoid: 1/(1+exp(-x)) (via exp + adds + div, no torch.sigmoid shortcut)
26+ - Sequential token scan (prefix-dependent), state carried across tokens
27+ - State pool gather/scatter via ssm/na index tensors
28+ 
29+Reduction order aligned to NPU VF pattern (VL=64 two-segment):
30+ - L2 norm sum: sum(pre) + sum(post) [reduce then add, matching vreduce_sum+vadd]
31+ - sk dot product: sum(pre + post) [add then reduce, matching vadd+vreduce_sum]
32+ - output dot product: sum(pre + post) [add then reduce, matching vadd+vreduce_sum]
33+This alignment is essential for the SPEC-frozen three-way comparison at 1e-5;
34+without it, CPU pairwise reduction vs NPU hardware reduction diverge by 1 bf16 ULP.
35+"""
36+ 
37+from typing import Optional, Tuple
38+ 
39+import torch
40+ 
41+_HEAD_DIM = 128
42+_L2_EPS = 1e-6
43+_VL = 64 # NPU vector lane width; two-segment reduction matches VF reduce_sum pattern
44+ 
45+ 
46+def _sigmoid(x: torch.Tensor) -> torch.Tensor:
47+ """sigmoid 1/(1+exp(-x)), matching the reference's exp + adds(1) + div chain."""
48+ return 1.0 / (1.0 + torch.exp(-x))
49+ 
50+ 
51+def fused_recurrent_kda_golden_cpu(
52+ query: torch.Tensor,
53+ key: torch.Tensor,
54+ value: torch.Tensor,
55+ state: torch.Tensor,
56+ beta: torch.Tensor,
57+ g: torch.Tensor,
58+ scale: Optional[float],
59+ a_log_v: torch.Tensor,
60+ dt_bias: torch.Tensor,
61+ lower_bound: float,
62+ layout_qkv: str,
63+ *,
64+ ssm_state_indices: Optional[torch.Tensor] = None,
65+ num_accepted_tokens: Optional[torch.Tensor] = None,
66+ cu_seqlens: Optional[torch.Tensor] = None,
67+) -> Tuple[torch.Tensor, torch.Tensor]:
68+ """CPU higher-precision golden reference for fused_recurrent_kda.
69+ 
70+ Computes the recurrent KDA decode on CPU with all-fp32 arithmetic and
71+ updates ``state`` in place. bf16 inputs are cast to fp32 at the start;
72+ the output is cast back to bf16 (matching the reference output dtype)
73+ and the state remains fp32.
74+ 
75+ Args:
76+ query: (B,S,N_kv,D) BSND or (B,N_kv,S,D) BNSD, bf16.
77+ key: same shape/dtype as query.
78+ value: (B,S,N_v,D) BSND or (B,N_v,S,D) BNSD, bf16.
79+ state: (pool,N_v,128,128), fp32 -- persistent recurrent state, updated in place.
80+ beta: (B,S,N_v,1) BSND or (B,N_v,S,1) BNSD, bf16.
81+ g: same layout/dtype as value.
82+ scale: float or None (None -> D**-0.5 = 0.08838834764831845).
83+ A_log: (N_v,), fp32 -- per-head log gain.
84+ dt_bias: (N_v,128), fp32 -- per-head per-dim bias.
85+ lower_bound: float in [-5, 0].
86+ layout_qkv: "BSND" or "BNSD".
87+ ssm_state_indices: optional (B*S,) int32 state-pool index map.
88+ num_accepted_tokens: optional (B,) int32 per-batch accepted token count.
89+ 
90+ Returns:
91+ (state, output) -- state is the in-place-updated input (fp32);
92+ output is bf16 with the same layout as the inputs.
93+ """
94+ if not (layout_qkv in ("BSND", "BNSD")):
95+ raise AssertionError(f"layout_qkv must be BSND or BNSD, got {layout_qkv!r}")
96+ 
97+ if cu_seqlens is not None:
98+ return _fused_recurrent_varlen_cpu(
99+ query, key, value, state, beta, g, scale, a_log_v, dt_bias,
100+ lower_bound, layout_qkv, cu_seqlens)
101+ 
102+ device = state.device # CPU
103+ 
104+ # Build BNSD logical views (axis reorder only)
105+ if layout_qkv == "BSND":
106+ q_view = query.permute(0, 2, 1, 3)
107+ k_view = key.permute(0, 2, 1, 3)
108+ v_view = value.permute(0, 2, 1, 3)
109+ g_view = g.permute(0, 2, 1, 3)
110+ beta_view = beta.permute(0, 2, 1, 3)
111+ else:
112+ q_view = query
113+ k_view = key
114+ v_view = value
115+ g_view = g
116+ beta_view = beta
117+ 
118+ batch, num_kv_heads, seq_length, dim_size = q_view.shape
119+ num_value_heads_v = v_view.shape[1]
120+ gqa_group = num_value_heads_v // num_kv_heads
121+ if not (num_value_heads_v % num_kv_heads == 0):
122+ raise AssertionError(f"GQA: N_v ({num_value_heads_v}) must be divisible by N_kv ({num_kv_heads})")
123+ if not (dim_size == _HEAD_DIM):
124+ raise AssertionError(f"only D={_HEAD_DIM} is supported, got D={dim_size}")
125+ 
126+ scale_value = float(scale) if scale is not None else dim_size ** -0.5
127+ 
128+ if ssm_state_indices is None:
129+ ssm = torch.arange(batch * seq_length, dtype=torch.int64, device=device)
130+ else:
131+ ssm = ssm_state_indices.to(torch.int64)
132+ if num_accepted_tokens is None:
133+ na = torch.ones(batch, dtype=torch.int64, device=device)
134+ else:
135+ na = num_accepted_tokens.to(torch.int64)
136+ 
137+ if layout_qkv == "BSND":
138+ output = torch.zeros(batch, seq_length, num_value_heads_v, dim_size, dtype=torch.bfloat16, device=device)
139+ else:
140+ output = torch.zeros(batch, num_value_heads_v, seq_length, dim_size, dtype=torch.bfloat16, device=device)
141+ 
142+ # GQA expansion
143+ if gqa_group > 1:
144+ q_exp = q_view.repeat_interleave(gqa_group, dim=1)
145+ k_exp = k_view.repeat_interleave(gqa_group, dim=1)
146+ else:
147+ q_exp = q_view
148+ k_exp = k_view
149+ 
150+ # Cast all inputs to fp32
151+ q_f32 = q_exp.float()
152+ k_f32 = k_exp.float()
153+ v_f32 = v_view.float()
154+ g_f32 = g_view.float()
155+ beta_f32 = beta_view[..., 0].float()
156+ a_log_f32 = a_log_v.float()
157+ dt_bias_f32 = dt_bias.float()
158+ 
159+ # L2 normalise (div form, eps inside sqrt -- matching reference)
160+ # Two-segment reduction aligned to NPU VF: reduce_sum(pre) + reduce_sum(post)
161+ q_sq = (q_f32[..., :_VL] * q_f32[..., :_VL]).sum(dim=-1, keepdim=True) + \
162+ (q_f32[..., _VL:] * q_f32[..., _VL:]).sum(dim=-1, keepdim=True)
163+ k_sq = (k_f32[..., :_VL] * k_f32[..., :_VL]).sum(dim=-1, keepdim=True) + \
164+ (k_f32[..., _VL:] * k_f32[..., _VL:]).sum(dim=-1, keepdim=True)
165+ q_scaled = (q_f32 / torch.sqrt(q_sq + _L2_EPS)) * scale_value
166+ k_norm = k_f32 / torch.sqrt(k_sq + _L2_EPS)
167+ 
168+ # Activate gates (all fp32)
169+ alpha = torch.exp(a_log_f32)
170+ gate_input = g_f32 + dt_bias_f32.unsqueeze(0).unsqueeze(2)
171+ gate = _sigmoid(alpha.reshape(1, -1, 1, 1) * gate_input)
172+ decay = gate * float(lower_bound)
173+ d_actual = torch.exp(decay)
174+ 
175+ beta_act = _sigmoid(beta_f32)
176+ 
177+ # Sequential token scan
178+ base = torch.arange(batch, device=device) * seq_length
179+ init_idx = ssm[base + na - 1]
180+ state_work = state[init_idx, :, :, :].clone()
181+ 
182+ for t in range(seq_length):
183+ k_t = k_norm[:, :, t, :]
184+ q_t = q_scaled[:, :, t, :]
185+ d_t = d_actual[:, :, t, :]
186+ v_t = v_f32[:, :, t, :]
187+ bt = beta_act[:, :, t]
188+ 
189+ # Two-segment reduction aligned to NPU VF: reduce_sum(pre + post)
190+ _prod = state_work * d_t.unsqueeze(2) * k_t.unsqueeze(2)
191+ sk = (_prod[..., :_VL] + _prod[..., _VL:]).sum(dim=-1) # (B, N_v, D)
192+ 
193+ delta = (v_t - sk) * bt.unsqueeze(-1) # (B, N_v, D)
194+ 
195+ state_new = state_work * d_t.unsqueeze(2) + delta.unsqueeze(-1) * k_t.unsqueeze(2)
196+ 
197+ # Two-segment reduction aligned to NPU VF: reduce_sum(pre + post)
198+ _snq = state_new * q_t.unsqueeze(2)
199+ out_t = (_snq[..., :_VL] + _snq[..., _VL:]).sum(dim=-1) # (B, N_v, D)
200+ 
201+ state_work = state_new
202+ 
203+ if layout_qkv == "BSND":
204+ output[:, t, :, :] = out_t.to(torch.bfloat16)
205+ else:
206+ output[:, :, t, :] = out_t.to(torch.bfloat16)
207+ 
208+ snap_idx = ssm[base + t]
209+ state[snap_idx, :, :, :] = state_work
210+ 
211+ return state, output
212+ 
213+ 
214+def _fused_recurrent_varlen_cpu(query, key, value, state, beta, g, scale,
215+ a_log_v2, dt_bias, lower_bound, layout_qkv,
216+ cu_seqlens):
217+ """TND varlen reference: per-sequence fixed-length runs, state per sequence.
218+ 
219+ Sequences are independent (state pool slot == sequence index, updated in
220+ place); the packed output keeps the input layout.
221+ """
222+ if cu_seqlens.dtype not in (torch.int32, torch.int64):
223+ raise TypeError(f"cu_seqlens must be int32/int64, got {cu_seqlens.dtype}")
224+ if cu_seqlens.dim() != 1 or cu_seqlens.numel() < 2:
225+ raise ValueError("cu_seqlens must be 1-D [N+1] with N >= 1")
226+ if query.shape[0] != 1:
227+ raise ValueError(f"varlen requires packed batch size 1, got B={query.shape[0]}")
228+ cu_list = cu_seqlens.tolist()
229+ if cu_list[0] != 0:
230+ raise ValueError("cu_seqlens[0] must be 0")
231+ if any(b < a for a, b in zip(cu_list, cu_list[1:])):
232+ raise ValueError("cu_seqlens must be non-decreasing")
233+ token_count = query.shape[1] if layout_qkv == "BSND" else query.shape[2]
234+ if cu_list[-1] != token_count:
235+ raise ValueError(f"cu_seqlens[-1] must equal T={token_count}, got {cu_list[-1]}")
236+ num_seqs = len(cu_list) - 1
237+ num_value_heads_v_v = value.shape[2] if layout_qkv == "BSND" else value.shape[1]
238+ dim_size_v = query.shape[-1]
239+ # Same per-token snapshot pool as the fixed path: sequence i reads its
240+ # incoming state from slot cu[i] and writes state[cu[i]:cu[i+1]].
241+ if not (state.shape[0] >= token_count):
242+ raise AssertionError(f"state pool must hold per-token slots (>= T={token_count})")
243+ if not (tuple(state.shape[1:]) == (num_value_heads_v_v, _HEAD_DIM, _HEAD_DIM)):
244+ raise AssertionError(
245+ f"state must be (pool,{num_value_heads_v_v},{_HEAD_DIM},{_HEAD_DIM}), got {tuple(state.shape)}")
246+ 
247+ def sl(t, lo, hi):
248+ return t[:, lo:hi] if layout_qkv == "BSND" else t[:, :, lo:hi]
249+ 
250+ if layout_qkv == "BSND":
251+ output = torch.zeros(1, token_count, num_value_heads_v_v, dim_size_v, dtype=torch.bfloat16, device=state.device)
252+ else:
253+ output = torch.zeros(1, num_value_heads_v_v, token_count, dim_size_v, dtype=torch.bfloat16, device=state.device)
254+ 
255+ for i in range(num_seqs):
256+ bos, eos = cu_list[i], cu_list[i + 1]
257+ if eos <= bos:
258+ raise ValueError(f"sequence {i} is empty")
259+ _, out_i = fused_recurrent_kda_golden_cpu(
260+ sl(query, bos, eos), sl(key, bos, eos), sl(value, bos, eos),
261+ state[bos:eos], sl(beta, bos, eos), sl(g, bos, eos),
262+ scale, a_log_v2, dt_bias, lower_bound, layout_qkv)
263+ if layout_qkv == "BSND":
264+ output[:, bos:eos] = out_i
265+ else:
266+ output[:, :, bos:eos] = out_i
267+ return state, output
@@ -0,0 +1,89 @@
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+ 
12+"""Minimal fused_recurrent_kda delivery test: BSND snapshot.
13+ 
14+The BSND case compares the snapshot kernel against the CPU FP32 golden.
15+"""
16+ 
17+import os
18+import sys
19+ 
20+import pytest
21+import torch
22+import torch_npu
23+ 
24+_THIS_DIR = os.path.dirname(os.path.abspath(__file__))
25+if _THIS_DIR not in sys.path:
26+ sys.path.insert(0, _THIS_DIR)
27+ 
28+_REPO_ROOT = _THIS_DIR
29+while not os.path.isdir(os.path.join(_REPO_ROOT, "src")):
30+ _PARENT = os.path.dirname(_REPO_ROOT)
31+ if _PARENT == _REPO_ROOT:
32+ break
33+ _REPO_ROOT = _PARENT
34+if _REPO_ROOT not in sys.path:
35+ sys.path.insert(0, _REPO_ROOT)
36+ 
37+from fused_recurrent_kda_golden import (
38+ fused_recurrent_kda_golden_cpu,
39+)
40+ 
41+from ops.pypto_pro.ling_3_1_flash.fused_recurrent_kda.fused_recurrent_kda_impl import (
42+ fused_recurrent_kda_wrapper,
43+)
44+ 
45+_DEVICE_ID = int(os.environ.get("TILE_FWK_DEVICE_ID", 0))
46+torch.npu.set_device(_DEVICE_ID)
47+DEV = torch.device(f"npu:{_DEVICE_ID}")
48+D = 128
49+SCALE = D ** -0.5
50+ 
51+ 
52+def _check(actual, expected, rtol, atol, name):
53+ a = actual.float().cpu()
54+ g = expected.float().cpu()
55+ if not (a.shape == g.shape):
56+ raise AssertionError(f"{name}: shape {tuple(a.shape)} != {tuple(g.shape)}")
57+ diff = (a - g).abs()
58+ ok = diff <= atol + rtol * g.abs()
59+ ratio = ok.float().mean().item()
60+ if not (ratio >= 0.99):
61+ raise AssertionError(f"{name}: matched_ratio={ratio:.6f} < 0.99 "
62+ f"(max_abs={diff.max().item():.3e}, rtol={rtol:g}, atol={atol:g})")
63+ 
64+ 
65+def _dense_inputs(batch=1, seq_len=4, num_key_heads=1, num_value_heads=2, lb=-1.0, seed=42):
66+ torch.manual_seed(seed)
67+ q = (torch.randn(batch, seq_len, num_key_heads, D) * 1.0).to(torch.bfloat16)
68+ k = (torch.randn(batch, seq_len, num_key_heads, D) * 1.0).to(torch.bfloat16)
69+ v = (torch.randn(batch, seq_len, num_value_heads, D) * 1.0).to(torch.bfloat16)
70+ g = (torch.randn(batch, seq_len, num_value_heads, D) * 1.0).to(torch.bfloat16)
71+ beta = (torch.randn(batch, seq_len, num_value_heads, 1) * 1.0).to(torch.bfloat16)
72+ state = torch.randn(batch * seq_len, num_value_heads, D, D, dtype=torch.float32) * 0.1
73+ a_log = (torch.randn(num_value_heads, dtype=torch.float32) * 0.5).clamp(-5.0, 5.0)
74+ dt_bias = torch.randn(num_value_heads, D, dtype=torch.float32) * 0.5
75+ inputs = (q, k, v, state, beta, g, a_log, dt_bias, lb)
76+ return inputs
77+ 
78+ 
79+@pytest.mark.soc("950")
80+def test_fused_recurrent_kda_bsnd():
81+ q, k, v, state, beta, g, a_log, dt_bias, lb = _dense_inputs()
82+ cpu_state, cpu_out = fused_recurrent_kda_golden_cpu(
83+ q, k, v, state.clone(), beta, g, SCALE, a_log, dt_bias, lb, "BSND")
84+ np_state, np_out = fused_recurrent_kda_wrapper(
85+ q.to(DEV), k.to(DEV), v.to(DEV), state.clone().to(DEV), beta.to(DEV),
86+ g.to(DEV), SCALE, a_log.to(DEV), dt_bias.to(DEV), lb, "BSND")
87+ torch.npu.synchronize()
88+ _check(np_out, cpu_out, 2 ** -7, 1e-3, "fused_recurrent_kda BSND out")
89+ _check(np_state, cpu_state, 1e-5, 1e-5, "fused_recurrent_kda BSND state")