Merged
feat(operator): Add CSA2 compressor fwd/bwd for deepseek_v4_1 with tests #925
叶凡Add on 26 days ago
feat(operator): Add CSA2 compressor fwd/bwd for deepseek_v4_1 with tests #925
Merged
叶凡Add on 26 days ago
Total: 5 files changed+2615-0
@@ -0,0 +1,443 @@
1+# CSA2 Compressor 算子说明文档(训练用)
2+ 
3+## 1. 算子概述
4+ 
5+CSA2 Compressor 是 DeepSeek V4.1-Flash 架构中的 **token 压缩器(latent compressor)**:将连续
6+`ratio` 个 token 压缩为 1 个 pre-RoPE latent,供 Attention 侧使用(RoPE / Hadamard 由 Attention
7+侧施加,压缩器本身不做)。KV 池化权重由 gate 投影经 softmax 产生。
8+ 
9+**本实现为训练算子**,算子实现只有三个文件,职责与依赖分层如下:
10+ 
11+### 1.1 文件组成
12+ 
13+| 文件 | 职责 | 对外接口 |
14+|---|---|---|
15+| `csa2_compressor_fwd_impl.py` | **前向实现**。包含三个 `@pypto.frontend.jit` kernel(`csa2_compressor_ratio1_kernel` 纯投影分支、`csa2_compressor_kernel` ratio=2 BSH 压缩分支、`csa2_compressor_th_kernel` ratio=2 TH (BS 合轴) 分支(含 prefill + decode)),并将算子注册到 `torch.library`(`pypto::csa2_compressor`,Meta shape 推导 + NPU dispatch) | `CSA2CompressorArgs`(namedtuple 参数打包)、`csa2_compressor_pypto(args)`(走 `torch.ops` 派发)、`npu_csa2_compressor(args)`(`@allow_in_graph` 直调,绕过派发,图捕获友好;内部按 `cu_seqlens` 是否为 None 分发到 `_csa2_compressor_bsh` / `_csa2_compressor_th`) |
16+| `csa2_compressor_bwd_impl.py` | **反向实现**。包含三个 kernel(`csa2_compressor_bwd_ratio1_kernel`、`csa2_compressor_bwd_kernel`(BSH)、`csa2_compressor_bwd_th_kernel`(TH),静态块对齐 + 权值单次 bf16 量化),注册为 `pypto::csa2_compressor_bwd`;wrapper 侧完成余数行零填、scratch 分配、权值预备与 state 切片 | `CSA2CompressorBwdArgs`(namedtuple 参数打包)、`csa2_compressor_bwd_pypto(args)`、`npu_csa2_compressor_bwd(args)`(按 `cu_seqlens` 分发到 `_csa2_compressor_bwd_bsh` / `_csa2_compressor_bwd_th`),返回 `(dx, dwkv, dwgate, dweight)` |
17+| `csa2_compressor.py` | **公共入口(autograd 组合层)**。不含 kernel,只做两件事:前向调 `npu_csa2_compressor` 并保存反向所需上下文(含前向**写后**的 state 切片);backward 调 `npu_csa2_compressor_bwd` 并按 forward 入参顺序回传梯度。同时处理 state 预分配(dim0 > bsz)的精确切片 | `CSA2CompressorFunction`(`torch.autograd.Function`)、`csa2_compressor(...)`(functional)、`CSA2Compressor`(`nn.Module`,持有 ratio / eps) |
18+ 
19+### 1.2 依赖分层
20+ 
21+```
22+csa2_compressor.py(autograd 入口,训练推荐用法)
23+ ├── csa2_compressor_fwd_impl.py → npu_csa2_compressor (前向, BSH/TH 分发)
24+ └── csa2_compressor_bwd_impl.py → npu_csa2_compressor_bwd (反向, BSH/TH 分发)
25+```
26+ 
27+- 入口文件的依赖边界(除 pip 包外)只有两个 impl 文件的 eager wrapper(本目录内相对引用),
28+ 三个文件可整体移植到任意包目录;
29+- 前向 / 反向 wrapper 供公共入口(§5)内部调用,**不对外直接调用**;训练统一经公共入口使用。
30+ 
31+测试位于 `tests/ops/deepseek_v4_1/`(精度 golden + 泛化用例 + 性能基准例),不属于算子实现。
32+ 
33+运行环境:昇腾 NPU(910B3 与 Ascend910_9392 均验证通过),基于 PyPTO 框架
34+(`pypto.frontend.jit`)开发,依赖 `torch` / `torch_npu`。测试经 `deepseek_v4_1.` 包式
35+导入加载本目录实现。TH 扩展(本 README 所载)另于 Ascend910(soc 251)/ CANN 9.1.0
36+上全量复测通过。
37+ 
38+---
39+ 
40+## 2. 正向算法
41+ 
42+记 `x: (bsz, seq, h)`(BSH;TH 见 §2.3),`h = 5120`(静态维,JIT 特化维度,主验证维;反向功能例 / 反向泛化例
43+另覆盖 `h = 4096`);`d = head_dim`(如 512 / 128);`ratio ∈ {1, 2}`。
44+ 
45+### 2.1 ratio == 1(纯投影分支)
46+ 
47+```
48+out = rms_norm(wkv(x)) # bf16 投影(不转 fp32),无 gate / state / 池化
49+```
50+ 
51+- 每 token 产出一个 latent,输出 `(bsz, seq, d)`,**永不返回 None**;
52+- `wkv` 保持 bf16,`wgate / kv_state / score_state` 不存在(传 `None`)。
53+ 
54+### 2.2 ratio == 2(压缩分支)
55+ 
56+公共投影(`wkv/wgate` 统一 bf16,乘积 fp32 累加;`x` 先 `float()`):
57+ 
58+```
59+kv = x_fp32 @ bf16(wkv)^T # (bsz, seq, d)
60+score = x_fp32 @ bf16(wgate)^T # (bsz, seq, d)
61+```
62+ 
63+**整段输入(start_pos == 0,训练常规用法,seq 可为任意长度)**:
64+ 
65+```
66+should_compress = seq >= 2
67+remainder = seq % 2 # 尾部余数 token 数
68+完整组 g([2g, 2g+2)):
69+ alpha_g = softmax(score_g, dim=组内) # 2 个 token 的池化权重
70+ latent_g = Σ_i alpha_g[i] * kv_g[i]
71+余数 token:
72+ kv_state[:bsz, :remainder], score_state[:bsz, :remainder] = 投影结果 # 原地写入
73+```
74+ 
75+**单 token 输入(start_pos != 0,每次输入位置 start_pos 处的 1 个 token)**:
76+ 
77+```
78+slot = start_pos % 2
79+kv_state[:bsz, slot], score_state[:bsz, slot] = 当前 token 投影结果 # 原地写入
80+should_compress = (start_pos + 1) % 2 == 0
81+组满时: latent = Σ_slot softmax(score_state, dim=槽位) * kv_state # 输出 1 行
82+```
83+ 
84+**输出**:`should_compress` 为真时
85+ 
86+```
87+out = rms_norm(latent.to(bf16)) # 池化结果先落回 bf16 再 RMSNorm → pre-RoPE latent
88+```
89+ 
90+形状 `(bsz, max(seq // ratio, 1), d)` bf16。**非压缩步**(整段输入时 `seq < 2`,或单 token 输入时
91+组未满)返回 `None`;kernel wrapper 仍返回同形状的**占位 tensor(未写入,值无定义)**,
92+调用方应以 `seq >= ratio` / `(start_pos+1) % ratio == 0` 判断是否消费输出。盲反传占位输出的语义
93+见 §4.2(整段输入 `seq < ratio` 为全零梯度;单 token 组未满会按当前 state 池化真实回传当前槽位
94+梯度——规范用法是不反传占位输出)。
95+ 
96+### 2.3 TH (BS 合轴) 模式
97+ 
98+x 为 `(t, h)` 2D 时按 `cu_seqlens` 分段(batch b 的 token 为 `x[cu[b]:cu[b+1]]`):
99+ 
100+- 每个 batch 段**独立**分组池化(组网格在段起点重启,不跨段配对);段尾余数 token 写
101+ `kv_state[b, 0]`;ratio==1 对分段不敏感(逐 token 投影);
102+- ratio==2 prefill 输出为**紧凑拼接**:batch b 的压缩行写到 `out_base[b]` 起
103+ (`out_base[b] = Σ_{i<b} L_i // ratio`,由 wrapper 设备侧计算后传入 kernel:B=1 短路
104+ 为常量 0,B>1 走 fp32 AiCore cumsum,均无 host 同步),
105+ 有效行数 `Σ_b L_b // ratio`,其后为 pad;总行数 `Sr = min(t, t//ratio + bsz)`;
106+- TH decode(start_pos != 0)要求每段恰 1 token(`cu_seqlens == [0, 1, ..., bsz]`),
107+ `slot = start_pos % 2` 全 batch 一致,跨 batch 批量处理,输出行按 batch 序;
108+- 长度 0 的段跳过:不写 state、不产生输出。
109+ 
110+### 2.4 数值约定
111+ 
112+- `kv_state` 初值 0,`score_state` 初值 `-inf`(`register_buffer` 语义);**前向原地更新**二者;
113+- softmax / rsqrt 使用 `PrecisionType.HIGH_PRECISION`;RMSNorm 内部 fp32,输入先 cast bf16
114+ (对齐 `kv.to(dtype)` 后再 norm);
115+- matmul fp32 累加。
116+ 
117+---
118+ 
119+## 3. 正向 wrapper 接口(`csa2_compressor_fwd_impl.py`)
120+ 
121+### 3.1 参数打包与注册
122+ 
123+```python
124+CSA2CompressorArgs = namedtuple('CSA2CompressorArgs',
125+ ['x', 'wkv', 'wgate', 'weight', 'kv_state', 'score_state', 'start_pos', 'cu_seqlens',
126+ 'ratio', 'eps']) # defaults=(None, 2, 1e-20); cu_seqlens 位于标量参数之前, BSH 时传 None
127+```
128+ 
129+算子已通过 `torch.library` 注册为 `pypto::csa2_compressor`(含 Meta shape 推导;NPU dispatch
130+注册依赖 torchair,未安装时自动跳过)。文件对外提供 `csa2_compressor_pypto(args)`(走
131+`torch.ops` 派发)与 `npu_csa2_compressor(args)`(`@allow_in_graph` 直调,绕过派发,图捕获
132+友好);后者先 `check_args` 校验,再按 `cu_seqlens` 是否为 None 分发到 `_csa2_compressor_bsh` /
133+`_csa2_compressor_th`(各自分配 out 并调 kernel;fwd 的 state 预分配切片在公共入口完成)。
134+二者供公共入口(§5)内部使用,不对外直接调用。
135+ 
136+### 3.2 tensor 契约
137+ 
138+| 参数 | 形状 | dtype | 说明 |
139+|---|---|---|---|
140+| `x` | BSH: `(bsz, seq, 5120)`;TH: `(t, 5120)` | bf16 | BSH 的 seq 为动态轴,h 为静态特化维(实测 5120) |
141+| `wkv` | `(d, 5120)` | bf16(接受 bf16/fp32,内部归一) | kv 投影权值;ratio1/2 统一 bf16 |
142+| `wgate` | `(d, 5120)` 或 `None` | bf16(接受 bf16/fp32,内部归一) | gate 投影权值;ratio==1 必须为 None |
143+| `weight` | `(d,)` | fp32 | RMSNorm 权重(`kv_norm.weight`) |
144+| `kv_state` | `(bsz, 2, d)` 或 `None` | fp32 | 不可微 cache,**前向原地更新**;ratio==1 必须为 None |
145+| `score_state` | `(bsz, 2, d)` 或 `None` | fp32 | 初值 `-inf`;同上 |
146+| `start_pos` | `(1,)` | int32(NPU 设备张量) | token 序列起始位置:`0` = 整段输入(从位置 0 开始分组),`>0` = 单 token 输入(当前位置 start_pos);需在 aclgraph 捕获前创建,勿在捕获内新建 |
147+| `cu_seqlens` | TH: `(bsz+1,)` 或 BSH: `None` | int32 | **TH (BS 合轴) 前缀和**:`cu[0]==0`、`cu[-1]==t`、非降;batch b 的 token 为 `x[cu[b]:cu[b+1]]`。x 为 3D (BSH) 时必须为 None |
148+| `ratio` | — | int | 1 或 2 |
149+| `eps` | — | float | RMSNorm epsilon(常用 `1e-20`) |
150+| 返回 `out` | BSH: ratio==1 `(bsz, seq, d)`;ratio==2 `(bsz, max(seq//2, 1), d)`。TH: ratio==1 `(t, d)`;ratio==2 prefill `(min(t, t//2+bsz), d)`(compact 压缩行 + pad),decode `(bsz, d)` | bf16 | 非压缩步为占位(见 §2.2) |
151+ 
152+**完整约束(模式与形状、dtype、start_pos 与 decode 单 token、state、反向输入、图捕获)见 §6**;
153+TH (BS 合轴) 语义与 `out_base` 说明见 §2.3。
154+ 
155+---
156+ 
157+## 4. 反向算法(`csa2_compressor_bwd_impl.py`)
158+ 
159+### 4.1 梯度语义
160+ 
161+- `kv_state / score_state` 视为**不可微 cache**(`register_buffer(persistent=False)`),不产生
162+ 梯度(返回 `None`);梯度回传到 `x / wkv / wgate / weight`。
163+- 单 token 输入时只回传**当前调用**产生的梯度,不回传历史 token 的梯度。
164+- 反向需要读**前向更新后**的 state(单 token 输入分支的池化来源)。
165+ 
166+### 4.2 三分支反向
167+ 
168+**ratio == 1**(`out = norm(wkv(x))`):
169+ 
170+```
171+kv = x @ wkv^T # 前向投影重算(bf16)
172+dkv, dweight = rms_norm_backward(grad_out, kv, weight)
173+dkv = dkv.to(bf16) # 对齐 kernel cube matmul 边界的量化点
174+dx = dkv @ wkv # (bsz, seq, h)
175+dwkv = Σ_{batch,seq} dkv^T @ x # (d, h),展平 batch/seq 求和
176+```
177+ 
178+**ratio == 2 整段输入**:完整组可微;余数 token 无输出 → **梯度为 0**。
179+ 
180+```
181+dlatent, dweight = rms_norm_backward(grad_out, bf16(latent), weight)
182+d_alpha = dlatent * kv_g
183+d_kv = dlatent * alpha # 完整组 token 的 kv 梯度
184+d_score = softmax_backward(d_alpha, alpha) # softmax 解析反向
185+```
186+ 
187+**ratio == 2 单 token 输入**:latent 由 state 池化,**仅当前 token 写入的槽位可微**:
188+ 
189+```
190+alpha = softmax(score_state) # 前向后的 state
191+dlatent, dweight = rms_norm_backward(grad_out, bf16(latent), weight)
192+d_kv[slot] = dlatent * alpha[slot] # slot = start_pos % 2,其余槽位梯度 0
193+d_sc[slot] = softmax_backward(dlatent * kv_state, alpha)[slot]
194+```
195+ 
196+**非压缩步的"盲反传"**(对占位输出直接 backward):整段输入 `seq < ratio` 时该段无组/槽贡献
197+→ 梯度全零;单 token 组未满时会按当前 state 池化**真实回传当前槽位的梯度(非零)**(与 golden
198+同口径)——规范用法是不消费、不反传该占位输出。
199+ 
200+### 4.3 公共尾段与数值策略
201+ 
202+所有分支汇合到公共尾段:
203+ 
204+```
205+dx = d_kv @ wkv + d_score @ wgate
206+dwkv = Σ d_kv^T @ x ; dwgate = Σ d_score^T @ x
207+```
208+ 
209+数值策略(对齐 kernel 的 bf16-MAC 形态):
210+ 
211+- `dx / dwkv / dwgate` 的 cube matmul 操作数在边界量化 bf16、fp32 累加,`dx` 单次最终舍入;
212+- 前向 `kv/score` 重算对齐 kernel gb 段语义:**权值单次量化 bf16**(`wkv/wgate.to(bf16)`,与
213+ golden 逐位一致),x 原生 bf16,乘积 fp32 精确、fp32 累加(残余差异仅有累加顺序,容差内覆盖);
214+- wrapper 侧完成 `d_kv/d_sc` scratch 分配与权值 bf16 量化预备,余数行零填(BSH 由 wrapper 批量
215+ 零填、TH 由 kernel 内按段零填);kernel 端各组块按 `valid_g` / 尾块 `valid_shape` 裁剪,无越界写。
216+ 
217+### 4.4 反向 wrapper 接口
218+ 
219+```python
220+CSA2CompressorBwdArgs = namedtuple('CSA2CompressorBwdArgs',
221+ ['grad_out', 'x', 'wkv', 'wgate', 'weight', 'kv_state', 'score_state',
222+ 'start_pos', 'cu_seqlens', 'ratio', 'eps']) # cu_seqlens 位于标量参数之前
223+# 返回: (dx, dwkv, dwgate, dweight)
224+```
225+ 
226+与正向同构:`csa2_compressor_bwd_pypto(args)` 走 `torch.ops` 派发,`npu_csa2_compressor_bwd(args)`
227+为 `@allow_in_graph` 直调,供公共入口(§5)内部使用,不对外直接调用。返回值:
228+ 
229+| 返回值 | 形状 | dtype | 说明 |
230+|---|---|---|---|
231+| `dx` | BSH `(bsz, seq, 5120)`;TH `(t, 5120)` | bf16 | 与 x 同形 |
232+| `dwkv` | `(d, 5120)` | 同 `wkv`(bf16) | |
233+| `dwgate` | `(d, 5120)` 或 `None` | 同 `wgate`(bf16) | ratio==1 时为 `None` |
234+| `dweight` | `(d,)` | fp32 | |
235+ 
236+入参契约同 §3.2(`grad_out` 形状与前向输出一致,bf16),另注意:
237+ 
238+- `kv_state / score_state` 必须传**前向更新后**的值(单 token 输入分支从中读取);
239+- state dim0 预分配(`> bsz`)同样支持:反向只读 state,wrapper 精确切片(TH 按段数 bsz),
240+ 无写回语义;
241+- BSH `grad_out` 按前向输出形状 `(bsz, max(seq//2,1), d)` 直传(无 padding);余数行梯度由
242+ wrapper 零填(`s1 % ratio != 0` 时批量清零各 batch 尾行);
243+- TH `grad_out` 为前向输出 2D `(Sr, d)`,仅每段 compact 前缀
244+ `[out_base[b], out_base[b]+ng_b)` 有效(pad 行不参与);段尾余数行梯度由 kernel 内按段零填。
245+ 
246+---
247+ 
248+## 5. 正反向联合接口(公共入口,`csa2_compressor.py`)
249+ 
250+对外暴露三种形式,内部串联前向 kernel 与反向 kernel:
251+ 
252+```python
253+CSA2CompressorFunction # torch.autograd.Function:forward / backward 入口
254+csa2_compressor(...) # functional 形式
255+CSA2Compressor(ratio, eps) # nn.Module 形式(持有 ratio / eps,权重与 state 由调用方传入)
256+```
257+ 
258+```python
259+# functional (cu_seqlens 位于标量参数 ratio/eps 之前)
260+out = csa2_compressor(x, wkv, wgate, weight, kv_state, score_state,
261+ start_pos, None, ratio=2, eps=1e-20) # BSH
262+out = csa2_compressor(x, wkv, wgate, weight, kv_state, score_state,
263+ start_pos, cu, ratio=2, eps=1e-20) # TH (x 2D)
264+ 
265+# nn.Module
266+model = CSA2Compressor(ratio=2, eps=1e-20)
267+out = model(x, wkv, wgate, weight, kv_state, score_state, start_pos, cu_seqlens=None)
268+```
269+ 
270+autograd 语义:
271+ 
272+- 前向调用 `npu_csa2_compressor`,**原地更新** `kv_state/score_state`,并经 `ctx.save_for_backward`
273+ 保存全部输入与前向**写后的 state 切片**(TH 下同时保存 `cu_seqlens`);
274+- `out.backward(grad_out)` 触发 `npu_csa2_compressor_bwd`,梯度按 forward 入参顺序返回
275+ (`dx, dwkv, dwgate, dweight, None, None, None, None, None, None`),落入各输入的 `.grad`;
276+- `kv_state/score_state/start_pos/ratio/eps/cu_seqlens` 无梯度;
277+- state 预分配(dim0 > bsz)时入口内精确切片(TH 按段数 bsz),前向原地写落回大 buffer
278+ `[0, bsz)` 行,反向经 ctx 保存的切片读到前向后的值。
279+ 
280+---
281+ 
282+## 6. 约束汇总(调用方必读)
283+ 
284+以下为算子**全部约束**。`check_args` 仅做 rank / shape / dtype / 设备一致性等**静态校验**;
285+标注「不校验」的约束不会报错,违反时结果未定义,须由调用方保证(算子内部不做任何 D2H 同步,
286+故无法在运行时校验设备标量/数组的**值**)。
287+ 
288+### 6.1 模式、形状与标量参数
289+ 
290+| 约束 | 校验 |
291+|---|---|
292+| `ratio ∈ {1, 2}` | ✅ |
293+| `start_pos` 必须为 `(1,)` int32 设备张量 | ✅ |
294+| `eps ≥ 0`(非负 float) | Module 构造与反向 wrapper 校验;前向 wrapper 不校验 |
295+| x 布局二选一(wrapper 按 `cu_seqlens` 分发):`cu_seqlens=None` → BSH,x 必须 rank 3 `(bsz, seq, h)`;`cu_seqlens` 给定 → TH,x 必须 rank 2 `(t, h)` 且 `cu_seqlens` 为 1D int32 `(bsz+1,)`;两者不一致报错 | ✅ |
296+| `cu_seqlens[0]==0`、`cu_seqlens[-1]==t`、非降(允许相等 = 空段);TH 下 batch 数 `bsz = numel-1`(不是 `t`) | ❌ 不校验 |
297+| `wkv.shape[1] == x.shape[-1]`;`weight.shape[0] == wkv.shape[0] == d`;`h`、`d` 为 JIT 静态特化维(不同取值触发重新编译;常用 `h` 4096/5120、`d` 512/128) | ✅ |
298+| BSH 整段输入 `seq < ratio` 无有效输出(返回占位,见 §2.2);TH 段长可为 0(空段跳过:不写 state、不产生输出) | — |
299+| `bsz / seq / t` 取 0 的极端形状未纳入当前验证范围 | — |
300+| 输出形状:BSH ratio1 `(bsz, seq, d)` / ratio2 `(bsz, max(seq//ratio,1), d)`;TH ratio1 `(t, d)` / ratio2 prefill `(min(t, t//ratio+bsz), d)`(compact 压缩行 + pad,**pad 行未写入、值未定义**)/ decode `(bsz, d)` | ✅(Meta 推导) |
301+ 
302+### 6.2 dtype 契约
303+ 
304+| 张量 | ratio==1 | ratio==2 |
305+|---|---|---|
306+| `x` / `grad_out` | bf16 | bf16 |
307+| `wkv` | 前向 bf16(接受 bf16/fp32,内部归一 bf16);反向同 | 前向 bf16(接受 bf16/fp32,内部归一 bf16);反向同 |
308+| `wgate` | 必须为 `None` | bf16(接受 bf16/fp32,内部归一 bf16) |
309+| `weight` | fp32(前向强制;反向 bf16/fp32) | 同左 |
310+| `kv_state` / `score_state` | 必须为 `None` | 必须提供,`(bsz, 2, d)` fp32 |
311+| `start_pos` | int32 `(1,)` | 同左 |
312+| `cu_seqlens` | TH 时 int32 `(bsz+1,)`;BSH 必须为 `None` | 同左 |
313+| 反向输出 dtype | `dwkv` 跟随 `wkv`、`dweight` 跟随 `weight`、`dwgate=None` | `dwkv/dwgate` 跟随 `wkv/wgate`、`dweight` 跟随 `weight` |
314+ 
315+注:`wkv/wgate` 在 ratio1/2 下统一 bf16。前向 wrapper 接受 bf16/fp32 并在 host 侧归一为 bf16,kernel 以 bf16 cube 执行、
316+fp32 累加;golden 同步按 bf16 权值对齐。反向 wrapper 同样放宽到 bf16/fp32 并内部统一量化 bf16。
317+ 
318+### 6.3 start_pos 与 decode 单 token(值不校验)
319+ 
320+- `start_pos` 为 `(1,)` int32 **设备张量**:`0` = 整段输入(prefill,从位置 0 分组);`>0` = 单 token
321+ (decode,当前位置);须在 aclgraph 捕获前创建、勿在捕获内新建。ratio==1 忽略该值(无 state)。
322+- **decode 仅支持每 batch 恰 1 token**(多 token decode 暂未实现):BSH 要求 `x seq == 1`;TH 要求
323+ `T == bsz`(即 `cu_seqlens == [0,1,...,bsz]`)。**不做运行时校验**(读 `start_pos` 需 D2H 同步);
324+ 违反时不报错,kernel decode 分支会按"行序 = batch 序"静默错算(BSH 忽略每 batch 第 0 行以外的
325+ token;TH 忽略实际段长)。
326+- 单 token 组未满时输出为占位(未写入);是否消费输出由调用方按 `(start_pos+1) % ratio == 0`
327+ 判断;盲反传语义见 §4.2。
328+ 
329+### 6.4 state 约束
330+ 
331+- ratio==2 必须提供 `kv_state/score_state`,形状 `(bsz, 2, d)` fp32;**前向原地更新**、不可微
332+ (梯度返回 `None`);反向必须传**前向更新后**的值;decode 分支仅当前 token 槽位可微。
333+- dim0 允许 `> bsz`(`max_batch_size` 预分配):前向经公共入口、反向经 wrapper 精确切片到
334+ `(bsz, 2, d)`(**TH 按段数 bsz,而非 t**);切片共享存储,原地写落回大 buffer `[0, bsz)` 行,
335+ `[bsz:)` 行不受影响。
336+- 初值惯例(`register_buffer`):`kv_state` 全 0、`score_state` 全 `-inf`。
337+ 
338+### 6.5 反向输入约束
339+ 
340+- `grad_out` 形状必须与前向输出一致(BSH `(bsz, n_out, d)`,n_out = `seq` / `max(seq//ratio,1)`;
341+ TH `(Sr, d)`,Sr = `t` / `min(t, t//ratio+bsz)`),dtype 与 `x` 相同(bf16)。
342+- **设备一致性**:反向显式校验 `grad_out / wkv / wgate / weight / kv_state / score_state / start_pos`
343+ 与 `x` 同设备(`cu_seqlens` 未纳入该校验);前向均未显式校验,须调用方保证全部输入同设备。
344+- 余数行零填:BSH 由 wrapper(`s1 % ratio != 0` 时批量清零各 batch 尾行);TH 由 kernel 内按段零填。
345+- 反向 wrapper 内部完成 `grad_out.contiguous()`、权值 `.to(bf16)` 量化与 scratch 分配
346+ (`torch.empty`,不引入额外算子约束)。
347+ 
348+### 6.6 图捕获(aclgraph)
349+ 
350+- `start_pos` / `cu_seqlens` 及各输入输出 buffer 须在捕获前创建;算子内部不做任何 D2H 同步
351+ (decode 单 token 校验因此不做,见 §6.3)。
352+- 形状动态性由 JIT 承担:`h` 静态特化,`bsz / seq / t` 动态;TH 的 `out_base` 前缀和由 wrapper
353+ 内设备侧小算子计算(B=1 短路为单 mul 归零;B>1 走 fp32 AiCore cumsum,规避 int32 cumsum
354+ 落 AICPU 的 ~39us 开销),图捕获下进入图。
355+ 
356+---
357+ 
358+## 7. 调用案例
359+ 
360+```python
361+import torch
362+import torch_npu # noqa: F401 —— NPU 设备初始化必需
363+from deepseek_v4_1.csa2_compressor import csa2_compressor, CSA2Compressor
364+ 
365+device = "npu:0"
366+bsz, seq, h, d = 8, 3, 5120, 512
367+ 
368+x = torch.rand((bsz, seq, h), dtype=torch.bfloat16, device=device).requires_grad_(True)
369+wkv = torch.rand((d, h), dtype=torch.bfloat16, device=device).requires_grad_(True)
370+wgate = torch.rand((d, h), dtype=torch.bfloat16, device=device).requires_grad_(True)
371+weight = (torch.rand((d,), dtype=torch.float32, device=device) + 0.5).requires_grad_(True)
372+kv_state = torch.zeros((bsz, 2, d), dtype=torch.float32, device=device)
373+score_state = torch.full((bsz, 2, d), float("-inf"), dtype=torch.float32, device=device)
374+start_pos = torch.zeros(1, dtype=torch.int32, device=device)
375+ 
376+# 方式一:functional
377+out = csa2_compressor(x, wkv, wgate, weight, kv_state, score_state,
378+ start_pos, ratio=2, eps=1e-20) # (bsz, seq//2, d) bf16
379+loss = out.float().mean()
380+loss.backward() # 梯度落入 x.grad / wkv.grad / wgate.grad / weight.grad
381+ 
382+# 方式二:nn.Module(持有 ratio / eps)
383+model = CSA2Compressor(ratio=2, eps=1e-20)
384+out = model(x, wkv, wgate, weight, kv_state, score_state, start_pos)
385+```
386+ 
387+其他场景调用形式不变,只换参数:
388+ 
389+| 场景 | 差异 |
390+|---|---|
391+| ratio=1 | `CSA2Compressor(ratio=1)`;`wkv` 用 bf16;`wgate / kv_state / score_state` 传 `None` |
392+| 单 token 输入 | BSH:`seq=1`;TH:`cu_seqlens == [0,1,...,bsz]`(每段 1 token);`start_pos` 传当前位置;组满(`(pos+1) % ratio == 0`)才有有效输出 |
393+| TH (BS 合轴) | `x` 传 2D `(t, h)`、`cu_seqlens` 传 `(bsz+1,)` int32 前缀和(BSH 时 `cu_seqlens` 必须传 `None`);ratio2 输出 2D compact + pad,ratio1 输出 `(t, d)` |
394+| state 预分配 | `kv_state / score_state` 的 dim0 可大于 bsz(按 max_batch_size),入口自动切片(TH 按段数) |
395+ 
396+---
397+ 
398+ 
399+## 8. 精度基线与测试
400+ 
401+精度基线(dtype 键控,与 golden `torch` 实现对比):
402+ 
403+| 输出 | dtype | atol | rtol | 备注 |
404+|---|---|---|---|---|
405+| `out` / `dx` | bf16 | 1e-4 | 0.0078125 | 舍入边界翻转类另加**越限元素比例 ≤ 1e-3** |
406+| ratio1 `dwkv` | bf16 | 1e-4 | 0.0078125 | **逐元素全量**(无越限比例豁免) |
407+| `kv_state` / `score_state` / `dweight` | fp32 | 2.5e-5 | 0.005 | 累积类 按 `n_tok = bsz*seq` 档放宽 atol |
408+| ratio2 `dwkv` / `dwgate` | bf16 | 1e-3(`n_tok≥65536` → 4e-3) | 0.0078125(bf16 1 ulp) | **逐元素全量**(无越限比例豁免);fp32 累加后单次舍入 |
409+ 
410+测试(`tests/ops/deepseek_v4_1/` 9 个文件、217 个用例,已全量通过):
411+ 
412+```bash
413+# 在 pypto-gym 仓库根目录执行
414+# 全量(实测约 12 分钟,含 128K 长序列泛化与性能基准例)
415+TILE_FWK_DEVICE_ID=0 python3 -m pytest tests/ops/deepseek_v4_1/ -v -s
416+ 
417+# 单文件 / 单用例
418+TILE_FWK_DEVICE_ID=0 python3 -m pytest tests/ops/deepseek_v4_1/test_csa2_compressor_fwd.py -v
419+TILE_FWK_DEVICE_ID=0 python3 -m pytest "tests/ops/deepseek_v4_1/test_CSA2_compressor_entry.py::test_csa2_entry_ratio1" -v
420+```
421+ 
422+| 测试文件 | 覆盖 |
423+|---|---|
424+| `test_csa2_compressor_fwd.py` | 前向:整段输入 / 余数 / d128 / ratio1 / 单 token / 单 token 组满压缩(含 TH golden) |
425+| `test_CSA2_compressor_fwd_gen.py` | 前向泛化:B 1~256、S 1~131072、对齐/不对齐 |
426+| `test_csa2_compressor_bwd.py` | 反向:ratio1/2、单 token、预分配 state + 17 组泛化(seq 128~128K)+ 3 性能基准例(含 bsz=1 seq=8K 调优目标例,含 TH golden) |
427+| `test_CSA2_compressor_bwd_gen.py` | 反向泛化:B/S/d 矩阵 + 单 token 双槽预填 |
428+| `test_CSA2_compressor_entry.py` | 公共入口 fwd+bwd 连跑(Module / functional / autograd.Function / 预分配 state) |
429+| `test_CSA2_compressor_entry_gen.py` | 入口泛化:大 B×大 S(128K token)、奇偶对齐档、随机泛化 |
430+| `test_CSA2_compressor_th_fwd.py` | **TH 前向**(18 例):cu_seqlens 分段、compact+pad 输出、ratio1/2、TH decode;泛化含 8 对齐边缘簇、B=32 varlen(T=4K/8K/16K/64K/128K,lens 为随机递增序列一次性生成后**固化字面量**,每次运行一致;同一 cu_seqlens 内对齐/不对齐混合),每条用例标注测试点 |
431+| `test_CSA2_compressor_th_bwd.py` | **TH 反向**(17 例):逐段组块反向、段尾余数零梯度、TH decode 盲反传(与 golden 同口径);同结构泛化(bwd 独立固化数据,含 T=64K/128K) |
432+| `test_CSA2_compressor_th_entry.py` | **TH 入口正反连跑**(17 例):Module/functional、max_batch_size 预分配(按段数切片)、同结构泛化(entry 独立固化数据,T=4K/8K/16K/128K + ratio1 大 varlen) |
433+ 
434+测试产物(2026-10-09 全量复测(TH 扩展前的 165 例),Ascend910_9392 / CANN 9.1.0;均位于 `tests/ops/deepseek_v4_1/perf/`):
435+ 
436+| 产物 | 路径 |
437+|---|---|
438+| 精度测试报告(165/165 通过,含 workspace/IO 采集) | `tests/ops/deepseek_v4_1/perf/CSA2_compressor_precision_report.md` |
439+| 性能测试报告(msprof 采集,golden 小算子 vs pypto kernel) | `tests/ops/deepseek_v4_1/perf/CSA2_compressor_perf_report.md` |
440+| 交付报告 | `tests/ops/deepseek_v4_1/perf/CSA2_compressor_交付报告.md` |
441+| 性能比对 / msprof 采集 / 解析 / 报告生成脚本 | `perf/perf_cmp_compressor.py` / `perf/run_msprof_perf.sh` / `perf/parse_msprof_perf.py` / `perf/gen_perf_report.py`、`perf/gen_precision_report.py` |
442+| 调优记录与根因分析 | `perf/logs/tune_record.md`、`perf/logs/msprof_analyze/ANALYSIS_2100_vs_4800.md` |
443+| 全量测试日志 / msprof 原始数据 | `logs/` |
@@ -0,0 +1,178 @@
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+"""CSA2 Compressor 公共入口:前向 kernel + 反向 kernel 连跑。
12+ 
13+对外暴露三种形式(对齐 liger_cross_entropy_loss.py 的公共入口风格):
14+ * ``CSA2CompressorFunction`` —— ``torch.autograd.Function``,前向/反向入口;
15+ * ``csa2_compressor`` —— functional 形式;
16+ * ``CSA2Compressor`` —— ``nn.Module`` 形式(持有 ratio / eps)。
17+ 
18+依赖边界(除 pip 包外)只有同包两个 eager wrapper 入口(相对导入, 直调绕过 torch.ops
19+派发; 本文件与两个 impl 文件可整体移植到任意包目录):
20+ * ``.csa2_compressor_fwd_impl.npu_csa2_compressor`` —— 前向 kernel
21+ * ``.csa2_compressor_bwd_impl.npu_csa2_compressor_bwd`` —— 反向 kernel
22+ 
23+接口约定(与两个 kernel 一致):
24+ x (batch, seq, h) bf16
25+ wkv (head_dim, h) ratio>1: fp32, ratio==1: bf16
26+ wgate (head_dim, h) 或 None ratio>1: fp32, ratio==1: None
27+ weight (head_dim,) fp32 归一化权重
28+ kv_state / score_state (batch, ratio, head_dim) 或 None ratio>1: fp32 cache, ratio==1: None;
29+ dim0 允许 >= batch (max_batch_size 预分配), 入口内精确切片,
30+ 原地写落回调用方 buffer 的 [0, batch) 行
31+ start_pos (1,) int32 设备张量(aclnn 图捕获前创建,勿在捕获内新建)
32+ cu_seqlens TH: (bsz+1,) int32 前缀和; BSH: None (位于标量参数之前)
33+ ratio 1 或 2
34+ eps RMSNorm epsilon(float)
35+ 
36+语义说明:
37+ 前向会**原地更新** kv_state/score_state(register_buffer 语义),反向从中读取
38+ 前向后的值;因此 state 作为不可微 cache,不产生梯度(返回 None);梯度回传到
39+ x / wkv / wgate / weight。
40+ 
41+用法:
42+ from deepseek_v4_1.csa2_compressor import csa2_compressor
43+ out = csa2_compressor(x, wkv, wgate, weight, kv_state, score_state, start_pos,
44+ cu_seqlens, 2, 1e-20)
45+ out.sum().backward() # dx / dwkv / dwgate / dweight 落到各输入的 .grad
46+"""
47+ 
48+from __future__ import annotations
49+ 
50+__all__ = [
51+ "CSA2CompressorFunction",
52+ "csa2_compressor",
53+ "CSA2Compressor",
54+]
55+ 
56+import collections # noqa: E402
57+import torch # noqa: E402
58+import torch.nn as nn # noqa: E402
59+import torch_npu # noqa: E402,F401 NPU 设备初始化必需
60+ 
61+CSA2CompressorGrads = collections.namedtuple('CSA2CompressorGrads', [
62+ 'x', 'wkv', 'wgate', 'weight', 'kv_state', 'score_state',
63+ 'start_pos', 'cu_seqlens', 'ratio', 'eps',
64+])
65+ 
66+try: # 包内布局 (如 deepseek_v4_1 包): 相对导入
67+ from .csa2_compressor_fwd_impl import ( # noqa: E402
68+ npu_csa2_compressor,
69+ CSA2CompressorArgs,
70+ )
71+ from .csa2_compressor_bwd_impl import ( # noqa: E402
72+ npu_csa2_compressor_bwd,
73+ CSA2CompressorBwdArgs,
74+ )
75+except ImportError: # 平铺交付布局: 算子与测试同目录, 作为顶层模块导入
76+ from csa2_compressor_fwd_impl import ( # noqa: E402
77+ npu_csa2_compressor,
78+ CSA2CompressorArgs,
79+ )
80+ from csa2_compressor_bwd_impl import ( # noqa: E402
81+ npu_csa2_compressor_bwd,
82+ CSA2CompressorBwdArgs,
83+ )
84+ 
85+ 
86+class CSA2CompressorFunction(torch.autograd.Function):
87+ """前向 kernel + 反向 kernel 的组合入口。"""
88+ 
89+ @staticmethod
90+ def forward(ctx, x, wkv, wgate, weight, kv_state, score_state, start_pos, cu_seqlens,
91+ ratio, eps):
92+ # state 允许按 max_batch_size 预分配 (dim0 >= 当前 batch, 对齐推理模型 buffer 惯例):
93+ # 入口内精确切片到 (batch, ratio, d) 以过 kernel 的 shape 契约; dim0 切片连续且共享
94+ # 存储, 前向的原地写仍落到调用方真实 buffer 的 [0, batch) 行, [batch:) 行不受影响;
95+ # 反向经 ctx 保存的是切片 (精确 shape, 且读到前向写后的值)。
96+ # BSH (cu_seqlens 为 None): batch = x.shape[0];
97+ # TH (BS 合轴, cu_seqlens 给定): batch = cu_seqlens 段数 (x dim0 为 token 总数 T)
98+ batch = cu_seqlens.shape[0] - 1 if cu_seqlens is not None else x.shape[0]
99+ if kv_state is not None and kv_state.shape[0] != batch:
100+ if not (kv_state.shape[0] > batch and score_state.shape[0] > batch):
101+ raise ValueError(
102+ f"state dim0 is ({kv_state.shape[0]}, {score_state.shape[0]}), "
103+ f"expected == batch {batch} or > it (max_batch_size 预分配)")
104+ kv_state = kv_state[:batch]
105+ score_state = score_state[:batch]
106+ out = npu_csa2_compressor(CSA2CompressorArgs(
107+ x=x, wkv=wkv, wgate=wgate, weight=weight,
108+ kv_state=kv_state, score_state=score_state,
109+ start_pos=start_pos, ratio=ratio, eps=eps, cu_seqlens=cu_seqlens,
110+ ))
111+ # 反向需要前向后的 state(前向已原地更新)与全部输入
112+ if ratio == 1:
113+ ctx.save_for_backward(x, wkv, weight, start_pos, cu_seqlens)
114+ else:
115+ ctx.save_for_backward(x, wkv, wgate, weight, kv_state, score_state, start_pos,
116+ cu_seqlens)
117+ ctx.ratio = ratio
118+ ctx.eps = eps
119+ return out
120+ 
121+ @staticmethod
122+ def backward(ctx, grad_out):
123+ if ctx.ratio == 1:
124+ x, wkv, weight, start_pos, cu_seqlens = ctx.saved_tensors
125+ wgate = kv_state = score_state = None
126+ else:
127+ x, wkv, wgate, weight, kv_state, score_state, start_pos, cu_seqlens = \
128+ ctx.saved_tensors
129+ 
130+ dx, dwkv, dwgate, dweight = npu_csa2_compressor_bwd(CSA2CompressorBwdArgs(
131+ grad_out=grad_out, x=x, wkv=wkv, wgate=wgate, weight=weight,
132+ kv_state=kv_state, score_state=score_state,
133+ start_pos=start_pos, ratio=ctx.ratio, eps=ctx.eps, cu_seqlens=cu_seqlens,
134+ ))
135+ # 顺序对齐 forward 入参: x, wkv, wgate, weight, kv_state, score_state,
136+ # start_pos, cu_seqlens, ratio, eps
137+ return CSA2CompressorGrads(
138+ dx, dwkv, dwgate, dweight, None, None, None, None, None, None)
139+ 
140+ 
141+def csa2_compressor(
142+ x,
143+ wkv,
144+ wgate,
145+ weight,
146+ kv_state,
147+ score_state,
148+ start_pos,
149+ cu_seqlens=None,
150+ ratio=2,
151+ eps=1e-20,
152+):
153+ """functional 入口:前向 +(按需)反向 autograd 连跑。"""
154+ return CSA2CompressorFunction.apply(
155+ x, wkv, wgate, weight, kv_state, score_state, start_pos, cu_seqlens, ratio, eps
156+ )
157+ 
158+ 
159+class CSA2Compressor(nn.Module):
160+ """nn.Module 入口:持有 ratio / eps 配置,权重与 state 由调用方按参数传入。"""
161+ 
162+ def __init__(self, ratio: int = 2, eps: float = 1e-20):
163+ super().__init__()
164+ if ratio not in (1, 2):
165+ raise ValueError(f"ratio is {ratio}, expected 1 or 2")
166+ if not isinstance(eps, float):
167+ raise TypeError(f"eps is {type(eps).__name__}, expected float")
168+ if eps < 0.0:
169+ raise ValueError(f"eps is {eps}, expected non-negative float")
170+ self.ratio = ratio
171+ self.eps = eps
172+ 
173+ def forward(self, x, wkv, wgate, weight, kv_state, score_state, start_pos,
174+ cu_seqlens=None):
175+ return csa2_compressor(
176+ x, wkv, wgate, weight, kv_state, score_state, start_pos,
177+ cu_seqlens, self.ratio, self.eps,
178+ )
@@ -0,0 +1,456 @@
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+"""CSA2 compressor fwd+bwd entry test (self-contained golden)."""
12+import logging
13+import os
14+import sys
15+from dataclasses import dataclass
16+from typing import Any
17+ 
18+import numpy as np
19+from numpy.testing import assert_allclose
20+import pytest
21+import torch
22+import torch_npu
23+ 
24+_p = os.path.dirname(os.path.abspath(__file__))
25+sys.path.insert(0, _p)
26+while _p != os.path.dirname(_p):
27+ if os.path.isdir(os.path.join(_p, "src")):
28+ sys.path.insert(0, os.path.join(_p, "src"))
29+ sys.path.insert(0, os.path.join(_p, "src", "pypto_gym", "ops", "pypto_tensor"))
30+ break
31+ _p = os.path.dirname(_p)
32+ 
33+try:
34+ from deepseek_v4_1.csa2_compressor import csa2_compressor, CSA2Compressor # noqa: E402
35+except ImportError:
36+ from csa2_compressor import csa2_compressor, CSA2Compressor
37+ 
38+logger = logging.getLogger(__name__)
39+EPS = 1e-20
40+OUT_ERR_RATIO = 1e-3
41+ATOL, RTOL = 1e-4, 7.8125e-3
42+ 
43+ 
44+def rms_norm_golden(x: torch.Tensor, eps: float, weight: torch.Tensor) -> torch.Tensor:
45+ dtype = x.dtype
46+ x = x.float()
47+ var = x.square().mean(-1, keepdim=True)
48+ x = x * torch.rsqrt(var + eps)
49+ return (weight * x).to(dtype)
50+ 
51+ 
52+@dataclass
53+class GoldenCompressInputsCSA2:
54+ x: Any
55+ wkv: Any
56+ wgate: Any
57+ weight: Any
58+ kv_state: Any # (bsz, ratio, head_dim) fp32, 就地更新
59+ score_state: Any # (bsz, ratio, head_dim) fp32, -inf 初值
60+ start_pos: Any # int
61+ ratio: Any
62+ eps: Any = 1e-20
63+ 
64+ 
65+def golden_compress_csa2(inputs: GoldenCompressInputsCSA2):
66+ """源码 Compressor.forward 的 golden (向量化, 逐行对应)。
67+ 
68+ prefill(start_pos==0): 完整组 unflatten 后 softmax(dim=2) 池化, 余数 split 一次写 state
69+ decode (start_pos!=0): 单 token 写 state[start_pos % ratio], 组满时对 state 池化
70+ 无压缩时返回 None, 否则返回 pre-RoPE latent。
71+ """
72+ x = inputs.x
73+ wkv = inputs.wkv
74+ wgate = inputs.wgate
75+ weight = inputs.weight
76+ kv_state = inputs.kv_state
77+ score_state = inputs.score_state
78+ start_pos = inputs.start_pos
79+ ratio = inputs.ratio
80+ eps = inputs.eps
81+ 
82+ bsz, seqlen, _ = x.size()
83+ dtype = x.dtype
84+ assert ratio in (1, 2), "ratio must be 1 or 2"
85+ 
86+ if ratio == 1:
87+ # 源码: return self.norm(self.wkv(x)) —— bf16 投影(不转 fp32), 无 gate/state,
88+ # 每 token 一个 latent, 忽略 start_pos
89+ kv = torch.matmul(x, wkv.transpose(-2, -1)) # bf16 -> bf16
90+ return rms_norm_golden(kv, eps, weight)
91+ 
92+ x = x.float()
93+ # wkv/wgate 统一 bf16: 与 kernel (wrapper 归一 bf16) 逐位对齐
94+ wkv = wkv.to(torch.bfloat16).float()
95+ wgate = wgate.to(torch.bfloat16).float()
96+ kv = torch.matmul(x, wkv.transpose(-2, -1)) # (bsz, seqlen, d)
97+ score = torch.matmul(x, wgate.transpose(-2, -1))
98+ 
99+ if start_pos == 0:
100+ # ---- prefill: 池化完整组, 尾部余数存 state ----
101+ should_compress = seqlen >= ratio
102+ remainder = seqlen % ratio
103+ cutoff = seqlen - remainder
104+ if remainder:
105+ kv, kv_state[:bsz, :remainder] = kv.split([cutoff, remainder], dim=1)
106+ score, score_state[:bsz, :remainder] = score.split([cutoff, remainder], dim=1)
107+ kv = kv.unflatten(1, (-1, ratio)) # (bsz, n_groups, ratio, d)
108+ score = score.unflatten(1, (-1, ratio))
109+ kv = (kv * score.softmax(dim=2)).sum(dim=2) # (bsz, n_groups, d)
110+ else:
111+ # ---- decode: 每步 1 个 token, 填槽位, 组满时池化 ----
112+ assert seqlen == 1, "decode branch requires exactly 1 token per step"
113+ should_compress = (start_pos + 1) % ratio == 0
114+ slot = start_pos % ratio
115+ kv_state[:bsz, slot] = kv.squeeze(1)
116+ score_state[:bsz, slot] = score.squeeze(1)
117+ if should_compress:
118+ kv = (kv_state[:bsz] * score_state[:bsz].softmax(dim=1)).sum(dim=1, keepdim=True)
119+ 
120+ if not should_compress:
121+ return None
122+ # 源码: return self.norm(kv.to(dtype)) —— 池化结果先落回 bf16 再 RMSNorm (pre-RoPE)
123+ return rms_norm_golden(kv.to(dtype), eps, weight)
124+ 
125+ 
126+def gen_inputs_csa2(
127+ bsz: int,
128+ seq: int,
129+ h: int,
130+ d: int,
131+ ratio: int,
132+ device: str,
133+):
134+ """生成输入: x / wkv / wgate / weight / kv_state(0) / score_state(-inf)
135+ 
136+ wkv/wgate 统一 bf16 (ratio1/2 同规格); ratio == 1 时源码没有 wgate/kv_state/
137+ score_state, 对应位置返回 None。
138+ """
139+ torch.manual_seed(42)
140+ x = torch.rand((bsz, seq, h), dtype=torch.bfloat16, device=device)
141+ weight = torch.rand((d,), dtype=torch.float32, device=device) + 0.5
142+ if ratio == 1:
143+ wkv = torch.rand((d, h), dtype=torch.bfloat16, device=device)
144+ return (x, wkv, None, weight, None, None)
145+ 
146+ # 保持 fp32 抽取再量化 bf16: 与统一 bf16 前的测试数据同值 (rand 的 dtype 会改变
147+ # 随机流), 使对比只反映 dtype 契约而非数据实现差异
148+ wkv = torch.rand((d, h), dtype=torch.float32, device=device).to(torch.bfloat16)
149+ wgate = torch.rand((d, h), dtype=torch.float32, device=device).to(torch.bfloat16)
150+ kv_state = torch.zeros((bsz, ratio, d), dtype=torch.float32, device=device)
151+ score_state = torch.full((bsz, ratio, d), float("-inf"), dtype=torch.float32, device=device)
152+ return (x, wkv, wgate, weight, kv_state, score_state)
153+ 
154+ 
155+def _assert_tensor(name, got, ref, rtol, atol, max_error_ratio=None):
156+ got_np = got.cpu().float().numpy()
157+ ref_np = ref.cpu().float().numpy()
158+ finite = np.isfinite(got_np) & np.isfinite(ref_np)
159+ if finite.any():
160+ diff = np.abs(got_np[finite] - ref_np[finite])
161+ ref_abs_mean = np.abs(ref_np[finite]).mean()
162+ else:
163+ diff = np.zeros(1)
164+ ref_abs_mean = 0.0
165+ logger.info(" [%s] shape=%s max_abs=%.6e mean_abs=%.6e |ref|mean=%.6f",
166+ name, tuple(got.shape), diff.max(), diff.mean(), ref_abs_mean)
167+ if max_error_ratio is None:
168+ assert_allclose(got_np, ref_np, rtol=rtol, atol=atol)
169+ return
170+ # "紧 rtol + 超阈元素比例阈值" (与 test_CSA2_compressor_fwd_gen.py /
171+ # test_CSA2_compressor_entry_gen.py 同一口径, 参考 common_utils/compare.py):
172+ # kernel 与 golden 的 fp32 前像存在累加顺序级差异, 偶发翻转 bf16(latent) 的舍入
173+ # 边界 → 个别元素 1-2 ulp 差; 该翻转是逐元素概率事件, 与规模/形状无关.
174+ with np.errstate(invalid="ignore"):
175+ diff_all = np.abs(got_np - ref_np)
176+ tol = atol + rtol * np.abs(ref_np)
177+ bad = finite & (diff_all > tol)
178+ bad |= ~finite & ~((got_np == ref_np) | (np.isnan(got_np) & np.isnan(ref_np)))
179+ n_bad = int(bad.sum())
180+ n_thr = round(max_error_ratio * ref_np.size)
181+ if n_bad:
182+ logger.info(" [%s] 越限元素 %s/%s (阈值 %s)", name, n_bad, ref_np.size, n_thr)
183+ assert n_bad <= n_thr, (
184+ f"{name}: 越限元素 {n_bad} > 阈值 {n_thr} "
185+ f"(max_error_ratio={max_error_ratio}x{ref_np.size}), max_diff={diff.max():.3e}")
186+ 
187+ 
188+ 
189+def _compressor_prep():
190+ device_id = int(os.environ.get("TILE_FWK_DEVICE_ID", 0))
191+ torch.npu.set_device(device_id)
192+ torch_npu.npu.config.allow_internal_format = True
193+ return f"npu:{device_id}"
194+ 
195+ 
196+def rms_norm_golden_backward(dy: torch.Tensor, x: torch.Tensor, weight: torch.Tensor, eps: float):
197+ """dy: dL/dy; x: RMSNorm 输入; 返回 (dx, dweight)
198+ 
199+ dx (dlatent/dkv) 是反向内部量, 保持 fp32 返回 —— kernel 侧 (rms_norm_backward_2d)
200+ 全程 fp32, 量化点在尾段 cube matmul 操作数 (见 golden_compress_csa2_backward 尾段
201+ 注释)。此处若按前向输出 dtype 回 cast bf16, dlatent 幅值大时 (decode 随机 state
202+ → rms 小 → dlatent ~O(1)) 会引入 ~2^-9 相对差而 kernel 无此量化。ratio==1 分支
203+ 在调用点显式量化 (对齐 kernel 的 dkv→bf16 cast 点)。
204+ """
205+ x_fp = x.float()
206+ w_fp = weight.float()
207+ hidden_dim = x_fp.shape[-1]
208+ var = x_fp.square().mean(-1, keepdim=True)
209+ rms = torch.rsqrt(var + eps)
210+ dy_fp = dy.float()
211+ 
212+ d_y = dy_fp * w_fp
213+ term1 = d_y * rms
214+ sum_term = torch.sum(d_y * x_fp, dim=-1, keepdim=True)
215+ term2 = x_fp * sum_term * (rms ** 3) / hidden_dim
216+ dx_fp = term1 - term2
217+ dweight = torch.sum(dy_fp * x_fp * rms, dim=list(range(dy_fp.dim() - 1)))
218+ return dx_fp, dweight.to(weight.dtype)
219+ 
220+ 
221+def softmax_golden(x: torch.Tensor, dim: int):
222+ x_max = torch.max(x, dim=dim, keepdim=True)[0]
223+ exp_x = torch.exp(x - x_max)
224+ return exp_x / torch.sum(exp_x, dim=dim, keepdim=True)
225+ 
226+ 
227+def softmax_golden_backward(dy: torch.Tensor, y: torch.Tensor, dim: int):
228+ """y = softmax(x, dim); dy = dL/dy -> dL/dx"""
229+ d = dy * y
230+ sum_d = torch.sum(d, dim=dim, keepdim=True)
231+ return y * (dy - sum_d)
232+ 
233+ 
234+def golden_compress_csa2_backward(inputs: GoldenCompressInputsCSA2, d_out: torch.Tensor):
235+ """CSA2 compressor 解析反向 (与前向三分支一一对应).
236+ 
237+ d_out: dL/dout, 形状与前向输出一致
238+ 返回 (dx, dwkv, dwgate, dweight); ratio == 1 时 dwgate 为 None
239+ 
240+ 反向 cube matmul 操作数量化约定 (对齐 kernel bf16-MAC 形态, 见函数尾段注释):
241+ dx / dwkv / dwgate 的操作数在 matmul 边界量化 bf16, fp32 累加, dx 单次最终
242+ 舍入 —— 与 kernel 的声明语义一致 (比率 1 分支天然对齐, 比率 2 显式镜像)。
243+ """
244+ x = inputs.x
245+ wkv = inputs.wkv
246+ wgate = inputs.wgate
247+ weight = inputs.weight
248+ kv_state = inputs.kv_state
249+ score_state = inputs.score_state
250+ start_pos = inputs.start_pos
251+ ratio = inputs.ratio
252+ eps = inputs.eps
253+ 
254+ bsz, seqlen, h = x.shape
255+ d = weight.shape[0]
256+ dtype = x.dtype
257+ assert ratio >= 1, "ratio must be >= 1"
258+ 
259+ if ratio == 1:
260+ # 前向: out = norm(wkv(x)) —— 投影结果本身即 norm 输入(bf16 路径下为 bf16)
261+ kv = torch.matmul(x, wkv.transpose(-2, -1))
262+ dkv, dweight = rms_norm_golden_backward(d_out, kv, weight, eps)
263+ # kernel 侧 dkv 在 cube matmul 边界量化 bf16 (Phase C dx 与 D 段 scratch 同点)
264+ dkv = dkv.to(dtype)
265+ dx = torch.matmul(dkv, wkv.float())
266+ dwkv = torch.matmul(dkv.reshape(-1, d).transpose(-2, -1), x.float().reshape(-1, h))
267+ return dx.to(dtype), dwkv.to(wkv.dtype), None, dweight.to(weight.dtype)
268+ 
269+ x_fp32 = x.float()
270+ # kv/score 重算对齐 kernel gb 段 bf16-MAC 语义: wkv/wgate 统一 bf16 (测试直接生成
271+ # bf16 权重, .to(bf16) 为 no-op), x 原生 bf16 (float() 精确); bf16×bf16 乘积在 fp32
272+ # 精确, 仅累加顺序与 kernel tile 分组不同 (容差内)
273+ wkv_b = wkv.to(torch.bfloat16).float()
274+ wgate_b = wgate.to(torch.bfloat16).float()
275+ kv = torch.matmul(x_fp32, wkv_b.transpose(-2, -1)) # (bsz, seqlen, d)
276+ score = torch.matmul(x_fp32, wgate_b.transpose(-2, -1))
277+ 
278+ dkv = torch.zeros_like(kv)
279+ dscore = torch.zeros_like(score)
280+ 
281+ if start_pos == 0:
282+ # ---- prefill: 完整组可微; 余数 token 无输出 → 梯度 0 ----
283+ remainder = seqlen % ratio
284+ cutoff = seqlen - remainder
285+ if cutoff > 0:
286+ n_groups = cutoff // ratio
287+ gkv = kv[:, :cutoff].reshape(bsz, n_groups, ratio, d)
288+ gsc = score[:, :cutoff].reshape(bsz, n_groups, ratio, d)
289+ alpha = gsc.softmax(dim=2, dtype=torch.float32)
290+ latent = (gkv * alpha).sum(dim=2) # (bsz, n_groups, d)
291+ dlatent, dweight = rms_norm_golden_backward(d_out, latent.to(dtype), weight, eps)
292+ dlatent4 = dlatent.unsqueeze(2)
293+ d_alpha = dlatent4 * gkv
294+ d_gkv = dlatent4 * alpha
295+ d_gsc = softmax_golden_backward(d_alpha, alpha, dim=2)
296+ dkv[:, :cutoff] = d_gkv.reshape(bsz, cutoff, d)
297+ dscore[:, :cutoff] = d_gsc.reshape(bsz, cutoff, d)
298+ else:
299+ dweight = torch.zeros(d, dtype=weight.dtype, device=weight.device)
300+ else:
301+ # ---- decode: latent 由 state 池化, 仅当前 token 写入的槽位可微 ----
302+ assert seqlen == 1, "decode branch requires exactly 1 token per step"
303+ slot = start_pos % ratio
304+ alpha = score_state[:bsz].softmax(dim=1, dtype=torch.float32) # (bsz, ratio, d)
305+ latent = (kv_state[:bsz] * alpha).sum(dim=1, keepdim=True) # (bsz, 1, d)
306+ dlatent, dweight = rms_norm_golden_backward(d_out, latent.to(dtype), weight, eps)
307+ d_alpha = dlatent * kv_state[:bsz]
308+ d_kv_slot = dlatent[:, 0] * alpha[:, slot] # (bsz, d)
309+ d_sc_slot = softmax_golden_backward(d_alpha, alpha, dim=1)[:, slot]
310+ dkv[:, 0] = d_kv_slot
311+ dscore[:, 0] = d_sc_slot
312+ 
313+ # ---- 反向 cube matmul 操作数量化约定 (对齐 kernel bf16-MAC 形态) ----
314+ # kernel 的 dx / dwkv / dwgate cube matmul 要求 A/B 同 dtype (bf16), fp32 累加:
315+ # dx 段: bf16(d_kv) @ bf16(wkv) + bf16(d_sc) @ bf16(wgate) (单次最终舍入)
316+ # dw 段: bf16(d_kv)/bf16(d_sc) @ x(原生 bf16, 值精确) fp32 累加
317+ # gb 段: kv/score 重算用单次量化 bf16 权值 (见函数头部, 同一口径)
318+ # golden 在相同量化点镜像: 操作数先量化 bf16 再以 fp32 精确矩阵乘 (乘积精确 +
319+ # fp32 累加, 仅累加顺序与 kernel tile 分组不同)。wkv/wgate 的量化值与 kernel
320+ # wrapper 的 wkv.to(bf16) 逐位一致 (同一 torch 调用), 对比仍能捕获 kernel 的
321+ # 结构/逻辑错误; 度量的是 "kernel 是否正确实现既定 bf16 语义", 不惩罚声明为
322+ # 语义的操作数量化。ratio==1 分支天然已对齐 (dkv 由 rms_norm_golden_backward
323+ # 直接返回 bf16, wkv 原生 bf16, x.float() 为精确值)。
324+ dkv_b = dkv.to(dtype).float()
325+ dscore_b = dscore.to(dtype).float()
326+ dx = torch.matmul(dkv_b, wkv_b) + torch.matmul(dscore_b, wgate_b)
327+ # dwkv/dwgate 需对 batch 与 seq 同时求和 → 先展平 (batch*seq, ·)
328+ dwkv = torch.matmul(dkv_b.reshape(-1, d).transpose(-2, -1), x_fp32.reshape(-1, h))
329+ dwgate = torch.matmul(dscore_b.reshape(-1, d).transpose(-2, -1), x_fp32.reshape(-1, h))
330+ return (dx.to(dtype), dwkv.to(wkv.dtype), dwgate.to(wgate.dtype), dweight.to(weight.dtype))
331+ 
332+ 
333+def _make_inputs(x, wkv, wgate, weight, kv_state, score_state, start_pos, ratio, eps):
334+ return GoldenCompressInputsCSA2(
335+ x=x, wkv=wkv, wgate=wgate, weight=weight,
336+ kv_state=kv_state, score_state=score_state,
337+ start_pos=start_pos, ratio=ratio, eps=eps)
338+ 
339+ 
340+def _assert_bwd(name, got, ref, rtol, atol, max_error_ratio=None):
341+ """max_error_ratio=None: 逐元素全量校验; =r: 允许 ≤ round(r*numel) 个元素超阈
342+ (参考 common_utils/compare.py, test_sparse_flash_attention_quant.py 同款)。"""
343+ got_np = got.cpu().float().numpy()
344+ ref_np = ref.cpu().float().numpy()
345+ diff = np.abs(got_np - ref_np)
346+ logger.info(" [%s] shape=%s max_abs=%.6e mean_abs=%.6e |ref|mean=%.6f",
347+ name, tuple(got.shape), diff.max(), diff.mean(), np.abs(ref_np).mean())
348+ if max_error_ratio is None:
349+ assert_allclose(got_np, ref_np, rtol=rtol, atol=atol)
350+ return
351+ tol = atol + rtol * np.abs(ref_np)
352+ bad = diff > tol
353+ n_bad, n_thr = int(bad.sum()), round(max_error_ratio * ref_np.size)
354+ if n_bad:
355+ logger.info(" [%s] 越限元素 %s/%s (阈值 %s), 前 10 个:",
356+ name, n_bad, ref_np.size, n_thr)
357+ for i in np.argwhere(bad)[:10]:
358+ i = tuple(int(v) for v in i)
359+ logger.info(" %s: got=%.8f ref=%.8f diff=%.3e thr=%.3e",
360+ i, got_np[i], ref_np[i], diff[i], tol[i])
361+ assert n_bad <= n_thr, (
362+ f"{name}: 越限元素 {n_bad} > 阈值 {n_thr} "
363+ f"(max_error_ratio={max_error_ratio}x{ref_np.size}), max_diff={diff.max():.3e}")
364+ 
365+def _assert_bwd_all(dx, gdx, dwkv, gdwkv, dwgate, gdwgate, dweight, gdweight,
366+ atol=1e-3, atol_dw=None, atol_dx=None):
367+ """精度基线 (dtype 键控): bf16 (dx / dwkv) atol=1e-4 rtol=0.0078125;
368+ ratio2 dwkv/dwgate (bf16): rtol=0.0078125 + atol 按 n_tok 档。
369+ 
370+ 文档化豁免 (累积类, 物理上不满足基线, 机制见各注释):
371+ * dx (bf16): 稀疏翻转类 → 基线 + 越限比例阈值 1e-3 (参考 common_utils/compare.py);
372+ 小 h 冒烟维度 (h=64, softmax alpha 未饱和敏感性, 越限率 0.5% 超比例阈值) 另经
373+ atol_dx 放宽
374+ * ratio2 dwkv/dwgate (bf16): 主误差为 fp32 累加重结合随 n_tok 增长 (128K 实测
375+ 越限 1.5%/12%) → atol 按 n_tok 档放宽 (调用方传 atol: 1e-3 / >=65536 取 4e-3);
376+ bf16 末次舍入另叠 ≤1 ulp, 由 rtol=0.0078125 覆盖
377+ * dweight (fp32): bf16(latent) 翻转累积随 token 数增长 → atol_dw 按 n_tok 档
378+ 放宽 (1e-2 / 3e-2 / 6e-2; 最低档覆盖单次翻转事件 ~4-8e-3 落在小 |ref| 元素)
379+ """
380+ if atol_dw is None:
381+ atol_dw = 1e-2
382+ if atol_dx is None:
383+ atol_dx = 1e-4
384+ _assert_bwd("dx", dx, gdx, rtol=0.0078125, atol=atol_dx, max_error_ratio=1e-3)
385+ if gdwgate is None:
386+ # ratio1: dwkv 为 bf16 输出 → bf16 基线 (实测 flat 通过, 128K worst_ratio 0.98)
387+ _assert_bwd("dwkv", dwkv, gdwkv, rtol=0.0078125, atol=1e-4)
388+ else:
389+ # ratio2: dwkv/dwgate 对外 dtype 随 wkv/wgate 变成 bf16 (输出分辨率 1 ulp =
390+ # 0.78125%), 故 rtol 必须取 bf16 ulp —— 合法的 1-ulp 差会超原 fp32 口径 0.005
391+ # (decode 实测 max_abs 0.03125 / rel 0.0056)。atol 沿袭原 n_tok 档 (累加顺序差)。
392+ _assert_bwd("dwkv", dwkv, gdwkv, rtol=0.0078125, atol=atol)
393+ _assert_bwd("dwgate", dwgate, gdwgate, rtol=0.0078125, atol=atol)
394+ # dweight = Σ dy·x·rms, x=bf16(pooled latent): 量化边界翻转随 token 数累积
395+ _assert_bwd("dweight", dweight, gdweight, rtol=0.005, atol=atol_dw)
396+ 
397+ 
398+def _run_entry_case(ra, bsz, seq, h, d, start_pos=0, use_module=True, atol_dx=None):
399+ """公共入口 forward + backward vs golden (前向三分支共用)."""
400+ device = _compressor_prep()
401+ x, wkv, wgate, weight, kv_state, score_state = gen_inputs_csa2(
402+ bsz, seq, h, d, ra, device)
403+ sp = torch.tensor([start_pos], dtype=torch.int32, device=device)
404+ 
405+ # golden 用独立 state 副本, 避免被 kernel 原地更新污染
406+ g_kv = kv_state.clone() if kv_state is not None else None
407+ g_sc = score_state.clone() if score_state is not None else None
408+ 
409+ for t in (x, wkv, wgate, weight):
410+ if t is not None:
411+ t.requires_grad_(True)
412+ 
413+ if use_module:
414+ model = CSA2Compressor(ratio=ra, eps=EPS)
415+ out = model(x, wkv, wgate, weight, kv_state, score_state, sp)
416+ else:
417+ out = csa2_compressor(
418+ x, wkv, wgate, weight, kv_state, score_state, sp, ratio=ra, eps=EPS)
419+ torch.npu.synchronize()
420+ 
421+ logger.info("=== entry ratio=%s bsz=%s seq=%s d=%s start_pos=%s ===",
422+ ra, bsz, seq, d, start_pos)
423+ 
424+ # ---- 前向 vs golden (golden 前向同时推进其 state 副本) ----
425+ g_inputs = _make_inputs(
426+ x.detach(), wkv.detach(),
427+ wgate.detach() if wgate is not None else None, weight.detach(),
428+ g_kv, g_sc, start_pos, ra, EPS)
429+ ref_out = golden_compress_csa2(g_inputs)
430+ if ref_out is not None:
431+ _assert_tensor("out", out.detach(), ref_out, rtol=RTOL, atol=ATOL,
432+ max_error_ratio=OUT_ERR_RATIO)
433+ 
434+ # ---- 反向 vs golden ----
435+ grad_out = torch.randn(out.shape, dtype=torch.bfloat16, device=device)
436+ out.backward(grad_out)
437+ torch.npu.synchronize()
438+ 
439+ gdx, gdwkv, gdwgate, gdweight = golden_compress_csa2_backward(g_inputs, grad_out)
440+ _assert_bwd_all(
441+ x.grad, gdx, wkv.grad, gdwkv,
442+ wgate.grad if wgate is not None else None, gdwgate,
443+ weight.grad, gdweight, atol_dx=atol_dx)
444+ logger.info(" PASS")
445+ 
446+ 
447+@pytest.mark.soc("910")
448+def test_csa2_entry_ratio2_prefill():
449+ """ratio == 2 prefill: seq % ratio == 0, 完整组可微"""
450+ _run_entry_case(ra=2, bsz=64, seq=2, h=5120, d=512, start_pos=0)
451+ 
452+ 
453+if __name__ == "__main__":
454+ test_csa2_entry_ratio2_prefill()
455+ logger.info("PASS")
456+