Merged
Revert "feat(kimi_linear_48b_a3b): Fuse KDA prefill path" #887
chengding888Add on Oct 27
Revert "feat(kimi_linear_48b_a3b): Fuse KDA prefill path" #887
Merged
Merged fromchengding888/pypto-gym1027intocann/pypto-gymmaster
Total: 17 files changed+5060-1270
| @@ -12,16 +12,10 @@ | |||
| 12 | 12 | ||
| 13 | | Operator | Toggle flag | Path | | 13 | | Operator | Toggle flag | Path | |
| 14 | |----------|-------------|------| | 14 | |----------|-------------|------| |
| 15 | -| `kda_fused_prefill` (prefill) | `USE_PTO_KDA` | [`src/pypto_gym/ops/pypto_tensor/kimi_linear_48b_a3b/kda/`](../../../ops/pypto_tensor/kimi_linear_48b_a3b/kda/) | | 15 | +| `kda_chunk` (prefill) | `USE_PTO_KDA` | [`ops/pypto_tensor/kimi_linear_48b_a3b/kda/`](../../../ops/pypto_tensor/kimi_linear_48b_a3b/kda/) | |
| 16 | -| `kda_fused_decode` (decode, T=1) | `USE_PTO_KDA` | 同上 | | ||
| 17 | 16 | ||
| 18 | -The prefill fused operator replaces the entire KDA subgraph of the `mode == 'chunk'` | 17 | +融合算子替换 `KimiDeltaAttention.forward` 中 prefill 的 `chunk_kda` 调用(KDA 线性注意力 |
| 19 | -branch in `KimiDeltaAttention.forward` (conv1d → gate → beta → chunk core → o_norm, | 18 | +层)。Decode(T=1 recurrent,走上游 torch `fused_recurrent_kda`)与全注意力 (MLA) 路径不受影响(仅 pto 化 chunk 路径)。 |
| 20 | -via `_try_kda_fused_prefill`). Decode (T=1) takes the `kda_fused_decode` path — a | ||
| 21 | -full-layer fusion including the projections (`_try_fused_decode`) — when `USE_PTO_KDA` | ||
| 22 | -is enabled and the conv/recurrent states have been seeded by prefill; graph mode goes | ||
| 23 | -through `StaticDecodeCache` from `kda_decode_graph.py`. For shapes outside the operator | ||
| 24 | -envelope, `NotImplementedError` → fallback to the torch reference path. | ||
| 25 | 19 | ||
| 26 | `--use_pypto` 模式依赖运行时 `kimi_linear_48b_a3b_pto_kernels/` 适配层包:脚本在导入 | 20 | `--use_pypto` 模式依赖运行时 `kimi_linear_48b_a3b_pto_kernels/` 适配层包:脚本在导入 |
| 27 | `transformers` 之前 `sys.path.insert(0, model_path)` 并 `import | 21 | `transformers` 之前 `sys.path.insert(0, model_path)` 并 `import |
| @@ -46,7 +40,7 @@ kimi_linear_48b_a3b_pto_kernels`,置 `USE_PTO_KDA = True`。该适配层包预 | |||
| 46 | # Baseline | 40 | # Baseline |
| 47 | python3 scripts/ask_Kimi-Linear-48B-A3B.py --model-path <weights_dir> --num_npus 4 | 41 | python3 scripts/ask_Kimi-Linear-48B-A3B.py --model-path <weights_dir> --num_npus 4 |
| 48 | 42 | ||
| 49 | -# PyPTO fused (KDA prefill + decode) | 43 | +# PyPTO fused (KDA chunk) |
| 50 | python3 scripts/ask_Kimi-Linear-48B-A3B.py --model-path <weights_dir> --num_npus 4 --use_pypto | 44 | python3 scripts/ask_Kimi-Linear-48B-A3B.py --model-path <weights_dir> --num_npus 4 --use_pypto |
| 51 | ``` | 45 | ``` |
| 52 | 46 | ||
| @@ -74,44 +68,82 @@ bash bench_Kimi-Linear-48B-A3B.sh | |||
| 74 | > 🟢 **可部署性能(真实路由、输出正确)= PyPTO 1.38x** —— 见下『全模型实测』表。 | 68 | > 🟢 **可部署性能(真实路由、输出正确)= PyPTO 1.38x** —— 见下『全模型实测』表。 |
| 75 | > ⚠️ 后面『图捕获吞吐代理』一节的**所有 graph / static-route 数字均为理想化代理**:用静态**假路由**换取可捕获性, | 69 | > ⚠️ 后面『图捕获吞吐代理』一节的**所有 graph / static-route 数字均为理想化代理**:用静态**假路由**换取可捕获性, |
| 76 | > **输出不正确、不是可运行模式**,仅用于量化 host 启动开销上限与「未来 PyPTO MoE kernel」可得的收益。 | 70 | > **输出不正确、不是可运行模式**,仅用于量化 host 启动开销上限与「未来 PyPTO MoE kernel」可得的收益。 |
| 71 | +> **切勿把代理数字(如 1.27x / 939 tok/s)当作可部署性能。** 唯一可部署的加速是 PyPTO **1.38x**(真实路由)。 | ||
| 72 | + | ||
| 77 | > **覆盖率前提:** PyPTO 的 JIT kernel 每进程绑定一张 NPU。单进程 | 73 | > **覆盖率前提:** PyPTO 的 JIT kernel 每进程绑定一张 NPU。单进程 |
| 78 | > `ask_Kimi-Linear-48B-A3B.py`(device_map)只覆盖约 **6/20** 层(见脚本顶部注释与 | 74 | > `ask_Kimi-Linear-48B-A3B.py`(device_map)只覆盖约 **6/20** 层(见脚本顶部注释与 |
| 79 | > 运行时 warning);**全量(20/20)覆盖需每卡一进程流水线** —— 仓库内 | 75 | > 运行时 warning);**全量(20/20)覆盖需每卡一进程流水线** —— 仓库内 |
| 80 | > `bench_kimi_multinpu.py`(torchrun)。 | 76 | > `bench_kimi_multinpu.py`(torchrun)。 |
| 81 | 77 | ||
| 82 | -### Full-model prefill (4 NPUs / graph) | 78 | +### 隔离 KDA chunk kernel(单算子实测,Eager vs PyPTO) |
| 83 | 79 | ||
| 84 | -`bench_kimi_multinpu.py`, all 27 layers (20 KDA) / 4 NPUs with one process per card / | 80 | +KDA chunk kernel 本地单算子 bench(prefill,avg-of-20,与 torch golden 对比): |
| 85 | -real checkpoint / bf16 / `--graph` (the static route makes the MoE segment capturable | ||
| 86 | -by NPUGraph): | ||
| 87 | 81 | ||
| 88 | -| Config | Old `kda_chunk` operator (removed) | ling `chunk_kda` operator | **`kda_fused_prefill` (this repo)** | vs old | vs ling | | 82 | +| 算子 | Eager (µs) | PyPTO (µs) | 加速比 | 精度(max\|abs diff\| vs torch golden) | |
| 89 | -|-------|-----------------------------------:|--------------------------:|------------------------------------:|:------:|:-------:| | 83 | +|------|-----------:|-----------:|:------:|----------------------------------------| |
| 90 | -| seq=300, fixed-178 | 313.9 ms | 190.7 ms | **171.4 ms** | **1.83x** | **1.11x** | | 84 | +| `kda_chunk` (prefill, T=256) | 29,649 | **6,982** | **4.25x** | 3e-5(正确) | |
| 91 | -| seq=2048, uniform-256 | 1131.1 ms | 425.6 ms | **385.2 ms** | **2.94x** | **1.11x** | | ||
| 92 | 85 | ||
| 93 | -> The old `kda_chunk` was the standalone PyPTO chunk operator that predated this fused | 86 | +> **输入形状:** q,k,v `[B,T,H,D]` bf16;g `[B,T,H,D]` fp32(逐通道门控);beta `[B,T,H]` fp32; |
| 94 | -> operator (since removed); ling is the `ling_3_0_flash/chunk_kda` PyPTO operator run | 87 | +> B=1, T=256, H=32, D=128;`initial_state=None`;`scale=D**-0.5`。 |
| 95 | -> on the same bench as a reference. All three use the same static route and the same | 88 | +> **kernel 加速比随序列长度增长** —— T=1024 时为 6.18x(chunk 算子规模越大融合收益越高)。 |
| 96 | -> graph configuration, so the numbers isolate the contribution of the KDA kernel itself. | 89 | + |
| 90 | +### 全模型实测(committed bench,可由仓库脚本复现) | ||
| 91 | + | ||
| 92 | +`bench_kimi_multinpu.py`,**全 27 层 / 4 卡每卡一进程 / seq=256 prefill / 真实 checkpoint / bf16** | ||
| 93 | +(1 warmup + 1 measured,真实路由、输出正确,`/data/public_models/Kimi-Linear-48B-A3B-Instruct`): | ||
| 94 | + | ||
| 95 | +| 模式 | prefill wall (ms) | 吞吐 (tok/s) | KDA 覆盖 | | ||
| 96 | +|------|-------------------|-------------|----------| | ||
| 97 | +| baseline(torch chunk) | 1844.7 | 138.8 | 0 pypto / 0 fallback | | ||
| 98 | +| **pypto** | **1335.4** | **191.7** | **20/20 层走 PyPTO,0 fallback** | | ||
| 99 | +| **加速比** | **1.38x (wall)** | **1.38x** | | | ||
| 100 | + | ||
| 101 | +> **计时口径:** wall (ms) 取自每卡一进程流水线的最慢 rank(1 warmup + 1 measured,measured iter 前 | ||
| 102 | +> `synchronize()+barrier()`);吞吐 tok/s = seq(256) ÷ wall(s)。 | ||
| 103 | + | ||
| 104 | +→ 每卡一进程下 **0 fallback / 全 20/20 KDA 覆盖**(真实权重,非 smoke)。这是**唯一可部署**的加速: | ||
| 105 | +真实路由、输出正确。**1.38x** 含流水线 bubble + 同步开销;隔离 KDA chunk kernel 单算子为 4.25x(见上), | ||
| 106 | +端到端被 host-bound 的 MoE 逐专家分发循环摊薄。 | ||
| 97 | 107 | ||
| 98 | **复现:** | 108 | **复现:** |
| 99 | -- seq=300: `MODEL_PATH=<weights> torchrun --nproc_per_node=4 bench_kimi_multinpu.py --mode prefill --pypto --graph --route fixed --seq 300 --report-file out.json` | 109 | +- 全模型 20/20 + 上表(每卡一进程,需 checkpoint): |
| 100 | -- seq=2048: 同上,`--route uniform --seq 2048` | 110 | + `MODEL_PATH=<weights> torchrun --nproc_per_node=4 bench_kimi_multinpu.py --pypto --seq 256 --report-file out.json`(baseline 去掉 `--pypto` 再跑一次)。 |
| 101 | - harness smoke(随机权重,无需 checkpoint): | 111 | - harness smoke(随机权重,无需 checkpoint): |
| 102 | `torchrun --nproc_per_node=2 bench_kimi_multinpu.py --random-weights --layers 4 --seq 80 --iters 2 --pypto` | 112 | `torchrun --nproc_per_node=2 bench_kimi_multinpu.py --random-weights --layers 4 --seq 80 --iters 2 --pypto` |
| 103 | - 单进程快速检查(~6/20,*不会*得到上面的全覆盖数字): | 113 | - 单进程快速检查(~6/20,*不会*得到上面的全覆盖数字): |
| 104 | `python3 scripts/ask_Kimi-Linear-48B-A3B.py --model-path <weights> --num_npus 4 --use_pypto` | 114 | `python3 scripts/ask_Kimi-Linear-48B-A3B.py --model-path <weights> --num_npus 4 --use_pypto` |
| 105 | -- 算子级 msprof:`MODEL_PATH=<weights> bash prof_Kimi-Linear-48B-A3B.sh` | 115 | +- 算子级 msprof:`MODEL_PATH=<weights> bash prof_Kimi-Linear-48B-A3B.sh`。 |
| 106 | 116 | ||
| 107 | -### Full-model decode (4 NPUs / real routing) | 117 | +--- |
| 108 | 118 | ||
| 109 | -| Mode | Baseline (torch) | Fused (PyPTO) | gain | | 119 | +### ⚠️ 图捕获吞吐代理(static-route graph-capture proxy — 非可部署 / NOT deployable) |
| 110 | -|------|-----------------:|--------------:|:----:| | ||
| 111 | -| eager | 88.58 ms/token | **73.30 ms/token** | **−17%** | | ||
| 112 | -| graph | 29.80 ms/token | **16.38 ms/token** | **−45%** | | ||
| 113 | 120 | ||
| 114 | -**Reproduce:** `MODEL_PATH=<weights> torchrun --nproc_per_node=4 bench_kimi_multinpu.py --mode decode --pypto [--graph] --report-file decode.json` | 121 | +> **本节以下所有数字都不是可部署性能**(静态假路由、输出不正确)。可部署数字见上方『全模型实测』(PyPTO 1.38x)。 |
| 122 | + | ||
| 123 | +> ⚠️ **静态路由吞吐代理:** 下表 graph 各格用**固定静态路由**(`--route fixed --active 178`)替换真实 MoE | ||
| 124 | +> 路由,以消除 `moe_infer` 的 host 同步(`.argsort()`/`.bincount()`/`.cpu().numpy()`/ | ||
| 125 | +> 数据依赖的逐专家循环),使 per-die 计算段可被 `torch.npu.NPUGraph` 捕获。真实 router 的 AICPU | ||
| 126 | +> argsort/bincount **无法**被捕获进 NPU graph,故 MoE +graph **必须**用固定假路由。**logits 与真实路由 | ||
| 127 | +> 不一致、输出值不正确、不可用于真实推理**(shape-faithful 但 | ||
| 128 | +> value-infidel 的**吞吐代理**)。真实可部署加速见上方 = **PyPTO 1.38x**(真实路由)。 | ||
| 129 | + | ||
| 130 | +4 卡 / seq=256 / 真实权重 / active=178 experts / 1 warmup + 1 measured pipeline wall(最慢 rank): | ||
| 131 | + | ||
| 132 | +| 模式 | wall (ms) | 吞吐 (tok/s) | 备注 | | ||
| 133 | +|------|-----------|-------------|------| | ||
| 134 | +| vec + graph(eager + graph,静态假路由) | 345.5 | 741 | 吞吐代理(不可部署 / 输出不正确 / 静态假路由)| | ||
| 135 | +| **pypto + graph(静态假路由)** | **272.7** | **939** | 吞吐代理(不可部署 / 输出不正确 / 静态假路由)| | ||
| 136 | +| **加速比(pypto+graph vs vec+graph)** | **1.27x** | **1.27x** | 仅代理,非可部署 | | ||
| 137 | + | ||
| 138 | +> 吞吐 tok/s = seq(256) ÷ wall(s)。 | ||
| 139 | + | ||
| 140 | +**说明:** PyPTO 对 KDA 的净贡献(同静态路由、同 graph):vec+graph 345.5ms → pypto+graph 272.7ms = | ||
| 141 | +**1.27x**。**与 qwen 不同**:qwen 经 PyPTO 后整网 compute-bound、图捕获冗余;kimi 27 层流水线即使用 | ||
| 142 | +PyPTO-KDA 仍 **launch/dispatch-bound** —— **host-bound 的 MoE 逐专家分发循环**仍是瓶颈,图捕获将其折叠。 | ||
| 143 | +故图捕获在 kimi 与 PyPTO 互补,但**需静态假路由、输出不正确、不可部署**。 | ||
| 144 | + | ||
| 145 | +**复现:** `MODEL_PATH=<weights> torchrun --nproc_per_node=4 bench_kimi_multinpu.py [--pypto] --graph | ||
| 146 | +--route fixed --active 178 --seq 256`(`--graph` 开图捕获;`--count-experts` 量测自然激活专家数)。 | ||
| 115 | 147 | ||
| 116 | ## 归档映射 | 148 | ## 归档映射 |
| 117 | 149 | ||
| @@ -121,7 +153,7 @@ by NPUGraph): | |||
| 121 | |---|---| | 153 | |---|---| |
| 122 | | `scripts/ask_*.py`, `bench_*.sh`, `prof_*.sh`, `sample_inputs.txt`, `README.md` | `modeling/transformers/kimi_linear_48b_a3b/` | | 154 | | `scripts/ask_*.py`, `bench_*.sh`, `prof_*.sh`, `sample_inputs.txt`, `README.md` | `modeling/transformers/kimi_linear_48b_a3b/` | |
| 123 | | `config.json` | `src/pypto_gym/transformers/kimi_linear_48b_a3b/config.json` | | 155 | | `config.json` | `src/pypto_gym/transformers/kimi_linear_48b_a3b/config.json` | |
| 124 | -| `modeling_kimi.py`, `configuration_kimi.py`, `kimi_fla_compat.py`, `kda_decode_graph.py`(trust_remote_code 打补丁版) | `src/pypto_gym/transformers/kimi_linear_48b_a3b/` | | 156 | +| `modeling_kimi.py`, `configuration_kimi.py`, `kimi_fla_compat.py`(trust_remote_code 打补丁版) | `src/pypto_gym/transformers/kimi_linear_48b_a3b/` | |
| 125 | | `kimi_linear_48b_a3b_pto_kernels/kda/*_impl.py`, `_device_guard.py`, `__init__.py`, `README.md` | `ops/pypto_tensor/kimi_linear_48b_a3b/` | | 157 | | `kimi_linear_48b_a3b_pto_kernels/kda/*_impl.py`, `_device_guard.py`, `__init__.py`, `README.md` | `ops/pypto_tensor/kimi_linear_48b_a3b/` | |
| 126 | | `kimi_linear_48b_a3b_pto_kernels/kda/{*_golden.py, test/*}` | `tests/ops/kimi_linear_48b_a3b/` | | 158 | | `kimi_linear_48b_a3b_pto_kernels/kda/{*_golden.py, test/*}` | `tests/ops/kimi_linear_48b_a3b/` | |
| 127 | 159 | ||
| @@ -75,7 +75,6 @@ _P = _HERE | |||
| 75 | while _P != "/" and not os.path.isdir(os.path.join(_P, "src", "pypto_gym")): | 75 | while _P != "/" and not os.path.isdir(os.path.join(_P, "src", "pypto_gym")): |
| 76 | _P = os.path.dirname(_P) | 76 | _P = os.path.dirname(_P) |
| 77 | _REPO_ROOT = _P | 77 | _REPO_ROOT = _P |
| 78 | -sys.path.insert(0, _REPO_ROOT) # top-level ops package (kernels) lives at the repo root | ||
| 79 | sys.path.insert(0, os.path.join(_REPO_ROOT, "src")) | 78 | sys.path.insert(0, os.path.join(_REPO_ROOT, "src")) |
| 80 | sys.path.insert(0, os.path.join(_REPO_ROOT, "src", "pypto_gym", "transformers", "kimi_linear_48b_a3b")) | 79 | sys.path.insert(0, os.path.join(_REPO_ROOT, "src", "pypto_gym", "transformers", "kimi_linear_48b_a3b")) |
| 81 | 80 | ||
| @@ -85,7 +84,7 @@ _REPO_CONFIG = os.path.join( | |||
| 85 | MODEL_PATH = os.environ.get("MODEL_PATH", "/data/models/Kimi-Linear-48B-A3B-Instruct") | 84 | MODEL_PATH = os.environ.get("MODEL_PATH", "/data/models/Kimi-Linear-48B-A3B-Instruct") |
| 86 | 85 | ||
| 87 | # per-process KDA coverage counter (incremented by the wrapped kernel wrappers) | 86 | # per-process KDA coverage counter (incremented by the wrapped kernel wrappers) |
| 88 | -_COVER = {"pypto_fused_prefill": 0, "fallback": 0} | 87 | +_COVER = {"pypto_chunk": 0, "fallback": 0, "pypto_graph_chunk": 0} |
| 89 | 88 | ||
| 90 | 89 | ||
| 91 | @dataclass | 90 | @dataclass |
| @@ -232,26 +231,25 @@ def _build_model(ctx, args): | |||
| 232 | 231 | ||
| 233 | 232 | ||
| 234 | def _wire_pypto(local_rank): | 233 | def _wire_pypto(local_rank): |
| 235 | - """Register the committed kernels package under the name modeling_kimi expects, enable | 234 | + """Register the committed kernels package under the name modeling_kimi expects, |
| 236 | - USE_PTO_KDA, and wrap the fused prefill operator to count pypto-vs-fallback. Binds | 235 | + enable USE_PTO_KDA, and wrap the chunk wrapper to count pypto-vs-fallback. Binds |
| 237 | PyPTO to THIS rank's NPU (TILE_FWK_DEVICE_ID was set to local_rank before import).""" | 236 | PyPTO to THIS rank's NPU (TILE_FWK_DEVICE_ID was set to local_rank before import).""" |
| 238 | import ops.pypto_tensor.kimi_linear_48b_a3b as pto | 237 | import ops.pypto_tensor.kimi_linear_48b_a3b as pto |
| 239 | sys.modules["kimi_linear_48b_a3b_pto_kernels"] = pto | 238 | sys.modules["kimi_linear_48b_a3b_pto_kernels"] = pto |
| 240 | - _orig = pto.kda_fused_prefill | 239 | + _orig = pto.kda_chunk_wrapper |
| 241 | 240 | ||
| 242 | - def counting_fused(*a, **kw): | 241 | + def counting_chunk(*a, **kw): |
| 243 | try: | 242 | try: |
| 244 | r = _orig(*a, **kw) | 243 | r = _orig(*a, **kw) |
| 245 | - _COVER["pypto_fused_prefill"] += 1 | 244 | + _COVER["pypto_chunk"] += 1 |
| 246 | return r | 245 | return r |
| 247 | except NotImplementedError: | 246 | except NotImplementedError: |
| 248 | _COVER["fallback"] += 1 | 247 | _COVER["fallback"] += 1 |
| 249 | raise | 248 | raise |
| 250 | 249 | ||
| 251 | - pto.kda_fused_prefill = counting_fused | 250 | + pto.kda_chunk_wrapper = counting_chunk |
| 252 | pto.USE_PTO_KDA = True | 251 | pto.USE_PTO_KDA = True |
| 253 | - log("PyPTO wired: USE_PTO_KDA=True (fused prefill + fused decode), " | 252 | + log("PyPTO wired: USE_PTO_KDA=True, kernel bound to this rank's NPU") |
| 254 | - "kernel bound to this rank's NPU") | ||
| 255 | 253 | ||
| 256 | 254 | ||
| 257 | def _mla_mask(t_step, kv_len, dev): | 255 | def _mla_mask(t_step, kv_len, dev): |
| @@ -441,9 +439,30 @@ def _make_graph_stage_run(ctx, args): | |||
| 441 | captured graph. HCCL recv/send stay OUTSIDE this (in _prefill_once).""" | 439 | captured graph. HCCL recv/send stay OUTSIDE this (in _prefill_once).""" |
| 442 | _install_static_route(ctx, args, tag="graph") | 440 | _install_static_route(ctx, args, tag="graph") |
| 443 | 441 | ||
| 444 | - # PyPTO + graph: the fused prefill path is capture-clean (stream-ordered, | 442 | + # PyPTO + graph: switch the captured KDA chunk branch to the DIRECT registered-op |
| 445 | - # no separate graph entrypoint), so nothing to flip here — the counting | 443 | + # call (kda_chunk_pypto), bypassing _dispatch_kda's non-capturable try/except. Off |
| 446 | - # wrapper from _wire_pypto also covers the warmup/capture invocations. | 444 | + # for eager-KDA graphs. The flag stays on through warmup + capture (the captured |
| 445 | + # graph then bakes in the registered op); replay just plays the recorded graph. | ||
| 446 | + if args.pypto: | ||
| 447 | + pto = sys.modules.get("kimi_linear_48b_a3b_pto_kernels") | ||
| 448 | + if pto is None: | ||
| 449 | + raise RuntimeError("[graph] --pypto set but kernels module not wired") | ||
| 450 | + pto.USE_PTO_KDA_GRAPH = True | ||
| 451 | + # Executed-proof probe: the graph branch calls kda_chunk_pypto DIRECTLY (not the | ||
| 452 | + # counted kda_chunk_wrapper), so wrap that exact symbol to count invocations during | ||
| 453 | + # the warmup AND capture forwards (replay bypasses python, so it counts warmup+capture | ||
| 454 | + # invocations, not replays). The capture pass is one of those invocations, so a non-zero | ||
| 455 | + # count proves the PyPTO KDA op was exercised during capture and recorded into the graph. | ||
| 456 | + if not getattr(pto, "kda_pypto_counted", False): | ||
| 457 | + _orig_pypto = pto.kda_chunk_pypto | ||
| 458 | + | ||
| 459 | + def _counting_pypto(*a, __orig=_orig_pypto, **kw): | ||
| 460 | + _COVER["pypto_graph_chunk"] += 1 | ||
| 461 | + return __orig(*a, **kw) | ||
| 462 | + | ||
| 463 | + pto.kda_chunk_pypto = _counting_pypto | ||
| 464 | + pto.kda_pypto_counted = True | ||
| 465 | + log("[graph] USE_PTO_KDA_GRAPH=True — captured KDA chunk -> kda_chunk_pypto (direct op)") | ||
| 447 | 466 | ||
| 448 | stage_forward = _make_stage_forward(ctx, args.seq) | 467 | stage_forward = _make_stage_forward(ctx, args.seq) |
| 449 | hin = torch.zeros(1, args.seq, ctx.cfg.hidden_size, dtype=torch.bfloat16, device=ctx.dev) | 468 | hin = torch.zeros(1, args.seq, ctx.cfg.hidden_size, dtype=torch.bfloat16, device=ctx.dev) |
| @@ -647,8 +666,9 @@ def _emit_report(ctx, args, result): | |||
| 647 | if ctx.rank != 0: | 666 | if ctx.rank != 0: |
| 648 | return | 667 | return |
| 649 | rows = [json.loads(g) for g in gathered] | 668 | rows = [json.loads(g) for g in gathered] |
| 650 | - total_fused = sum(r["coverage"].get("pypto_fused_prefill", 0) for r in rows) | 669 | + total_chunk = sum(r["coverage"]["pypto_chunk"] for r in rows) |
| 651 | total_fb = sum(r["coverage"]["fallback"] for r in rows) | 670 | total_fb = sum(r["coverage"]["fallback"] for r in rows) |
| 671 | + total_graph_chunk = sum(r["coverage"].get("pypto_graph_chunk", 0) for r in rows) | ||
| 652 | slowest = max(r["wall_ms"] for r in rows) | 672 | slowest = max(r["wall_ms"] for r in rows) |
| 653 | # best-of-N pipeline wall = slowest stage's best iteration (pipeline gated by the | 673 | # best-of-N pipeline wall = slowest stage's best iteration (pipeline gated by the |
| 654 | # slowest stage); report the max over ranks of each rank's best-of-N. | 674 | # slowest stage); report the max over ranks of each rank's best-of-N. |
| @@ -668,7 +688,9 @@ def _emit_report(ctx, args, result): | |||
| 668 | "prefill_wall_ms_pipeline": slowest, | 688 | "prefill_wall_ms_pipeline": slowest, |
| 669 | "prefill_wall_ms_pipeline_best": slowest_best, | 689 | "prefill_wall_ms_pipeline_best": slowest_best, |
| 670 | "npu_compute_us_total": total_compute_us, | 690 | "npu_compute_us_total": total_compute_us, |
| 671 | - "kda_pypto_fused_prefill_total": total_fused, "kda_fallback_total": total_fb, | 691 | + "kda_pypto_chunk_total": total_chunk, "kda_fallback_total": total_fb, |
| 692 | + # executed-proof: warmup+capture PyPTO KDA invocations (non-zero => op recorded into the graph) | ||
| 693 | + "kda_pypto_graph_chunk_total": total_graph_chunk, | ||
| 672 | "per_rank": rows, | 694 | "per_rank": rows, |
| 673 | } | 695 | } |
| 674 | if static: # any fixed/uniform fake route (graph OR eager-static) is value-infidel | 696 | if static: # any fixed/uniform fake route (graph OR eager-static) is value-infidel |
| @@ -9,8 +9,10 @@ describing the contract. | |||
| 9 | 9 | ||
| 10 | | Operator | Subdirectory | Status | | 10 | | Operator | Subdirectory | Status | |
| 11 | |----------|--------------|--------| | 11 | |----------|--------------|--------| |
| 12 | -| `kda_fused_prefill` (Kimi Delta Attention, prefill) | [`kda/`](kda/) | Available | | 12 | +| `kda_chunk` (Kimi Delta Attention, prefill/chunk) | [`kda/`](kda/) | Available | |
| 13 | -| `kda_fused_decode` (Kimi Delta Attention, decode) | [`kda/`](kda/) | Available | | 13 | + |
| 14 | +PyPTO covers the prefill (`mode == 'chunk'`) path only; decode runs the upstream | ||
| 15 | +torch recurrent path. | ||
| 14 | 16 | ||
| 15 | ## Common shape constraints | 17 | ## Common shape constraints |
| 16 | 18 | ||
| @@ -21,15 +23,18 @@ Kimi-Linear-48B-A3B's KDA (`linear_attn_config`) has: | |||
| 21 | | `D` | Per-head dimension (`head_k_dim == head_v_dim`) | 128 | | 23 | | `D` | Per-head dimension (`head_k_dim == head_v_dim`) | 128 | |
| 22 | | `H` | KDA head count (`num_heads == num_k_heads`) | 32 | | 24 | | `H` | KDA head count (`num_heads == num_k_heads`) | 32 | |
| 23 | 25 | ||
| 24 | -The kernels keep the per-channel log-gate (`g in [-5, 0]`) numerically stable | 26 | +The chunk kernel processes each chunk in subchunks of 16 steps for fp32 numerical |
| 25 | -in fp32. The wrappers raise `NotImplementedError` outside the supported | 27 | +stability of the per-channel log-gate (`g in [-5, 0]`). Wrappers mirror the upstream |
| 26 | -envelope (e.g. tensors off the bound NPU) and the modeling layer falls back to | 28 | +`fla.ops.kda.chunk_kda` signature and raise `NotImplementedError` outside the |
| 27 | -the reference torch path. | 29 | +supported envelope (e.g. tensors off the bound NPU). |
| 28 | 30 | ||
| 29 | ## Integration | 31 | ## Integration |
| 30 | 32 | ||
| 31 | -The kernel is wired into the model through the | 33 | +The kernel is wired into the model through the |
| 32 | -[modeling_kimi.py](../../../transformers/kimi_linear_48b_a3b/modeling_kimi.py). | 34 | +[modeling_kimi.py](../../../transformers/kimi_linear_48b_a3b/modeling_kimi.py) |
| 33 | -The ops package is injected as sys.modules["kimi_linear_48b_a3b_pto_kernels"], | 35 | +dispatch hook: the ops package is injected as |
| 34 | -exposing USE_PTO_KDA (opt-in switch, default off) together with the PyPTO prefill | 36 | +`sys.modules["kimi_linear_48b_a3b_pto_kernels"]`, exposing `USE_PTO_KDA` (opt-in |
| 35 | -and decode entry points. | 37 | +switch, default off) and `kda_chunk_wrapper`; decode uses the unchanged upstream |
| 38 | +`fused_recurrent_kda`. For torch.compile / torchair ACLGraph capture, | ||
| 39 | +`kda_chunk_pypto` is registered as `pypto::kda_chunk_kimi` (Meta + NPU) and is | ||
| 40 | +selected under `USE_PTO_KDA_GRAPH`. | ||
| @@ -10,26 +10,26 @@ | |||
| 10 | Kimi-Linear-48B-A3B PyPTO 融合算子库 | 10 | Kimi-Linear-48B-A3B PyPTO 融合算子库 |
| 11 | 11 | ||
| 12 | 实际集成的算子: | 12 | 实际集成的算子: |
| 13 | -- KDA (Kimi Delta Attention) fused prefill: uses `kda_fused_prefill` for the | 13 | +- KDA (Kimi Delta Attention) chunk 融合版: 融合 chunk/subchunk 级别的 KDA kernel, |
| 14 | - PyPTO prefill path. | 14 | + 用于 prefill 阶段替代 FLA/torch 原始实现。 |
| 15 | 15 | ||
| 16 | 融合范围: | 16 | 融合范围: |
| 17 | -- kda_fused_prefill covers the whole per-layer KDA prefill attention subgraph; | 17 | +- chunk_kda 内部的 l2norm + cumulative-gate + pairwise decay + triangular-inverse |
| 18 | - see kda/README.md for details. | 18 | + + recurrent state carry 等子算子的融合(subchunk=16 数值稳定)。 |
| 19 | 19 | ||
| 20 | 应用场景: | 20 | 应用场景: |
| 21 | - Kimi-Linear-48B-A3B-Instruct 模型的 prefill 推理加速,通过 sys.modules 注入 | 21 | - Kimi-Linear-48B-A3B-Instruct 模型的 prefill 推理加速,通过 sys.modules 注入 |
| 22 | kimi_linear_48b_a3b_pto_kernels 模块。 | 22 | kimi_linear_48b_a3b_pto_kernels 模块。 |
| 23 | 23 | ||
| 24 | 注入方式: | 24 | 注入方式: |
| 25 | -- sys.modules["kimi_linear_48b_a3b_pto_kernels"] 提供 USE_PTO_KDA 开关和 kda_fused_prefill 函数。 | 25 | +- sys.modules["kimi_linear_48b_a3b_pto_kernels"] 提供 USE_PTO_KDA 开关和 kda_chunk_wrapper 函数。 |
| 26 | 26 | ||
| 27 | ACLGraph / torch.compile: | 27 | ACLGraph / torch.compile: |
| 28 | -- Graph capture uses the same `kda_fused_prefill` path; there is no separate | 28 | +- kda_chunk_pypto 经 torch.library 注册为 pypto::kda_chunk_kimi |
| 29 | - graph-only operator. | 29 | + (Meta + NPU),可被 torchair/aclgraph 图捕获;eager 默认路径仍走 *_wrapper,互不影响。 |
| 30 | """ | 30 | """ |
| 31 | 31 | ||
| 32 | -from .kda.kda_fused_prefill_impl import kda_fused_prefill | 32 | +from .kda.kda_chunk_impl import kda_chunk_wrapper, kda_chunk_pypto |
| 33 | 33 | ||
| 34 | # NOTE(multi-NPU coverage): PyPTO binds a JIT kernel to ONE NPU per process. With | 34 | # NOTE(multi-NPU coverage): PyPTO binds a JIT kernel to ONE NPU per process. With |
| 35 | # the wrappers enabled on a model sharded across NPUs (single-process device_map), | 35 | # the wrappers enabled on a model sharded across NPUs (single-process device_map), |
| @@ -39,7 +39,18 @@ from .kda.kda_fused_prefill_impl import kda_fused_prefill | |||
| 39 | # NPU (pipeline / tensor parallel). See kda/README.md. | 39 | # NPU (pipeline / tensor parallel). See kda/README.md. |
| 40 | USE_PTO_KDA = False | 40 | USE_PTO_KDA = False |
| 41 | 41 | ||
| 42 | +# NPU-graph capture flag (off by default — preserves existing behavior). When True, | ||
| 43 | +# KimiDeltaAttention.forward's chunk branch calls ``kda_chunk_pypto`` (the registered | ||
| 44 | +# torch.ops.pypto.kda_chunk_kimi custom op) DIRECTLY, bypassing the _dispatch_kda | ||
| 45 | +# try/except NotImplementedError fallback. The try/except is NOT capturable by an NPU | ||
| 46 | +# graph (control flow on a host-raised exception), so the graph path must call the | ||
| 47 | +# registered op with no host-side branch. Only meaningful under graph capture, where | ||
| 48 | +# the bench guarantees cache_params=None -> initial_state=None, cu_seqlens=None. | ||
| 49 | +USE_PTO_KDA_GRAPH = False | ||
| 50 | + | ||
| 42 | __all__ = [ | 51 | __all__ = [ |
| 43 | 'USE_PTO_KDA', | 52 | 'USE_PTO_KDA', |
| 44 | - 'kda_fused_prefill', | 53 | + 'USE_PTO_KDA_GRAPH', |
| 54 | + 'kda_chunk_wrapper', | ||
| 55 | + 'kda_chunk_pypto', | ||
| 45 | ] | 56 | ] |
| @@ -1,4 +1,4 @@ | |||
| 1 | -# KDA — Kimi Delta Attention (fused_prefill + fused_decode) PyPTO kernels | 1 | +# KDA — Kimi Delta Attention (chunk + fused_decode) PyPTO kernels |
| 2 | 2 | ||
| 3 | Fused PyPTO Ascend-NPU implementation of the **Kimi Delta Attention (KDA)** linear-attention | 3 | Fused PyPTO Ascend-NPU implementation of the **Kimi Delta Attention (KDA)** linear-attention |
| 4 | core used by `KimiDeltaAttention` in Kimi-Linear-48B-A3B-Instruct. KDA is a refined gated | 4 | core used by `KimiDeltaAttention` in Kimi-Linear-48B-A3B-Instruct. KDA is a refined gated |
| @@ -8,26 +8,43 @@ Two kernels: | |||
| 8 | 8 | ||
| 9 | | File | Op | Path | Default | | 9 | | File | Op | Path | Default | |
| 10 | |------|----|------|---------| | 10 | |------|----|------|---------| |
| 11 | -| `kda_fused_prefill_impl.py` | `kda_fused_prefill` | prefill (`mode == 'chunk'`) | dispatched when `USE_PTO_KDA` | | 11 | +| `kda_chunk_impl.py` | `kda_chunk_wrapper` | prefill (`mode == 'chunk'`) | dispatched when `USE_PTO_KDA` | |
| 12 | | `kda_fused_decode_impl.py` | `kda_fused_decode_step` | decode | called from `kda_decode_graph.py` | | 12 | | `kda_fused_decode_impl.py` | `kda_fused_decode_step` | decode | called from `kda_decode_graph.py` | |
| 13 | 13 | ||
| 14 | -Both wrappers are `@allow_in_graph` and stream-ordered (NPU-graph capturable). The | 14 | +The wrapper mirrors the upstream `fla.ops.kda.chunk_kda` signature and is `@allow_in_graph` |
| 15 | -reference FLA/torch path (`chunk_kda` / `fused_recurrent_kda` via `kimi_fla_compat`) is | 15 | +(torch.compile / aclgraph capture compatible). |
| 16 | -preserved as the fallback: out-of-envelope shapes raise `NotImplementedError` and the | ||
| 17 | -modeling layer falls back. | ||
| 18 | 16 | ||
| 19 | -## Fused prefill (`kda_fused_prefill_impl.py`) | 17 | +## Math (per (b,h), state `S = [V,K]`, state_v_first) |
| 20 | 18 | ||
| 21 | -The single PyPTO prefill operator: one fused PyPTO kernel covers the whole | 19 | +``` |
| 22 | -per-layer KDA attention core between the projections and `o_proj` — | 20 | +q,k L2-normalized: x / (sqrt(sum(x*x)) + 1e-6) |
| 23 | -`conv1d(k=4)+silu → l2norm → gate transform → beta sigmoid → WY-chunked gated | 21 | +g = log-space gate (lower_bound(-5) * sigmoid(...)), alpha = exp(g) |
| 24 | -delta rule → o_norm (RMSNorm × sigmoid gate) → bf16 out`. | 22 | +S' = S * alpha # Diag(alpha) decay on the K axis |
| 23 | +pred = S' @ k # [V] | ||
| 24 | +delta = beta * (v - pred) # [V] | ||
| 25 | +S_new = S' + delta ⊗ k # outer product -> [V,K] | ||
| 26 | +o = scale * (S_new @ q) # [V], scale = K**-0.5 | ||
| 27 | +``` | ||
| 25 | 28 | ||
| 26 | -## Numerical stability | 29 | +The **chunk** kernel runs this recurrence in blocks: cumulative gate `G = cumsum(g)`, |
| 30 | +pairwise decay `exp(G_i - G_j)` for `j <= i`, triangular inverse `(I + A_kk)^-1` (via | ||
| 31 | +nilpotent doubling), and inter-/intra-chunk state carry. See the `kda_chunk_impl.py` | ||
| 32 | +module docstring for the per-subchunk equations. | ||
| 27 | 33 | ||
| 28 | -A naive exponential factorization can overflow in fp32 for long decay ranges. | 34 | +### Numerical stability — subchunk = 16 |
| 29 | -The fused kernel uses 16-row pivot bands to keep intra-chunk decay exponents within a safe range, | 35 | +The real KDA gate accumulates to `G ≈ -640` over a 128-step chunk; factorizing the |
| 30 | -while cross-chunk decay remains non-positive and is safe by construction. | 36 | +intra-chunk decay as `q·exp(G)` / `k·exp(-G)` overflows fp32 (`exp(+640) = inf → NaN`). |
| 37 | +The chunk kernel processes each chunk in **subchunks of `SUB = 16` steps**, carrying the | ||
| 38 | +recurrent state across subchunks. Within a 16-step subchunk the cumulative-gate range is at | ||
| 39 | +most `16*5 = 80`, so `exp(80) ≈ 5.5e34 < 3.4e38` stays in fp32 range and never overflows. | ||
| 40 | +Mathematically identical to `chunk_size = 16`. | ||
| 41 | + | ||
| 42 | +### Kernel dtype — FP32 (intentional, ≠ model bf16) | ||
| 43 | +The kernel computes in **FP32**, not the model's native bfloat16. This is a deliberate | ||
| 44 | +stability choice, not an oversight: the per-channel log-gate's `exp(±G)` factorization | ||
| 45 | +needs FP32 headroom (see above), and bf16 (~3 mantissa bits) would lose the delta-rule | ||
| 46 | +state. The q/k/v/g casts are done **host-side** (`.float()`) so there is no dependency on | ||
| 47 | +NPU-side bf16↔fp32 `aclnnCast`; the output is cast back to the input dtype by the wrapper. | ||
| 31 | 48 | ||
| 32 | ## Shapes / constraints | 49 | ## Shapes / constraints |
| 33 | 50 | ||
| @@ -36,14 +53,14 @@ while cross-chunk decay remains non-positive and is safe by construction. | |||
| 36 | | heads `H` | 32 (validated 4 / 32) | | 53 | | heads `H` | 32 (validated 4 / 32) | |
| 37 | | head_k_dim `K` | 128 | | 54 | | head_k_dim `K` | 128 | |
| 38 | | head_v_dim `V` | 128 | | 55 | | head_v_dim `V` | 128 | |
| 39 | -| WY chunk | 128 tokens (static) | | 56 | +| chunk subchunk `SUB` | 16 | |
| 40 | -| q/k/v | bf16 `[B,T,H,128]` pre-conv projections (host packs to fp32) | | 57 | +| `use_qk_l2norm_in_kernel` | `True` (L2 norm done on host before packing) | |
| 41 | -| g_raw / g_gate / b_raw | projection outputs, any float dtype (bf16 in the model) | | 58 | +| dtype | q/k/v/g bf16/fp16/fp32 in, fp32 state, out cast back to input dtype | |
| 42 | -| state dtype | fp32 `[B,H,V,K]` | | 59 | + |
| 43 | -| output dtype | bf16 in-kernel; wrapper casts back to the input dtype if needed | | 60 | +FLA layout: `q,k,g [B,T,H,128]`, `v [B,T,H,128]`, `beta [B,T,H]`, `state [B,H,V,K]` fp32. |
| 44 | - | 61 | +Out-of-envelope shapes (`K != 128`, `V != 128`, |
| 45 | -Unsupported shapes or execution modes raise `NotImplementedError`, and | 62 | +`use_qk_l2norm_in_kernel=False`) raise `NotImplementedError`; the modeling layer then falls |
| 46 | -`_try_kda_fused_prefill` falls back to the reference torch prefill path. | 63 | +back to the torch chunk/recurrent path. |
| 47 | 64 | ||
| 48 | **Single-NPU binding.** PyPTO binds a JIT kernel to one NPU per process (the device of the | 65 | **Single-NPU binding.** PyPTO binds a JIT kernel to one NPU per process (the device of the |
| 49 | first launch). For a model sharded across NPUs via `device_map`, the wrapper raises | 66 | first launch). For a model sharded across NPUs via `device_map`, the wrapper raises |
| @@ -53,68 +70,90 @@ coverage requires one process per NPU (pipeline/tensor parallel). | |||
| 53 | 70 | ||
| 54 | ## Accuracy | 71 | ## Accuracy |
| 55 | 72 | ||
| 56 | -Checked against the torch composition the operator fuses (conv1d+silu → gate → | 73 | +Checked against the `_naive_recurrent_kda` golden (and the `vec_chunk_kda` torch chunked |
| 57 | -beta → `_naive_recurrent_kda` core → o_norm) by | 74 | +op) by the tests in `tests/ops/kimi_linear_48b_a3b/`, on Ascend 910B3: |
| 58 | -`tests/ops/kimi_linear_48b_a3b/test_kda_fused_prefill.py`, on Ascend 910: | 75 | + |
| 59 | - | 76 | +- chunk: `B ∈ {1,2}`, `H ∈ {4,32}`, `T ∈ {64,128,300,512,1000}`, realistic gate `g=-5·rand` |
| 60 | -- `B ∈ {1,2}`, `H ∈ {4,32}`, `T ∈ {128, 300, 512}` — exact chunk, non-%128 | 77 | + AND worst-case `g=-5·ones` (cumulative `≈ -640`) — **max abs error ~6.1e-5** (bf16, |
| 61 | - tail and multi-chunk state carry; the remaining cases cover H=32, B>1, | 78 | + vs the fp32 naive-recurrent golden; well within the 6e-3 test tolerance). |
| 62 | - worst-case gate (`g ≈ -5` everywhere), no-initial-state and the | 79 | + |
| 63 | - continuing-prefill conv-cache path. All compared against an **all-fp32 | 80 | +Test inputs match the real model's dtypes (probed from `KimiDeltaAttention.forward`, see |
| 64 | - golden** (fp32 conv+silu, exact naive recurrence, fp32 o_norm): | 81 | +`tests/.../test_cases.json` `probe`): q/k/v bf16, **g and beta fp32** (`fused_kda_gate` / |
| 65 | - dO ≤ 1e-2 (≈1 bf16 ulp — the single final round-to-bf16, i.e. the | 82 | +`.float().sigmoid()`), `initial_state` fp32. |
| 66 | - format floor), dS ≤ 1e-5, conv-state **bit-exact** (it seeds decode). | ||
| 67 | - | ||
| 68 | -Test inputs match the real model's dtypes: q/k/v bf16 (pre-conv projections), | ||
| 69 | -g_raw/g_gate/b_raw bf16 (projection outputs), dt_bias/A_log/o_norm.weight fp32 | ||
| 70 | -parameters, initial_state fp32. | ||
| 71 | 83 | ||
| 72 | > **验证范围说明(scenario-B 限制):** 被替换的原算子是 `fla.ops.kda.{chunk_kda, | 84 | > **验证范围说明(scenario-B 限制):** 被替换的原算子是 `fla.ops.kda.{chunk_kda, |
| 73 | > fused_recurrent_kda}`(Triton/CUDA 实现)。`fla`/Triton 在 Ascend 环境**不可用** | 85 | > fused_recurrent_kda}`(Triton/CUDA 实现)。`fla`/Triton 在 Ascend 环境**不可用** |
| 74 | > (`modeling_kimi.py` 的 `ImportError` 分支即据此回退到 `kimi_fla_compat` 的纯 torch | 86 | > (`modeling_kimi.py` 的 `ImportError` 分支即据此回退到 `kimi_fla_compat` 的纯 torch |
| 75 | > 实现)。因此**无法**在本硬件上直接对比 kernel 与**真实 fla 融合算子**的输出。 | 87 | > 实现)。因此**无法**在本硬件上直接对比 kernel 与**真实 fla 融合算子**的输出。 |
| 76 | > | 88 | > |
| 77 | -> The substitute baseline is `_naive_recurrent_kda` — a plain per-timestep recurrence | 89 | +> 替代基准采用**两个相互独立的参考实现**交叉校验,而非单一“算法等价重写”—— |
| 78 | -> straight from the KDA defining equations, with no chunking or matrix inversion, so it | 90 | +> 这一点很关键,可避免“参考与 kernel 共享同一算法误解、却互相吻合”的循环验证盲区: |
| 79 | -> is structurally independent of the kernel's blocked algorithm. Cross-check: | 91 | +> 1. **`_naive_recurrent_kda`(主 golden)**——逐时间步朴素递归,直接照 KDA 定义式 |
| 80 | -> dS ≤ 3.9e-6, dO ≤ 8.8e-3 (≈1 bf16 ulp, the format floor). | 92 | +> (per-channel 对数门 `g`、`alpha=exp(g)`、delta-rule 外积更新、q/k L2norm、`scale=K**-0.5`, |
| 93 | +> 见 `kda_chunk_impl.py` 模块 docstring 与 Kimi-Linear KDA 数学定义)实现,**不含**任何 | ||
| 94 | +> 分块/矩阵求逆技巧。kernel 的精度即是对拍它(chunk 6.1e-5)。 | ||
| 95 | +> 2. **`vec_chunk_kda`(第二参考)**——分块矩阵算法(subchunk=16,nilpotent 三角求逆), | ||
| 96 | +> 与 kernel 同构但纯 torch;它独立地对拍 `_naive_recurrent_kda`(≤6e-5)。 | ||
| 81 | > | 97 | > |
| 82 | -> **Residual risk:** the golden is this repo's own transcription of the KDA math and | 98 | +> 由于①是定义式逐步递归、②是分块算法,二者**结构独立**:kernel 同时吻合两者,已排除 |
| 83 | -> has not been bit-compared with the upstream CUDA `fla.ops.kda` kernel. **To close it** | 99 | +> “实现误解被参考掩盖”的主要风险。**残余风险**仅剩一项且已界定:①②均是 KDA 数学的 |
| 84 | -> (needs a CUDA machine): run `kimi_fla_compat.vec_chunk_kda` vs the real | 100 | +> **本仓库转写**,未与上游 CUDA `fla.ops.kda` kernel 逐位对拍。**关闭方式**(需 CUDA 机器、 |
| 85 | -> `fla.ops.kda.chunk_kda` once on a GPU and record the result here; until then this is | 101 | +> 非本 Ascend 环境):在一台 GPU 上跑一次 `vec_chunk_kda` vs 真实 `fla.ops.kda.chunk_kda` |
| 86 | -> a disclosed, known gap. | 102 | +> 的差异并记录于此;在拿到该数据前,本集成按“已披露的已知差距”对待。 |
| 87 | 103 | ||
| 88 | -## Graph capture | 104 | +## Performance |
| 89 | - | 105 | + |
| 90 | -The fused wrappers do **not** call `torch_npu.npu.synchronize()` — the kernel enqueues | 106 | +The fused chunk kernel reduces KDA prefill cost vs the torch chunked op, with the gain |
| 91 | -on the current stream and downstream ops are stream-ordered after it, so a device-wide | 107 | +growing with sequence length. Decode (T=1 recurrent) is roughly parity, so it is left on the |
| 92 | -sync is unnecessary (and would abort NPU-graph capture). The prefill dispatch lives at | 108 | +upstream torch path; PyPTO covers the prefill/chunk path only. |
| 93 | -the fused-subgraph level (`_try_kda_fused_prefill` in `modeling_kimi.py`); its | 109 | + |
| 94 | -try/except resolves to the fused branch during warmup + capture, so a captured stage | 110 | +## ACLGraph / 图捕获 |
| 95 | -bakes in the fused op. Capture+replay of the operator is regression-tested in | 111 | + |
| 96 | -`test_kda_fused_prefill.py::test_kda_fused_prefill_graph_capture` (bit-exact vs | 112 | +The chunk kernel is registered with `torch.library` as `pypto::kda_chunk_kimi` (Meta + NPU |
| 97 | -eager); the full-model `--graph` bench captures every KDA layer through this | 113 | +keys; see the registration block at the bottom of `kda_chunk_impl.py`, mirroring |
| 98 | -path. The decode stage is captured via `kda_decode_graph.py`'s | 114 | +`phi_3_mini_4k_instruct/rms_norm`). The Meta ("fake") impl gives a graph tracer the output |
| 99 | -`StaticDecodeCache` + `kda_fused_decode_step`. | 115 | +shape/dtype rule without launching the kernel. `kda_chunk_pypto` is the capturable entry point |
| 116 | +(`torch.ops.pypto.kda_chunk_kimi`); the default eager dispatch still uses `kda_chunk_wrapper`, | ||
| 117 | +so this adds capture-readiness without touching the verified eager path. | ||
| 118 | + | ||
| 119 | +The wrappers do **not** call `torch_npu.npu.synchronize()` — the kernel enqueues on the | ||
| 120 | +current stream and downstream ops are stream-ordered after it, so a device-wide sync is | ||
| 121 | +unnecessary (and would abort aclgraph capture). Verified safe: op tests are bit-identical | ||
| 122 | +with the sync removed, and the full-model bench keeps identical KDA coverage. | ||
| 123 | + | ||
| 124 | +**Verified** (`tests/ops/kimi_linear_48b_a3b/test_kda_aclgraph.py`, on NPU): | ||
| 125 | +- registered NPU op == eager wrapper, **bit-identical** (chunk); | ||
| 126 | +- Meta shape inference correct under `FakeTensorMode`; | ||
| 127 | +- the op composes into a **`torch.compile(fullgraph=True)`** graph with **no graph break** | ||
| 128 | + (`aot_eager` + `eager`, bit-exact); | ||
| 129 | +- **real torchair aclgraph capture** (`torch_npu.dynamo.torchair`, `get_npu_backend`, | ||
| 130 | + `mode="reduce-overhead"`) **captures + replays bit-exact** (`diff=0`) — this is the | ||
| 131 | + npugraph/stream-capture path, which needs **no GE converter**. | ||
| 132 | + | ||
| 133 | +**Remaining for whole-model aclgraph:** the KDA op itself is capture-ready (above). Running | ||
| 134 | +the *entire* Kimi model under a single torchair `reduce-overhead` graph additionally | ||
| 135 | +requires every other op (MoE routing, attention, conv) to be capture-clean; that end-to-end | ||
| 136 | +model capture is the next step and is not yet validated here. (torchair's separate GE-graph | ||
| 137 | +mode is a different path that *would* need a per-op GE converter — not pursued, since the | ||
| 138 | +npugraph capture above already works for this fused kernel.) | ||
| 100 | 139 | ||
| 101 | ## Files | 140 | ## Files |
| 102 | 141 | ||
| 103 | | File | Description | | 142 | | File | Description | |
| 104 | |------|-------------| | 143 | |------|-------------| |
| 105 | -| `kda_fused_prefill_impl.py` | Fused prefill operator — `kda_fused_prefill` (conv+silu, gate, beta, WY-chunk KDA core, o_norm; one kernel) | | 144 | +| `kda_chunk_impl.py` | Chunk/prefill kernel + `kda_chunk_wrapper` (`@allow_in_graph`) + `torch.library` reg (`pypto::kda_chunk_kimi`, Meta+NPU) + `kda_chunk_pypto` | |
| 106 | -| `kda_fused_decode_impl.py` | Decode kernel + `kda_fused_decode` (eager, guarded) + `kda_fused_decode_step` (capture-safe) | | 145 | +| `_device_guard.py` | Shared single-NPU bind guard (partial-coverage fallback) | |
| 107 | -| `_device_guard.py` | Single-NPU binding guard shared by both wrappers | | 146 | +| `__init__.py` | Package init — re-exports `kda_chunk_wrapper` (eager) and `kda_chunk_pypto` (capturable) | |
| 108 | -| `__init__.py` | Package init — re-exports `kda_fused_prefill` (prefill) and `kda_fused_decode`/`kda_fused_decode_step` (decode) | | 147 | +| `README.md` | This document | |
| 109 | 148 | ||
| 110 | ## 状态 | 149 | ## 状态 |
| 111 | 150 | ||
| 112 | | 维度 | 状态 | | 151 | | 维度 | 状态 | |
| 113 | |------|------| | 152 | |------|------| |
| 114 | -| 单算子精度 | ✅ `tests/ops/kimi_linear_48b_a3b/test_kda_fused_prefill.py` — vs 全 fp32 golden: dO ≤ 8.8e-3 (≈1 bf16 ulp), dS ≤ 3.9e-6, conv-state bit-exact | | 153 | +| 单算子精度 | ✅ chunk 测试通过(PRECISION_PASS)— `tests/ops/kimi_linear_48b_a3b/test_kda_chunk.py`,max abs err 6.1e-5 | |
| 115 | -| 整网集成 | ✅ `USE_PTO_KDA` + `sys.modules` injection + fused-subgraph dispatch (`_try_kda_fused_prefill`) with `NotImplementedError` → torch fallback | | 154 | +| 整网集成 | ✅ 已接入 — `USE_PTO_KDA` 开关 + `sys.modules` 注入 + `NotImplementedError` → 上游 torch fallback;端到端可跑通,PyPTO 运行间结果可复现(逐字节一致)。与 torch 参考 **非** bit-exact(kernel 与 torch 参考**均为 fp32 计算 + bf16 I/O**,差异仅来自实现/算子顺序的舍入,单算子 ~6.1e-5;greedy argmax 在 token 级可能分叉) | |
| 116 | -| ACLGraph | ✅ no device-wide sync; NPUGraph capture+replay regression-tested in `test_kda_fused_prefill.py`; full-model `--graph` bench captures every KDA layer | | 155 | +| ACLGraph | ✅ 算子级已验证 — chunk kernel `torch.library` 注册(`pypto::kda_chunk_kimi`,Meta+NPU),且 wrapper 去除了多余的 `torch_npu.npu.synchronize()`(kernel 走 stream 顺序,去同步后算子测试逐位一致、整网 bench KDA 覆盖不变且更快)。`test_kda_aclgraph.py` 验证:注册 op == wrapper 逐位一致、Meta 推导正确、`torch.compile(fullgraph)` 无 graph break、**真实 torchair aclgraph(reduce-overhead)capture+replay 逐位一致(diff=0,无需 GE converter)**。整网 aclgraph(其余算子也需 capture-clean)为后续工作 | |
| 117 | -| 性能 | Benchmarked with `bench_kimi_multinpu.py --mode prefill --pypto [--graph]` | | 156 | +| 性能调优 | ✅ chunk nested-64 已调优(subchunk=16,prefill 1.05–1.26x)。详见上级 `modeling/transformers/kimi_linear_48b_a3b/README.md` 性能对比 | |
| 118 | 157 | ||
| 119 | --- | 158 | --- |
| 120 | 159 | ||
| @@ -8,18 +8,19 @@ | |||
| 8 | # ----------------------------------------------------------------------------------------------------------- | 8 | # ----------------------------------------------------------------------------------------------------------- |
| 9 | """KDA (Kimi Delta Attention) PyPTO kernel package. | 9 | """KDA (Kimi Delta Attention) PyPTO kernel package. |
| 10 | 10 | ||
| 11 | - prefill : ``kda_fused_prefill`` implements the fused PyPTO prefill path. | 11 | + prefill : ``kda_chunk_wrapper`` replaces ``fla.ops.kda.chunk_kda`` in |
| 12 | - Unsupported inputs fall back to the reference torch path in the | 12 | + ``KimiDeltaAttention.forward``; ``kda_chunk_pypto`` is the |
| 13 | - modeling layer. | 13 | + torch.library-registered capturable entry. |
| 14 | decode : ``kda_fused_decode`` (eager, guarded) and | 14 | decode : ``kda_fused_decode`` (eager, guarded) and |
| 15 | ``kda_fused_decode_step`` (capture-safe, no guards) run the whole | 15 | ``kda_fused_decode_step`` (capture-safe, no guards) run the whole |
| 16 | per-token KDA path in one operator. | 16 | per-token KDA path in one operator. |
| 17 | 17 | ||
| 18 | -See ``README.md`` for algorithm and dispatch details. | 18 | +See ``README.md`` for the algorithm, the subchunk=16 stability rationale and the |
| 19 | +dispatch toggles. | ||
| 19 | """ | 20 | """ |
| 20 | __all__ = [ | 21 | __all__ = [ |
| 21 | # prefill | 22 | # prefill |
| 22 | - "kda_fused_prefill", | 23 | + "kda_chunk_wrapper", "kda_chunk_pypto", |
| 23 | # decode | 24 | # decode |
| 24 | "kda_fused_decode", "kda_fused_decode_step", | 25 | "kda_fused_decode", "kda_fused_decode_step", |
| 25 | "prepare_kda_fused_weights", "KdaFusedWeights", | 26 | "prepare_kda_fused_weights", "KdaFusedWeights", |
| @@ -27,7 +28,7 @@ __all__ = [ | |||
| 27 | "seed_fused_buffers", | 28 | "seed_fused_buffers", |
| 28 | ] | 29 | ] |
| 29 | 30 | ||
| 30 | -from .kda_fused_prefill_impl import kda_fused_prefill | 31 | +from .kda_chunk_impl import kda_chunk_wrapper, kda_chunk_pypto |
| 31 | from .kda_fused_decode_impl import ( | 32 | from .kda_fused_decode_impl import ( |
| 32 | kda_fused_decode, | 33 | kda_fused_decode, |
| 33 | kda_fused_decode_step, | 34 | kda_fused_decode_step, |
| @@ -0,0 +1,423 @@ | |||
| 1 | +# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 9 | +"""kda_chunk — chunked Kimi Delta Attention (KDA) kernel for Kimi-Linear-48B-A3B. | ||
| 10 | + | ||
| 11 | +Per-channel-gate chunked linear attention (the KDA prefill path), validated | ||
| 12 | +against the golden ``_naive_recurrent_kda`` (state_v_first, ``[B,H,V,K]``). Drop-in | ||
| 13 | +PyPTO replacement for the upstream ``fla.ops.kda.chunk_kda`` entry point used by | ||
| 14 | +``KimiDeltaAttention`` during prefill (``mode == 'chunk'``). | ||
| 15 | + | ||
| 16 | +TILING — NESTED 64-outer / 16-inner (the current shipped layout): | ||
| 17 | + The host->kernel loop steps a 64-row OUTER tile. All elementwise / row-local | ||
| 18 | + vector pre-compute over those 64 rows (cumulative gate, exp(G), exp(-G), qd, | ||
| 19 | + kd, kg_pos, beta*v, beta*kg, state-update key) runs at | ||
| 20 | + ``set_vec_tile_shapes(64, 128)`` -> ~4x fewer vector-pipe launches than a flat | ||
| 21 | + 16-row tile. The intra-chunk pairwise term and the serial state-coupled | ||
| 22 | + matmuls stay at M=16 inside a compile-time ``range(4)`` (NSUB) loop, because | ||
| 23 | + the pairwise matmuls are block-diagonal and the state matmuls read the | ||
| 24 | + serially-updated state per sub-block. | ||
| 25 | + | ||
| 26 | +NUMERICAL-STABILITY INVARIANT (non-negotiable): | ||
| 27 | + qd=q*exp(G), kd=k*exp(-G) uses exp(-G). The real KDA gate is a per-channel | ||
| 28 | + log-gate g in [-5, 0]. Over a 16-step window the cumulative gate range is at | ||
| 29 | + most 16*5 = 80, so exp(80) ~ 5.5e34 < 3.4e38 (fp32-safe). A 64-step window | ||
| 30 | + would give exp(320) = inf (NaN). | ||
| 31 | + | ||
| 32 | + THE 64-OUTER TILE NEVER WIDENS THAT WINDOW. The cumulative gate is computed | ||
| 33 | + BLOCK-DIAGONALLY: ``tril_le64`` is a [64,64] block-diagonal lower-triangular | ||
| 34 | + matrix (4 independent 16x16 blocks, zero off-block), so G[row] is the cumsum | ||
| 35 | + of g WITHIN its own 16-block only and every exp argument stays bounded by 80, | ||
| 36 | + exactly as a flat chunk_size=16. Matches the recurrent golden to < 1e-7 even | ||
| 37 | + for the strongest gate g=-5. | ||
| 38 | + | ||
| 39 | +Per 16-subchunk c, for one (b,h), with state S=[V,K] (n = SUB = 16): | ||
| 40 | + g_cum = cumsum_n(g) # [n,K] (block-local), all <= 0 | ||
| 41 | + qd is q*exp(g_cum); kd is k*exp(-g_cum); kg_pos is k*exp(g_cum) | ||
| 42 | + a_qk: scaled qd·kdᵀ masked by tril_le # [n,n] | ||
| 43 | + a_kk: beta * (kg_pos·kdᵀ) masked by tril_lt # [n,n] strict-lower, nilpotent | ||
| 44 | + t_inv: inverse of (I + a_kk) # via nilpotent doubling | ||
| 45 | + u and w: apply t_inv to (beta*v) and (beta*exp(g_cum)*k) | ||
| 46 | + v_new is u - w·stateᵀ # [n,V] | ||
| 47 | + o is scale*(qd·stateᵀ) + a_qk·v_new # [n,V] | ||
| 48 | + g_last is g_cum[n-1]; kg is exp(g_last - g_cum)*k # [n,K] (g_last - g_cum <= 0, safe) | ||
| 49 | + state: exp(g_last)*state + contraction of v_newᵀ with kg # [V,K] | ||
| 50 | + | ||
| 51 | +Tile geometry: | ||
| 52 | + * Outer tile OUT = 64 rows; inner subchunk SUB = 16 rows; head dim K = V = 128. | ||
| 53 | + * Triangular inverse via nilpotent doubling (4 doublings: 2^4 = 16). | ||
| 54 | + | ||
| 55 | +Scope (caller-enforced via wrapper): | ||
| 56 | + * head_k_dim K = 128, head_v_dim V = 128. | ||
| 57 | + * ``use_qk_l2norm_in_kernel = True`` (L2 norm done on host before packing). | ||
| 58 | + | ||
| 59 | +Out-of-scope shapes raise ``NotImplementedError``. The modeling-layer hook falls | ||
| 60 | +back to the upstream / torch chunk function in that case. | ||
| 61 | +""" | ||
| 62 | +__all__ = ["kda_chunk_wrapper"] | ||
| 63 | + | ||
| 64 | +import os | ||
| 65 | +import sys | ||
| 66 | + | ||
| 67 | +import pypto | ||
| 68 | +import torch | ||
| 69 | +import torch_npu # noqa: F401 required for NPU device init | ||
| 70 | +from torch._dynamo import allow_in_graph | ||
| 71 | + | ||
| 72 | +# Same-dir sibling import: works both as a package (.kda.kda_chunk_impl) and when | ||
| 73 | +# the kda dir is put on sys.path directly (the op tests import it that way). | ||
| 74 | +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | ||
| 75 | +from _device_guard import _bound_device_ok # noqa: E402 | ||
| 76 | + | ||
| 77 | + | ||
| 78 | +# Inner subchunk size (SUB) and outer tile (OUT). SUB bounds the cumulative-gate | ||
| 79 | +# range to SUB*5 so exp(-G) stays in fp32 range; OUT=4*SUB batches the safe | ||
| 80 | +# row-local vector work without widening that gate window (block-diagonal tril). | ||
| 81 | +SUB = 16 | ||
| 82 | +OUT = 64 | ||
| 83 | +NSUB = OUT // SUB # 4 | ||
| 84 | + | ||
| 85 | + | ||
| 86 | +# --------------------------------------------------------------------------- | ||
| 87 | +# Triangular inverse via nilpotent doubling. | ||
| 88 | +# For a strict-lower nilpotent m whose sixteenth power vanishes, the inverse | ||
| 89 | +# of (I minus m) equals the product over j of (I plus m raised to the power | ||
| 90 | +# two-to-the-j). With a sub-block of 16, the sixteenth power is zero, so four | ||
| 91 | +# doublings (which reach the power of 16) suffice. We want the inverse of | ||
| 92 | +# (I plus a_kk), so we pass m as the negation of a_kk. | ||
| 93 | +# --------------------------------------------------------------------------- | ||
| 94 | + | ||
| 95 | +def inverse_nilpotent(m, eye16): | ||
| 96 | + """m, eye16: 16-by-16; returns the inverse of (I minus m). With SUB equal to | ||
| 97 | + 16 this needs four nilpotent doublings. | ||
| 98 | + """ | ||
| 99 | + # matmul tile m16 k16 n16 | ||
| 100 | + pypto.set_cube_tile_shapes([16, 16], [16, 16], [16, 16]) | ||
| 101 | + pypto.set_vec_tile_shapes(16, 16) | ||
| 102 | + acc = eye16 + m # I + m | ||
| 103 | + p = m | ||
| 104 | + for _ in range(3): | ||
| 105 | + p = pypto.matmul(p, p, pypto.DT_FP32) # m^{2^j} | ||
| 106 | + acc = pypto.matmul(acc, eye16 + p, pypto.DT_FP32) # acc *= (I + m^{2^j}) | ||
| 107 | + return acc | ||
| 108 | + | ||
| 109 | + | ||
| 110 | +# --------------------------------------------------------------------------- | ||
| 111 | +# Per-64-row outer tile: widened vector pre-compute + 4 serial 16-subchunks. | ||
| 112 | +# --------------------------------------------------------------------------- | ||
| 113 | + | ||
| 114 | +def pypto_kda_outer64(query, key, value, gate, beta, state, tril_le64, tril_le16, tril_lt16, eye16, scale): | ||
| 115 | + """query,key,gate: [64,K]; value: [64,V]; beta: [64,1]; state: [V,K]. | ||
| 116 | + Returns o [64,V], state_new [V,K]. Vector pre-compute batched at 64 rows; | ||
| 117 | + cube/state work done per 16-sub-block with serial state carry. | ||
| 118 | + """ | ||
| 119 | + # ---- widened (64-row) vector pre-compute ---- | ||
| 120 | + pypto.set_vec_tile_shapes(64, 128) | ||
| 121 | + # block-diagonal cumulative gate: [64,64]@[64,128]->[64,128] | ||
| 122 | + pypto.set_cube_tile_shapes([64, 64], [64, 64], [128, 128]) | ||
| 123 | + g_cum = pypto.matmul(tril_le64, gate, pypto.DT_FP32) # [64,K] per-block cumsum (<=0) | ||
| 124 | + pypto.set_vec_tile_shapes(64, 128) | ||
| 125 | + exp_g = pypto.exp(g_cum) # (0,1] | ||
| 126 | + exp_neg_g = pypto.exp(g_cum * (-1.0)) # bounded by exp(SUB*5) | ||
| 127 | + qd = query * exp_g # [64,K] | ||
| 128 | + kd = key * exp_neg_g # [64,K] | ||
| 129 | + kg_pos = key * exp_g # [64,K] | ||
| 130 | + bv = value * beta # [64,V] | ||
| 131 | + bgk = kg_pos * beta # [64,K] | ||
| 132 | + | ||
| 133 | + o_blocks = [] | ||
| 134 | + cur_state = state # [V,K] serial carry | ||
| 135 | + for c in range(NSUB): | ||
| 136 | + s0 = c * SUB | ||
| 137 | + qd_b = qd[s0:s0 + SUB, :] | ||
| 138 | + kd_b = kd[s0:s0 + SUB, :] | ||
| 139 | + kgp_b = kg_pos[s0:s0 + SUB, :] | ||
| 140 | + bv_b = bv[s0:s0 + SUB, :] | ||
| 141 | + bgk_b = bgk[s0:s0 + SUB, :] | ||
| 142 | + beta_b = beta[s0:s0 + SUB, :] | ||
| 143 | + gcum_b = g_cum[s0:s0 + SUB, :] | ||
| 144 | + key_b = key[s0:s0 + SUB, :] | ||
| 145 | + | ||
| 146 | + # a_qk: scaled qd·kdᵀ masked by tril_le ; [16,128]@[128,16]->[16,16] | ||
| 147 | + pypto.set_cube_tile_shapes([16, 16], [128, 128], [16, 16]) | ||
| 148 | + aqk = pypto.matmul(qd_b, kd_b, pypto.DT_FP32, b_trans=True) | ||
| 149 | + pypto.set_vec_tile_shapes(16, 16) | ||
| 150 | + aqk = aqk * scale * tril_le16 | ||
| 151 | + | ||
| 152 | + pypto.set_cube_tile_shapes([16, 16], [128, 128], [16, 16]) | ||
| 153 | + akk = pypto.matmul(kgp_b, kd_b, pypto.DT_FP32, b_trans=True) | ||
| 154 | + pypto.set_vec_tile_shapes(16, 16) | ||
| 155 | + akk = (akk * beta_b) * tril_lt16 # strict-lower | ||
| 156 | + t_inv = inverse_nilpotent(akk * (-1.0), eye16) # inverse of (I + a_kk) | ||
| 157 | + | ||
| 158 | + # u and w: apply the triangular inverse to beta*v and beta*exp(G)*k ; [16,16]@[16,128]->[16,128] | ||
| 159 | + pypto.set_cube_tile_shapes([16, 16], [16, 16], [128, 128]) | ||
| 160 | + u = pypto.matmul(t_inv, bv_b, pypto.DT_FP32) | ||
| 161 | + w = pypto.matmul(t_inv, bgk_b, pypto.DT_FP32) | ||
| 162 | + | ||
| 163 | + # w_s: w times stateᵀ (state-coupled) ; [16,128]@[128,128]->[16,128] | ||
| 164 | + pypto.set_cube_tile_shapes([16, 16], [128, 128], [128, 128]) | ||
| 165 | + w_s = pypto.matmul(w, cur_state, pypto.DT_FP32, b_trans=True) | ||
| 166 | + pypto.set_vec_tile_shapes(16, 128) | ||
| 167 | + v_new = u - w_s # [16,V] | ||
| 168 | + | ||
| 169 | + # o_inter: scaled qd times stateᵀ (state-coupled) ; [16,128]@[128,128]->[16,128] | ||
| 170 | + pypto.set_cube_tile_shapes([16, 16], [128, 128], [128, 128]) | ||
| 171 | + o_inter = pypto.matmul(qd_b, cur_state, pypto.DT_FP32, b_trans=True) | ||
| 172 | + pypto.set_vec_tile_shapes(16, 128) | ||
| 173 | + o_inter = o_inter * scale | ||
| 174 | + # o_intra: a_qk times v_new ; [16,16]@[16,128]->[16,128] | ||
| 175 | + pypto.set_cube_tile_shapes([16, 16], [16, 16], [128, 128]) | ||
| 176 | + o_intra = pypto.matmul(aqk, v_new, pypto.DT_FP32) | ||
| 177 | + pypto.set_vec_tile_shapes(16, 128) | ||
| 178 | + o_b = o_inter + o_intra # [16,V] | ||
| 179 | + o_blocks.append(o_b) | ||
| 180 | + | ||
| 181 | + # state update for this sub-block (serial carry) | ||
| 182 | + g_last = gcum_b[SUB - 1:SUB, :] # [1,K] | ||
| 183 | + exp_g_last = pypto.exp(g_last) # [1,K] | ||
| 184 | + kg = key_b * pypto.exp(g_last - gcum_b) # [16,K] (arg<=0) | ||
| 185 | + # upd: v_newᵀ contracted with kg ; [128,16]@[16,128]->[128,128] | ||
| 186 | + pypto.set_cube_tile_shapes([128, 128], [16, 16], [128, 128]) | ||
| 187 | + upd = pypto.matmul(v_new, kg, pypto.DT_FP32, a_trans=True) | ||
| 188 | + pypto.set_vec_tile_shapes(128, 128) | ||
| 189 | + cur_state = cur_state * exp_g_last + upd # [V,K] | ||
| 190 | + | ||
| 191 | + o = pypto.concat(o_blocks, dim=0) # [64,V] | ||
| 192 | + return o, cur_state | ||
| 193 | + | ||
| 194 | + | ||
| 195 | +# --------------------------------------------------------------------------- | ||
| 196 | +# Layer I — kernel impl (loops over BH and 64-row outer tiles). | ||
| 197 | +# --------------------------------------------------------------------------- | ||
| 198 | + | ||
| 199 | +def _kda_chunk_kernel_impl(query, key, value, gate, beta, states, | ||
| 200 | + tril_le64, tril_le16, tril_lt16, eye16, | ||
| 201 | + core_attn_out, last_state_data): | ||
| 202 | + """query,key,gate: [BH,T,K]; value: [BH,T,V]; beta: [BH,T,1]; | ||
| 203 | + states/last_state_data: [BH,V,K]; core_attn_out: [BH,T,V]. | ||
| 204 | + T is padded to a multiple of OUT=64 by the host wrapper.""" | ||
| 205 | + bh = states.shape[0] | ||
| 206 | + t = query.shape[1] | ||
| 207 | + d = query.shape[2] | ||
| 208 | + scale = float(d) ** -0.5 | ||
| 209 | + | ||
| 210 | + for bh_idx in pypto.loop(bh, name="LOOP_BH", idx_name="bh_idx", parallel=True): | ||
| 211 | + pypto.set_vec_tile_shapes(128, 128) | ||
| 212 | + last_state = states[bh_idx] # [V,K] (loop-carried, in-place) | ||
| 213 | + for s_idx in pypto.loop(0, t, OUT, name="LOOP_S", idx_name="s_idx", | ||
| 214 | + submit_before_loop=True): | ||
| 215 | + q_v = pypto.view(query, [1, OUT, 128], [bh_idx, s_idx, 0]).reshape([OUT, 128]) | ||
| 216 | + k_v = pypto.view(key, [1, OUT, 128], [bh_idx, s_idx, 0]).reshape([OUT, 128]) | ||
| 217 | + v_v = pypto.view(value, [1, OUT, 128], [bh_idx, s_idx, 0]).reshape([OUT, 128]) | ||
| 218 | + g_v = pypto.view(gate, [1, OUT, 128], [bh_idx, s_idx, 0]).reshape([OUT, 128]) | ||
| 219 | + b_v = pypto.view(beta, [1, OUT, 1], [bh_idx, s_idx, 0]).reshape([OUT, 1]) | ||
| 220 | + | ||
| 221 | + o, cur_state = pypto_kda_outer64(q_v, k_v, v_v, g_v, b_v, last_state, | ||
| 222 | + tril_le64, tril_le16, tril_lt16, eye16, scale) | ||
| 223 | + | ||
| 224 | + o_blk = o.reshape([1, OUT, 128]) | ||
| 225 | + pypto.assemble(o_blk, [bh_idx, s_idx, 0], core_attn_out) | ||
| 226 | + last_state[:] = cur_state # in-place loop carry | ||
| 227 | + | ||
| 228 | + ls_blk = last_state.reshape([1, 128, 128]) | ||
| 229 | + pypto.assemble(ls_blk, [bh_idx, 0, 0], last_state_data) | ||
| 230 | + | ||
| 231 | + | ||
| 232 | +# --------------------------------------------------------------------------- | ||
| 233 | +# Layer J — JIT entry (module-level dynamic shapes). | ||
| 234 | +# --------------------------------------------------------------------------- | ||
| 235 | + | ||
| 236 | +_BH = pypto.DYNAMIC | ||
| 237 | +_T = pypto.DYNAMIC | ||
| 238 | +_QKG = [_BH, _T, 128] | ||
| 239 | +_V = [_BH, _T, 128] | ||
| 240 | +_BETA = [_BH, _T, 1] | ||
| 241 | +_STATE = [_BH, 128, 128] | ||
| 242 | +_OUT = [_BH, _T, 128] | ||
| 243 | +_LL64 = [OUT, OUT] | ||
| 244 | +_LL16 = [SUB, SUB] | ||
| 245 | + | ||
| 246 | + | ||
| 247 | +@pypto.frontend.jit | ||
| 248 | +def kda_chunk_npu( | ||
| 249 | + query: pypto.Tensor(_QKG, pypto.DT_FP32), | ||
| 250 | + key: pypto.Tensor(_QKG, pypto.DT_FP32), | ||
| 251 | + value: pypto.Tensor(_V, pypto.DT_FP32), | ||
| 252 | + gate: pypto.Tensor(_QKG, pypto.DT_FP32), | ||
| 253 | + beta: pypto.Tensor(_BETA, pypto.DT_FP32), | ||
| 254 | + states: pypto.Tensor(_STATE, pypto.DT_FP32), | ||
| 255 | + tril_le64: pypto.Tensor(_LL64, pypto.DT_FP32), | ||
| 256 | + tril_le16: pypto.Tensor(_LL16, pypto.DT_FP32), | ||
| 257 | + tril_lt16: pypto.Tensor(_LL16, pypto.DT_FP32), | ||
| 258 | + eye16: pypto.Tensor(_LL16, pypto.DT_FP32), | ||
| 259 | + core_attn_out: pypto.Tensor(_OUT, pypto.DT_FP32), | ||
| 260 | + last_state_data: pypto.Tensor(_STATE, pypto.DT_FP32), | ||
| 261 | +): | ||
| 262 | + _kda_chunk_kernel_impl(query, key, value, gate, beta, states, | ||
| 263 | + tril_le64, tril_le16, tril_lt16, eye16, | ||
| 264 | + core_attn_out, last_state_data) | ||
| 265 | + | ||
| 266 | + | ||
| 267 | +# --------------------------------------------------------------------------- | ||
| 268 | +# Layer K — host wrapper (FLA call signature, @allow_in_graph). | ||
| 269 | +# --------------------------------------------------------------------------- | ||
| 270 | + | ||
| 271 | +_K = 128 | ||
| 272 | +_V_DIM = 128 | ||
| 273 | + | ||
| 274 | + | ||
| 275 | +def _build_tril_eye(device): | ||
| 276 | + """Build the four constant mask/identity tensors the kernel needs: | ||
| 277 | + block-diagonal 64-by-64 lower-tri (4 independent 16-by-16 blocks, zero | ||
| 278 | + off-block) so the cumulative-gate window stays within SUB which is 16 steps, | ||
| 279 | + plus the 16-by-16 lower-tri (inclusive), strict-lower, and identity. | ||
| 280 | + Returns (tril_le64, tril_le16, tril_lt16, eye16).""" | ||
| 281 | + idx64 = torch.arange(OUT, device=device) | ||
| 282 | + blk = (idx64[:, None] // SUB) == (idx64[None, :] // SUB) | ||
| 283 | + tril_le64 = ((idx64[:, None] >= idx64[None, :]) & blk).float() | ||
| 284 | + idx16 = torch.arange(SUB, device=device) | ||
| 285 | + tril_le16 = (idx16[:, None] >= idx16[None, :]).float() | ||
| 286 | + tril_lt16 = (idx16[:, None] > idx16[None, :]).float() | ||
| 287 | + eye16 = torch.eye(SUB, dtype=torch.float32, device=device) | ||
| 288 | + return tril_le64, tril_le16, tril_lt16, eye16 | ||
| 289 | + | ||
| 290 | + | ||
| 291 | +@allow_in_graph | ||
| 292 | +def kda_chunk_wrapper(q, k, v, g, beta, initial_state=None, | ||
| 293 | + output_final_state=True, use_qk_l2norm_in_kernel=True, | ||
| 294 | + cu_seqlens=None, scale=None, **kwargs): | ||
| 295 | + """FLA-layout chunk/prefill KDA wrapper for Kimi-Linear-48B-A3B. | ||
| 296 | + | ||
| 297 | + Mirrors the upstream ``fla.ops.kda.chunk_kda`` signature so the modeling | ||
| 298 | + layer can swap it in when ``USE_PTO_KDA`` is set. Nested 64-outer / 16-inner | ||
| 299 | + tiling (inner subchunk SUB=16 keeps the exp window fp32-safe). | ||
| 300 | + | ||
| 301 | + q,k,v,g: [B,T,H,128]; beta: [B,T,H]; initial_state: [B,H,V,K] fp32 or None. | ||
| 302 | + Returns ``(out [B,T,H,V] same dtype as q, final_state [B,H,V,K] fp32)``. | ||
| 303 | + | ||
| 304 | + Constraints (raises ``NotImplementedError`` otherwise): | ||
| 305 | + * head_k_dim K = 128, head_v_dim V = 128 | ||
| 306 | + * ``use_qk_l2norm_in_kernel`` is True | ||
| 307 | + """ | ||
| 308 | + in_dtype = q.dtype | ||
| 309 | + batch, seq_len, num_heads, head_k_dim = q.shape | ||
| 310 | + head_v_dim = v.shape[-1] | ||
| 311 | + | ||
| 312 | + if (head_k_dim != _K) or (head_v_dim != _V_DIM) or (not use_qk_l2norm_in_kernel): | ||
| 313 | + raise NotImplementedError( | ||
| 314 | + "kda_chunk_wrapper requires head_k_dim=128, head_v_dim=128, " | ||
| 315 | + "use_qk_l2norm_in_kernel=True; " | ||
| 316 | + f"got K={head_k_dim}, V={head_v_dim}, use_qk_l2norm_in_kernel={use_qk_l2norm_in_kernel}" | ||
| 317 | + ) | ||
| 318 | + | ||
| 319 | + device = q.device | ||
| 320 | + if not _bound_device_ok(device): | ||
| 321 | + raise NotImplementedError( | ||
| 322 | + "PyPTO KDA binds to a single NPU per process; tensor is on a " | ||
| 323 | + "different NPU -> torch fallback (for an NPU-sharded model, only " | ||
| 324 | + "the bound device's KDA layers run on PyPTO)") | ||
| 325 | + bh = batch * num_heads | ||
| 326 | + | ||
| 327 | + # L2 norm in kernel (match golden exactly), done on host before packing. | ||
| 328 | + qf = q.float() | ||
| 329 | + kf = k.float() | ||
| 330 | + qf = qf / (qf.pow(2).sum(-1, keepdim=True).sqrt() + 1e-6) | ||
| 331 | + kf = kf / (kf.pow(2).sum(-1, keepdim=True).sqrt() + 1e-6) | ||
| 332 | + | ||
| 333 | + pad = (OUT - seq_len % OUT) % OUT | ||
| 334 | + seq_len_pad = seq_len + pad | ||
| 335 | + | ||
| 336 | + def pack(x, lastdim): | ||
| 337 | + x = x.permute(0, 2, 1, 3).contiguous().reshape(bh, seq_len, lastdim) | ||
| 338 | + if pad: | ||
| 339 | + x = torch.nn.functional.pad(x, (0, 0, 0, pad)) | ||
| 340 | + return x.contiguous() | ||
| 341 | + | ||
| 342 | + q2 = pack(qf, head_k_dim) | ||
| 343 | + k2 = pack(kf, head_k_dim) | ||
| 344 | + v2 = pack(v.float(), head_v_dim) | ||
| 345 | + g2 = pack(g.float(), head_k_dim) | ||
| 346 | + b2 = beta.float().permute(0, 2, 1).contiguous().reshape(bh, seq_len, 1) | ||
| 347 | + if pad: | ||
| 348 | + b2 = torch.nn.functional.pad(b2, (0, 0, 0, pad)) | ||
| 349 | + b2 = b2.contiguous() | ||
| 350 | + | ||
| 351 | + if initial_state is None: | ||
| 352 | + st = torch.zeros(bh, head_v_dim, head_k_dim, dtype=torch.float32, device=device) | ||
| 353 | + else: | ||
| 354 | + st = initial_state.float().reshape(bh, head_v_dim, head_k_dim).contiguous() | ||
| 355 | + | ||
| 356 | + tril_le64, tril_le16, tril_lt16, eye16 = _build_tril_eye(device) | ||
| 357 | + | ||
| 358 | + out2 = torch.zeros(bh, seq_len_pad, head_v_dim, dtype=torch.float32, device=device) | ||
| 359 | + last_state = torch.zeros(bh, head_v_dim, head_k_dim, dtype=torch.float32, device=device) | ||
| 360 | + | ||
| 361 | + kda_chunk_npu(q2, k2, v2, g2, b2, st, | ||
| 362 | + tril_le64, tril_le16, tril_lt16, eye16, | ||
| 363 | + out2, last_state) | ||
| 364 | + # No explicit synchronize: the kernel enqueues on the current stream, so the | ||
| 365 | + # reads below (and the model's downstream ops) are stream-ordered after it. | ||
| 366 | + # Dropping the device-wide sync is required for torch.compile/aclgraph capture | ||
| 367 | + # and avoids serializing every KDA layer. Verified: op tests bit-identical and | ||
| 368 | + # aclgraph capture+replay bit-exact without it. | ||
| 369 | + out = out2[:, :seq_len].reshape(batch, num_heads, seq_len, head_v_dim).permute(0, 2, 1, 3).contiguous().to(in_dtype) | ||
| 370 | + final_state = last_state.reshape(batch, num_heads, head_v_dim, head_k_dim) | ||
| 371 | + return out, (final_state if output_final_state else None) | ||
| 372 | + | ||
| 373 | + | ||
| 374 | +# --------------------------------------------------------------------------- | ||
| 375 | +# Layer L — torch.library registration (torch.compile / aclgraph capture). | ||
| 376 | +# --------------------------------------------------------------------------- | ||
| 377 | +# `@allow_in_graph` above lets dynamo treat the wrapper as an opaque call, but | ||
| 378 | +# graph capture (torchair / aclgraph) additionally needs a Meta ("fake") impl so | ||
| 379 | +# the tracer can infer output shapes/dtypes WITHOUT launching the NPU kernel. | ||
| 380 | +# Registering the op as `pypto::kda_chunk_kimi` (Meta + NPU keys) provides that; | ||
| 381 | +# the model reaches it via `kda_chunk_pypto` only when aclgraph is enabled, so | ||
| 382 | +# the default eager dispatch path (kda_chunk_wrapper) is unchanged. Mirrors the | ||
| 383 | +# sibling phi_3_mini_4k_instruct/rms_norm registration. output_final_state is | ||
| 384 | +# fixed True here (the cache always needs the state); cu_seqlens must be None. | ||
| 385 | +pyptolib = torch.library.Library("pypto", "FRAGMENT") # type: ignore[arg-type] | ||
| 386 | + | ||
| 387 | +if not hasattr(torch.ops.pypto, "kda_chunk_kimi"): | ||
| 388 | + pyptolib.define( | ||
| 389 | + "kda_chunk_kimi(Tensor q, Tensor k, Tensor v, Tensor g, Tensor beta, " | ||
| 390 | + "Tensor? initial_state, float scale, bool use_qk_l2norm_in_kernel) " | ||
| 391 | + "-> (Tensor, Tensor)") | ||
| 392 | + | ||
| 393 | + @torch.library.impl(pyptolib, "kda_chunk_kimi", "Meta") # type: ignore[arg-type] | ||
| 394 | + def _kda_chunk_kimi_meta(q, k, v, g, beta, initial_state, scale, | ||
| 395 | + use_qk_l2norm_in_kernel): | ||
| 396 | + batch, seq_len, num_heads, head_k_dim = q.shape | ||
| 397 | + head_v_dim = v.shape[-1] | ||
| 398 | + out = torch.empty((batch, seq_len, num_heads, head_v_dim), | ||
| 399 | + dtype=q.dtype, device=q.device) | ||
| 400 | + final_state = torch.empty((batch, num_heads, head_v_dim, head_k_dim), | ||
| 401 | + dtype=torch.float32, device=q.device) | ||
| 402 | + return out, final_state | ||
| 403 | + | ||
| 404 | + @torch.library.impl(pyptolib, "kda_chunk_kimi", "NPU") # type: ignore[arg-type] | ||
| 405 | + def _kda_chunk_kimi_npu(q, k, v, g, beta, initial_state, scale, | ||
| 406 | + use_qk_l2norm_in_kernel): | ||
| 407 | + return kda_chunk_wrapper( | ||
| 408 | + q, k, v, g, beta, initial_state=initial_state, | ||
| 409 | + output_final_state=True, | ||
| 410 | + use_qk_l2norm_in_kernel=use_qk_l2norm_in_kernel, scale=scale) | ||
| 411 | + | ||
| 412 | + | ||
| 413 | +def kda_chunk_pypto(q, k, v, g, beta, initial_state=None, scale=None, | ||
| 414 | + use_qk_l2norm_in_kernel=True): | ||
| 415 | + """aclgraph-capturable entry: routes through ``torch.ops.pypto.kda_chunk_kimi``. | ||
| 416 | + | ||
| 417 | + Same result as ``kda_chunk_wrapper`` (always returns ``(out, final_state)``), | ||
| 418 | + but as a registered custom op it can be captured by torch.compile / aclgraph. | ||
| 419 | + """ | ||
| 420 | + if scale is None: | ||
| 421 | + scale = q.shape[-1] ** -0.5 | ||
| 422 | + return torch.ops.pypto.kda_chunk_kimi( | ||
| 423 | + q, k, v, g, beta, initial_state, scale, use_qk_l2norm_in_kernel) | ||
| @@ -1,590 +0,0 @@ | |||
| 1 | -# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd. | ||
| 2 | -# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | -# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | -# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | -# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | -# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | -# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | -# ----------------------------------------------------------------------------------------------------------- | ||
| 9 | -"""kda_fused_prefill — fused chunked Kimi Delta Attention (KDA) prefill kernel. | ||
| 10 | - | ||
| 11 | -PyPTO kernel replaces the whole per-layer KDA attention core between | ||
| 12 | -the projections and ``o_proj``: | ||
| 13 | - conv1d(k=4)+silu (q,k,v) -> l2norm -> gate transform -> beta sigmoid | ||
| 14 | - -> WY-chunked gated delta-rule -> o_norm (RMSNorm * sigmoid gate) | ||
| 15 | - -> bf16 output | ||
| 16 | - | ||
| 17 | -CORE MATH (per 128-token chunk, per (b,h), state S = [K,V]): | ||
| 18 | - gcum = tril_incl @ g # [128,K] per-channel cumsum | ||
| 19 | - A = tril-decay(k) / A_qk = tril(q) # 16-row pivot bands (see below) | ||
| 20 | - a_inv = (I + beta*A_strict)^-1 * beta # 8x16 hierarchical block inverse | ||
| 21 | - w,u = a_inv @ (k*exp(gcum)), a_inv @ v # WY/UT transform | ||
| 22 | - vi = u - w @ S # chunk-local correction | ||
| 23 | - oc = (q*exp(gcum)) @ S + A_qk @ vi # output | ||
| 24 | - S' = S * exp(gcum[last]) + kdec^T @ vi # state update (no dense KxK | ||
| 25 | - # transition is materialized) | ||
| 26 | -""" | ||
| 27 | -__all__ = ["kda_fused_prefill", "KdaPrefillInputs", "KdaPrefillWeights"] | ||
| 28 | - | ||
| 29 | -import sys | ||
| 30 | -from dataclasses import dataclass | ||
| 31 | -from pathlib import Path | ||
| 32 | -from typing import NamedTuple | ||
| 33 | - | ||
| 34 | -import pypto | ||
| 35 | -import torch | ||
| 36 | -import torch_npu # noqa: F401 required for NPU device init | ||
| 37 | -from torch._dynamo import allow_in_graph | ||
| 38 | - | ||
| 39 | -sys.path.insert(0, str(Path(__file__).resolve().parent)) | ||
| 40 | -from _device_guard import _bound_device_ok # noqa: E402 | ||
| 41 | - | ||
| 42 | -OUT = 128 # WY chunk length (static) | ||
| 43 | -_BC = 16 # intra-chunk decay pivot band (exp window <= 15*5 = 75) | ||
| 44 | -_NC = OUT // _BC # 8 bands per chunk | ||
| 45 | -_DECAY_CAP = 80.0 # clamp col-factor exponent below fp32 exp overflow (~88.7) | ||
| 46 | -_L2_EPS = 1e-6 | ||
| 47 | - | ||
| 48 | - | ||
| 49 | -# --------------------------------------------------------------------------- | ||
| 50 | -# Host-side argument groups (public API) | ||
| 51 | -# --------------------------------------------------------------------------- | ||
| 52 | - | ||
| 53 | -class KdaPrefillInputs(NamedTuple): | ||
| 54 | - """Per-call fused-prefill input tensors.""" | ||
| 55 | - q: torch.Tensor # [B,T,H,128] pre-conv projection (bf16) | ||
| 56 | - k: torch.Tensor | ||
| 57 | - v: torch.Tensor | ||
| 58 | - g_raw: torch.Tensor # [B,T,H*128] f_b_proj output (any float dtype) | ||
| 59 | - g_gate: torch.Tensor # [B,T,H*128] g_b_proj output | ||
| 60 | - b_raw: torch.Tensor # [B,T,H] b_proj output | ||
| 61 | - | ||
| 62 | - | ||
| 63 | -class KdaPrefillWeights(NamedTuple): | ||
| 64 | - """Per-layer weight-only parameters plus config scalars.""" | ||
| 65 | - dt_bias: torch.Tensor # [H*128] fp32 parameter | ||
| 66 | - a_log: torch.Tensor # [1,1,H,1] or [H] fp32 parameter (log gate-decay) | ||
| 67 | - o_norm_w: torch.Tensor # [128] fp32 o_norm weight | ||
| 68 | - conv_wq: torch.Tensor # [H*128, 4] fp32 depthwise conv weight | ||
| 69 | - conv_wk: torch.Tensor # [H*128, 4] fp32 depthwise conv weight | ||
| 70 | - conv_wv: torch.Tensor # [H*128, 4] fp32 depthwise conv weight | ||
| 71 | - lower_bound: float = -5.0 | ||
| 72 | - rms_eps: float = 1e-5 | ||
| 73 | - | ||
| 74 | - | ||
| 75 | -class _PackedPrefill(NamedTuple): | ||
| 76 | - """Host-packed kernel operands plus the dims the unpack step needs.""" | ||
| 77 | - x_q: torch.Tensor # [BH, 3+Tpad, 128] fp32 pre-conv | ||
| 78 | - x_k: torch.Tensor | ||
| 79 | - x_v: torch.Tensor | ||
| 80 | - cw_q: torch.Tensor # [BH, 4, 128] fp32 per-tap conv weights | ||
| 81 | - cw_k: torch.Tensor | ||
| 82 | - cw_v: torch.Tensor | ||
| 83 | - g2: torch.Tensor # [BH, Tpad, 128] fp32 gate-raw | ||
| 84 | - gg2: torch.Tensor # [BH, Tpad, 128] fp32 output gate | ||
| 85 | - b2: torch.Tensor # [BH, Tpad, 1] fp32 beta-raw | ||
| 86 | - a_scl: torch.Tensor # [BH, 1, 1] fp32 exp(a_log) | ||
| 87 | - a_bias: torch.Tensor # [BH, 1, 128] fp32 exp(a_log)*dt_bias | ||
| 88 | - o_w: torch.Tensor # [1, 128] fp32 o_norm weight | ||
| 89 | - batch: int | ||
| 90 | - heads: int | ||
| 91 | - seq_len: int | ||
| 92 | - pad: int | ||
| 93 | - head_k_dim: int | ||
| 94 | - head_v_dim: int | ||
| 95 | - device: torch.device | ||
| 96 | - in_dtype: torch.dtype | ||
| 97 | - | ||
| 98 | - | ||
| 99 | -# --------------------------------------------------------------------------- | ||
| 100 | -# Traced-side operand groups | ||
| @@ -18,8 +18,8 @@ Kimi Linear 是混合线性注意力架构:3:1 的 **KDA**(Kimi Delta Attent | |||
| 18 | 18 | ||
| 19 | | Operation | PyPTO Integrated | Toggle flag | Fallback | Notes | | 19 | | Operation | PyPTO Integrated | Toggle flag | Fallback | Notes | |
| 20 | |-----------|:---:|-------------|----------|-------| | 20 | |-----------|:---:|-------------|----------|-------| |
| 21 | -| KDA prefill | Yes | `USE_PTO_KDA` | `chunk_kda` (torch `vec_chunk_kda`) | Uses `kda_fused_prefill` (fused conv+gate+beta+KDA core+o_norm kernel) | | 21 | +| KDA chunk (prefill) | Yes | `USE_PTO_KDA` | `chunk_kda` (torch `vec_chunk_kda`) | 融合 subchunk=16 KDA chunk kernel | |
| 22 | -| KDA decode (T=1) | Yes | `USE_PTO_KDA` | `fused_recurrent_kda` (torch `_naive_recurrent_kda`) | Uses `kda_fused_decode` (full layer fusion incl. projections); requires prefill-seeded conv/recurrent states; graph mode via `kda_decode_graph.py` | | 22 | +| KDA decode (T=1) | No | — | `fused_recurrent_kda` (torch `_naive_recurrent_kda`) | 仅 pto 化 chunk/prefill 路径;decode 走上游 torch recurrent | |
| 23 | | FusedRMSNormGated | No | — | torch `FusedRMSNormGated` | 后注意力门控归一化 | | 23 | | FusedRMSNormGated | No | — | torch `FusedRMSNormGated` | 后注意力门控归一化 | |
| 24 | | ShortConvolution | No | — | torch causal depthwise conv1d | KDA 前处理因果卷积 | | 24 | | ShortConvolution | No | — | torch causal depthwise conv1d | KDA 前处理因果卷积 | |
| 25 | | 全注意力 (MLA) | No | — | eager / sdpa | 标准 HuggingFace 注意力 | | 25 | | 全注意力 (MLA) | No | — | eager / sdpa | 标准 HuggingFace 注意力 | |
| @@ -64,8 +64,8 @@ kernel 模块通过 `sys.modules["kimi_linear_48b_a3b_pto_kernels"]` 暴露: | |||
| 64 | 64 | ||
| 65 | | Variable | Type | Default | 说明 | | 65 | | Variable | Type | Default | 说明 | |
| 66 | |----------|------|---------|------| | 66 | |----------|------|---------|------| |
| 67 | -| `USE_PTO_KDA` | `bool` | `False` | Enables the PyPTO fused prefill kernel | | 67 | +| `USE_PTO_KDA` | `bool` | `False` | 启用 PyPTO 融合 KDA chunk kernel (prefill) | |
| 68 | -| `kda_fused_prefill` | callable | — | Fused prefill wrapper (`@allow_in_graph`) | | 68 | +| `kda_chunk_wrapper` | callable | — | FLA-layout chunk wrapper(`@allow_in_graph`) | |
| 69 | 69 | ||
| 70 | ask 脚本在 `from transformers import` 之前 `sys.path.insert(0, ...)` 并 | 70 | ask 脚本在 `from transformers import` 之前 `sys.path.insert(0, ...)` 并 |
| 71 | `import kimi_linear_48b_a3b_pto_kernels`,`--use_pypto` 时置 `USE_PTO_KDA = True`。 | 71 | `import kimi_linear_48b_a3b_pto_kernels`,`--use_pypto` 时置 `USE_PTO_KDA = True`。 |
| @@ -87,7 +87,6 @@ ask 脚本在 `from transformers import` 之前 `sys.path.insert(0, ...)` 并 | |||
| 87 | | `configuration_kimi.py` | `KimiLinearConfig`(原样拷贝,未改) | | 87 | | `configuration_kimi.py` | `KimiLinearConfig`(原样拷贝,未改) | |
| 88 | | `kimi_fla_compat.py` | `fla` 的纯 torch 替代(非 KDA helpers + torch 基线 KDA op) | | 88 | | `kimi_fla_compat.py` | `fla` 的纯 torch 替代(非 KDA helpers + torch 基线 KDA op) | |
| 89 | | `modeling_kimi.py` | 模型图:`KimiDeltaAttention` 等;KDA chunk/decode 的 sys.modules 注入分发 | | 89 | | `modeling_kimi.py` | 模型图:`KimiDeltaAttention` 等;KDA chunk/decode 的 sys.modules 注入分发 | |
| 90 | -| `kda_decode_graph.py` | `StaticDecodeCache` — graph-capturable decode cache,接线 fused decode op | | ||
| 91 | 90 | ||
| 92 | ## 相关目录 | 91 | ## 相关目录 |
| 93 | 92 | ||
| @@ -519,71 +519,40 @@ class KimiMLAAttention(nn.Module): | |||
| 519 | ) | 519 | ) |
| 520 | 520 | ||
| 521 | 521 | ||
| 522 | -def _run_kda(mode, kda_kwargs): | 522 | +def _dispatch_kda(primary_fn, fallback_fn, kda_kwargs): |
| 523 | - """Run the REFERENCE KDA op for this forward -> (o, recurrent_state). | 523 | + """Run the KDA op, falling back to the torch implementation if the PyPTO |
| 524 | + wrapper raises NotImplementedError (off-bound-device or unsupported shape).""" | ||
| 525 | + try: | ||
| 526 | + return primary_fn(**kda_kwargs) | ||
| 527 | + except NotImplementedError: | ||
| 528 | + return fallback_fn(**kda_kwargs) | ||
| 524 | 529 | ||
| 525 | - Upstream FLA/torch only: ``fused_recurrent_kda`` for the T<=64 decode | 530 | + |
| 526 | - branch, ``chunk_kda`` for prefill. The PyPTO dispatch happens one level up, | 531 | +def _run_kda(mode, kda_kwargs): |
| 527 | - at the fused-subgraph level (_try_kda_fused_prefill), which replaces the | 532 | + """Select the KDA backend for this forward and run it -> (o, recurrent_state). |
| 528 | - whole conv -> gate -> beta -> chunk -> o_norm block; this function only | 533 | + |
| 529 | - runs when that fused path is ineligible (varlen/masked batch, training, | 534 | + Factored out of KimiDeltaAttention.forward so our PyPTO dispatch guard |
| 530 | - K != 128, USE_PTO_KDA off). | 535 | + (USE_PTO_KDA / USE_PTO_KDA_GRAPH) lives here rather than adding branches to |
| 536 | + the vendored forward. KDA PyPTO covers prefill (chunk) only; decode (T<=64, | ||
| 537 | + 'fused_recurrent') always takes the upstream torch path. | ||
| 531 | """ | 538 | """ |
| 532 | if mode != 'chunk': | 539 | if mode != 'chunk': |
| 533 | - return fused_recurrent_kda(**kda_kwargs) | 540 | + return _dispatch_kda(fused_recurrent_kda, fused_recurrent_kda, kda_kwargs) |
| 534 | - return chunk_kda(**kda_kwargs) | ||
| 535 | - | ||
| 536 | - | ||
| 537 | -def _try_kda_fused_prefill(layer, hidden_states, cache_params, attention_mask, | ||
| 538 | - cu_seqlens): | ||
| 539 | - """Try the fused PyPTO KDA prefill path. | ||
| 540 | - | ||
| 541 | - Returns the final projected output, or None when the fused path is | ||
| 542 | - disabled/ineligible/unsupported (the wrapper raises NotImplementedError | ||
| 543 | - for out-of-envelope shapes; caught here).""" | ||
| 544 | - batch_size, q_len = hidden_states.shape[0], hidden_states.shape[1] | ||
| 545 | - if q_len <= 64 or attention_mask is not None or cu_seqlens is not None: | ||
| 546 | - return None | ||
| 547 | - if layer.training: | ||
| 548 | - return None | ||
| 549 | pto = sys.modules.get("kimi_linear_48b_a3b_pto_kernels") | 541 | pto = sys.modules.get("kimi_linear_48b_a3b_pto_kernels") |
| 550 | - if pto is None or not getattr(pto, "USE_PTO_KDA", False): | 542 | + # NPU-graph capture path: call the registered PyPTO op DIRECTLY (no |
| 551 | - return None | 543 | + # _dispatch_kda try/except — a host-raised exception is not capturable). |
| 552 | - if not hasattr(pto, "kda_fused_prefill"): | 544 | + # Guarded by USE_PTO_KDA_GRAPH (off by default). The bench only sets this |
| 553 | - return None | 545 | + # for the captured region where cache_params is None, so initial_state and |
| 554 | - from ops.pypto_tensor.kimi_linear_48b_a3b.kda.kda_fused_prefill_impl import ( | 546 | + # cu_seqlens are None and kda_chunk_pypto's reduced signature applies. |
| 555 | - KdaPrefillInputs, KdaPrefillWeights) | 547 | + if pto is not None and getattr(pto, "USE_PTO_KDA_GRAPH", False): |
| 556 | - inputs = KdaPrefillInputs( | 548 | + return pto.kda_chunk_pypto( |
| 557 | - q=layer.q_proj(hidden_states).view(batch_size, q_len, layer.num_heads, layer.head_dim), | 549 | + q=kda_kwargs["q"], k=kda_kwargs["k"], v=kda_kwargs["v"], |
| 558 | - k=layer.k_proj(hidden_states).view(batch_size, q_len, layer.num_heads, layer.head_dim), | 550 | + g=kda_kwargs["g"], beta=kda_kwargs["beta"], |
| 559 | - v=layer.v_proj(hidden_states).view(batch_size, q_len, layer.num_heads, layer.head_dim), | 551 | + initial_state=kda_kwargs["initial_state"], use_qk_l2norm_in_kernel=True) |
| 560 | - g_raw=layer.f_b_proj(layer.f_a_proj(hidden_states)), | 552 | + primary_fn = chunk_kda |
| 561 | - g_gate=layer.g_b_proj(layer.g_a_proj(hidden_states)), | 553 | + if pto is not None and getattr(pto, "USE_PTO_KDA", False): |
| 562 | - b_raw=layer.b_proj(hidden_states)) | 554 | + primary_fn = pto.kda_chunk_wrapper |
| 563 | - weights = KdaPrefillWeights( | 555 | + return _dispatch_kda(primary_fn, chunk_kda, kda_kwargs) |
| 564 | - dt_bias=layer.dt_bias, a_log=layer.A_log, o_norm_w=layer.o_norm.weight, | ||
| 565 | - conv_wq=layer.q_conv1d.weight.reshape(-1, layer.conv_size), | ||
| 566 | - conv_wk=layer.k_conv1d.weight.reshape(-1, layer.conv_size), | ||
| 567 | - conv_wv=layer.v_conv1d.weight.reshape(-1, layer.conv_size), | ||
| 568 | - lower_bound=getattr(layer.config, "gate_lower_bound", -5.0), | ||
| 569 | - rms_eps=layer.o_norm.eps) | ||
| 570 | - conv_cache = None | ||
| 571 | - recurrent_state = None | ||
| 572 | - if cache_params is not None: | ||
| 573 | - if cache_params.conv_states[layer.layer_idx] is not None: | ||
| 574 | - conv_cache = cache_params.conv_states[layer.layer_idx] | ||
| 575 | - recurrent_state = cache_params.recurrent_states[layer.layer_idx] | ||
| 576 | - try: | ||
| 577 | - o, st, cs = pto.kda_fused_prefill( | ||
| 578 | - inputs, weights, | ||
| 579 | - initial_state=recurrent_state, output_final_state=True, | ||
| 580 | - conv_cache=conv_cache) | ||
| 581 | - except NotImplementedError: | ||
| 582 | - return None | ||
| 583 | - if cache_params is not None: | ||
| 584 | - cache_params.recurrent_states[layer.layer_idx] = st | ||
| 585 | - cache_params.conv_states[layer.layer_idx] = cs | ||
| 586 | - return layer.o_proj(o.reshape(batch_size, q_len, -1)) | ||
| 587 | 556 | ||
| 588 | 557 | ||
| 589 | class Conv1dResult(NamedTuple): | 558 | class Conv1dResult(NamedTuple): |
| @@ -760,14 +729,6 @@ class KimiDeltaAttention(nn.Module): | |||
| 760 | raise ValueError("Only chunk mode is supported in training.") | 729 | raise ValueError("Only chunk mode is supported in training.") |
| 761 | 730 | ||
| 762 | cu_seqlens = kwargs.get('cu_seqlens') | 731 | cu_seqlens = kwargs.get('cu_seqlens') |
| 763 | - | ||
| 764 | - # Fused PyPTO prefill (conv+gate+beta+chunk+o_norm in one kernel). | ||
| 765 | - # Returns None (ineligible / NotImplementedError) -> standard path. | ||
| 766 | - fused = _try_kda_fused_prefill(self, hidden_states, cache_params, | ||
| 767 | - attention_mask, cu_seqlens) | ||
| 768 | - if fused is not None: | ||
| 769 | - return fused | ||
| 770 | - | ||
| 771 | indices = None | 732 | indices = None |
| 772 | if attention_mask is not None: | 733 | if attention_mask is not None: |
| 773 | indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:]) | 734 | indices, cu_seqlens, _ = get_unpad_data(attention_mask[:, -q_len:]) |
| @@ -783,6 +744,17 @@ class KimiDeltaAttention(nn.Module): | |||
| 783 | x, '... (h d) -> ... h d', d=self.head_k_dim), (r.q, r.k)) | 744 | x, '... (h d) -> ... h d', d=self.head_k_dim), (r.q, r.k)) |
| 784 | v = rearrange(r.v, '... (h d) -> ... h d', d=self.head_dim) | 745 | v = rearrange(r.v, '... (h d) -> ... h d', d=self.head_dim) |
| 785 | 746 | ||
| 747 | + # PyPTO injection (via sys.modules): swap in the fused KDA kernel when | ||
| 748 | + # enabled and shape constraints are met; otherwise fall back to the | ||
| 749 | + # torch chunk / recurrent function. | ||
| 750 | + # | ||
| 751 | + # NOTE(multi-NPU coverage): the wrapper raises NotImplementedError (caught | ||
| 752 | + # below) for any KDA layer whose tensors are NOT on the single NPU PyPTO is | ||
| 753 | + # bound to. So under a single-process device_map shard, only the bound NPU's | ||
| 754 | + # KDA layers run on PyPTO (e.g. ~6 of 20 with 4-way sharding) and the rest | ||
| 755 | + # take this torch fallback. The wrapper emits a one-time RuntimeWarning so | ||
| 756 | + # this is not silent. Note (future work): for full 20/20 PyPTO coverage run | ||
| 757 | + # one process per NPU (pipeline / tensor parallel); see kda/README.md. | ||
| 786 | kda_kwargs = dict( | 758 | kda_kwargs = dict( |
| 787 | q=q, k=k, v=v, g=g, beta=beta, initial_state=r.recurrent_state, | 759 | q=q, k=k, v=v, g=g, beta=beta, initial_state=r.recurrent_state, |
| 788 | output_final_state=True, use_qk_l2norm_in_kernel=True, cu_seqlens=cu_seqlens) | 760 | output_final_state=True, use_qk_l2norm_in_kernel=True, cu_seqlens=cu_seqlens) |
| @@ -6,21 +6,28 @@ | |||
| 6 | # INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | 6 | # INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. |
| 7 | # See LICENSE in the root of the software repository for the full text of the License. | 7 | # See LICENSE in the root of the software repository for the full text of the License. |
| 8 | # ----------------------------------------------------------------------------------------------------------- | 8 | # ----------------------------------------------------------------------------------------------------------- |
| 9 | -"""Shared scaffold for the KDA op tests. | 9 | +"""Shared scaffold for the KDA chunk op tests. |
| 10 | 10 | ||
| 11 | -Holds the common imports, the ``_HAS_NPU`` torch_npu detection, the logging | 11 | +Holds the boilerplate ``test_kda_chunk.py`` uses: the common imports, the |
| 12 | -config, the sys.path inserts for the impl + golden dirs, and the golden op | 12 | +``_HAS_NPU`` torch_npu detection, the logging config, the sys.path inserts for |
| 13 | -import. Input builders live in each test (they differ per operator ABI). | 13 | +the impl + golden dirs, and the golden op import. |
| 14 | """ | 14 | """ |
| 15 | 15 | ||
| 16 | -__all__ = ["_HAS_NPU", "torch_npu", "_naive_recurrent_kda", | 16 | +__all__ = ["_HAS_NPU", "torch_npu", "_naive_recurrent_kda", "make_kda_inputs", |
| 17 | + "KdaCase", "KdaInputs", "chunk_grid", | ||
| 17 | "HEAD_DIM", "RTOL", "ATOL"] | 18 | "HEAD_DIM", "RTOL", "ATOL"] |
| 18 | 19 | ||
| 19 | import logging | 20 | import logging |
| 20 | import sys | 21 | import sys |
| 22 | +from dataclasses import dataclass | ||
| 21 | from pathlib import Path | 23 | from pathlib import Path |
| 24 | +from typing import NamedTuple, Optional | ||
| 22 | 25 | ||
| 23 | -# Single source of truth for the op-test envelope. | 26 | +import torch |
| 27 | + | ||
| 28 | +# Single source of truth for the op-test envelope. The chunk tests | ||
| 29 | +# iterate these grids AND test_cases_sync.py asserts test_cases.json documents | ||
| 30 | +# exactly the same set — so the JSON cannot silently drift from what runs. | ||
| 24 | HEAD_DIM = 128 # head_k_dim == head_v_dim (real Kimi config) | 31 | HEAD_DIM = 128 # head_k_dim == head_v_dim (real Kimi config) |
| 25 | RTOL = ATOL = 6e-3 # tolerance vs the fp32 naive-recurrent golden | 32 | RTOL = ATOL = 6e-3 # tolerance vs the fp32 naive-recurrent golden |
| 26 | 33 | ||
| @@ -34,7 +41,7 @@ except ImportError: | |||
| 34 | logging.info("torch_npu not available; this test only runs on Ascend NPU.") | 41 | logging.info("torch_npu not available; this test only runs on Ascend NPU.") |
| 35 | _HAS_NPU = False | 42 | _HAS_NPU = False |
| 36 | 43 | ||
| 37 | -# impl lives under ops/.../kimi_linear_48b_a3b/kda; golden is same-dir. | 44 | +# impl lives under src/.../kimi_linear_48b_a3b/kda; golden is same-dir. |
| 38 | _IMPL = (Path(__file__).resolve().parents[3] | 45 | _IMPL = (Path(__file__).resolve().parents[3] |
| 39 | / "ops" / "pypto_tensor" / "kimi_linear_48b_a3b" / "kda") | 46 | / "ops" / "pypto_tensor" / "kimi_linear_48b_a3b" / "kda") |
| 40 | sys.path.insert(0, str(_IMPL)) | 47 | sys.path.insert(0, str(_IMPL)) |
| @@ -42,3 +49,65 @@ sys.path.insert(0, str(Path(__file__).resolve().parent)) | |||
| 42 | 49 | ||
| 43 | from kda_golden import _naive_recurrent_kda # noqa: E402 | 50 | from kda_golden import _naive_recurrent_kda # noqa: E402 |
| 44 | 51 | ||
| 52 | + | ||
| 53 | +@dataclass | ||
| 54 | +class KdaCase: | ||
| 55 | + """Spec for one KDA test case (shared by the chunk tests). | ||
| 56 | + | ||
| 57 | + gate: 'rand' -> realistic log-gate g=-5*rand in [-5,0]; 'ones' -> worst-case | ||
| 58 | + g=-5 everywhere. | ||
| 59 | + """ | ||
| 60 | + batch: int | ||
| 61 | + num_heads: int | ||
| 62 | + seq_len: int | ||
| 63 | + with_state: bool = True | ||
| 64 | + gate: str = "rand" | ||
| 65 | + dtype: torch.dtype = torch.bfloat16 | ||
| 66 | + seed: int = 0 | ||
| 67 | + | ||
| 68 | + | ||
| 69 | +class KdaInputs(NamedTuple): | ||
| 70 | + """Tensors for one KDA case, as built by ``make_kda_inputs``.""" | ||
| 71 | + q: torch.Tensor | ||
| 72 | + k: torch.Tensor | ||
| 73 | + v: torch.Tensor | ||
| 74 | + g: torch.Tensor | ||
| 75 | + beta: torch.Tensor | ||
| 76 | + h0: Optional[torch.Tensor] | ||
| 77 | + scale: float | ||
| 78 | + | ||
| 79 | + | ||
| 80 | +def make_kda_inputs(case, dev): | ||
| 81 | + """Build a reproducible ``KdaInputs`` for ``case`` on device ``dev``.""" | ||
| 82 | + torch.manual_seed(case.seed) | ||
| 83 | + head_k_dim = head_v_dim = 128 | ||
| 84 | + b, h, t, dt = case.batch, case.num_heads, case.seq_len, case.dtype | ||
| 85 | + q = (torch.randn(b, t, h, head_k_dim) * 0.5).to(dt).to(dev) | ||
| 86 | + k = (torch.randn(b, t, h, head_k_dim) * 0.5).to(dt).to(dev) | ||
| 87 | + v = (torch.randn(b, t, h, head_v_dim) * 0.5).to(dt).to(dev) | ||
| 88 | + # NOTE: probed from KimiDeltaAttention.forward (see test_cases.json "probe"): | ||
| 89 | + # the real model emits g in fp32 (fused_kda_gate) and beta in fp32 | ||
| 90 | + # (.float().sigmoid()), while q/k/v are bf16. Match those real dtypes. | ||
| 91 | + if case.gate == "ones": | ||
| 92 | + g = (-5.0 * torch.ones(b, t, h, head_k_dim)).to(torch.float32).to(dev) | ||
| 93 | + else: | ||
| 94 | + g = (-5.0 * torch.rand(b, t, h, head_k_dim)).to(torch.float32).to(dev) | ||
| 95 | + beta = torch.sigmoid(torch.randn(b, t, h)).to(torch.float32).to(dev) | ||
| 96 | + h0 = (torch.randn(b, h, head_v_dim, head_k_dim) * 0.3).float().to(dev) if case.with_state else None | ||
| 97 | + scale = head_k_dim ** -0.5 | ||
| 98 | + return KdaInputs(q, k, v, g, beta, h0, scale) | ||
| 99 | + | ||
| 100 | + | ||
| 101 | +def chunk_grid(): | ||
| 102 | + """Return the 42-case chunk/prefill op-test grid (shared with test_cases_sync).""" | ||
| 103 | + cases = [] | ||
| 104 | + # realistic gate then worst-case g=-5 gate; seq_len/batch/heads sweep. | ||
| 105 | + for gate in ("rand", "ones"): | ||
| 106 | + for seq_len in (64, 128, 300, 512, 1000): | ||
| 107 | + for batch in (1, 2): | ||
| 108 | + for num_heads in (4, 32): | ||
| 109 | + cases.append(KdaCase(batch, num_heads, seq_len, gate=gate)) | ||
| 110 | + # no-initial-state path. | ||
| 111 | + cases.append(KdaCase(1, 4, 128, with_state=False, gate="rand")) | ||
| 112 | + cases.append(KdaCase(1, 32, 300, with_state=False, gate="rand")) | ||
| 113 | + return cases | ||
| @@ -0,0 +1,95 @@ | |||
| 1 | +# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 9 | +"""Contract test: ``test_cases.json`` documents EXACTLY the op-test run grid. | ||
| 10 | + | ||
| 11 | +``test_cases.json`` is a descriptive file — ``test_kda_chunk.py`` drives its grid | ||
| 12 | +directly from ``_kda_test_common.chunk_grid`` and does **not** read the JSON. That | ||
| 13 | +left the JSON free to drift from what actually runs (it did: the no-initial-state | ||
| 14 | +cases were mis-documented as having an ``initial_state``). This test closes that | ||
| 15 | +gap by asserting the JSON documents exactly the same set of cases and the same | ||
| 16 | +shape/dtype/tolerance/scale envelope. It needs no NPU, so it runs everywhere. | ||
| 17 | +""" | ||
| 18 | + | ||
| 19 | +import json | ||
| 20 | +import logging | ||
| 21 | +from pathlib import Path | ||
| 22 | + | ||
| 23 | +from _kda_test_common import chunk_grid, HEAD_DIM, RTOL, ATOL | ||
| 24 | + | ||
| 25 | +logging.basicConfig(level=logging.INFO, format="%(message)s") | ||
| 26 | + | ||
| 27 | +_JSON = Path(__file__).resolve().parent / "test_cases.json" | ||
| 28 | + | ||
| 29 | + | ||
| 30 | +def _case_key(case): | ||
| 31 | + """(B, H, T, gate, with_state) identity of a run-grid KdaCase.""" | ||
| 32 | + return (case.batch, case.num_heads, case.seq_len, case.gate, case.with_state) | ||
| 33 | + | ||
| 34 | + | ||
| 35 | +def _json_key(c): | ||
| 36 | + """Same identity, read back from a test_cases.json entry (q is [B,T,H,K]).""" | ||
| 37 | + q = c["input"]["q"]["shape"] | ||
| 38 | + has_state = c["input"].get("initial_state") is not None | ||
| 39 | + return (q[0], q[2], q[1], c["gate"], has_state) | ||
| 40 | + | ||
| 41 | + | ||
| 42 | +def test_cases_json_matches_grid(): | ||
| 43 | + data = json.loads(_JSON.read_text()) | ||
| 44 | + tc = data["test_cases"] | ||
| 45 | + by_key = {_case_key(c): c for c in chunk_grid()} | ||
| 46 | + | ||
| 47 | + for label, grid, cases in ( | ||
| 48 | + ("chunk", chunk_grid(), [c for c in tc if c["id"].startswith("chunk")]),): | ||
| 49 | + want = {_case_key(c) for c in grid} | ||
| 50 | + got = {_json_key(c) for c in cases} | ||
| 51 | + assert len(grid) == len(cases), ( | ||
| 52 | + f"{label}: run grid has {len(grid)} cases, test_cases.json has {len(cases)}") | ||
| 53 | + assert want == got, ( | ||
| 54 | + f"{label}: test_cases.json case set != run grid.\n" | ||
| 55 | + f" only in grid: {sorted(want - got)}\n" | ||
| 56 | + f" only in json: {sorted(got - want)}") | ||
| 57 | + | ||
| 58 | + for c in tc: | ||
| 59 | + inp = c["input"] | ||
| 60 | + cid = c["id"] | ||
| 61 | + for t in ("q", "k", "v"): | ||
| 62 | + assert inp[t]["dtype"] == "bfloat16", f"{cid}: {t} must be bf16 (real model)" | ||
| 63 | + assert inp["g"]["dtype"] == "float32", f"{cid}: g must be fp32 (fused_kda_gate)" | ||
| 64 | + assert inp["beta"]["dtype"] == "float32", f"{cid}: beta must be fp32 (.float().sigmoid())" | ||
| 65 | + assert inp["q"]["shape"][-1] == HEAD_DIM and inp["v"]["shape"][-1] == HEAD_DIM, \ | ||
| 66 | + f"{cid}: head dim must be {HEAD_DIM}" | ||
| 67 | + assert abs(c["rtol"] - RTOL) < 1e-12 and abs(c["atol"] - ATOL) < 1e-12, \ | ||
| 68 | + f"{cid}: tolerance must be rtol=atol={RTOL}" | ||
| 69 | + assert abs(inp["scale"]["value"] - HEAD_DIM ** -0.5) < 1e-12, \ | ||
| 70 | + f"{cid}: scale must be HEAD_DIM**-0.5" | ||
| 71 | + case = by_key[_json_key(c)] | ||
| 72 | + b, t, h = case.batch, case.seq_len, case.num_heads | ||
| 73 | + assert inp["q"]["shape"] == [b, t, h, HEAD_DIM], f"{cid}: q shape" | ||
| 74 | + assert inp["beta"]["shape"] == [b, t, h], f"{cid}: beta shape" | ||
| 75 | + if case.with_state: | ||
| 76 | + assert inp.get("initial_state") is not None, \ | ||
| 77 | + f"{cid}: with_state case must document initial_state" | ||
| 78 | + assert inp["initial_state"]["shape"] == [b, h, HEAD_DIM, HEAD_DIM], \ | ||
| 79 | + f"{cid}: initial_state shape" | ||
| 80 | + else: | ||
| 81 | + assert inp.get("initial_state") is None, \ | ||
| 82 | + f"{cid}: no-state case must have initial_state null/absent" | ||
| 83 | + | ||
| 84 | + logging.info(f"[sync] test_cases.json documents exactly {len(tc)} cases, " | ||
| 85 | + f"matching the chunk_grid() run set") | ||
| 86 | + | ||
| 87 | + | ||
| 88 | +def main(): | ||
| 89 | + test_cases_json_matches_grid() | ||
| 90 | + logging.info("[PRECISION_PASS]") | ||
| 91 | + logging.info("All tests passed!") | ||
| 92 | + | ||
| 93 | + | ||
| 94 | +if __name__ == "__main__": | ||
| 95 | + main() | ||
| @@ -0,0 +1,141 @@ | |||
| 1 | +# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 9 | +"""ACLGraph / torch.library registration test for the KDA kernels. | ||
| 10 | + | ||
| 11 | +The chunk kernel is registered as ``pypto::kda_chunk_kimi`` | ||
| 12 | +(Meta + NPU keys) so they can be captured by torch.compile / aclgraph. This test | ||
| 13 | +asserts two properties of that registration without needing torchair: | ||
| 14 | + | ||
| 15 | +1. **Op == wrapper** — the registered NPU op (`kda_*_pypto`) returns bit-for-bit | ||
| 16 | + the same result as the eager `kda_*_wrapper` it delegates to, so routing the | ||
| 17 | + model through the registered op under aclgraph cannot change numerics. | ||
| 18 | +2. **Meta shape inference** — the Meta ("fake") impl produces the correct output | ||
| 19 | + shapes/dtypes under ``FakeTensorMode`` (what the graph tracer relies on), so a | ||
| 20 | + capture pass can infer shapes without launching the kernel. | ||
| 21 | +""" | ||
| 22 | + | ||
| 23 | +import logging | ||
| 24 | +import os | ||
| 25 | + | ||
| 26 | +import torch | ||
| 27 | + | ||
| 28 | +import pypto | ||
| 29 | + | ||
| 30 | +from _kda_test_common import _HAS_NPU, torch_npu, make_kda_inputs, KdaCase | ||
| 31 | + | ||
| 32 | +from kda_chunk_impl import kda_chunk_wrapper, kda_chunk_pypto | ||
| 33 | + | ||
| 34 | + | ||
| 35 | +def _assert_identical(a, b, name): | ||
| 36 | + assert torch.equal(a.cpu(), b.cpu()), f"{name}: registered op != wrapper (not bit-identical)" | ||
| 37 | + | ||
| 38 | + | ||
| 39 | +def test_registered_op_matches_wrapper(npu_device): | ||
| 40 | + """The registered NPU op must equal the eager wrapper, bit-for-bit.""" | ||
| 41 | + for case, wrapper, pypto_fn, tag in ( | ||
| 42 | + (KdaCase(1, 4, 128, gate="rand"), kda_chunk_wrapper, kda_chunk_pypto, "chunk"),): | ||
| 43 | + q, k, v, g, beta, h0, scale = make_kda_inputs(case, npu_device) | ||
| 44 | + ow, sw = wrapper(q, k, v, g, beta, h0, scale=scale) | ||
| 45 | + op, sp = pypto_fn(q, k, v, g, beta, initial_state=h0, scale=scale) | ||
| 46 | + _assert_identical(op.float(), ow.float(), f"{tag} out") | ||
| 47 | + _assert_identical(sp, sw, f"{tag} state") | ||
| 48 | + logging.info(f"[aclgraph {tag}] registered pypto::kda_{tag}_kimi == wrapper (bit-identical)") | ||
| 49 | + | ||
| 50 | + | ||
| 51 | +def test_torch_compile_fullgraph(npu_device): | ||
| 52 | + """Registered op composes into a torch.compile fullgraph (no graph break), bit-exact.""" | ||
| 53 | + # aot_eager exercises Meta fake-prop + the NPU impl, which a capture pass relies on. | ||
| 54 | + # The real torchair aclgraph (reduce-overhead) capture is covered by | ||
| 55 | + # test_aclgraph_capture; torchair GE-graph mode would still need a per-op GE converter. | ||
| 56 | + q, k, v, g, beta, h0, scale = make_kda_inputs(KdaCase(1, 4, 128, gate="rand"), npu_device) | ||
| 57 | + | ||
| 58 | + class _M(torch.nn.Module): | ||
| 59 | + def forward(self, q, k, v, g, beta, h0): | ||
| 60 | + return kda_chunk_pypto(q, k, v, g, beta, initial_state=h0, scale=scale) | ||
| 61 | + | ||
| 62 | + m = _M() | ||
| 63 | + eo, es = m(q, k, v, g, beta, h0) | ||
| 64 | + for backend in ("aot_eager", "eager"): | ||
| 65 | + cm = torch.compile(m, backend=backend, fullgraph=True, dynamic=False) | ||
| 66 | + co, cs = cm(q, k, v, g, beta, h0) | ||
| 67 | + _assert_identical(co.float(), eo.float(), f"compile[{backend}] out") | ||
| 68 | + _assert_identical(cs, es, f"compile[{backend}] state") | ||
| 69 | + logging.info(f"[aclgraph compile] fullgraph torch.compile(backend={backend}) " | ||
| 70 | + f"traces pypto::kda_chunk_kimi with no graph break (bit-exact)") | ||
| 71 | + | ||
| 72 | + | ||
| 73 | +def test_meta_shape_inference(): | ||
| 74 | + """The Meta impl infers output shapes/dtypes under FakeTensorMode.""" | ||
| 75 | + from torch._subclasses.fake_tensor import FakeTensorMode | ||
| 76 | + dev = "npu" if _HAS_NPU else "cpu" | ||
| 77 | + b, t, h, d = 1, 100, 32, 128 | ||
| 78 | + with FakeTensorMode(): | ||
| 79 | + q = torch.empty(b, t, h, d, dtype=torch.bfloat16, device=dev) | ||
| 80 | + k = torch.empty(b, t, h, d, dtype=torch.bfloat16, device=dev) | ||
| 81 | + v = torch.empty(b, t, h, d, dtype=torch.bfloat16, device=dev) | ||
| 82 | + gg = torch.empty(b, t, h, d, dtype=torch.float32, device=dev) | ||
| 83 | + beta = torch.empty(b, t, h, dtype=torch.float32, device=dev) | ||
| 84 | + out, st = torch.ops.pypto.kda_chunk_kimi(q, k, v, gg, beta, None, d ** -0.5, True) | ||
| 85 | + assert tuple(out.shape) == (b, t, h, d) and out.dtype == torch.bfloat16, "chunk meta out" | ||
| 86 | + assert tuple(st.shape) == (b, h, d, d) and st.dtype == torch.float32, "chunk meta state" | ||
| 87 | + logging.info("[aclgraph meta] Meta shape inference OK for kda_chunk_kimi") | ||
| 88 | + | ||
| 89 | + | ||
| 90 | +def test_aclgraph_capture(npu_device): | ||
| 91 | + """Real torchair aclgraph (reduce-overhead) capture + replay is bit-exact. | ||
| 92 | + | ||
| 93 | + This is the end-to-end proof that the registered op is graph-capturable: it | ||
| 94 | + works because the wrapper does NOT call torch_npu.npu.synchronize() (which | ||
| 95 | + would abort capture); the kernel is stream-ordered instead. Skips cleanly if | ||
| 96 | + torchair is unavailable. | ||
| 97 | + """ | ||
| 98 | + try: | ||
| 99 | + import torchair | ||
| 100 | + except ImportError: | ||
| 101 | + logging.info("[aclgraph capture] torchair unavailable; skipped") | ||
| 102 | + return | ||
| 103 | + q, k, v, g, beta, h0, scale = make_kda_inputs(KdaCase(1, 4, 128, gate="rand"), npu_device) | ||
| 104 | + | ||
| 105 | + class _M(torch.nn.Module): | ||
| 106 | + def forward(self, q, k, v, g, beta, h0): | ||
| 107 | + return kda_chunk_pypto(q, k, v, g, beta, initial_state=h0, scale=scale) | ||
| 108 | + | ||
| 109 | + m = _M() | ||
| 110 | + eo, es = m(q, k, v, g, beta, h0) | ||
| 111 | + cfg = torchair.CompilerConfig() | ||
| 112 | + cfg.mode = "reduce-overhead" # aclgraph / npugraph capture | ||
| 113 | + cm = torch.compile(m, backend=torchair.get_npu_backend(compiler_config=cfg), dynamic=False) | ||
| 114 | + for _ in range(3): # warmup capture + replays | ||
| 115 | + co, cs = cm(q, k, v, g, beta, h0) | ||
| 116 | + _assert_identical(co.float(), eo.float(), "aclgraph capture out") | ||
| 117 | + _assert_identical(cs, es, "aclgraph capture state") | ||
| 118 | + logging.info("[aclgraph capture] torchair reduce-overhead capture+replay bit-exact (diff=0)") | ||
| 119 | + | ||
| 120 | + | ||
| 121 | +def main(): | ||
| 122 | + pypto.set_host_options(compile_monitor_enable=1, compile_timeout=10, | ||
| 123 | + compile_timeout_stage=5, | ||
| 124 | + compile_monitor_print_interval=2) | ||
| 125 | + test_meta_shape_inference() | ||
| 126 | + if not _HAS_NPU: | ||
| 127 | + logging.info("skip NPU op-equality check: no NPU") | ||
| 128 | + return | ||
| 129 | + torch_npu.npu.config.allow_internal_format = True | ||
| 130 | + device_id = int(os.environ.get("TILE_FWK_DEVICE_ID", 0)) | ||
| 131 | + torch.npu.set_device(device_id) | ||
| 132 | + npu_device = f"npu:{device_id}" | ||
| 133 | + test_registered_op_matches_wrapper(npu_device) | ||
| 134 | + test_torch_compile_fullgraph(npu_device) | ||
| 135 | + test_aclgraph_capture(npu_device) | ||
| 136 | + logging.info("[PRECISION_PASS]") | ||
| 137 | + logging.info("All tests passed!") | ||
| 138 | + | ||
| 139 | + | ||
| 140 | +if __name__ == "__main__": | ||
| 141 | + main() | ||
| @@ -0,0 +1,74 @@ | |||
| 1 | +# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd. | ||
| 2 | +# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | +# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | +# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | +# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | +# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | +# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | +# ----------------------------------------------------------------------------------------------------------- | ||
| 9 | +"""Numerical test for the kimi_linear_48b_a3b KDA chunk/prefill PyPTO kernel.""" | ||
| 10 | + | ||
| 11 | +import logging | ||
| 12 | +import os | ||
| 13 | + | ||
| 14 | +import numpy as np | ||
| 15 | +import torch | ||
| 16 | + | ||
| 17 | +import pypto | ||
| 18 | + | ||
| 19 | +from _kda_test_common import _HAS_NPU, torch_npu, _naive_recurrent_kda, make_kda_inputs, chunk_grid | ||
| 20 | + | ||
| 21 | +from kda_chunk_impl import kda_chunk_wrapper | ||
| 22 | + | ||
| 23 | + | ||
| 24 | +def run_case(case, dev): | ||
| 25 | + """Run one chunk-kernel case and assert it matches the golden recurrent op.""" | ||
| 26 | + q, k, v, g, beta, h0, scale = make_kda_inputs(case, dev) | ||
| 27 | + | ||
| 28 | + og, sg = _naive_recurrent_kda(q, k, v, g, beta, initial_state=h0, | ||
| 29 | + output_final_state=True, | ||
| 30 | + use_qk_l2norm_in_kernel=True, scale=scale) | ||
| 31 | + op, sp = kda_chunk_wrapper(q, k, v, g, beta, h0, scale=scale) | ||
| 32 | + | ||
| 33 | + name = f"B{case.batch}H{case.num_heads}T{case.seq_len}_state{case.with_state}_g{case.gate}" | ||
| 34 | + out_diff = (op.cpu().float() - og.cpu().float()).abs().max().item() | ||
| 35 | + st_diff = (sp.cpu().float() - sg.cpu().float()).abs().max().item() | ||
| 36 | + logging.info(f"[{name}] out.max_diff={out_diff:.3e} state.max_diff={st_diff:.3e}") | ||
| 37 | + | ||
| 38 | + np.testing.assert_allclose(op.cpu().float().numpy(), og.cpu().float().numpy(), | ||
| 39 | + rtol=6e-3, atol=6e-3, err_msg=f"{name}: out mismatch") | ||
| 40 | + np.testing.assert_allclose(sp.cpu().float().numpy(), sg.cpu().float().numpy(), | ||
| 41 | + rtol=6e-3, atol=6e-3, err_msg=f"{name}: state mismatch") | ||
| 42 | + return max(out_diff, st_diff) | ||
| 43 | + | ||
| 44 | + | ||
| 45 | +def test_kda_chunk(): | ||
| 46 | + if not _HAS_NPU: | ||
| 47 | + return | ||
| 48 | + torch_npu.npu.config.allow_internal_format = True | ||
| 49 | + device_id = int(os.environ.get("TILE_FWK_DEVICE_ID", 0)) | ||
| 50 | + torch.npu.set_device(device_id) | ||
| 51 | + dev = f"npu:{device_id}" | ||
| 52 | + | ||
| 53 | + max_err = 0.0 | ||
| 54 | + # chunk_grid() is the single source of truth (enforced by test_cases_sync.py). | ||
| 55 | + for case in chunk_grid(): | ||
| 56 | + max_err = max(max_err, run_case(case, dev)) | ||
| 57 | + | ||
| 58 | + logging.info(f"\n[summary] max abs error across all cases = {max_err:.3e}") | ||
| 59 | + | ||
| 60 | + | ||
| 61 | +def main(): | ||
| 62 | + pypto.set_host_options(compile_monitor_enable=1, compile_timeout=10, | ||
| 63 | + compile_timeout_stage=5, | ||
| 64 | + compile_monitor_print_interval=2) | ||
| 65 | + test_kda_chunk() | ||
| 66 | + logging.info("[PRECISION_PASS]") | ||
| 67 | + logging.info("All tests passed!") | ||
| 68 | + | ||
| 69 | + | ||
| 70 | +if __name__ == "__main__": | ||
| 71 | + if _HAS_NPU: | ||
| 72 | + main() | ||
| 73 | + else: | ||
| 74 | + logging.info("skip: no NPU") | ||
| @@ -6,263 +6,155 @@ | |||
| 6 | # INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. | 6 | # INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE. |
| 7 | # See LICENSE in the root of the software repository for the full text of the License. | 7 | # See LICENSE in the root of the software repository for the full text of the License. |
| 8 | # ----------------------------------------------------------------------------------------------------------- | 8 | # ----------------------------------------------------------------------------------------------------------- |
| 9 | -"""Model-integration dispatch test for the kimi_linear_48b_a3b KDA prefill path. | 9 | +"""End-to-end dispatch-equivalence test for the kimi_linear_48b_a3b KDA integration. |
| 10 | 10 | ||
| 11 | -Exercises the ACTUAL modeling hook ``_try_kda_fused_prefill`` (modeling_kimi.py) | 11 | +The op test (``test_kda_chunk.py``) checks the PyPTO kernel against the |
| 12 | -with a minimal stub layer and a stub ``kimi_linear_48b_a3b_pto_kernels`` module, | 12 | +naive-recurrent golden. This test instead exercises the |
| 13 | -without loading the model: | 13 | +**integration glue** the model actually runs: ``_dispatch_kda`` (modeling_kimi.py) |
| 14 | +picks the PyPTO wrapper as ``primary_fn`` when ``USE_PTO_KDA`` is set and falls | ||
| 15 | +back to the torch ``chunk_kda`` on ``NotImplementedError``. On Ascend that torch | ||
| 16 | +fallback resolves (via the ``fla`` ImportError branch) to ``vec_chunk_kda`` in | ||
| 17 | +``kimi_fla_compat``. | ||
| 14 | 18 | ||
| 15 | -1. ``USE_PTO_KDA`` off -> hook returns None, fused operator not called; | 19 | +Two things are asserted, mirroring exactly the kwargs dict the model builds |
| 16 | -2. ineligible prefill (``q_len <= 64`` / attention mask / training) -> None, | 20 | +(modeling_kimi.py:625-633): |
| 17 | - operator not called; | ||
| 18 | -3. operator raising ``NotImplementedError`` -> None (fallback protocol); | ||
| 19 | -4. success path -> operator called with the layer's projections, the result | ||
| 20 | - passes through ``layer.o_proj``, and the recurrent/conv states are written | ||
| 21 | - back to the cache. | ||
| 22 | 21 | ||
| 23 | -Numerical correctness of the fused kernel itself is covered by | 22 | +1. **Branch equivalence** — the PyPTO primary path and the torch fallback path |
| 24 | -``test_kda_fused_prefill.py`` (which also carries the graph-capture regression | 23 | + produce the same output/state (within the op tolerance). This is the |
| 25 | -check); this file deliberately does not duplicate that coverage. | 24 | + end-to-end claim ("swapping the fused kernel in does not change results"), |
| 25 | + which the kernel-vs-golden op tests do not directly cover. | ||
| 26 | +2. **Fallback trigger** — on an out-of-envelope shape (K != 128) the wrapper | ||
| 27 | + raises ``NotImplementedError`` and ``_dispatch_kda`` returns the torch | ||
| 28 | + result, i.e. the model degrades gracefully instead of crashing. | ||
| 29 | + | ||
| 30 | +The 3-line ``_dispatch_kda`` contract is mirrored here as ``_dispatch_kda`` and | ||
| 31 | +pinned to the real source by ``test_dispatch_source_matches`` so the mirror | ||
| 32 | +cannot silently drift from modeling_kimi.py. | ||
| 26 | """ | 33 | """ |
| 27 | 34 | ||
| 28 | -import functools | ||
| 29 | import logging | 35 | import logging |
| 30 | import os | 36 | import os |
| 31 | import sys | 37 | import sys |
| 32 | -import types | 38 | +from pathlib import Path |
| 33 | 39 | ||
| 40 | +import numpy as np | ||
| 34 | import torch | 41 | import torch |
| 35 | 42 | ||
| 36 | -logging.basicConfig(level=logging.INFO, format="%(message)s") | 43 | +import pypto |
| 37 | 44 | ||
| 38 | -# bootstrap the repo layout onto sys.path: src/ carries the pypto_gym modeling | 45 | +from _kda_test_common import _HAS_NPU, torch_npu, make_kda_inputs, KdaCase |
| 39 | -# package, the repo root carries the top-level ops package with the kernels | ||
| 40 | -# (same walk-up pattern as tests/ops/phi_3_mini_4k_instruct) | ||
| 41 | -_p = os.path.dirname(os.path.abspath(__file__)) | ||
| 42 | -while not os.path.isdir(os.path.join(_p, "src")): | ||
| 43 | - _p = os.path.dirname(_p) | ||
| 44 | -sys.path.insert(0, os.path.join(_p, "src")) | ||
| 45 | -sys.path.insert(0, _p) | ||
| 46 | 46 | ||
| 47 | -from pypto_gym.transformers.kimi_linear_48b_a3b.modeling_kimi import ( # noqa: E402 | 47 | +from kda_chunk_impl import kda_chunk_wrapper |
| 48 | - _try_kda_fused_prefill as try_kda_fused_prefill) | ||
| 49 | 48 | ||
| 50 | -_PTO_MOD = "kimi_linear_48b_a3b_pto_kernels" | 49 | +# vec_chunk_kda is the torch op the model falls back to on Ascend (the `fla` |
| 51 | - | 50 | +# ImportError branch in modeling_kimi maps `chunk_kda` -> this drop-in). |
| 52 | -B, T, H, D = 1, 128, 4, 128 | 51 | +_COMPAT_DIR = (Path(__file__).resolve().parents[3] |
| 53 | -P = H * D | 52 | + / "src" / "pypto_gym" / "transformers" / "kimi_linear_48b_a3b") |
| 53 | +sys.path.insert(0, str(_COMPAT_DIR)) | ||
| 54 | +from kimi_fla_compat import vec_chunk_kda # noqa: E402 | ||
| 54 | 55 | ||
| 55 | 56 | ||
| 56 | -def _fill_proj(hs, value): | 57 | +def _dispatch_kda(primary_fn, fallback_fn, kda_kwargs): |
| 57 | - """Stub projection: [B,T,hidden] -> [B,T,P] constant fill.""" | 58 | + """Mirror of modeling_kimi.py ``_dispatch_kda`` (pinned by the source test). |
| 58 | - return torch.full((hs.shape[0], hs.shape[1], P), value, device=hs.device) | ||
| 59 | 59 | ||
| 60 | - | 60 | + Run the KDA op, falling back to the torch implementation if the PyPTO |
| 61 | -def _zeros_proj(hs, last_dim): | 61 | + wrapper raises NotImplementedError (off-bound-device or unsupported shape). |
| 62 | - """Stub projection: [B,T,hidden] -> [B,T,last_dim] zeros.""" | 62 | + """ |
| 63 | - return torch.zeros(hs.shape[0], hs.shape[1], last_dim, device=hs.device) | ||
| 64 | - | ||
| 65 | - | ||
| 66 | -class _StubLayer: | ||
| 67 | - """Minimal stand-in for KimiDeltaAttention: only the attributes the hook | ||
| 68 | - touches. Projections return fixed tensors; o_proj is a real Linear so the | ||
| 69 | - test proves the hook's result actually passes through it.""" | ||
| 70 | - | ||
| 71 | - def __init__(self, device): | ||
| 72 | - self.layer_idx = 0 | ||
| 73 | - self.training = False | ||
| 74 | - self.num_heads = H | ||
| 75 | - self.head_dim = D | ||
| 76 | - self.conv_size = 4 | ||
| 77 | - self.config = types.SimpleNamespace(gate_lower_bound=-5.0) | ||
| 78 | - # projections: [B,T,hidden] -> [B,T,P] | ||
| 79 | - self.q_proj = functools.partial(_fill_proj, value=0.1) | ||
| 80 | - self.k_proj = functools.partial(_fill_proj, value=0.2) | ||
| 81 | - self.v_proj = functools.partial(_fill_proj, value=0.3) | ||
| 82 | - self.f_a_proj = functools.partial(_zeros_proj, last_dim=D) | ||
| 83 | - self.g_a_proj = functools.partial(_zeros_proj, last_dim=D) | ||
| 84 | - self.f_b_proj = functools.partial(_zeros_proj, last_dim=P) | ||
| 85 | - self.g_b_proj = functools.partial(_zeros_proj, last_dim=P) | ||
| 86 | - self.b_proj = functools.partial(_zeros_proj, last_dim=H) | ||
| 87 | - self.dt_bias = torch.zeros(P) | ||
| 88 | - # "A_log" mirrors the model's checkpoint-key attribute (see the | ||
| 89 | - # naming note on KimiDeltaAttention.A_log in modeling_kimi.py); | ||
| 90 | - # setattr keeps the non-snake_case mirror name out of the linter. | ||
| 91 | - setattr(self, "A_log", torch.zeros(1, 1, H, 1)) | ||
| 92 | - self.o_norm = types.SimpleNamespace(weight=torch.ones(D), eps=1e-5) | ||
| 93 | - self.q_conv1d = types.SimpleNamespace( | ||
| 94 | - weight=torch.zeros(P, 1, self.conv_size)) | ||
| 95 | - self.k_conv1d = types.SimpleNamespace( | ||
| 96 | - weight=torch.zeros(P, 1, self.conv_size)) | ||
| 97 | - self.v_conv1d = types.SimpleNamespace( | ||
| 98 | - weight=torch.zeros(P, 1, self.conv_size)) | ||
| 99 | - torch.manual_seed(0) | ||
| 100 | - self.o_proj = torch.nn.Linear(P, 8, bias=False, | ||
| 101 | - dtype=torch.bfloat16) # model dtype | ||
| 102 | - | ||
| 103 | - | ||
| 104 | -class _StubCache: | ||
| 105 | - """Minimal stand-in for KimiDynamicCache: the two lists the hook indexes.""" | ||
| 106 | - | ||
| 107 | - def __init__(self, layer_idx, conv_state=None): | ||
| 108 | - self.conv_states = [None] * (layer_idx + 1) | ||
| 109 | - self.recurrent_states = [None] * (layer_idx + 1) | ||
| 110 | - self.conv_states[layer_idx] = conv_state | ||
| 111 | - | ||
| 112 | - | ||
| 113 | -def _install_stub_pto(op, use_flag=True): | ||
| 114 | - """Install a stub kimi_linear_48b_a3b_pto_kernels module; returns a restore | ||
| 115 | - callable. ``op`` is the fake kda_fused_prefill (a plain function).""" | ||
| 116 | - saved = sys.modules.get(_PTO_MOD) | ||
| 117 | - mod = types.ModuleType(_PTO_MOD) | ||
| 118 | - mod.USE_PTO_KDA = use_flag | ||
| 119 | - mod.kda_fused_prefill = op | ||
| 120 | - sys.modules[_PTO_MOD] = mod | ||
| 121 | - | ||
| 122 | - def restore(): | ||
| 123 | - if saved is None: | ||
| 124 | - sys.modules.pop(_PTO_MOD, None) | ||
| 125 | - else: | ||
| 126 | - sys.modules[_PTO_MOD] = saved | ||
| 127 | - return restore | ||
| 128 | - | ||
| 129 | - | ||
| 130 | -def _run_hook(layer, hidden_states, cache_params=None, | ||
| 131 | - attention_mask=None, cu_seqlens=None): | ||
| 132 | - return try_kda_fused_prefill( | ||
| 133 | - layer, hidden_states, cache_params, attention_mask, cu_seqlens) | ||
| 134 | - | ||
| 135 | - | ||
| 136 | -def _counting_op(calls): | ||
| 137 | - def op(*a, **kw): | ||
| 138 | - calls.append(1) | ||
| 139 | - return op | ||
| 140 | - | ||
| 141 | - | ||
| 142 | -def test_hook_disabled(): | ||
| 143 | - """USE_PTO_KDA off -> None, operator not called.""" | ||
| 144 | - calls = [] | ||
| 145 | - restore = _install_stub_pto(_counting_op(calls), use_flag=False) | ||
| 146 | try: | 63 | try: |
| 147 | - layer = _StubLayer("cpu") | 64 | + return primary_fn(**kda_kwargs) |
| 148 | - hs = torch.zeros(B, T, 8) | 65 | + except NotImplementedError: |
| 149 | - assert _run_hook(layer, hs) is None | 66 | + return fallback_fn(**kda_kwargs) |
| 150 | - assert not calls | ||
| 151 | - finally: | ||
| 152 | - restore() | ||
| 153 | 67 | ||
| 154 | 68 | ||
| 155 | -def test_hook_ineligible(): | 69 | +def _model_kwargs(case, dev): |
| 156 | - """Representative ineligible guards -> None, operator not called.""" | 70 | + """Build the exact kda_kwargs dict the modeling layer passes (no `scale`; |
| 157 | - calls = [] | 71 | + both wrapper and vec_chunk_kda default scale = K**-0.5).""" |
| 158 | - restore = _install_stub_pto(_counting_op(calls)) | 72 | + q, k, v, g, beta, h0, _scale = make_kda_inputs(case, dev) |
| 73 | + return dict(q=q, k=k, v=v, g=g, beta=beta, initial_state=h0, | ||
| 74 | + output_final_state=True, use_qk_l2norm_in_kernel=True, | ||
| 75 | + cu_seqlens=None) | ||
| 76 | + | ||
| 77 | + | ||
| 78 | +def _assert_close(a, b, name): | ||
| 79 | + np.testing.assert_allclose(a.cpu().float().numpy(), b.cpu().float().numpy(), | ||
| 80 | + rtol=6e-3, atol=6e-3, err_msg=name) | ||
| 81 | + | ||
| 82 | + | ||
| 83 | +def test_branch_equivalence(npu_device): | ||
| 84 | + """PyPTO primary path == torch fallback path on the model's kwargs dict.""" | ||
| 85 | + max_err = 0.0 | ||
| 86 | + for case in (KdaCase(1, 4, 128, gate="rand"), | ||
| 87 | + KdaCase(2, 32, 300, gate="rand"), | ||
| 88 | + KdaCase(1, 32, 512, gate="ones"), # worst-case gate | ||
| 89 | + KdaCase(1, 4, 128, with_state=False, gate="rand")): | ||
| 90 | + kw = _model_kwargs(case, npu_device) | ||
| 91 | + o_p, s_p = _dispatch_kda(kda_chunk_wrapper, vec_chunk_kda, kw) | ||
| 92 | + # torch reference branch (what _dispatch_kda returns when USE_PTO_KDA is off). | ||
| 93 | + o_t, s_t = vec_chunk_kda(**kw) | ||
| 94 | + name = f"B{case.batch}H{case.num_heads}T{case.seq_len}_state{case.with_state}_g{case.gate}" | ||
| 95 | + _assert_close(o_p, o_t, f"{name}: out branch mismatch") | ||
| 96 | + _assert_close(s_p, s_t, f"{name}: state branch mismatch") | ||
| 97 | + err = max((o_p.cpu().float() - o_t.cpu().float()).abs().max().item(), | ||
| 98 | + (s_p.cpu().float() - s_t.cpu().float()).abs().max().item()) | ||
| 99 | + logging.info(f"[equiv {name}] pypto-vs-torch max_diff={err:.3e}") | ||
| 100 | + max_err = max(max_err, err) | ||
| 101 | + logging.info(f"[equiv summary] max abs error pypto-vs-torch-fallback = {max_err:.3e}") | ||
| 102 | + | ||
| 103 | + | ||
| 104 | +def test_fallback_trigger(npu_device): | ||
| 105 | + """Out-of-envelope shape (K=64) -> wrapper raises -> dispatch returns torch.""" | ||
| 106 | + case = KdaCase(1, 4, 128, gate="rand") | ||
| 107 | + q, k, v, g, beta, h0, _ = make_kda_inputs(case, npu_device) | ||
| 108 | + # Truncate K (head_k_dim) to 64 so the wrapper's envelope check rejects it. | ||
| 109 | + q64, k64, g64 = q[..., :64], k[..., :64], g[..., :64] | ||
| 110 | + h064 = h0[..., :64] if h0 is not None else None | ||
| 111 | + kw = dict(q=q64, k=k64, v=v, g=g64, beta=beta, initial_state=h064, | ||
| 112 | + output_final_state=True, use_qk_l2norm_in_kernel=True, cu_seqlens=None) | ||
| 113 | + | ||
| 114 | + # Wrapper must reject the unsupported shape ... | ||
| 115 | + raised = False | ||
| 159 | try: | 116 | try: |
| 160 | - layer = _StubLayer("cpu") | 117 | + kda_chunk_wrapper(**kw) |
| 161 | - hs = torch.zeros(B, T, 8) | 118 | + except NotImplementedError: |
| 162 | - # short prefill (decode-side, q_len <= 64) | 119 | + raised = True |
| 163 | - assert _run_hook(layer, torch.zeros(B, 32, 8)) is None | 120 | + assert raised, "kda_chunk_wrapper must raise NotImplementedError for K != 128" |
| 164 | - # varlen / masked batch | 121 | + |
| 165 | - mask = torch.ones(B, T, dtype=torch.long) | 122 | + # ... and _dispatch_kda must transparently return the torch fallback result. |
| 166 | - assert _run_hook(layer, hs, attention_mask=mask) is None | 123 | + o_disp, s_disp = _dispatch_kda(kda_chunk_wrapper, vec_chunk_kda, kw) |
| 167 | - # training | 124 | + o_ref, s_ref = vec_chunk_kda(**kw) |
| 168 | - layer.training = True | 125 | + _assert_close(o_disp, o_ref, "fallback out mismatch") |
| 169 | - assert _run_hook(layer, hs) is None | 126 | + _assert_close(s_disp, s_ref, "fallback state mismatch") |
| 170 | - layer.training = False | 127 | + logging.info("[fallback] K=64 -> NotImplementedError -> torch fallback OK") |
| 171 | - assert not calls | ||
| 172 | - finally: | ||
| 173 | - restore() | ||
| 174 | 128 | ||
| 175 | 129 | ||
| 176 | -def test_hook_fallback(): | 130 | +def test_dispatch_source_matches(): |
| 177 | - """Operator raising NotImplementedError -> None (fallback protocol).""" | 131 | + """Pin the mirrored _dispatch_kda to the real modeling_kimi source so the |
| 178 | - def raising_op(*a, **kw): | 132 | + test cannot drift from the integration it claims to cover. |
| 179 | - raise NotImplementedError("off-bound NPU") | 133 | + """ |
| 180 | - | 134 | + src = (_COMPAT_DIR / "modeling_kimi.py").read_text() |
| 181 | - restore = _install_stub_pto(raising_op) | 135 | + for needle in ("def _dispatch_kda(primary_fn, fallback_fn, kda_kwargs):", |
| 182 | - try: | 136 | + "return primary_fn(**kda_kwargs)", |
| 183 | - layer = _StubLayer("cpu") | 137 | + "except NotImplementedError:", |
| 184 | - hs = torch.zeros(B, T, 8) | 138 | + "return fallback_fn(**kda_kwargs)"): |
| 185 | - assert _run_hook(layer, hs) is None | 139 | + assert needle in src, f"modeling_kimi._dispatch_kda contract changed: missing {needle!r}" |
| 186 | - finally: | 140 | + logging.info("[source] mirrored _dispatch_kda matches modeling_kimi.py") |
| 187 | - restore() | ||
| 188 | - | ||
| 189 | - | ||
| 190 | -def test_hook_success(): | ||
| 191 | - """Success path: operator called, o_proj applied, states written back.""" | ||
| 192 | - calls = [] | ||
| 193 | - fake_o = torch.full((B, T, H, D), 0.5, dtype=torch.bfloat16) | ||
| 194 | - fake_state = torch.full((B, H, D, D), 0.25) | ||
| 195 | - fake_cs = tuple(torch.full((B, P, 3), 0.75) for _ in range(3)) | ||
| 196 | - conv_in = torch.full((B, P, 3), 0.125) | ||
| 197 | - | ||
| 198 | - def fake_op(inputs, weights, initial_state=None, output_final_state=True, | ||
| 199 | - conv_cache=None, **kw): | ||
| 200 | - calls.append({"inputs": inputs, "weights": weights, | ||
| 201 | - "conv_cache": conv_cache, "initial_state": initial_state}) | ||
| 202 | - return fake_o, fake_state, fake_cs | ||
| 203 | - | ||
| 204 | - restore = _install_stub_pto(fake_op) | ||
| 205 | - try: | ||
| 206 | - layer = _StubLayer("cpu") | ||
| 207 | - hs = torch.zeros(B, T, 8) | ||
| 208 | - st_in = torch.full((B, H, D, D), 0.0625) | ||
| 209 | - cache = _StubCache(layer.layer_idx, conv_state=conv_in) | ||
| 210 | - cache.recurrent_states[layer.layer_idx] = st_in | ||
| 211 | - | ||
| 212 | - out = _run_hook(layer, hs, cache_params=cache) | ||
| 213 | - | ||
| 214 | - # the operator ran exactly once, with the layer's projections and the | ||
| 215 | - # cache's conv history / recurrent state | ||
| 216 | - assert len(calls) == 1 | ||
| 217 | - c = calls[0] | ||
| 218 | - assert c["inputs"].q.shape == (B, T, H, D) | ||
| 219 | - assert c["inputs"].v.shape == (B, T, H, D) | ||
| 220 | - assert c["inputs"].g_raw.shape == (B, T, P) | ||
| 221 | - assert c["inputs"].b_raw.shape == (B, T, H) | ||
| 222 | - assert c["weights"].a_log is getattr(layer, "A_log") | ||
| 223 | - assert c["conv_cache"] is conv_in | ||
| 224 | - assert c["initial_state"] is st_in | ||
| 225 | - | ||
| 226 | - # the hook's return value is o_proj applied to the operator's output | ||
| 227 | - expected = layer.o_proj(fake_o.reshape(B, T, P)) | ||
| 228 | - assert out.shape == expected.shape | ||
| 229 | - assert torch.equal(out, expected) | ||
| 230 | - | ||
| 231 | - # recurrent + conv states written back into the cache | ||
| 232 | - assert cache.recurrent_states[layer.layer_idx] is fake_state | ||
| 233 | - assert cache.conv_states[layer.layer_idx] is fake_cs | ||
| 234 | - finally: | ||
| 235 | - restore() | ||
| 236 | - | ||
| 237 | - | ||
| 238 | -def test_hook_success_no_cache(): | ||
| 239 | - """Success path without a cache: operator still called, nothing to write.""" | ||
| 240 | - calls = [] | ||
| 241 | - | ||
| 242 | - def fake_op(*a, **kw): | ||
| 243 | - calls.append(1) | ||
| 244 | - return (torch.zeros(B, T, H, D, dtype=torch.bfloat16), | ||
| 245 | - torch.zeros(B, H, D, D), | ||
| 246 | - tuple(torch.zeros(B, P, 3) for _ in range(3))) | ||
| 247 | - | ||
| 248 | - restore = _install_stub_pto(fake_op) | ||
| 249 | - try: | ||
| 250 | - layer = _StubLayer("cpu") | ||
| 251 | - hs = torch.zeros(B, T, 8) | ||
| 252 | - out = _run_hook(layer, hs, cache_params=None) | ||
| 253 | - assert out is not None | ||
| 254 | - assert len(calls) == 1 | ||
| 255 | - finally: | ||
| 256 | - restore() | ||
| 257 | 141 | ||
| 258 | 142 | ||
| 259 | def main(): | 143 | def main(): |
| 260 | - """Direct-script entry: run all hook tests.""" | 144 | + pypto.set_host_options(compile_monitor_enable=1, compile_timeout=10, |
| 261 | - test_hook_disabled() | 145 | + compile_timeout_stage=5, |
| 262 | - test_hook_ineligible() | 146 | + compile_monitor_print_interval=2) |
| 263 | - test_hook_fallback() | 147 | + test_dispatch_source_matches() |
| 264 | - test_hook_success() | 148 | + if not _HAS_NPU: |
| 265 | - test_hook_success_no_cache() | 149 | + logging.info("skip NPU cases: no NPU") |
| 150 | + return | ||
| 151 | + torch_npu.npu.config.allow_internal_format = True | ||
| 152 | + device_id = int(os.environ.get("TILE_FWK_DEVICE_ID", 0)) | ||
| 153 | + torch.npu.set_device(device_id) | ||
| 154 | + npu_device = f"npu:{device_id}" | ||
| 155 | + test_branch_equivalence(npu_device) | ||
| 156 | + test_fallback_trigger(npu_device) | ||
| 157 | + logging.info("[PRECISION_PASS]") | ||
| 266 | logging.info("All tests passed!") | 158 | logging.info("All tests passed!") |
| 267 | 159 | ||
| 268 | 160 | ||
| @@ -1,228 +0,0 @@ | |||
| 1 | -# Copyright (c) 2025-2026 Huawei Technologies Co., Ltd. | ||
| 2 | -# This program is free software, you can redistribute it and/or modify it under the terms and conditions of | ||
| 3 | -# CANN Open Software License Agreement Version 2.0 (the "License"). | ||
| 4 | -# Please refer to the License for details. You may not use this file except in compliance with the License. | ||
| 5 | -# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, | ||
| 6 | -# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. | ||
| 7 | -# See LICENSE in the root of the software repository for the full text of the License. | ||
| 8 | -# ----------------------------------------------------------------------------------------------------------- | ||
| 9 | -"""Numerical + graph-capture tests for the kimi_linear_48b_a3b KDA fused prefill PyPTO kernel. | ||
| 10 | -""" | ||
| 11 | - | ||
| 12 | -import logging | ||
| 13 | -import os | ||
| 14 | -from collections import namedtuple | ||
| 15 | - | ||
| 16 | -import numpy as np | ||
| 17 | -import torch | ||
| 18 | - | ||
| 19 | -from _kda_test_common import _HAS_NPU, torch_npu, HEAD_DIM | ||
| 20 | - | ||
| 21 | -from kimi_fla_compat import ( | ||
| 22 | - ShortConvolution, | ||
| 23 | - _naive_recurrent_kda, | ||
| 24 | - fused_kda_gate, | ||
| 25 | -) | ||
| 26 | -from kda_fused_prefill_impl import ( | ||
| 27 | - KdaPrefillInputs, | ||
| 28 | - KdaPrefillWeights, | ||
| 29 | - kda_fused_prefill, | ||
| 30 | -) | ||
| 31 | - | ||
| 32 | -RMS_EPS = 1e-5 | ||
| 33 | -CONV_K = 4 | ||
| 34 | -RTOL_O = ATOL_O = 1.5e-2 | ||
| 35 | -RTOL_S = ATOL_S = 1e-4 | ||
| 36 | - | ||
| 37 | -Case = namedtuple("Case", "shape seed cache gate state", | ||
| 38 | - defaults=(7, False, "rand", True)) | ||
| 39 | - | ||
| 40 | -_CASES = ( | ||
| 41 | - Case((1, 128, 4)), | ||
| 42 | - Case((2, 300, 4)), | ||
| 43 | - Case((1, 512, 32)), | ||
| 44 | - Case((1, 512, 32), gate="ones"), | ||
| 45 | - Case((1, 300, 32), state=False), | ||
| 46 | - Case((2, 300, 32), cache=True), | ||
| 47 | -) | ||
| 48 | - | ||
| 49 | - | ||
| 50 | -def _conv_module(weight, device): | ||
| 51 | - m = ShortConvolution(weight.shape[0], CONV_K, activation="silu").to( | ||
| 52 | - device=device, dtype=weight.dtype) | ||
| 53 | - with torch.no_grad(): | ||
| 54 | - m.weight.copy_(weight.reshape(weight.shape[0], 1, CONV_K)) | ||
| 55 | - return m | ||
| 56 | - | ||
| 57 | - | ||
| 58 | -def _conv_silu_fp32(x, w, hist=None): | ||
| 59 | - """fp32 conv+silu on (bf16) x with optional [B, p, 3] pre-history -- | ||
| 60 | - the same math the kernel's conv branch computes.""" | ||
| 61 | - b, t, h, d = x.shape | ||
| 62 | - xf = x.reshape(b, t, h * d).float().permute(0, 2, 1) | ||
| 63 | - left = (hist if hist is not None else | ||
| 64 | - torch.zeros(b, h * d, CONV_K - 1, device=xf.device)) | ||
| 65 | - xc = torch.cat([left, xf], dim=2) | ||
| 66 | - y = torch.nn.functional.conv1d( | ||
| 67 | - xc, w.reshape(h * d, 1, CONV_K).float(), groups=h * d) | ||
| 68 | - return torch.nn.functional.silu(y[..., :t]).permute(0, 2, 1).view(b, t, h, d) | ||
| 69 | - | ||
| 70 | - | ||
| 71 | -def make_fused_inputs(shape, dev, seed=7, with_cache=False, gate="rand"): | ||
| 72 | - """Model-realistic fused-prefill call args (grouped API tuples).""" | ||
| 73 | - b, t, h = shape | ||
| 74 | - torch.manual_seed(seed) | ||
| 75 | - p = h * HEAD_DIM | ||
| 76 | - q = (torch.randn(b, t, h, HEAD_DIM) * 0.5).to(torch.bfloat16).to(dev) | ||
| 77 | - k = (torch.randn(b, t, h, HEAD_DIM) * 0.5).to(torch.bfloat16).to(dev) | ||
| 78 | - v = (torch.randn(b, t, h, HEAD_DIM) * 0.5).to(torch.bfloat16).to(dev) | ||
| 79 | - wq = (torch.randn(p, CONV_K) * 0.3).to(torch.bfloat16).to(dev) | ||
| 80 | - wk = (torch.randn(p, CONV_K) * 0.3).to(torch.bfloat16).to(dev) | ||
| 81 | - wv = (torch.randn(p, CONV_K) * 0.3).to(torch.bfloat16).to(dev) | ||
| 82 | - if gate == "ones": | ||
| 83 | - g_raw = torch.full((b, t, p), 10.0, device=dev).to(torch.bfloat16) | ||
| 84 | - else: | ||
| 85 | - g_raw = torch.randn(b, t, p, device=dev).to(torch.bfloat16) | ||
| 86 | - g_gate = torch.randn(b, t, p, device=dev).to(torch.bfloat16) | ||
| 87 | - b_raw = torch.randn(b, t, h, device=dev).to(torch.bfloat16) | ||
| 88 | - dt_bias = torch.randn(p, dtype=torch.float32, device=dev) | ||
| 89 | - a_log = (torch.log(torch.rand(h, dtype=torch.float32, device=dev) | ||
| 90 | - .uniform_(1, 16)).view(1, 1, h, 1)) # model param shape | ||
| 91 | - o_w = torch.randn(HEAD_DIM, dtype=torch.float32, device=dev) * 0.2 + 1.0 | ||
| 92 | - h0 = (torch.randn(b, h, HEAD_DIM, HEAD_DIM) * 0.3).to(dev) | ||
| 93 | - cache = tuple((torch.randn(b, p, CONV_K - 1) * 0.3).to(dev) | ||
| 94 | - for _ in range(3)) if with_cache else None | ||
| 95 | - inputs = KdaPrefillInputs(q=q, k=k, v=v, g_raw=g_raw, g_gate=g_gate, | ||
| 96 | - b_raw=b_raw) | ||
| 97 | - weights = KdaPrefillWeights(dt_bias=dt_bias, a_log=a_log, o_norm_w=o_w, | ||
| 98 | - conv_wq=wq, conv_wk=wk, conv_wv=wv) | ||
| 99 | - return inputs, weights, h0, cache | ||
| 100 | - | ||
| 101 | - | ||
| 102 | -@torch.no_grad() | ||
| 103 | -def _golden_prefill(inputs, weights, dev, initial_state=None, conv_cache=None): | ||
| 104 | - """ALL-fp32 golden: fp32 conv+silu -> gate -> beta -> exact naive | ||
| 105 | - recurrence -> fp32 o_norm. The conv HISTORY comes from the bf16 | ||
| 106 | - ShortConvolution modules (the decode-seeding contract, checked | ||
| 107 | - bit-exact separately).""" | ||
| 108 | - q, k, v = inputs.q, inputs.k, inputs.v | ||
| 109 | - b, t, h, d = q.shape | ||
| 110 | - cs = conv_cache if conv_cache is not None else (None, None, None) | ||
| 111 | - q_c = _conv_silu_fp32(q, weights.conv_wq, cs[0]) | ||
| 112 | - k_c = _conv_silu_fp32(k, weights.conv_wk, cs[1]) | ||
| 113 | - v_c = _conv_silu_fp32(v, weights.conv_wv, cs[2]) | ||
| 114 | - g = fused_kda_gate(inputs.g_raw, weights.a_log, HEAD_DIM, g_bias=weights.dt_bias) | ||
| 115 | - beta = inputs.b_raw.float().sigmoid() | ||
| 116 | - o, st = _naive_recurrent_kda( | ||
| 117 | - q_c, k_c, v_c, g, beta, initial_state=initial_state, | ||
| 118 | - output_final_state=True, use_qk_l2norm_in_kernel=True) | ||
| 119 | - var = o.pow(2).mean(-1, keepdim=True) | ||
| 120 | - o = (o * torch.rsqrt(var + RMS_EPS) * weights.o_norm_w | ||
| 121 | - * torch.sigmoid(inputs.g_gate.view(b, t, h, d).float())) | ||
| 122 | - | ||
| 123 | - convs = (_conv_module(weights.conv_wq, dev), | ||
| 124 | - _conv_module(weights.conv_wk, dev), | ||
| 125 | - _conv_module(weights.conv_wv, dev)) | ||
| 126 | - _, cq = convs[0](q.reshape(b, t, h * d), cache=cs[0], output_final_state=True) | ||
| 127 | - _, ck = convs[1](k.reshape(b, t, h * d), cache=cs[1], output_final_state=True) | ||
| 128 | - _, cv = convs[2](v.reshape(b, t, h * d), cache=cs[2], output_final_state=True) | ||
| 129 | - return o, st, (cq, ck, cv) | ||
| 130 | - | ||
| 131 | - | ||
| 132 | -def run_case(dev, case): | ||
| 133 | - """Run one fused prefill case and assert it matches the fp32 golden.""" | ||
| 134 | - inputs, weights, h0, cache = make_fused_inputs(case.shape, dev, case.seed, | ||
| 135 | - case.cache, case.gate) | ||
| 136 | - initial = h0 if case.state else None | ||
| 137 | - o_ref, s_ref, cs_ref = _golden_prefill(inputs, weights, dev, | ||
| 138 | - initial_state=initial, | ||
| 139 | - conv_cache=cache) | ||
| 140 | - o_f, s_f, cs_f = kda_fused_prefill(inputs, weights, initial_state=initial, | ||
| 141 | - output_final_state=True, conv_cache=cache) | ||
| 142 | - | ||
| 143 | - b, t, h = case.shape | ||
| 144 | - name = (f"B{b}H{h}T{t}{'_cache' if case.cache else ''}_g{case.gate}" | ||
| 145 | - f"{'' if case.state else '_nostate'}") | ||
| 146 | - do = (o_f.float() - o_ref).abs().max().item() | ||
| 147 | - ds = (s_f - s_ref).abs().max().item() | ||
| 148 | - logging.info("[%s] out=%.2e (<=1 bf16 ULP) state=%.2e conv_history=bit-exact", | ||
| 149 | - name, do, ds) | ||
| 150 | - | ||
| 151 | - np.testing.assert_allclose(o_f.float().cpu().numpy(), o_ref.cpu().numpy(), | ||
| 152 | - rtol=RTOL_O, atol=ATOL_O, err_msg=f"{name}: out mismatch") | ||
| 153 | - np.testing.assert_allclose(s_f.cpu().numpy(), s_ref.cpu().numpy(), | ||
| 154 | - rtol=RTOL_S, atol=RTOL_S, err_msg=f"{name}: state mismatch") | ||
| 155 | - # the conv history seeds decode — it must be bit-exact | ||
| 156 | - for a, r in zip(cs_f, cs_ref): | ||
| 157 | - assert torch.equal(a.cpu(), r.cpu()), f"{name}: conv history not bit-exact" | ||
| 158 | - return do, ds | ||
| 159 | - | ||
| 160 | - | ||
| 161 | -def test_kda_fused_prefill(): | ||
| 162 | - """True-precision test vs the all-fp32 golden (format-floor error).""" | ||
| 163 | - if not _HAS_NPU: | ||
| 164 | - return | ||
| 165 | - torch_npu.npu.config.allow_internal_format = True | ||
| 166 | - device_id = int(os.environ.get("TILE_FWK_DEVICE_ID", 0)) | ||
| 167 | - torch.npu.set_device(device_id) | ||
| 168 | - dev = f"npu:{device_id}" | ||
| 169 | - | ||
| 170 | - worst_o = worst_s = 0.0 | ||
| 171 | - for case in _CASES: | ||
| 172 | - do, ds = run_case(dev, case) | ||
| 173 | - worst_o, worst_s = max(worst_o, do), max(worst_s, ds) | ||
| 174 | - | ||
| 175 | - logging.info("\n[summary] worst true error: out=%.2e (bf16 format floor), " | ||
| 176 | - "state=%.2e (fp32 WY)", worst_o, worst_s) | ||
| 177 | - | ||
| 178 | - | ||
| 179 | -def test_kda_fused_prefill_graph_capture(): | ||
| 180 | - """NPUGraph capture+replay regression check, bit-exact vs the eager call.""" | ||
| 181 | - if not _HAS_NPU: | ||
| 182 | - return | ||
| 183 | - if not hasattr(torch_npu.npu, "NPUGraph"): | ||
| 184 | - logging.info("[graph] torch.npu.NPUGraph unavailable; skipped") | ||
| 185 | - return | ||
| 186 | - torch_npu.npu.config.allow_internal_format = True | ||
| 187 | - device_id = int(os.environ.get("TILE_FWK_DEVICE_ID", 0)) | ||
| 188 | - torch.npu.set_device(device_id) | ||
| 189 | - dev = f"npu:{device_id}" | ||
| 190 | - | ||
| 191 | - inputs, weights, h0, _cache = make_fused_inputs((1, 128, 4), dev) | ||
| 192 | - kwargs = {"initial_state": h0, "output_final_state": True} | ||
| 193 | - | ||
| 194 | - # eager reference (also triggers the JIT compile, which must stay OUTSIDE | ||
| 195 | - # the capture region) | ||
| 196 | - o_e, s_e, cs_e = kda_fused_prefill(inputs, weights, **kwargs) | ||
| 197 | - o_ref, s_ref = o_e.clone(), s_e.clone() | ||
| 198 | - cs_ref = tuple(c.clone() for c in cs_e) | ||
| 199 | - torch_npu.npu.synchronize() | ||
| 200 | - | ||
| 201 | - # capture the same invocation (static input tensors, same as the bench's | ||
| 202 | - # stage capture), then replay and compare | ||
| 203 | - g = torch_npu.npu.NPUGraph() | ||
| 204 | - with torch_npu.npu.graph(g): | ||
| 205 | - o_c, s_c, cs_c = kda_fused_prefill(inputs, weights, **kwargs) | ||
| 206 | - g.replay() | ||
| 207 | - torch_npu.npu.synchronize() | ||
| 208 | - | ||
| 209 | - assert torch.equal(o_c, o_ref), "graph replay: out differs from eager" | ||
| 210 | - assert torch.equal(s_c, s_ref), "graph replay: state differs from eager" | ||
| 211 | - for a, r in zip(cs_c, cs_ref): | ||
| 212 | - assert torch.equal(a, r), "graph replay: conv history differs from eager" | ||
| 213 | - logging.info("[graph] NPUGraph capture+replay bit-exact (out/state/conv-history)") | ||
| 214 | - | ||
| 215 | - | ||
| 216 | -def main(): | ||
| 217 | - """Direct-script entry: run both prefill tests.""" | ||
| 218 | - test_kda_fused_prefill() | ||
| 219 | - test_kda_fused_prefill_graph_capture() | ||
| 220 | - logging.info("[PRECISION_PASS]") | ||
| 221 | - logging.info("All tests passed!") | ||
| 222 | - | ||
| 223 | - | ||
| 224 | -if __name__ == "__main__": | ||
| 225 | - if _HAS_NPU: | ||
| 226 | - main() | ||
| 227 | - else: | ||
| 228 | - logging.info("skip: no NPU") | ||