Merged
refactor: improve DeepSeek-V4.1 LI low-precision quantization #941
refactor: improve DeepSeek-V4.1 LI low-precision quantization #941
Merged
xiaomagemafeifeiAdd on Sep 29
Total: 21 files changed+1175-761
@@ -50,7 +50,7 @@ recipe 按模型配置中的模块路径匹配 Attention linear、shared expert
50 50 
51QAT 下做 MXFP4 量化时可以使用 `--extension.quantization.dst_type_max` 传参来指定量化时目标域的最大值。参数默认值为 0.0 对应 `Amax(Dtype)`;可以传参 7.0,以防止量化数据中的最大值被截断而产生较大精度损失。51QAT 下做 MXFP4 量化时可以使用 `--extension.quantization.dst_type_max` 传参来指定量化时目标域的最大值。参数默认值为 0.0 对应 `Amax(Dtype)`;可以传参 7.0,以防止量化数据中的最大值被截断而产生较大精度损失。
52 52 
53-DeepSeek-V4/V4.1 完整的的 QAT 启动方式见[快速上手](../user-guides/quickstart.md#deepseek-v41-torchao-npu-低精度训练),对应的 qat 脚本同时启用 MXFP4 QAT 和稀疏 attention 量化,后者的自定义算子依赖见下一节。53+DeepSeek-V4/V4.1 的完整 QAT 启动方式见[快速上手](../user-guides/quickstart.md#deepseek-v41-torchao-npu-低精度训练)。V4.1 QAT 脚本同时启用 routed expert MXFP4 fake quant、Lightning Indexer 和稀疏 attention/KV source Compressor 量化,相关自定义算子依赖见下一节。
54 54 
55## Attention 量化55## Attention 量化
56 56 
@@ -86,21 +86,40 @@ Lightning Indexer(LI)的 Q/K 量化通过 `li-quantization` 单独选择,
86 86 
87LI 各模式的实现细节不同:`fp8` 使用 8 bit E4M3 数据,按 token-head 动态量化,scale 以 FP32 保存;`mxfp8` 使用 8 bit E4M3 数据和 E8M0 scale;`mxfp4` 使用 4 bit E2M1 数据和 E8M0 scale;`hif8` 使用 8 bit HiFloat8 数据,按 tensor 动态量化,scale 以 FP32 保存。CANN 的 `quant_mode` 由这些数据格式和量化粒度共同决定。87LI 各模式的实现细节不同:`fp8` 使用 8 bit E4M3 数据,按 token-head 动态量化,scale 以 FP32 保存;`mxfp8` 使用 8 bit E4M3 数据和 E8M0 scale;`mxfp4` 使用 4 bit E2M1 数据和 E8M0 scale;`hif8` 使用 8 bit HiFloat8 数据,按 tensor 动态量化,scale 以 FP32 保存。CANN 的 `quant_mode` 由这些数据格式和量化粒度共同决定。
88 88 
89-`li-quantization` 默认传参为 none 不启用量化。当前独立 LI 配置入口匹配 DeepSeek-V4 的模块结构。89+`li-quantization` 默认值为 `None`,即不启用 LI 量化。本节表中的四种格式适用于 DeepSeek-V4;DeepSeek-V4.1 当前仅支持 `mxfp4`,并使用下一节说明的独立 QLI/QSLI 实现。
90 90 
91-### DeepSeek-V4.1 稀疏 attention KV Cache 量化91+### DeepSeek-V4.1 LI 与稀疏 attention 量化
92 92 
93-`--extension.quantization.enable-sparse-attention-quantization` 将 V4.1 稀疏 attention 替换为混合量化路径:swa_kv 使用 `mxfp8_bf16`,cmp_kv 使用 `mxfp4_bf16`。该路径对 KV 量化再反量化后调用 sparse attention 算子,以引入对应的量化误差。93+QLI(Quantized Lightning Indexer,量化索引器)与 QSLI(Quantized Sparse Lightning Indexer,量化稀疏索引器)负责为每个 query 选择参与稀疏 attention 的 Top-K key。在当前 V4.1 实现中,两者都将 indexer 的 Q/K 量化为 MXFP4,主要区别是选分的搜索范围及是否生产候选池:
94+ 
95+| 实现 | 搜索范围 | 候选池行为 | 使用位置 |
96+| --- | --- | --- | --- |
97+| QLI(`quant_lightning_indexer`) | 当前 query 因果可见的全部 key | 候选源层除输出自身 Top-K 外,还生成候选块表供后续层使用;未启用候选池的层只输出 Top-K | 候选源层,以及候选池之外的选分层 |
98+| QSLI(`quant_sparse_lightning_indexer`) | 传入候选块表限定的可见 key | 消费候选源层生成的块表,重新选出本层 Top-K,并将原块表继续向后传递 | 使用候选池的 Reindex 层 |
99+ 
100+候选池保存 key 的块索引,每块包含 `candidate_block_size` 个位置,最多保留 `candidate_topk_blocks` 个块。它与最终的 `index_topk` 个 key 是两级筛选:QLI 候选源层先确定候选块,后续 QSLI 层使用各自的 query 和权重在这些块内重新选分。Reuse 层直接沿用已有选择,不调用 QLI 或 QSLI。
101+ 
102+`li-quantization=mxfp4` 同时启用这两种实现,由模型层的角色和候选池配置自动选择,无需分别指定。两者输出的索引交给 sparse attention 计算注意力;训练反向均使用 BF16 SLIKG 消费教师信号,QLI/QSLI 本身不替代 sparse attention。
103+ 
104+V4.1 的 indexer 训练目标通过 sparse attention 反向提供 teacher(教师信号),再由 selector 的 SLIKG 反向消费。标准 A5 融合路径会同时导入两侧 BF16 override 作为 fallback;在此前提下,以下两个配置可以独立替换对应一侧:
105+ 
106+- `--extension.quantization.li-quantization mxfp4`:将 BF16 LI selector 替换为 MXFP4 QLI/QSLI,SLIKG 反向保持 BF16。
107+- `--extension.quantization.enable-sparse-attention-quantization`:同时替换 KV source Compressor 和 sparse attention;sparse attention 反向继续提供 indexer teacher。
108+ 
109+稀疏 attention 量化路径中,swa_kv 使用 `mxfp8_bf16`,cmp_kv 使用 `mxfp4_bf16`。该路径对 KV 量化再反量化后调用 sparse attention 算子,以引入对应的量化误差。
94 110 
95该缓存布局使用按组保存的 BF16 scale:滑窗 KV 为 8 bit E4M3 数据,每 32 个元素共享一个 BF16 scale;压缩 KV 为 4 bit E2M1 数据,每 16 个元素共享一个 BF16 scale。MXFP4 数据以 `uint8` 打包,每个字节包含两个 4 bit 值。V4.1 的反向计算使用量化反量化的 `swa_kv` 和 `cmp_kv`,并结合量化前向的输出和 LSE 计算梯度。111该缓存布局使用按组保存的 BF16 scale:滑窗 KV 为 8 bit E4M3 数据,每 32 个元素共享一个 BF16 scale;压缩 KV 为 4 bit E2M1 数据,每 16 个元素共享一个 BF16 scale。MXFP4 数据以 `uint8` 打包,每个字节包含两个 4 bit 值。V4.1 的反向计算使用量化反量化的 `swa_kv` 和 `cmp_kv`,并结合量化前向的输出和 LSE 计算梯度。
96 112 
97> [!NOTE]113> [!NOTE]
98-> 启用前需参考 [Ascend C 自定义算子编译安装说明](https://gitcode.com/cann/cann-recipes-infer/blob/master/ops/ascendc/README.md),编译并安装 `kv_compress_epilog_v2`,并配置自定义算子环境变量。114+> 启用 DeepSeek-V4.1 LI 量化(`li-quantization=mxfp4`)前,需参考 [cannbot-dsl 算子编译安装说明](https://gitcode.com/cann/cannbot-dsl/blob/master/net/native_package/README.md),编译并安装 QLI 和 QSLI 算子。
115+>
116+> 启用稀疏 attention 量化前,需参考 [Ascend C 自定义算子编译安装说明](https://gitcode.com/cann/cann-recipes-infer/blob/master/ops/ascendc/README.md),编译并安装 `kv_compress_epilog_v2`,并配置自定义算子环境变量。
99 117 
100-在 V4.1 的 CPT 命令中追加以下参数即可启用,QAT 脚本已包含这些开关:118+在 V4.1 的 CPT 命令中追加以下参数,可以同时启用两侧量化;QAT 脚本已包含这些开关:
101 119 
102```bash120```bash
103--extension.quantization.enable-quantized-training \121--extension.quantization.enable-quantized-training \
122+--extension.quantization.li-quantization mxfp4 \
104--extension.quantization.enable-sparse-attention-quantization123--extension.quantization.enable-sparse-attention-quantization
105```124```
106 125 
@@ -152,8 +171,8 @@ FSDP 的参数通信和梯度通信是两个阶段:参数在模块计算前通
152| `enable-quantized-training` | `False` | 低精度训练总开关 |171| `enable-quantized-training` | `False` | 低精度训练总开关 |
153| `recipe` | `all_block_fp8` | 选择 `all_mxfp8`、`mix` 或 `all_block_fp8` |172| `recipe` | `all_block_fp8` | 选择 `all_mxfp8`、`mix` 或 `all_block_fp8` |
154| `enable-mxfp4-qat` | `False` | Routed expert 的 MXFP4 fake quant 约束 |173| `enable-mxfp4-qat` | `False` | Routed expert 的 MXFP4 fake quant 约束 |
155-| `li-quantization` | `none` | V4 LI Q/K 量化,可选 `fp8`、`mxfp8`、`mxfp4`、`hif8` |174+| `li-quantization` | `None` | LI Q/K 量化;V4 可选 `fp8`、`mxfp8`、`mxfp4`、`hif8`,V4.1 仅支持 `mxfp4` |
156-| `enable-sparse-attention-quantization` | `False` | V4.1 稀疏 attention 混合量化 |175+| `enable-sparse-attention-quantization` | `False` | V4.1 KV source Compressor 与稀疏 attention 混合量化 |
157| `dst-type-max` | `0.0` | 用于 MXFP4 量化的目标类型最大值,可取值 0.0, 6.0-12.0 |176| `dst-type-max` | `0.0` | 用于 MXFP4 量化的目标类型最大值,可取值 0.0, 6.0-12.0 |
158| `enable-fsdp-prequantize` | `False` | Block FP8 权重在 FSDP all-gather 前预量化 |177| `enable-fsdp-prequantize` | `False` | Block FP8 权重在 FSDP all-gather 前预量化 |
159| `kv-norm-quantization.format` | 未设置 | V4 nope KV Cache 量化格式,目前为 `mxfp8`(8 bit E4M3) |178| `kv-norm-quantization.format` | 未设置 | V4 nope KV Cache 量化格式,目前为 `mxfp8`(8 bit E4M3) |
@@ -173,4 +192,5 @@ FSDP 的参数通信和梯度通信是两个阶段:参数在模块计算前通
173- [量化配置字段](../../torchtitan_npu/config/configs.py)192- [量化配置字段](../../torchtitan_npu/config/configs.py)
174- [TorchAO-NPU converter 与 recipe](../../interfaces/torchao_converter.py)193- [TorchAO-NPU converter 与 recipe](../../interfaces/torchao_converter.py)
175- [Block FP8 权重与 FSDP 预量化实现](../../experiments/torchao-npu/torchao_npu/wrapper_tensors/block_mx_wrapper_tensor.py)194- [Block FP8 权重与 FSDP 预量化实现](../../experiments/torchao-npu/torchao_npu/wrapper_tensors/block_mx_wrapper_tensor.py)
195+- [V4.1 Lightning Indexer 量化实现](../../experiments/torchao-npu/torchao_npu/quantized_modules/v41_lightning_indexer.py)
176- [V4.1 稀疏 attention 量化实现](../../experiments/torchao-npu/torchao_npu/quantized_modules/v41_sparse_attention.py)196- [V4.1 稀疏 attention 量化实现](../../experiments/torchao-npu/torchao_npu/quantized_modules/v41_sparse_attention.py)
@@ -91,8 +91,9 @@ export PYTHONPATH="/path/to/custom/parent${PYTHONPATH:+:${PYTHONPATH}}"
91 91 
92`/path/to/custom/parent` 必须直接包含 `torchao_npu/__init__.py`。使用仓内源码时,可将其92`/path/to/custom/parent` 必须直接包含 `torchao_npu/__init__.py`。使用仓内源码时,可将其
93替换为 `<torchtitan-npu>/experiments/torchao-npu`。通用训练脚本只透传量化 CLI,93替换为 `<torchtitan-npu>/experiments/torchao-npu`。通用训练脚本只透传量化 CLI,
94-不会自动修改可选依赖路径。具体命令见94+不会自动修改可选依赖路径。具体命令见快速上手中的
95-[快速上手](./quickstart.md#deepseek-v4-torchao-npu-低精度训练)。95+[DeepSeek-V4](./quickstart.md#deepseek-v4-torchao-npu-低精度训练) 与
96+[DeepSeek-V4.1](./quickstart.md#deepseek-v41-torchao-npu-低精度训练) 入口。
96 97 
97## PyPI 安装98## PyPI 安装
98 99 
@@ -143,7 +143,7 @@ bash examples/deepseek_v4/deepseek_v4_flash_cpt_4k_a3.sh \
143| `enable-quantized-training` | `--enable-quantized-training` / `--no-enable-quantized-training` | 启用或关闭低精度训练,默认关闭。 |143| `enable-quantized-training` | `--enable-quantized-training` / `--no-enable-quantized-training` | 启用或关闭低精度训练,默认关闭。 |
144| `recipe` | `all_mxfp8`、`mix`、`all_block_fp8`、`all_hif8` | 选择全 MXFP8、混合 MXFP8/Block FP8、全 Block FP8 或全 HiF8。 |144| `recipe` | `all_mxfp8`、`mix`、`all_block_fp8`、`all_hif8` | 选择全 MXFP8、混合 MXFP8/Block FP8、全 Block FP8 或全 HiF8。 |
145| `enable-mxfp4-qat` | `--enable-mxfp4-qat` / `--no-enable-mxfp4-qat` | 为 routed expert 启用或关闭 MXFP4 QAT 约束,默认关闭。 |145| `enable-mxfp4-qat` | `--enable-mxfp4-qat` / `--no-enable-mxfp4-qat` | 为 routed expert 启用或关闭 MXFP4 QAT 约束,默认关闭。 |
146-| `li-quantization` | `fp8`、`mxfp8`、`mxfp4`、`hif8` | 选择 DeepSeek-V4 LI Q/K 的量化类型,默认不启用。 |146+| `li-quantization` | `fp8`、`mxfp8`、`mxfp4`、`hif8` | 选择 LI Q/K 的量化类型,默认不启用;DeepSeek-V4.1 仅支持 `mxfp4`。 |
147| `kv-norm-quantization.format` | `mxfp8` | 启用 DeepSeek-V4 KV Cache 的 MXFP8 量化。 |147| `kv-norm-quantization.format` | `mxfp8` | 启用 DeepSeek-V4 KV Cache 的 MXFP8 量化。 |
148| `enable-fsdp-prequantize` | `--enable-fsdp-prequantize` / `--no-enable-fsdp-prequantize` | 在 FSDP all-gather 前预量化 Block FP8 权重,减少通信量,默认关闭。 |148| `enable-fsdp-prequantize` | `--enable-fsdp-prequantize` / `--no-enable-fsdp-prequantize` | 在 FSDP all-gather 前预量化 Block FP8 权重,减少通信量,默认关闭。 |
149| `enable-hif8-save-quant-codes` | `--enable-hif8-save-quant-codes` / `--no-enable-hif8-save-quant-codes` | 把 HiF8 量化矩乘算子(`npu_quantize`/`npu_dynamic_quant`/`npu_grouped_matmul`/`npu_quant_matmul`)结果保留在 selective activation checkpointing 保存边界内,backward 不再重新推导;仅在 `recipe=all_hif8` 时生效,默认关闭。 |149| `enable-hif8-save-quant-codes` | `--enable-hif8-save-quant-codes` / `--no-enable-hif8-save-quant-codes` | 把 HiF8 量化矩乘算子(`npu_quantize`/`npu_dynamic_quant`/`npu_grouped_matmul`/`npu_quant_matmul`)结果保留在 selective activation checkpointing 保存边界内,backward 不再重新推导;仅在 `recipe=all_hif8` 时生效,默认关闭。 |
@@ -151,19 +151,23 @@ bash examples/deepseek_v4/deepseek_v4_flash_cpt_4k_a3.sh \
151 151 
152### DeepSeek-V4.1 TorchAO-NPU 低精度训练152### DeepSeek-V4.1 TorchAO-NPU 低精度训练
153 153 
154-DeepSeek-V4.1 复用上述 TorchAO-NPU 低精度入口,当前面向 A5(Ascend 950)硬件。稀疏 attention 量化的配置、依赖和限制见[低精度训练特性指南](../feature_guides/low_precision_training.md#deepseek-v41-稀疏-attention-量化)。154+DeepSeek-V4.1 复用上述 TorchAO-NPU 低精度入口,当前面向 A5(Ascend 950)硬件。Lightning Indexer 与稀疏 attention 量化的配置、组合、依赖和限制见[低精度训练特性指南](../feature_guides/low_precision_training.md#deepseek-v41-li-与稀疏-attention-量化)。
155 155 
156-DeepSeek-V4.1 稀疏 attention 的 KV Cache 量化使用独立的156+DeepSeek-V4.1 使用 `li-quantization=mxfp4` 启用 Lightning Indexer量化,使用
157-`enable-sparse-attention-quantization` 开关。上述配置的默认值、组合限制和完整参数见[低精度训练特性指南](../feature_guides/low_precision_training.md)。启动日志中出现 `Applied TorchAO-NPU recipe=...` 表示 recipe 已应用。157+`enable-sparse-attention-quantization` 启用 KV source Compressor 与稀疏 attention 量化。两项可在
158+标准 A5 融合路径提供 BF16 fallback 的前提下独立选择;`USE_GOLDEN=1` 不提供这些
159+fallback。启动日志中出现
160+`Applied TorchAO-NPU recipe=...` 表示 recipe 已应用。
158 161 
159-deepseek v4.1 模型做低精预训练可运行以下脚本:162+DeepSeek-V4.1 模型做 Block FP8 低精度预训练可运行以下脚本:
160 163 
161```bash164```bash
162HF_ASSETS_PATH=/path/to/DeepSeek-V41_tokenizer \165HF_ASSETS_PATH=/path/to/DeepSeek-V41_tokenizer \
163bash examples/deepseek_v4_1/debug/deepseek_v4_1_flash_8p_cpt_4k_a5.sh166bash examples/deepseek_v4_1/debug/deepseek_v4_1_flash_8p_cpt_4k_a5.sh
164```167```
165 168 
166-deepseek v4.1 模型做QAT训练可运行以下脚本:169+DeepSeek-V4.1 模型做 QAT 训练可运行以下脚本。该入口同时启用 routed expert MXFP4
170+fake quant、Lightning Indexer 和稀疏 attention/KV source Compressor 量化:
167 171 
168```bash172```bash
169HF_ASSETS_PATH=/path/to/DeepSeek-V41_tokenizer \173HF_ASSETS_PATH=/path/to/DeepSeek-V41_tokenizer \
@@ -7,6 +7,8 @@
7# A5 wrapper around the common DeepSeek-V4.1 Flash CPT launcher. Keep the shared7# A5 wrapper around the common DeepSeek-V4.1 Flash CPT launcher. Keep the shared
8# model, training, and parallelism defaults in the A3 script; this entrypoint8# model, training, and parallelism defaults in the A3 script; this entrypoint
9# only supplies A5-specific runtime and fused-operator settings.9# only supplies A5-specific runtime and fused-operator settings.
10+# This entry enables routed-expert MXFP4 fake quant, V4.1 QLI/QSLI, and
11+# sparse-attention/KV-source Compressor quantization.
10# Append CLI arguments to override the defaults below:12# Append CLI arguments to override the defaults below:
11# ./examples/deepseek_v4_1/debug/deepseek_v4_1_flash_8p_qat_4k_a5.sh --training.steps 513# ./examples/deepseek_v4_1/debug/deepseek_v4_1_flash_8p_qat_4k_a5.sh --training.steps 5
12 14 
@@ -18,6 +20,7 @@ QUANTIZATION_ARGS=(
18 --extension.quantization.enable-quantized-training20 --extension.quantization.enable-quantized-training
19 --extension.quantization.recipe all_block_fp821 --extension.quantization.recipe all_block_fp8
20 --extension.quantization.enable-mxfp4-qat22 --extension.quantization.enable-mxfp4-qat
23+ --extension.quantization.li-quantization mxfp4
21 --extension.quantization.enable-sparse-attention-quantization24 --extension.quantization.enable-sparse-attention-quantization
22)25)
23 26 
@@ -20,9 +20,8 @@
20# Run from the repository root:20# Run from the repository root:
21# NGPU=1 bash examples/deepseek_v4_1/debug/deepseek_v4_1_stripped_1p_a5.sh --training.steps 521# NGPU=1 bash examples/deepseek_v4_1/debug/deepseek_v4_1_stripped_1p_a5.sh --training.steps 5
22#22#
23-# Append CLI arguments to override the defaults below. The fused ds41 pair is selected23+# Append CLI arguments to override the defaults below. The TorchAO-NPU option replaces
24-# explicitly, because the override defaults to the pre-quantization kernel; set LEGACY=1 to24+# the selector with QLI/QSLI; sparse attention remains the BF16 teacher provider.
25-# drive the same layers with that pool-free kernel instead.
26 25 
27set -euo pipefail26set -euo pipefail
28 27 
@@ -37,15 +36,12 @@ export TORCHTITAN_ENGRAM_TABLE_ROWS="${TORCHTITAN_ENGRAM_TABLE_ROWS:-100000}"
37# SMLA's backward emits, and the model refuses a half-fused stack rather than training an36# SMLA's backward emits, and the model refuses a half-fused stack rather than training an
38# indexer that never receives a gradient.37# indexer that never receives a gradient.
39#38#
40-# `legacy` is passed explicitly because the override now defaults to the pre-quantization
41-# kernel; this example exists to drive the quantized pair, so it opts in. LEGACY=1 selects
42-# the pool-free kernel instead, which is the baseline the pooled path is measured against.
43LIGHTNING_INDEXER_OVERRIDE="torchtitan_npu.override.deepseek_v4_1.lightning_indexer.asc"39LIGHTNING_INDEXER_OVERRIDE="torchtitan_npu.override.deepseek_v4_1.lightning_indexer.asc"
44-if [[ "${LEGACY:-0}" == "1" ]]; then40+ 
45- LIGHTNING_INDEXER_OVERRIDE="${LIGHTNING_INDEXER_OVERRIDE}={\"legacy\":true}"41+QUANTIZATION_ARGS=(
46-else42+ --extension.quantization.enable-quantized-training
47- LIGHTNING_INDEXER_OVERRIDE="${LIGHTNING_INDEXER_OVERRIDE}={\"legacy\":false}"43+ --extension.quantization.li-quantization mxfp4
48-fi44+)
49 45 
50CLI_OVERRIDES="${CLI_OVERRIDES:-torchtitan_npu.override.common.rms_norm.asc \46CLI_OVERRIDES="${CLI_OVERRIDES:-torchtitan_npu.override.common.rms_norm.asc \
51 torchtitan_npu.override.common.rope.asc_complex \47 torchtitan_npu.override.common.rope.asc_complex \
@@ -71,4 +67,5 @@ exec bash scripts/run_train.sh \
71 --checkpoint.no-enable \67 --checkpoint.no-enable \
72 --metrics.log-freq 1 \68 --metrics.log-freq 1 \
73 --override.imports ${CLI_OVERRIDES} \69 --override.imports ${CLI_OVERRIDES} \
70+ "${QUANTIZATION_ARGS[@]}" \
74 "$@"71 "$@"
@@ -170,7 +170,7 @@ bash examples/deepseek_v4_1/debug/deepseek_v4_1_flash_8p_cpt_4k_a3.sh \
170| `common.rope.asc_partial`(A5 文本) | 同上三处文本位点;单个 `inplace_partial_rotary_mul` 只旋转尾部 `dim` 通道 | AscendC partial rotary |170| `common.rope.asc_partial`(A5 文本) | 同上三处文本位点;单个 `inplace_partial_rotary_mul` 只旋转尾部 `dim` 通道 | AscendC partial rotary |
171| `common.rope.asc_half_rotation` | 视觉塔 2D 位置表的 half 旋转(半宽 cos/sin,融合前复制为全宽表,逐 batch 折叠保位置) | 同上 |171| `common.rope.asc_half_rotation` | 视觉塔 2D 位置表的 half 旋转(半宽 cos/sin,融合前复制为全宽表,逐 batch 折叠保位置) | 同上 |
172| `sparse_attn.asc`(仅 A5,须与下一行同开) | 替换完整 attention forward;反向除自身梯度外还在 `topk_scores` 梯度上产出 indexer 教师 | Ascend sparse flash MLA |172| `sparse_attn.asc`(仅 A5,须与下一行同开) | 替换完整 attention forward;反向除自身梯度外还在 `topk_scores` 梯度上产出 indexer 教师 | Ascend sparse flash MLA |
173-| `lightning_indexer.asc`(仅 A5,须与上一行同开) | 替换 selector 节点;候选池由量化算子对 `ds41.quant_lightning_indexer` / `quant_sparse_lightning_indexer` 承担,条目默认走未量化 `lightning_indexer`,加 `={"legacy":false}` 启用 | QLI / QSLI / SLIKG |173+| `lightning_indexer.asc`(仅 A5,须与上一行同开) | 替换 selector 节点 |
174| `common.swiglu_group.asc`(仅 A5) | `*.moe.routed_experts.inner_experts` 的 grouped SwiGLU(FQN 限定) | cann_ops_nn.swiglu_group |174| `common.swiglu_group.asc`(仅 A5) | `*.moe.routed_experts.inner_experts` 的 grouped SwiGLU(FQN 限定) | cann_ops_nn.swiglu_group |
175| `common.swiglu_group.asc_shared_experts`(仅 A5) | `*.moe.shared_experts` 的 SwiGLU(FQN 限定,不替换视觉 MLP) | 同上 |175| `common.swiglu_group.asc_shared_experts`(仅 A5) | `*.moe.shared_experts` 的 SwiGLU(FQN 限定,不替换视觉 MLP) | 同上 |
176| `common.token_dispatcher.asc` | 公共 MoE 的 permute / re-routing / unpermute;reference 不启用 | Ascend token dispatcher |176| `common.token_dispatcher.asc` | 公共 MoE 的 permute / re-routing / unpermute;reference 不启用 | Ascend token dispatcher |
@@ -0,0 +1,276 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved.
2+#
3+# This source code is licensed under the BSD-style license found in the
4+# LICENSE file in the root directory of this source tree.
5+ 
6+from types import SimpleNamespace
7+ 
8+import pytest
9+import torch
10+from torchao.quantization.qat import QATStep
11+from torchao_npu.configs.module_swap_configs.quant_v41_lightning_indexer import (
12+ QuantV41LightningIndexerConfig,
13+ _quant_v41_lightning_indexer_transform,
14+)
15+from torchao_npu.quantized_modules import v41_lightning_indexer as lightning_indexer
16+ 
17+ 
18+def _metadata(tokens=4, compressed_tokens=2):
19+ compressed = SimpleNamespace(
20+ cu_seqlens=torch.tensor([0, compressed_tokens], dtype=torch.int32),
21+ residual=torch.zeros(1, dtype=torch.int32),
22+ seqused=torch.tensor([compressed_tokens], dtype=torch.int32),
23+ )
24+ kernel = SimpleNamespace(
25+ q=SimpleNamespace(
26+ cu_seqlens=torch.tensor([0, tokens], dtype=torch.int32),
27+ seqused=torch.tensor([tokens], dtype=torch.int32),
28+ ),
29+ frame_for=lambda ratio: compressed,
30+ )
31+ return SimpleNamespace(kernel=kernel)
32+ 
33+ 
34+def _selector(*, mode="full", candidate_topk_blocks=3):
35+ selector = lightning_indexer.QuantV41LightningIndexer()
36+ selector.index_topk = 4
37+ selector.compress_ratio = 2
38+ selector.candidate_topk_blocks = candidate_topk_blocks
39+ selector.candidate_block_size = 2 if candidate_topk_blocks > 0 else -1
40+ selector.mode = mode
41+ selector.has_candidate_pool = candidate_topk_blocks > 0
42+ selector.num_global_queries = torch.tensor(16.0)
43+ return selector
44+ 
45+ 
46+@pytest.fixture
47+def bypass_mxfp4_pack(monkeypatch):
48+ monkeypatch.setattr(lightning_indexer, "_pack_mxfp4", lambda value: (value, value.new_zeros(1)))
49+ 
50+ 
51+def _inputs():
52+ return (
53+ torch.zeros(1, 4, 2, 64, dtype=torch.bfloat16, requires_grad=True),
54+ torch.zeros(1, 2, 64, dtype=torch.bfloat16, requires_grad=True),
55+ torch.zeros(1, 4, 2, dtype=torch.float32, requires_grad=True),
56+ )
57+ 
58+ 
59+@pytest.mark.parametrize(
60+ "query_count, expected_teacher",
61+ [(8.0, 1.0), (32.0, 0.25), (None, None)],
62+ ids=["two-rows", "eight-rows", "missing-count"],
63+)
64+def test_qli_source_sorts_selection_publishes_pool_and_runs_slikg(
65+ monkeypatch, bypass_mxfp4_pack, query_count, expected_teacher
66+):
67+ q, k, w = _inputs()
68+ selector = _selector()
69+ selector.num_global_queries = None if query_count is None else torch.tensor(query_count)
70+ masks = _metadata()
71+ masks.kernel.q.seqused = torch.tensor([2], dtype=torch.int32)
72+ masks.kernel.frame_for(2).seqused = torch.tensor([1], dtype=torch.int32)
73+ unsorted = torch.tensor([3, -1, 1, 2], dtype=torch.int32).repeat(4, 1).unsqueeze(1)
74+ candidate_blocks = torch.tensor(
75+ [[[0, 1, -1]], [[0, -1, -1]], [[1, 0, -1]], [[1, -1, -1]]],
76+ dtype=torch.int32,
77+ )
78+ seen = {}
79+ 
80+ def qli_metadata(**kwargs):
81+ seen["qli_metadata"] = kwargs
82+ return torch.tensor([7], dtype=torch.int32)
83+ 
84+ def qli(*args, **kwargs):
85+ seen["qli"] = (args, kwargs)
86+ return unsorted, torch.empty(0), candidate_blocks, torch.empty(0)
87+ 
88+ def slikg_metadata(**kwargs):
89+ seen["slikg_metadata"] = kwargs
90+ return torch.tensor([9], dtype=torch.int32)
91+ 
92+ def slikg(**kwargs):
93+ seen["slikg"] = kwargs
94+ return (
95+ torch.full_like(kwargs["q"], 2),
96+ torch.full_like(kwargs["k"], 3),
97+ torch.full_like(kwargs["w"], 4),
98+ torch.empty(0),
99+ )
100+ 
101+ monkeypatch.setattr(
102+ torch.ops.cann_ops_transformer,
103+ "ds41",
104+ SimpleNamespace(
105+ quant_lightning_indexer_metadata=qli_metadata,
106+ quant_lightning_indexer=qli,
107+ ),
108+ raising=False,
109+ )
110+ monkeypatch.setattr(
111+ torch.ops.cann_ops_transformer,
112+ "sparse_lightning_indexer_kl_loss_grad_metadata",
113+ slikg_metadata,
114+ raising=False,
115+ )
116+ monkeypatch.setattr(
117+ torch.ops.cann_ops_transformer,
118+ "sparse_lightning_indexer_kl_loss_grad",
119+ slikg,
120+ raising=False,
121+ )
122+ 
123+ indices, scores, candidate = selector(q, k, w, masks, candidates_BL1C=None)
124+ # A later microbatch must not change the denominator saved with this graph.
125+ selector.num_global_queries = torch.tensor(64.0)
126+ if query_count is None:
127+ with pytest.raises(RuntimeError, match=r"Set Selector\.num_global_queries"):
128+ scores.backward(torch.full_like(scores, 8.0))
129+ assert "slikg" not in seen
130+ return
131+ scores.backward(torch.full_like(scores, 8.0))
132+ 
133+ assert torch.equal(indices[0, 0], torch.tensor([3, 2, 1, -1], dtype=torch.int32))
134+ assert scores.shape == indices.shape and scores.requires_grad
135+ assert torch.equal(candidate, candidate_blocks.unsqueeze(0))
136+ assert seen["qli_metadata"]["candidate_topk_blocks"] == 3
137+ assert seen["qli"][1]["return_value"] is False
138+ assert torch.equal(seen["slikg"]["sparse_indices"], indices.reshape(4, 1, 4))
139+ assert torch.equal(seen["slikg"]["attn_softmax_l1_norm"], torch.full((4, 1, 4), expected_teacher))
140+ for options in (seen["qli_metadata"], seen["qli"][1], seen["slikg_metadata"], seen["slikg"]):
141+ torch.testing.assert_close(options["seqused_q"], torch.tensor([2], dtype=torch.int32))
142+ torch.testing.assert_close(options["seqused_k"], torch.tensor([1], dtype=torch.int32))
143+ assert torch.equal(q.grad, torch.full_like(q, 2))
144+ assert torch.equal(k.grad, torch.full_like(k, 3))
145+ assert torch.equal(w.grad, torch.full_like(w, 4))
146+ 
147+ 
148+def test_qsli_searcher_recovers_candidate_lengths_and_passes_pool_through(monkeypatch, bypass_mxfp4_pack):
149+ q, k, w = _inputs()
150+ selector = _selector(mode="reindex", candidate_topk_blocks=4)
151+ candidate = torch.tensor(
152+ [[[[0, 2, -1, -1]], [[1, -1, -1, -1]], [[0, 1, 2, -1]], [[2, -1, -1, -1]]]],
153+ dtype=torch.int32,
154+ )
155+ topk_indices = torch.arange(4, dtype=torch.int32).repeat(4, 1).unsqueeze(1)
156+ seen = {}
157+ 
158+ def metadata(block_length, **kwargs):
159+ seen["block_length"] = block_length
160+ seen["metadata"] = kwargs
161+ return torch.tensor([7], dtype=torch.int32)
162+ 
163+ def qsli(*args, **kwargs):
164+ seen["qsli"] = (args, kwargs)
165+ return topk_indices, torch.empty(0)
166+ 
167+ monkeypatch.setattr(
168+ torch.ops.cann_ops_transformer,
169+ "ds41",
170+ SimpleNamespace(
171+ quant_sparse_lightning_indexer_metadata=metadata,
172+ quant_sparse_lightning_indexer=qsli,
173+ ),
174+ raising=False,
175+ )
176+ 
177+ indices, scores, candidate_out = selector(q, k, w, _metadata(), candidates_BL1C=candidate)
178+ 
179+ assert indices.shape == scores.shape == (1, 4, 4)
180+ torch.testing.assert_close(candidate_out, candidate, rtol=0, atol=0)
181+ assert torch.equal(seen["block_length"], torch.tensor([[2], [1], [3], [1]], dtype=torch.int32))
182+ assert torch.equal(seen["qsli"][0][4], candidate.squeeze(0))
183+ assert seen["qsli"][0][7:] == (1, 2)
184+ assert seen["qsli"][1]["descale_k"].numel() == 1
185+ for options in (seen["metadata"], seen["qsli"][1]):
186+ torch.testing.assert_close(options["seqused_q"], torch.tensor([4], dtype=torch.int32))
187+ torch.testing.assert_close(options["seqused_k"], torch.tensor([2], dtype=torch.int32))
188+ 
189+ 
190+def test_qli_without_candidate_pool_does_not_publish_kernel_candidate_outputs(monkeypatch, bypass_mxfp4_pack):
191+ q, k, w = _inputs()
192+ selector = _selector(candidate_topk_blocks=-1)
193+ candidate_blocks = torch.zeros((4, 1, 1), dtype=torch.int32)
194+ topk_indices = torch.arange(4, dtype=torch.int32).repeat(4, 1).unsqueeze(1)
195+ seen = {}
196+ 
197+ def metadata(**kwargs):
198+ seen["metadata"] = kwargs
199+ return torch.tensor([7], dtype=torch.int32)
200+ 
201+ def qli(*args, **kwargs):
202+ return topk_indices, torch.empty(0), candidate_blocks, torch.ones_like(candidate_blocks)
203+ 
204+ monkeypatch.setattr(
205+ torch.ops.cann_ops_transformer,
206+ "ds41",
207+ SimpleNamespace(
208+ quant_lightning_indexer_metadata=metadata,
209+ quant_lightning_indexer=qli,
210+ ),
211+ raising=False,
212+ )
213+ 
214+ indices, scores, candidate = selector(q, k, w, _metadata(), candidates_BL1C=None)
215+ 
216+ assert indices.shape == scores.shape == (1, 4, 4)
217+ assert candidate is None
218+ assert seen["metadata"]["candidate_topk_blocks"] == -1
219+ assert seen["metadata"]["candidate_block_size"] == -1
220+ 
221+ 
222+def test_candidate_source_requires_an_enabled_pool():
223+ with pytest.raises(ValueError, match="candidate source requires"):
224+ lightning_indexer._validate_candidate_role(
225+ candidate_topk_blocks=-1,
226+ candidate_block_size=-1,
227+ is_source=True,
228+ candidate=None,
229+ )
230+ 
231+ 
232+def test_pack_mxfp4_uses_ds41_byte_layout(monkeypatch):
233+ q = torch.zeros(2, 3, 64, dtype=torch.bfloat16)
234+ calls = {}
235+ 
236+ def dynamic_mx_quant(value, **kwargs):
237+ calls["value"] = value
238+ calls["kwargs"] = kwargs
239+ return torch.zeros(2, 3, 32, dtype=torch.uint8), torch.zeros(2, 3, 1, 2, dtype=torch.uint8)
240+ 
241+ monkeypatch.setattr(lightning_indexer.torch_npu, "npu_dynamic_mx_quant", dynamic_mx_quant)
242+ 
243+ data, scale = lightning_indexer._pack_mxfp4(q)
244+ 
245+ assert data.shape == (2, 3, 32) and data.dtype is torch.uint8
246+ assert scale.shape == (2, 3, 1, 2) and scale.dtype is torch.uint8
247+ assert calls["value"].is_contiguous()
248+ assert calls["kwargs"]["block_size"] == 32
249+ 
250+ 
251+def test_module_swap_installs_and_restores_the_v41_selector_forward(monkeypatch):
252+ class SelectorHost(torch.nn.Module):
253+ def forward(self, *args, **kwargs):
254+ return "original", args, kwargs
255+ 
256+ host = SelectorHost()
257+ original_forward = host.forward
258+ captured = {}
259+ 
260+ def quantized_forward(self, q, k, w, attention_masks, *, candidates_BL1C):
261+ captured.update(self=self, args=(q, k, w, attention_masks), candidate=candidates_BL1C)
262+ return "quantized"
263+ 
264+ monkeypatch.setattr(lightning_indexer.QuantV41LightningIndexer, "forward", quantized_forward)
265+ _quant_v41_lightning_indexer_transform(host, QuantV41LightningIndexerConfig())
266+ operands = tuple(object() for _ in range(4))
267+ candidate = object()
268+ 
269+ assert host(*operands, candidates_BL1C=candidate) == "quantized"
270+ assert captured == {"self": host, "args": operands, "candidate": candidate}
271+ 
272+ _quant_v41_lightning_indexer_transform(host, QuantV41LightningIndexerConfig(step=QATStep.CONVERT))
273+ result = host(*operands, candidates_BL1C=candidate)
274+ 
275+ assert result[0] == "original"
276+ assert host._torchao_npu_original_forward == original_forward
@@ -7,11 +7,37 @@ from types import SimpleNamespace
7 7 
8import pytest8import pytest
9import torch9import torch
10+from torchao.quantization.qat import QATStep
11+from torchao_npu.configs.module_swap_configs.quant_v41_sparse_attention import (
12+ QuantV41SparseAttentionConfig,
13+ _quant_v41_sparse_attention_transform,
14+)
15+from torchao_npu.quantized_modules import v41_lightning_indexer as lightning_indexer
10from torchao_npu.quantized_modules import v41_sparse_attention as sparse_attention16from torchao_npu.quantized_modules import v41_sparse_attention as sparse_attention
11 17 
12 18 
19+def _metadata(*, tokens=4, compressed_tokens=2):
20+ compressed = SimpleNamespace(
21+ cu_seqlens=torch.tensor([0, compressed_tokens], dtype=torch.int32),
22+ residual=torch.zeros(1, dtype=torch.int32),
23+ seqused=torch.tensor([compressed_tokens], dtype=torch.int32),
24+ )
25+ kernel = SimpleNamespace(
26+ q=SimpleNamespace(
27+ cu_seqlens=torch.tensor([0, tokens], dtype=torch.int32),
28+ seqused=torch.tensor([tokens], dtype=torch.int32),
29+ ),
30+ swa_k=SimpleNamespace(
31+ cu_seqlens=torch.tensor([0, tokens], dtype=torch.int32),
32+ seqused=torch.tensor([tokens], dtype=torch.int32),
33+ ),
34+ frame_for=lambda ratio: compressed,
35+ )
36+ return SimpleNamespace(kernel=kernel)
37+ 
38+ 
13def _fake_mla_apply(captured):39def _fake_mla_apply(captured):
14- def apply(q, swa_k, cmp_k, indices, sinks, attention_masks, scale, ratio, window):40+ def apply(q, swa_k, cmp_k, indices, sinks, attention_masks, scale, ratio, window, scores, wants_teacher):
15 captured.update(41 captured.update(
16 q=q,42 q=q,
17 swa_k=swa_k,43 swa_k=swa_k,
@@ -22,6 +48,8 @@ def _fake_mla_apply(captured):
22 scale=scale,48 scale=scale,
23 ratio=ratio,49 ratio=ratio,
24 window=window,50 window=window,
51+ scores=scores,
52+ wants_teacher=wants_teacher,
25 )53 )
26 lse = torch.zeros((1, q.shape[0], q.shape[1]), dtype=q.dtype, device=q.device)54 lse = torch.zeros((1, q.shape[0], q.shape[1]), dtype=q.dtype, device=q.device)
27 return q, lse55 return q, lse
@@ -44,17 +72,30 @@ def test_sparse_mla_quantizes_only_swa_and_preserves_main_kv_in_both_passes(
44 cmp_k = (72 cmp_k = (
45 torch.ones((cmp_tokens, 1, 4), device=device, dtype=torch.bfloat16, requires_grad=True) if with_shared else None73 torch.ones((cmp_tokens, 1, 4), device=device, dtype=torch.bfloat16, requires_grad=True) if with_shared else None
46 )74 )
47- indices = torch.zeros((4, 1, 2), device=device, dtype=torch.int32) if with_shared else None75+ indices = (
76+ torch.tensor([[[0, -1]], [[1, 0]], [[0, 1]], [[1, -1]]], device=device, dtype=torch.int32)
77+ if with_shared
78+ else None
79+ )
80+ scores = torch.empty((4, 1, 2), device=device, dtype=torch.float32, requires_grad=True) if with_shared else None
48 sinks = torch.ones((2,), device=device, dtype=torch.float32, requires_grad=True)81 sinks = torch.ones((2,), device=device, dtype=torch.float32, requires_grad=True)
49- cu_q = torch.tensor([0, 4], device=device, dtype=torch.int32)82+ attention_masks = _metadata(tokens=4, compressed_tokens=cmp_tokens)
50- cu_cmp = torch.tensor([0, cmp_tokens], device=device, dtype=torch.int32) if with_shared else None83+ attention_masks.kernel.q.seqused = torch.tensor([2], dtype=torch.int32)
51- remainder = torch.zeros((1,), device=device, dtype=torch.int32) if ratio > 1 else None84+ attention_masks.kernel.swa_k.seqused = torch.tensor([3], dtype=torch.int32)
85+ attention_masks.kernel.frame_for(ratio).seqused = torch.tensor([min(cmp_tokens, 1)], dtype=torch.int32)
86+ expected_residual = attention_masks.kernel.frame_for(ratio).residual if ratio > 0 else None
87+ expected_lengths = {
88+ "seqused_q": attention_masks.kernel.q.seqused,
89+ "seqused_ori_kv": attention_masks.kernel.swa_k.seqused,
90+ "seqused_cmp_kv": attention_masks.kernel.frame_for(ratio).seqused if ratio > 0 else None,
91+ }
52 forward_metadata = torch.tensor([7], device=device, dtype=torch.int32)92 forward_metadata = torch.tensor([7], device=device, dtype=torch.int32)
53 grad_metadata = torch.tensor([9], device=device, dtype=torch.int32)93 grad_metadata = torch.tensor([9], device=device, dtype=torch.int32)
54 metadata_calls = []94 metadata_calls = []
55 quantize_calls = []95 quantize_calls = []
56 forward_kwargs = {}96 forward_kwargs = {}
57 lse = torch.zeros((1, q.shape[0], q.shape[1]), device=device, dtype=q.dtype)97 lse = torch.zeros((1, q.shape[0], q.shape[1]), device=device, dtype=q.dtype)
98+ teacher = torch.arange(8, device=device, dtype=torch.float32).reshape(4, 1, 2) if with_shared else torch.empty(0)
58 99 
59 def metadata(*args, **kwargs):100 def metadata(*args, **kwargs):
60 metadata_calls.append((args, kwargs))101 metadata_calls.append((args, kwargs))
@@ -80,16 +121,18 @@ def test_sparse_mla_quantizes_only_swa_and_preserves_main_kv_in_both_passes(
80 assert kwargs["cmp_sparse_indices"] is indices121 assert kwargs["cmp_sparse_indices"] is indices
81 assert kwargs["sinks"] is sinks122 assert kwargs["sinks"] is sinks
82 assert kwargs["metadata"] is grad_metadata123 assert kwargs["metadata"] is grad_metadata
83- assert kwargs["cmp_residual_kv"] is remainder124+ assert kwargs["cmp_residual_kv"] is expected_residual
84 assert kwargs["softmax_scale"] == 0.5125 assert kwargs["softmax_scale"] == 0.5
85 assert kwargs["cmp_ratio"] == max(ratio, 1)126 assert kwargs["cmp_ratio"] == max(ratio, 1)
127+ for name, expected in expected_lengths.items():
128+ assert kwargs[name] is expected
86 return (129 return (
87 torch.full_like(q, 2),130 torch.full_like(q, 2),
88 torch.full_like(swa_k, 3),131 torch.full_like(swa_k, 3),
89 torch.full_like(cmp_k, 4) if cmp_k is not None else None,132 torch.full_like(cmp_k, 4) if cmp_k is not None else None,
90 torch.full_like(sinks, 5),133 torch.full_like(sinks, 5),
91 None,134 None,
92- None,135+ teacher,
93 )136 )
94 137 
95 monkeypatch.setattr(sparse_attention, "sparse_flash_mla_metadata", metadata)138 monkeypatch.setattr(sparse_attention, "sparse_flash_mla_metadata", metadata)
@@ -104,10 +147,12 @@ def test_sparse_mla_quantizes_only_swa_and_preserves_main_kv_in_both_passes(
104 cmp_k,147 cmp_k,
105 indices,148 indices,
106 sinks,149 sinks,
107- forward_metadata,150+ attention_masks,
108 0.5,151 0.5,
109 ratio,152 ratio,
110 2,153 2,
154+ scores,
155+ with_shared,
111 )156 )
112 157 
113 assert returned_lse is lse158 assert returned_lse is lse
@@ -120,22 +165,27 @@ def test_sparse_mla_quantizes_only_swa_and_preserves_main_kv_in_both_passes(
120 assert forward_kwargs["metadata"] is forward_metadata165 assert forward_kwargs["metadata"] is forward_metadata
121 assert forward_kwargs["cmp_sparse_indices"] is indices166 assert forward_kwargs["cmp_sparse_indices"] is indices
122 assert forward_kwargs["sinks"] is sinks167 assert forward_kwargs["sinks"] is sinks
123- assert forward_kwargs["cmp_residual_kv"] is remainder168+ assert forward_kwargs["cmp_residual_kv"] is expected_residual
124- assert len(metadata_calls) == 2
125 169 
126 output.sum().backward()170 output.sum().backward()
171+ 
172+ assert len(metadata_calls) == 2
173+ for options in (forward_kwargs, *(kwargs for _, kwargs in metadata_calls)):
174+ for name, expected in expected_lengths.items():
175+ assert options[name] is expected
127 torch.testing.assert_close(q.grad, torch.full_like(q, 2))176 torch.testing.assert_close(q.grad, torch.full_like(q, 2))
128 torch.testing.assert_close(swa_k.grad, torch.full_like(swa_k, 3))177 torch.testing.assert_close(swa_k.grad, torch.full_like(swa_k, 3))
129 torch.testing.assert_close(sinks.grad, torch.full_like(sinks, 5))178 torch.testing.assert_close(sinks.grad, torch.full_like(sinks, 5))
130 if with_shared:179 if with_shared:
131 torch.testing.assert_close(cmp_k.grad, torch.full_like(cmp_k, 4))180 torch.testing.assert_close(cmp_k.grad, torch.full_like(cmp_k, 4))
181+ torch.testing.assert_close(scores.grad, teacher.masked_fill(indices < 0, 0.0))
132 182 
133 183 
134def test_forward_ratio_zero_passes_window_only_inputs_to_mla(monkeypatch):184def test_forward_ratio_zero_passes_window_only_inputs_to_mla(monkeypatch):
135 captured = {}185 captured = {}
136 monkeypatch.setattr(sparse_attention._SparseMLA, "apply", _fake_mla_apply(captured))186 monkeypatch.setattr(sparse_attention._SparseMLA, "apply", _fake_mla_apply(captured))
137 187 
138- device = "npu"188+ device = "cpu"
139 q = torch.randn((1, 4, 2, 512), device=device, dtype=torch.bfloat16)189 q = torch.randn((1, 4, 2, 512), device=device, dtype=torch.bfloat16)
140 swa_k = torch.randn((1, 4, 512), device=device, dtype=torch.bfloat16)190 swa_k = torch.randn((1, 4, 512), device=device, dtype=torch.bfloat16)
141 metadata = SimpleNamespace(191 metadata = SimpleNamespace(
@@ -163,13 +213,15 @@ def test_forward_ratio_zero_passes_window_only_inputs_to_mla(monkeypatch):
163 assert captured["attention_masks"] is metadata213 assert captured["attention_masks"] is metadata
164 assert captured["ratio"] == 0214 assert captured["ratio"] == 0
165 assert captured["window"] == 3215 assert captured["window"] == 3
216+ assert captured["scores"] is None
217+ assert captured["wants_teacher"] is False
166 218 
167 219 
168def test_forward_ratio_one_uses_full_resolution_shared_kv_without_residual(monkeypatch):220def test_forward_ratio_one_uses_full_resolution_shared_kv_without_residual(monkeypatch):
169 captured = {}221 captured = {}
170 monkeypatch.setattr(sparse_attention._SparseMLA, "apply", _fake_mla_apply(captured))222 monkeypatch.setattr(sparse_attention._SparseMLA, "apply", _fake_mla_apply(captured))
171 223 
172- device = "npu"224+ device = "cpu"
173 q = torch.randn((1, 4, 2, 512), device=device, dtype=torch.bfloat16)225 q = torch.randn((1, 4, 2, 512), device=device, dtype=torch.bfloat16)
174 swa_k = torch.randn((1, 4, 512), device=device, dtype=torch.bfloat16)226 swa_k = torch.randn((1, 4, 512), device=device, dtype=torch.bfloat16)
175 cmp_k = torch.randn((1, 4, 512), device=device, dtype=torch.bfloat16)227 cmp_k = torch.randn((1, 4, 512), device=device, dtype=torch.bfloat16)
@@ -182,6 +234,7 @@ def test_forward_ratio_one_uses_full_resolution_shared_kv_without_residual(monke
182 softmax_scale=0.125,234 softmax_scale=0.125,
183 compress_ratio=1,235 compress_ratio=1,
184 )236 )
237+ topk_scores = torch.empty((1, 4, 2), device=device, dtype=torch.float32, requires_grad=True)
185 238 
186 output = module(239 output = module(
187 q,240 q,
@@ -190,18 +243,21 @@ def test_forward_ratio_one_uses_full_resolution_shared_kv_without_residual(monke
190 metadata,243 metadata,
191 cmp_k=cmp_k,244 cmp_k=cmp_k,
192 topk_indices=torch.zeros((1, 4, 2), device=device, dtype=torch.int64),245 topk_indices=torch.zeros((1, 4, 2), device=device, dtype=torch.int64),
246+ topk_scores=topk_scores,
193 )247 )
194 248 
195 assert output.shape == q.shape249 assert output.shape == q.shape
196 assert captured["attention_masks"] is metadata250 assert captured["attention_masks"] is metadata
197 assert captured["cmp_k"].shape == (4, 1, 512)251 assert captured["cmp_k"].shape == (4, 1, 512)
252+ assert captured["scores"].shape == (4, 1, 2)
253+ assert captured["wants_teacher"] is True
198 254 
199 255 
200def test_forward_ratio_two_passes_the_selection_through_in_tnd_layout(monkeypatch):256def test_forward_ratio_two_passes_the_selection_through_in_tnd_layout(monkeypatch):
201 captured = {}257 captured = {}
202 monkeypatch.setattr(sparse_attention._SparseMLA, "apply", _fake_mla_apply(captured))258 monkeypatch.setattr(sparse_attention._SparseMLA, "apply", _fake_mla_apply(captured))
203 259 
204- device = "npu"260+ device = "cpu"
205 q = torch.randn((1, 4, 2, 512), device=device, dtype=torch.bfloat16)261 q = torch.randn((1, 4, 2, 512), device=device, dtype=torch.bfloat16)
206 swa_k = torch.randn((1, 4, 512), device=device, dtype=torch.bfloat16)262 swa_k = torch.randn((1, 4, 512), device=device, dtype=torch.bfloat16)
207 cmp_k = torch.randn((1, 2, 512), device=device, dtype=torch.bfloat16)263 cmp_k = torch.randn((1, 2, 512), device=device, dtype=torch.bfloat16)
@@ -219,6 +275,7 @@ def test_forward_ratio_two_passes_the_selection_through_in_tnd_layout(monkeypatc
219 softmax_scale=0.25,275 softmax_scale=0.25,
220 compress_ratio=2,276 compress_ratio=2,
221 )277 )
278+ topk_scores = torch.empty((1, 4, 2), device=device, dtype=torch.float32, requires_grad=True)
222 279 
223 output = module(280 output = module(
224 q,281 q,
@@ -227,6 +284,7 @@ def test_forward_ratio_two_passes_the_selection_through_in_tnd_layout(monkeypatc
227 metadata,284 metadata,
228 cmp_k=cmp_k,285 cmp_k=cmp_k,
229 topk_indices=topk_indices,286 topk_indices=topk_indices,
287+ topk_scores=topk_scores,
230 )288 )
231 289 
232 assert output.shape == q.shape290 assert output.shape == q.shape
@@ -236,3 +294,165 @@ def test_forward_ratio_two_passes_the_selection_through_in_tnd_layout(monkeypatc
236 assert captured["indices"].reshape(1, 4, 2).tolist() == topk_indices.tolist()294 assert captured["indices"].reshape(1, 4, 2).tolist() == topk_indices.tolist()
237 assert captured["cmp_k"].shape == (2, 1, 512)295 assert captured["cmp_k"].shape == (2, 1, 512)
238 assert captured["ratio"] == 2296 assert captured["ratio"] == 2
297+ assert captured["scores"].shape == (4, 1, 2)
298+ assert captured["wants_teacher"] is True
299+ 
300+ 
301+def test_forward_eval_keeps_sparse_quantization_without_teacher_carrier(monkeypatch):
302+ captured = {}
303+ monkeypatch.setattr(sparse_attention._SparseMLA, "apply", _fake_mla_apply(captured))
304+ module = sparse_attention.QuantV41SparseAttention(window_size=3, softmax_scale=0.125, compress_ratio=1)
305+ module.eval()
306+ q = torch.zeros((1, 4, 2, 4), dtype=torch.bfloat16)
307+ cmp_k = torch.zeros((1, 4, 4), dtype=torch.bfloat16)
308+ 
309+ output = module(
310+ q,
311+ torch.zeros((1, 4, 4), dtype=torch.bfloat16),
312+ torch.zeros(2, dtype=torch.float32),
313+ _metadata(tokens=4, compressed_tokens=4),
314+ cmp_k=cmp_k,
315+ topk_indices=torch.zeros((1, 4, 2), dtype=torch.int32),
316+ )
317+ 
318+ assert output.shape == q.shape
319+ assert captured["scores"] is None
320+ assert captured["wants_teacher"] is False
321+ 
322+ 
323+def test_forward_training_requires_teacher_carrier_for_compressed_kv():
324+ module = sparse_attention.QuantV41SparseAttention(window_size=3, softmax_scale=0.125, compress_ratio=1)
325+ 
326+ with pytest.raises(ValueError, match="requires topk_scores"):
327+ module(
328+ torch.zeros((1, 4, 2, 4), dtype=torch.bfloat16),
329+ torch.zeros((1, 4, 4), dtype=torch.bfloat16),
330+ torch.zeros(2, dtype=torch.float32),
331+ _metadata(tokens=4, compressed_tokens=4),
332+ cmp_k=torch.zeros((1, 4, 4), dtype=torch.bfloat16),
333+ topk_indices=torch.zeros((1, 4, 2), dtype=torch.int32),
334+ )
335+ 
336+ 
337+def test_module_swap_forwards_teacher_carrier_and_restores_original(monkeypatch):
338+ class SparseAttentionHost(torch.nn.Module):
339+ def forward(self, *args, **kwargs):
340+ return "original", args, kwargs
341+ 
342+ host = SparseAttentionHost()
343+ original_forward = host.forward
344+ captured = {}
345+ 
346+ def quantized_forward(self, q, swa_k, attn_sink, attention_masks, **kwargs):
347+ captured.update(self=self, args=(q, swa_k, attn_sink, attention_masks), kwargs=kwargs)
348+ return "quantized"
349+ 
350+ monkeypatch.setattr(sparse_attention.QuantV41SparseAttention, "forward", quantized_forward)
351+ _quant_v41_sparse_attention_transform(host, QuantV41SparseAttentionConfig())
352+ operands = tuple(object() for _ in range(4))
353+ cmp_k, indices, scores = object(), object(), object()
354+ 
355+ assert host(*operands, cmp_k=cmp_k, topk_indices=indices, topk_scores=scores, ignored=True) == "quantized"
356+ assert captured["self"] is host
357+ assert captured["args"] == operands
358+ assert captured["kwargs"] == {"cmp_k": cmp_k, "topk_indices": indices, "topk_scores": scores}
359+ 
360+ _quant_v41_sparse_attention_transform(host, QuantV41SparseAttentionConfig(step=QATStep.CONVERT))
361+ result = host(*operands, topk_scores=scores)
362+ 
363+ assert result[0] == "original"
364+ assert host._torchao_npu_original_forward == original_forward
365+ 
366+ 
367+def test_quantized_sparse_teacher_reaches_quantized_lightning_indexer_slikg(monkeypatch):
368+ tokens, topk = 4, 2
369+ attention_masks = _metadata(tokens=tokens, compressed_tokens=2)
370+ idx_q = torch.zeros((tokens, 2, 4), dtype=torch.bfloat16, requires_grad=True)
371+ idx_k = torch.zeros((2, 1, 4), dtype=torch.bfloat16, requires_grad=True)
372+ idx_w = torch.zeros((tokens, 2), dtype=torch.float32, requires_grad=True)
373+ selected = torch.tensor([[[1, -1]], [[1, 0]], [[1, 0]], [[0, -1]]], dtype=torch.int32)
374+ teacher = torch.arange(tokens * topk, dtype=torch.float32).reshape(tokens, 1, topk)
375+ seen = {}
376+ 
377+ monkeypatch.setattr(lightning_indexer, "_pack_mxfp4", lambda value: (value, value.new_zeros(1)))
378+ monkeypatch.setattr(
379+ torch.ops.cann_ops_transformer,
380+ "ds41",
381+ SimpleNamespace(
382+ quant_lightning_indexer_metadata=lambda **kwargs: torch.tensor([1], dtype=torch.int32),
383+ quant_lightning_indexer=lambda *args, **kwargs: (selected, torch.empty(0), torch.empty(0), torch.empty(0)),
384+ ),
385+ raising=False,
386+ )
387+ monkeypatch.setattr(
388+ torch.ops.cann_ops_transformer,
389+ "sparse_lightning_indexer_kl_loss_grad_metadata",
390+ lambda **kwargs: torch.tensor([2], dtype=torch.int32),
391+ raising=False,
392+ )
393+ 
394+ def slikg(**kwargs):
395+ seen["teacher"] = kwargs["attn_softmax_l1_norm"]
396+ return torch.full_like(idx_q, 2), torch.full_like(idx_k, 3), torch.full_like(idx_w, 4), torch.empty(0)
397+ 
398+ monkeypatch.setattr(
399+ torch.ops.cann_ops_transformer,
400+ "sparse_lightning_indexer_kl_loss_grad",
401+ slikg,
402+ raising=False,
403+ )
404+ monkeypatch.setattr(sparse_attention, "sparse_flash_mla_metadata", lambda *args, **kwargs: torch.tensor([3]))
405+ monkeypatch.setattr(sparse_attention, "sparse_flash_mla_grad_metadata", lambda *args, **kwargs: torch.tensor([4]))
406+ monkeypatch.setattr(sparse_attention, "fake_quantize_mx_bf16", lambda value, **kwargs: value)
407+ monkeypatch.setattr(
408+ torch.ops.cann_ops_transformer,
409+ "sparse_flash_mla",
410+ lambda q, **kwargs: (q + 1, torch.zeros((1, tokens, q.shape[1]), dtype=q.dtype)),
411+ )
412+ 
413+ def sparse_flash_mla_grad(q, grad_output, output, lse, **kwargs):
414+ return (
415+ torch.ones_like(q),
416+ torch.ones_like(kwargs["ori_kv"]),
417+ torch.ones_like(kwargs["cmp_kv"]),
418+ torch.ones_like(kwargs["sinks"]),
419+ None,
420+ teacher,
421+ )
422+ 
423+ monkeypatch.setattr(torch.ops.cann_ops_transformer, "sparse_flash_mla_grad", sparse_flash_mla_grad)
424+ 
425+ indices, scores, _ = lightning_indexer._QuantV41LightningIndexerTND.apply(
426+ idx_q,
427+ idx_k,
428+ idx_w,
429+ topk,
430+ 2,
431+ attention_masks,
432+ -1,
433+ -1,
434+ False,
435+ None,
436+ torch.tensor(16.0),
437+ )
438+ output, _ = sparse_attention._SparseMLA.apply(
439+ torch.zeros((tokens, 2, 4), dtype=torch.bfloat16, requires_grad=True),
440+ torch.zeros((tokens, 1, 4), dtype=torch.bfloat16, requires_grad=True),
441+ torch.zeros((2, 1, 4), dtype=torch.bfloat16, requires_grad=True),
442+ indices,
443+ torch.zeros(2, dtype=torch.float32, requires_grad=True),
444+ attention_masks,
445+ 0.5,
446+ 2,
447+ 3,
448+ scores,
449+ True,
450+ )
451+ 
452+ output.sum().backward()
453+ 
454+ expected_teacher = teacher.masked_fill(indices < 0, 0.0) / 16.0
455+ torch.testing.assert_close(seen["teacher"], expected_teacher)
456+ torch.testing.assert_close(idx_q.grad, torch.full_like(idx_q, 2))
457+ torch.testing.assert_close(idx_k.grad, torch.full_like(idx_k, 3))
458+ torch.testing.assert_close(idx_w.grad, torch.full_like(idx_w, 4))
@@ -8,6 +8,7 @@ from torchao_npu.configs import (
8 ParamSwapConfig,8 ParamSwapConfig,
9 QuantCompressorConfig,9 QuantCompressorConfig,
10 QuantLightningIndexerConfig,10 QuantLightningIndexerConfig,
11+ QuantV41LightningIndexerConfig,
11 QuantV41SparseAttentionConfig,12 QuantV41SparseAttentionConfig,
12)13)
13 14 
@@ -16,6 +17,7 @@ __all__ = [
16 "ParamSwapConfig",17 "ParamSwapConfig",
17 "QuantCompressorConfig",18 "QuantCompressorConfig",
18 "QuantLightningIndexerConfig",19 "QuantLightningIndexerConfig",
20+ "QuantV41LightningIndexerConfig",
19 "QuantV41SparseAttentionConfig",21 "QuantV41SparseAttentionConfig",
20]22]
21 23 
@@ -9,6 +9,7 @@ from torchao_npu.configs.module_swap import ModuleSwapConfig
9from torchao_npu.configs.module_swap_configs import (9from torchao_npu.configs.module_swap_configs import (
10 QuantCompressorConfig,10 QuantCompressorConfig,
11 QuantLightningIndexerConfig,11 QuantLightningIndexerConfig,
12+ QuantV41LightningIndexerConfig,
12 QuantV41SparseAttentionConfig,13 QuantV41SparseAttentionConfig,
13 quant_mode_for_config,14 quant_mode_for_config,
14)15)
@@ -19,6 +20,7 @@ __all__ = [
19 "ParamSwapConfig",20 "ParamSwapConfig",
20 "QuantCompressorConfig",21 "QuantCompressorConfig",
21 "QuantLightningIndexerConfig",22 "QuantLightningIndexerConfig",
23+ "QuantV41LightningIndexerConfig",
22 "QuantV41SparseAttentionConfig",24 "QuantV41SparseAttentionConfig",
23 "quant_mode_for_config",25 "quant_mode_for_config",
24]26]
@@ -8,6 +8,7 @@
8__all__ = [8__all__ = [
9 "QuantCompressorConfig",9 "QuantCompressorConfig",
10 "QuantLightningIndexerConfig",10 "QuantLightningIndexerConfig",
11+ "QuantV41LightningIndexerConfig",
11 "QuantV41SparseAttentionConfig",12 "QuantV41SparseAttentionConfig",
12 "quant_mode_for_config",13 "quant_mode_for_config",
13]14]
@@ -17,4 +18,5 @@ from torchao_npu.configs.module_swap_configs.quant_lightning_indexer import (
17 QuantLightningIndexerConfig,18 QuantLightningIndexerConfig,
18 quant_mode_for_config,19 quant_mode_for_config,
19)20)
21+from torchao_npu.configs.module_swap_configs.quant_v41_lightning_indexer import QuantV41LightningIndexerConfig
20from torchao_npu.configs.module_swap_configs.quant_v41_sparse_attention import QuantV41SparseAttentionConfig22from torchao_npu.configs.module_swap_configs.quant_v41_sparse_attention import QuantV41SparseAttentionConfig
@@ -0,0 +1,54 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved.
2+#
3+# This source code is licensed under the BSD-style license found in the
4+# LICENSE file in the root directory of this source tree.
5+ 
6+"""Module-swap configuration for the DeepSeek-V4.1 QLI/QSLI path."""
7+ 
8+__all__ = ["QuantV41LightningIndexerConfig"]
9+ 
10+from dataclasses import dataclass
11+from types import MethodType
12+ 
13+from torchao.quantization.qat import QATStep
14+from torchao.quantization.transform_module import register_quantize_module_handler
15+ 
16+from torchao_npu.configs.module_swap import ModuleSwapConfig
17+ 
18+ 
19+@dataclass(kw_only=True, slots=True)
20+class QuantV41LightningIndexerConfig(ModuleSwapConfig):
21+ """Install the ds41 MXFP4 QLI/QSLI selector with its SLIKG backward."""
22+ 
23+ 
24+def _quantized_forward(
25+ self,
26+ idx_q_BLHiDi,
27+ idx_k_BNDi,
28+ weights_BLHi,
29+ attention_masks,
30+ *,
31+ candidates_BL1C,
32+):
33+ from torchao_npu.quantized_modules.v41_lightning_indexer import QuantV41LightningIndexer
34+ 
35+ return QuantV41LightningIndexer.forward(
36+ self,
37+ idx_q_BLHiDi,
38+ idx_k_BNDi,
39+ weights_BLHi,
40+ attention_masks,
41+ candidates_BL1C=candidates_BL1C,
42+ )
43+ 
44+ 
45+@register_quantize_module_handler(QuantV41LightningIndexerConfig)
46+def _quant_v41_lightning_indexer_transform(module, config: QuantV41LightningIndexerConfig):
47+ if not hasattr(module, "_torchao_npu_original_forward"):
48+ module._torchao_npu_original_forward = module.forward
49+ if config.step == QATStep.PREPARE:
50+ module._torchao_npu_module_swap_config = config
51+ module.forward = MethodType(_quantized_forward, module)
52+ else:
53+ module.forward = module._torchao_npu_original_forward
54+ return module
@@ -21,13 +21,23 @@ class QuantV41SparseAttentionConfig(ModuleSwapConfig):
21 """Install FP8 SWA fake quantization; main KV is supplied by QuantCompressor."""21 """Install FP8 SWA fake quantization; main KV is supplied by QuantCompressor."""
22 22 
23 23 
24-def _quantized_forward(self, q, swa_k, attn_sink, attention_masks, *, cmp_k=None, topk_indices=None, **kwargs):24+def _quantized_forward(
25+ self,
26+ q,
27+ swa_k,
28+ attn_sink,
29+ attention_masks,
30+ *,
31+ cmp_k=None,
32+ topk_indices=None,
33+ topk_scores=None,
34+ **kwargs,
35+):
25 from torchao_npu.quantized_modules.v41_sparse_attention import QuantV41SparseAttention36 from torchao_npu.quantized_modules.v41_sparse_attention import QuantV41SparseAttention
26 37 
27 # Same argument order as the port this replaces, so the swap stays invisible to the38 # Same argument order as the port this replaces, so the swap stays invisible to the
28- # host. ``topk_scores`` may arrive in kwargs and is ignored: the teacher edge lives39+ # host. Unknown extension keywords remain ignorable, while ``topk_scores`` must keep
29- # in the sparse-attention port, which threads ``topk_scores`` into SMLAG; this module40+ # the SMLAG-to-SLIKG teacher edge intact.
30- # replaces only the attention computation and returns the output unchanged.
31 del kwargs41 del kwargs
32 return QuantV41SparseAttention.forward(42 return QuantV41SparseAttention.forward(
33 self,43 self,
@@ -37,6 +47,7 @@ def _quantized_forward(self, q, swa_k, attn_sink, attention_masks, *, cmp_k=None
37 attention_masks,47 attention_masks,
38 cmp_k=cmp_k,48 cmp_k=cmp_k,
39 topk_indices=topk_indices,49 topk_indices=topk_indices,
50+ topk_scores=topk_scores,
40 )51 )
41 52 
42 53 
@@ -487,9 +487,6 @@ def mxfp4_dequantize(
487 assert output_shape[axis] % block_size == 0, f"quant dim must be divisible by block_size ({block_size})"487 assert output_shape[axis] % block_size == 0, f"quant dim must be divisible by block_size ({block_size})"
488 488 
489 # Use cached 256-entry LUT (indexed by full byte, no nibble splitting)489 # Use cached 256-entry LUT (indexed by full byte, no nibble splitting)
490- # pyrefly: ignore [bad-assignment, bad-argument-type, bad-argument-count]
491- # (_get_fp4_e2m1_pair_lut is wrapped by @torch.compiler.disable, which
492- # collapses its signature to (fn) -> Any in pyrefly's view.)
493 lut: torch.Tensor = _get_fp4_e2m1_pair_lut(data.device, torch.bfloat16, low_first)490 lut: torch.Tensor = _get_fp4_e2m1_pair_lut(data.device, torch.bfloat16, low_first)
494 idx = data.to(torch.uint8).reshape(-1).to(torch.long)491 idx = data.to(torch.uint8).reshape(-1).to(torch.long)
495 values = torch.index_select(lut, dim=0, index=idx)492 values = torch.index_select(lut, dim=0, index=idx)
@@ -528,7 +525,6 @@ def mxfp4_dequantize(
528 return result.to(output_dtype)525 return result.to(output_dtype)
529 526 
530 527 
531-@torch.compiler.disable
532@functools.cache528@functools.cache
533def _get_fp4_e2m1_pair_lut(device, dtype=torch.bfloat16, low_first: bool = True) -> torch.Tensor:529def _get_fp4_e2m1_pair_lut(device, dtype=torch.bfloat16, low_first: bool = True) -> torch.Tensor:
534 """LUT mapping a packed uint8 byte to a pair of decoded FP4 values.530 """LUT mapping a packed uint8 byte to a pair of decoded FP4 values.
@@ -0,0 +1,317 @@
1+# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved.
2+#
3+# This source code is licensed under the BSD-style license found in the
4+# LICENSE file in the root directory of this source tree.
5+ 
6+"""DeepSeek-V4.1 QLI/QSLI selection with an SLIKG backward edge."""
7+ 
8+__all__ = ["QuantV41LightningIndexer"]
9+ 
10+import cann_ops_transformer # noqa: F401 # register torch.ops.cann_ops_transformer
11+import torch
12+import torch_npu
13+ 
14+# This training adapter packs both Q and K as TND with separate scale tensors.
15+_LAYOUT = "TND"
16+# Right-down causal masking matches the BF16 selector and SLIKG backward.
17+# Although QLI/QSLI also support mode 0, switching requires coordinated changes
18+# to model visibility, cmp_residual_k, metadata, and backward semantics.
19+_MASK_MODE = 3
20+# The packed-MXFP4 ABI is the only value either kernel accepts; the number labels the
21+# storage format (two E2M1 values per byte plus uE8M0 scales), it is not a precision knob.
22+_QUANT_MODE = 1
23+# MXFP4 uses one E8M0 scale per 32 elements. The kernels and _pack_mxfp4's
24+# [T, H, D/64, 2] scale layout require this group size.
25+_MX_BLOCK_SIZE = 32
26+ 
27+ 
28+def _kernel_options(attention_masks, ratio: int) -> dict[str, object]:
29+ compressed = attention_masks.kernel.frame_for(ratio)
30+ return {
31+ "cu_seqlens_q": attention_masks.kernel.q.cu_seqlens,
32+ "cu_seqlens_k": compressed.cu_seqlens,
33+ "seqused_q": attention_masks.kernel.q.seqused,
34+ "seqused_k": compressed.seqused,
35+ "cmp_residual_k": compressed.residual,
36+ "layout_q": _LAYOUT,
37+ "layout_k": _LAYOUT,
38+ "mask_mode": _MASK_MODE,
39+ "cmp_ratio": ratio,
40+ }
41+ 
42+ 
43+def _quantized_kernel_geometry(num_heads: int, head_dim: int, topk: int) -> dict[str, int]:
44+ return {
45+ "num_heads_q": num_heads,
46+ "num_heads_k": 1,
47+ "head_dim": head_dim,
48+ "topk": topk,
49+ }
50+ 
51+ 
52+def _slikg_kernel_geometry(num_heads: int, head_dim: int, topk: int) -> dict[str, int | None]:
53+ return {
54+ "num_heads_q": num_heads,
55+ "num_heads_k": 1,
56+ "head_dim": head_dim,
57+ "topk": topk,
58+ "max_seqlen_q": None,
59+ "max_seqlen_k": None,
60+ }
61+ 
62+ 
63+def _pack_mxfp4(x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
zx1029
zx1029zx1029Oct 8

这个量化算子在 torchao_npu/quantization/quant_primitives/mx.py 下边有实现不需要重新写一个

likedislike
xiaomagemafeifei
xiaomagemafeifei
Oct 8 Comments:
likedislike
64+ """Pack one ``[T, H, D]`` operand into the ds41 MXFP4 ABI."""
65+ if x.ndim != 3:
66+ raise ValueError(f"QLI operands must be rank-3 TND tensors, got shape {tuple(x.shape)}")
67+ rows, heads, head_dim = x.shape
68+ if head_dim % 64 != 0:
69+ raise ValueError(f"QLI head_dim must be divisible by 64, got {head_dim}")
70+ data, scale = torch_npu.npu_dynamic_mx_quant(
71+ x.contiguous(),
72+ axis=-1,
73+ dst_type=torch_npu.float4_e2m1fn_x2,
74+ block_size=_MX_BLOCK_SIZE,
75+ round_mode="rint",
76+ scale_alg=2,
77+ dst_type_max=0.0,
78+ )
79+ return (
80+ data.view(torch.uint8).reshape(rows, heads, head_dim // 2).contiguous(),
81+ scale.view(torch.uint8).reshape(rows, heads, head_dim // 64, 2).contiguous(),
82+ )
83+ 
84+ 
85+def _candidate_length(candidate_block_indices: torch.Tensor) -> torch.Tensor:
86+ """Recover the valid prefix length from QLI's contiguous ``-1`` tail."""
87+ return (candidate_block_indices >= 0).sum(dim=-1).to(torch.int32).contiguous()
88+ 
89+ 
90+def _validate_candidate_role(
91+ *,
92+ candidate_topk_blocks: int,
93+ candidate_block_size: int,
94+ is_source: bool,
95+ candidate: torch.Tensor | None,
96+) -> None:
97+ has_candidate_pool = candidate_topk_blocks > 0
98+ if is_source and not has_candidate_pool:
99+ raise ValueError("a candidate source requires candidate_topk_blocks > 0")
100+ if has_candidate_pool and candidate_block_size <= 0:
101+ raise ValueError("an enabled candidate pool requires candidate_block_size > 0")
102+ 
103+ expects_candidate = has_candidate_pool and not is_source
104+ if (candidate is not None) != expects_candidate:
105+ role = (
106+ "a searcher requires the source candidate table"
107+ if expects_candidate
108+ else "this layer cannot consume a candidate table"
109+ )
110+ raise ValueError(f"the candidate table disagrees with this layer's role: {role}")
111+ if candidate is not None and (candidate.ndim != 4 or candidate.shape[0] != 1 or candidate.shape[2] != 1):
112+ raise ValueError(f"the model candidate table must have shape [1, T, 1, capacity], got {tuple(candidate.shape)}")
113+ 
114+ 
115+def _quantized_forward(
116+ idx_q: torch.Tensor,
117+ idx_k: torch.Tensor,
118+ idx_w: torch.Tensor,
119+ topk: int,
120+ *,
121+ candidate_topk_blocks: int,
122+ candidate_block_size: int,
123+ is_source: bool,
124+ candidate: torch.Tensor | None,
125+ **kernel_options,
126+) -> tuple[torch.Tensor, torch.Tensor | None]:
127+ """Run QLI for a producer/pool-free layer or QSLI for a searcher."""
128+ _validate_candidate_role(
129+ candidate_topk_blocks=candidate_topk_blocks,
130+ candidate_block_size=candidate_block_size,
131+ is_source=is_source,
132+ candidate=candidate,
133+ )
134+ 
135+ geometry = _quantized_kernel_geometry(idx_q.shape[1], idx_q.shape[2], topk)
136+ idx_q_mxfp4, idx_q_scale = _pack_mxfp4(idx_q)
137+ idx_k_mxfp4, idx_k_scale = _pack_mxfp4(idx_k)
138+ 
139+ if candidate is None:
140+ qli_metadata = torch.ops.cann_ops_transformer.ds41.quant_lightning_indexer_metadata(
141+ **kernel_options,
142+ **geometry,
143+ candidate_topk_blocks=candidate_topk_blocks,
144+ candidate_block_size=candidate_block_size,
145+ )
146+ topk_indices, _, candidate_block_indices, _ = torch.ops.cann_ops_transformer.ds41.quant_lightning_indexer(
147+ idx_q_mxfp4,
148+ idx_k_mxfp4,
149+ idx_w,
150+ idx_q_scale,
151+ idx_k_scale,
152+ topk,
153+ _QUANT_MODE,
154+ metadata=qli_metadata,
155+ return_value=False,
156+ candidate_topk_blocks=candidate_topk_blocks,
157+ candidate_block_size=candidate_block_size,
158+ **kernel_options,
159+ )
160+ return topk_indices, candidate_block_indices.unsqueeze(0) if is_source else None
161+ 
162+ block_indices = candidate.squeeze(0)
163+ block_length = _candidate_length(block_indices)
164+ qsli_metadata = torch.ops.cann_ops_transformer.ds41.quant_sparse_lightning_indexer_metadata(
165+ block_length,
166+ **kernel_options,
167+ **geometry,
168+ quant_mode=_QUANT_MODE,
169+ candidate_block_size=candidate_block_size,
170+ )
171+ topk_indices, _ = torch.ops.cann_ops_transformer.ds41.quant_sparse_lightning_indexer(
172+ idx_q_mxfp4,
173+ idx_k_mxfp4,
174+ idx_w,
175+ idx_q_scale,
176+ block_indices,
177+ block_length,
178+ topk,
179+ _QUANT_MODE,
180+ candidate_block_size,
181+ descale_k=idx_k_scale,
182+ metadata=qsli_metadata,
183+ return_value=False,
184+ **kernel_options,
185+ )
186+ return topk_indices, candidate
187+ 
188+ 
189+class _QuantV41LightningIndexerTND(torch.autograd.Function):
190+ """QLI/QSLI forward paired with the BF16 SLIKG training backward."""
191+ 
192+ @staticmethod
193+ def forward( # pyrefly: ignore [bad-override]
194+ ctx,
195+ idx_q,
196+ idx_k,
197+ idx_w,
198+ topk,
199+ ratio,
200+ attention_masks,
201+ candidate_topk_blocks,
202+ candidate_block_size,
203+ is_source,
204+ candidate,
205+ num_global_queries,
206+ ):
207+ topk_indices, candidate_out = _quantized_forward(
208+ idx_q,
209+ idx_k,
210+ idx_w,
211+ topk,
212+ candidate_topk_blocks=candidate_topk_blocks,
213+ candidate_block_size=candidate_block_size,
214+ is_source=is_source,
215+ candidate=candidate,
216+ **_kernel_options(attention_masks, ratio),
217+ )
218+ topk_indices = topk_indices.sort(dim=-1, descending=True).values
219+ topk_scores = topk_indices.new_empty(topk_indices.shape, dtype=torch.float32, requires_grad=True)
220+ 
221+ ctx.save_for_backward(idx_q, idx_k, idx_w, topk_indices, num_global_queries)
222+ ctx.topk = topk
223+ ctx.ratio = ratio
224+ ctx.attention_masks = attention_masks
225+ return topk_indices, topk_scores, candidate_out
226+ 
227+ @staticmethod
228+ def backward( # pyrefly: ignore [bad-override]
229+ ctx,
230+ grad_indices,
231+ attn_softmax_l1_norm,
232+ grad_candidate,
233+ ):
234+ del grad_indices, grad_candidate
235+ if attn_softmax_l1_norm is None:
236+ return (None,) * 11
237+ 
238+ idx_q, idx_k, idx_w, topk_indices, num_global_queries = ctx.saved_tensors
239+ if num_global_queries is None:
240+ raise RuntimeError("Set Selector.num_global_queries before training the indexer")
241+ # Match the BF16 path: the trainer counts queries across the full step and DP mesh.
242+ attn_softmax_l1_norm = attn_softmax_l1_norm / num_global_queries
243+ options = _kernel_options(ctx.attention_masks, ctx.ratio)
244+ slikg_metadata = torch.ops.cann_ops_transformer.sparse_lightning_indexer_kl_loss_grad_metadata(
245+ **_slikg_kernel_geometry(idx_q.shape[1], idx_q.shape[2], ctx.topk),
246+ **options,
247+ )
248+ dq, dk, dw, _ = torch.ops.cann_ops_transformer.sparse_lightning_indexer_kl_loss_grad(
249+ q=idx_q,
250+ k=idx_k,
251+ w=idx_w,
252+ sparse_indices=topk_indices,
253+ attn_softmax_l1_norm=attn_softmax_l1_norm,
254+ metadata=slikg_metadata,
255+ **options,
256+ )
257+ return (
258+ dq,
259+ dk,
260+ dw,
261+ None, # topk
262+ None, # ratio
263+ None, # attention_masks
264+ None, # candidate_topk_blocks
265+ None, # candidate_block_size
266+ None, # is_source
267+ None, # candidate
268+ None, # num_global_queries
269+ )
270+ 
271+ 
272+class QuantV41LightningIndexer(torch.nn.Module):
273+ """Forward behavior installed on a DeepSeek-V4.1 ``Selector`` instance."""
274+ 
275+ # The module-swap handler binds this forward to a Selector instance. Declare the
276+ # host-owned fields here so static analysis does not fall back to nn.Module's
277+ # dynamic attribute type (Module | Tensor).
278+ index_topk: int
279+ compress_ratio: int
280+ candidate_topk_blocks: int
281+ candidate_block_size: int
282+ has_candidate_pool: bool
283+ mode: str
284+ num_global_queries: torch.Tensor | None
285+ 
286+ def forward(
287+ self,
288+ idx_q_BLHiDi: torch.Tensor,
289+ idx_k_BNDi: torch.Tensor,
290+ weights_BLHi: torch.Tensor,
291+ attention_masks,
292+ *,
293+ candidates_BL1C: torch.Tensor | None,
294+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]:
295+ if idx_q_BLHiDi.shape[0] != 1 or idx_k_BNDi.shape[0] != 1 or weights_BLHi.shape[0] != 1:
296+ raise ValueError("V4.1 QLI/QSLI requires one packed TND row (model batch size 1)")
297+ 
298+ topk = self.index_topk
299+ is_source = self.has_candidate_pool and self.mode == "full"
300+ topk_indices, topk_scores, candidate = _QuantV41LightningIndexerTND.apply(
301+ idx_q_BLHiDi.squeeze(0),
302+ idx_k_BNDi.squeeze(0).unsqueeze(1),
303+ weights_BLHi.squeeze(0).float(),
304+ topk,
305+ self.compress_ratio,
306+ attention_masks,
307+ self.candidate_topk_blocks,
308+ self.candidate_block_size,
309+ is_source,
310+ candidates_BL1C,
311+ self.num_global_queries,
312+ )
313+ return (
314+ topk_indices.reshape(1, -1, topk),
315+ topk_scores.reshape(1, -1, topk),
316+ candidate,
317+ )
@@ -48,13 +48,16 @@ def _kernel_options(attention_masks, ratio, window_size):
48 convention two call sites have to keep in step.48 convention two call sites have to keep in step.
49 """49 """
50 # Only ratio 0 has no compressed axis, and the kernels spell that ``None``. Every50 # Only ratio 0 has no compressed axis, and the kernels spell that ``None``. Every
51- # other ratio has one -- at ratio 1 it is the row itself and its frame carries no51+ # other ratio has one -- at ratio 1 it is the row itself and its frame carries a zero
52- # residual, which is exactly what the kernel wants there.52+ # residual tensor, which is exactly what the kernel wants there.
53 compressed = attention_masks.kernel.frame_for(ratio) if ratio > 0 else None53 compressed = attention_masks.kernel.frame_for(ratio) if ratio > 0 else None
54 return dict(54 return dict(
55 cu_seqlens_q=attention_masks.kernel.q.cu_seqlens,55 cu_seqlens_q=attention_masks.kernel.q.cu_seqlens,
56 cu_seqlens_ori_kv=attention_masks.kernel.swa_k.cu_seqlens,56 cu_seqlens_ori_kv=attention_masks.kernel.swa_k.cu_seqlens,
57 cu_seqlens_cmp_kv=None if compressed is None else compressed.cu_seqlens,57 cu_seqlens_cmp_kv=None if compressed is None else compressed.cu_seqlens,
58+ seqused_q=attention_masks.kernel.q.seqused,
59+ seqused_ori_kv=attention_masks.kernel.swa_k.seqused,
60+ seqused_cmp_kv=None if compressed is None else compressed.seqused,
58 cmp_residual_kv=None if compressed is None else compressed.residual,61 cmp_residual_kv=None if compressed is None else compressed.residual,
59 cmp_ratio=max(ratio, 1),62 cmp_ratio=max(ratio, 1),
60 ori_mask_mode=4,63 ori_mask_mode=4,
@@ -81,12 +84,16 @@ def _kernel_geometry(topk_indices, cmp_k):
81 84 
82 85 
83class _SparseMLA(torch.autograd.Function):86class _SparseMLA(torch.autograd.Function):
84- """The port's SMLAG with the SWA input fake-quantized.87+ """The port's SMLAG and teacher edge with the SWA input fake-quantized.
85 88 
86 Identical to the override's Function except that ``swa_k`` is Q/DQ'd before the89 Identical to the override's Function except that ``swa_k`` is Q/DQ'd before the
87 kernel call and the *quantized* tensor is what gets saved, so the backward replays90 kernel call and the *quantized* tensor is what gets saved, so the backward replays
88 the same operand the forward used. The quantized tensor's gradient is the gradient91 the same operand the forward used. The quantized tensor's gradient is the gradient
89 the originals would have received, which is the identity STE.92 the originals would have received, which is the identity STE.
93+ 
94+ ``topk_scores`` is an autograd carrier only: forward never reads its value, while
95+ backward publishes SMLAG's compressed-attention marginal as its gradient for the
96+ LightningIndexer SLIKG backward to consume.
90 """97 """
91 98 
92 @staticmethod99 @staticmethod
@@ -101,6 +108,8 @@ class _SparseMLA(torch.autograd.Function):
101 softmax_scale,108 softmax_scale,
102 ratio,109 ratio,
103 window_size,110 window_size,
111+ topk_scores,
112+ wants_teacher,
104 ):113 ):
105 options = _kernel_options(attention_masks, ratio, window_size)114 options = _kernel_options(attention_masks, ratio, window_size)
106 geometry = _kernel_geometry(topk_indices, cmp_k)115 geometry = _kernel_geometry(topk_indices, cmp_k)
@@ -137,6 +146,7 @@ class _SparseMLA(torch.autograd.Function):
137 lse,146 lse,
138 )147 )
139 ctx.softmax_scale, ctx.ratio, ctx.window_size = softmax_scale, ratio, window_size148 ctx.softmax_scale, ctx.ratio, ctx.window_size = softmax_scale, ratio, window_size
149+ ctx.wants_teacher = wants_teacher
140 # The mask is a dataclass, so ``save_for_backward`` cannot take it; it is a150 # The mask is a dataclass, so ``save_for_backward`` cannot take it; it is a
141 # context attribute instead. That is not extra retention: it holds the same151 # context attribute instead. That is not extra retention: it holds the same
142 # boundary tensors the graph already keeps for the backward, and the node -- and152 # boundary tensors the graph already keeps for the backward, and the node -- and
@@ -160,7 +170,7 @@ class _SparseMLA(torch.autograd.Function):
160 **options,170 **options,
161 **_kernel_geometry(topk_indices, cmp_k),171 **_kernel_geometry(topk_indices, cmp_k),
162 )172 )
163- dq, dswa_k, dcmp_k, dsinks, _, _ = torch.ops.cann_ops_transformer.sparse_flash_mla_grad(173+ dq, dswa_k, dcmp_k, dsinks, _, cmp_softmax_l1_norm = torch.ops.cann_ops_transformer.sparse_flash_mla_grad(
164 q,174 q,
165 grad_output.contiguous(),175 grad_output.contiguous(),
166 output,176 output,
@@ -171,18 +181,15 @@ class _SparseMLA(torch.autograd.Function):
171 cmp_sparse_indices=topk_indices,181 cmp_sparse_indices=topk_indices,
172 sinks=sinks,182 sinks=sinks,
173 metadata=smla_grad_metadata,183 metadata=smla_grad_metadata,
174- seqused_q=None,
175- seqused_ori_kv=None,
176- seqused_cmp_kv=None,
177 ori_topk_length=None,184 ori_topk_length=None,
178 cmp_topk_length=None,185 cmp_topk_length=None,
179 softmax_scale=ctx.softmax_scale,186 softmax_scale=ctx.softmax_scale,
180 **options,187 **options,
181 )188 )
182 # One gradient per forward input, in order: (q, swa_k, cmp_k, topk_indices,189 # One gradient per forward input, in order: (q, swa_k, cmp_k, topk_indices,
183- # sinks, attention_masks, softmax_scale, ratio, window_size). PyTorch silently190+ # sinks, attention_masks, softmax_scale, ratio, window_size, topk_scores,
184- # ignores extra trailing entries, so a count mismatch here would not raise -- it191+ # wants_teacher). PyTorch silently ignores extra trailing entries, so spell out
185- # would quietly starve a later input, which is why the list is spelled out.192+ # every slot to keep the teacher on the carrier input.
186 return (193 return (
187 dq,194 dq,
188 dswa_k,195 dswa_k,
@@ -193,6 +200,8 @@ class _SparseMLA(torch.autograd.Function):
193 None,200 None,
194 None,201 None,
195 None,202 None,
203+ (cmp_softmax_l1_norm.masked_fill(topk_indices < 0, 0.0) if ctx.wants_teacher else None),
204+ None,
196 )205 )
197 206 
198 207 
@@ -218,7 +227,17 @@ class QuantV41SparseAttention(torch.nn.Module):
218 *,227 *,
219 cmp_k=None,228 cmp_k=None,
220 topk_indices=None,229 topk_indices=None,
230+ topk_scores=None,
221 ):231 ):
232+ if (cmp_k is None) != (topk_indices is None):
233+ raise ValueError("cmp_k and topk_indices must be provided together")
234+ wants_teacher = self.training and cmp_k is not None
235+ teacher_scores = None
236+ if wants_teacher:
237+ if topk_scores is None:
238+ raise ValueError("QuantV41SparseAttention requires topk_scores to publish the LightningIndexer teacher")
239+ teacher_scores = topk_scores.reshape(-1, 1, topk_scores.shape[-1])
240+ 
222 # The selection arrives document-local from the fused selector, which chose it241 # The selection arrives document-local from the fused selector, which chose it
223 # with the same kernel: the two share one coordinate system, and ``-1`` is how242 # with the same kernel: the two share one coordinate system, and ``-1`` is how
224 # both spell an unused slot. Order is left exactly as it came -- the selector243 # both spell an unused slot. Order is left exactly as it came -- the selector
@@ -237,5 +256,7 @@ class QuantV41SparseAttention(torch.nn.Module):
237 self.softmax_scale,256 self.softmax_scale,
238 self.compress_ratio,257 self.compress_ratio,
239 self.window_size,258 self.window_size,
259+ teacher_scores,
260+ wants_teacher,
240 )261 )
241 return output.reshape_as(q)262 return output.reshape_as(q)
@@ -49,6 +49,7 @@ from torchtitan_npu.models.common.metadata_extension import (
49from torchtitan_npu.models.deepseek_v4.compressor import LightningIndexer49from torchtitan_npu.models.deepseek_v4.compressor import LightningIndexer
50from torchtitan_npu.models.deepseek_v4_1.attention import CompressedSparseInnerAttention250from torchtitan_npu.models.deepseek_v4_1.attention import CompressedSparseInnerAttention2
51from torchtitan_npu.models.deepseek_v4_1.compressor import Compressor as V41Compressor51from torchtitan_npu.models.deepseek_v4_1.compressor import Compressor as V41Compressor
52+from torchtitan_npu.models.deepseek_v4_1.indexer import Selector as V41Selector
52from torchtitan_npu.override.common.swiglu_group.ascendc import AscGroupedExperts, _ensure_cann_ops_loaded53from torchtitan_npu.override.common.swiglu_group.ascendc import AscGroupedExperts, _ensure_cann_ops_loaded
53from torchtitan_npu.patches.torchtitan.models.common.linear import BatchedLinear54from torchtitan_npu.patches.torchtitan.models.common.linear import BatchedLinear
54 55 
@@ -118,6 +119,7 @@ _DEFAULT_TARGET_CONFIG_TYPES = (
118 LightningIndexerMetadata.Config,119 LightningIndexerMetadata.Config,
119 CompressedSparseInnerAttention2.Config,120 CompressedSparseInnerAttention2.Config,
120 V41Compressor.Config,121 V41Compressor.Config,
122+ V41Selector.Config,
121)123)
122 124 
123 125 
@@ -153,6 +155,10 @@ def _get_npu_quantized_module_cls(parent_cls: type[Module]) -> type[Module]:
153 155 
154 NpuQuantizedModule.__name__ = f"NpuQuantized{parent_cls.__name__}"156 NpuQuantizedModule.__name__ = f"NpuQuantized{parent_cls.__name__}"
155 NpuQuantizedModule.__qualname__ = f"NpuQuantized{parent_cls.__name__}"157 NpuQuantizedModule.__qualname__ = f"NpuQuantized{parent_cls.__name__}"
158+ if issubclass(parent_cls, V41Selector):
xuyujun
xuyujunxuyujunOct 9

这里仅按父类无条件标记 teacher consumer/provider,会与实际 forward 不一致。新 handler 的 CONVERT 会恢复原 reference forward,但 converter 生成的 Selector 仍标记 consumes_indexer_teacher=True,配对检查放行后模型不构建 reference metadata,实际 forward 会报错。建议按真正安装的 teacher module swap/step 管理能力,或明确限制不支持的恢复入口,并补 converter 生成的真实 Selector 回归。标准 PREPARE recipe 不受此问题影响。

likedislike
xiaomagemafeifei
xiaomagemafeifei
Oct 9 Comments:
likedislike
wanghui0
wanghui0
Oct 10 Comments:
likedislike
159+ NpuQuantizedModule.Config.consumes_indexer_teacher = True
160+ if issubclass(parent_cls, CompressedSparseInnerAttention2):
161+ NpuQuantizedModule.Config.provides_indexer_teacher = True
156 _npu_quantized_module_cache[parent_cls] = NpuQuantizedModule162 _npu_quantized_module_cache[parent_cls] = NpuQuantizedModule
157 return NpuQuantizedModule163 return NpuQuantizedModule
158 164 
@@ -488,6 +494,7 @@ _DSV41_CONFIG_FILTERS = {
488 "dense": _DSV4_CONFIG_FILTERS["dense"],494 "dense": _DSV4_CONFIG_FILTERS["dense"],
489 "routed_expert": _DSV4_CONFIG_FILTERS["routed_expert"],495 "routed_expert": _DSV4_CONFIG_FILTERS["routed_expert"],
490 "compressor": _is_v41_kv_source,496 "compressor": _is_v41_kv_source,
497+ "lightning_indexer": match_config_fqn_suffix(".attention.indexer.selector"),
491 "sparse_attention": match_config_fqn_suffix(".attention.inner_attention"),498 "sparse_attention": match_config_fqn_suffix(".attention.inner_attention"),
492}499}
493 500 
@@ -888,11 +895,19 @@ def _recipe_converters(
888 ]895 ]
889 896 
890 if li_quantization is not None:897 if li_quantization is not None:
891- li_config = _quant_lightning_indexer(898+ li_config: QuantLightningIndexerConfig | QuantV41LightningIndexerConfig
wanghui0

QuantLightningIndexerConfig改成QuantV4LightningIndexerConfig,以及完成连带相关修改

likedislike
xiaomagemafeifei
xiaomagemafeifei
Oct 9 Comments:
likedislike
892- li_kernel_config or LightningIndexerKernelConfig(),899+ if model_type == "v41":
893- li_quantization=li_quantization,900+ if li_quantization != "mxfp4":
894- dst_type_max=dst_type_max,901+ raise ValueError("DeepSeek-V4.1 QLI/QSLI supports only li_quantization='mxfp4'")
895- )902+ from torchao_npu.configs import QuantV41LightningIndexerConfig
903+ 
904+ li_config = QuantV41LightningIndexerConfig()
905+ else:
906+ li_config = _quant_lightning_indexer(
907+ li_kernel_config or LightningIndexerKernelConfig(),
908+ li_quantization=li_quantization,
909+ dst_type_max=dst_type_max,
910+ )
896 converters.append(911 converters.append(
897 _quantization_converter(912 _quantization_converter(
898 li_config,913 li_config,
@@ -900,15 +915,16 @@ def _recipe_converters(
900 model_compile_enabled=model_compile_enabled,915 model_compile_enabled=model_compile_enabled,
901 )916 )
902 )917 )
903- converters.append(918+ if model_type == "v4":
904- _quantization_converter(919+ converters.append(
905- None,920+ _quantization_converter(
906- filters["lightning_indexer_metadata"],921+ None,
907- model_compile_enabled=model_compile_enabled,922+ filters["lightning_indexer_metadata"],
wanghui0

同样地,从统一性的角度,V4.1为何不需要处理metadata,但是V4.0需要?可否统一?

likedislike
xiaomagemafeifei
xiaomagemafeifei
Oct 8 Comments:
likedislike
908- replacement_config_type=_QuantizedLightningIndexerMetadataAdapter.Config,923+ model_compile_enabled=model_compile_enabled,
909- replacement_kwargs={"quant_mode": li_config.quant_mode},924+ replacement_config_type=_QuantizedLightningIndexerMetadataAdapter.Config,
925+ replacement_kwargs={"quant_mode": cast("QuantLightningIndexerConfig", li_config).quant_mode},
926+ )
910 )927 )
911- )
912 if enable_sparse_attention_quantization:928 if enable_sparse_attention_quantization:
913 if "sparse_attention" in filters:929 if "sparse_attention" in filters:
914 from torchao_npu.configs import QuantCompressorConfig, QuantV41SparseAttentionConfig930 from torchao_npu.configs import QuantCompressorConfig, QuantV41SparseAttentionConfig
@@ -999,7 +1015,9 @@ def apply_quantization_converter(
999 model_type = _model_type_for_spec(model_spec)1015 model_type = _model_type_for_spec(model_spec)
1000 1016 
1001 li_kernel_config = (1017 li_kernel_config = (
1002- _get_li_kernel_config(model_spec.model) if quantization_config.li_quantization is not None else None1018+ _get_li_kernel_config(model_spec.model)
1019+ if model_type == "v4" and quantization_config.li_quantization is not None
1020+ else None
1003 )1021 )
1004 converters = _recipe_converters(1022 converters = _recipe_converters(
1005 quantization_config.recipe,1023 quantization_config.recipe,
@@ -167,6 +167,32 @@ def test_recipe_converters_select_filters_for_model_type(
167 assert bool(sparse_attention_converters) is expect_sparse_attention_converter167 assert bool(sparse_attention_converters) is expect_sparse_attention_converter
168 168 
169 169 
170+def test_v41_li_quantization_alone_selects_only_the_qli_qsli_converter(converter_module):
171+ from torchao_npu.configs import QuantV41LightningIndexerConfig
172+ 
173+ converters = converter_module._recipe_converters(
174+ "mix",
175+ model_type="v41",
176+ enable_sparse_attention_quantization=False,
177+ enable_mxfp4_qat=False,
178+ dst_type_max=0.0,
179+ enable_fsdp_prequantize=False,
180+ model_compile_enabled=False,
181+ li_quantization="mxfp4",
182+ )
183+ 
184+ li_converters = [
185+ converter
186+ for converter in converters
187+ if converter.filter_fn is converter_module._DSV41_CONFIG_FILTERS["lightning_indexer"]
188+ ]
189+ assert len(li_converters) == 1
190+ assert isinstance(li_converters[0].base_config, QuantV41LightningIndexerConfig)
191+ assert not any(
192+ converter.filter_fn is converter_module._DSV41_CONFIG_FILTERS["sparse_attention"] for converter in converters
193+ )
194+ 
195+ 
170def test_recipe_converters_warn_when_sparse_attention_filter_is_unavailable(converter_module, caplog):196def test_recipe_converters_warn_when_sparse_attention_filter_is_unavailable(converter_module, caplog):
171 with caplog.at_level(logging.WARNING):197 with caplog.at_level(logging.WARNING):
172 converters = converter_module._recipe_converters(198 converters = converter_module._recipe_converters(
@@ -372,6 +398,73 @@ def _capture_compressor_encoding(monkeypatch, width):
372 return captured398 return captured
373 399 
374 400 
401+@pytest.mark.parametrize("li_enabled", [False, True], ids=["bf16-li", "qli"])
402+@pytest.mark.parametrize("sparse_enabled", [False, True], ids=["bf16-smla", "quant-smla"])
403+def test_v41_teacher_pair_survives_independent_quantization_switches(
404+ converter_module,
405+ li_enabled,
406+ sparse_enabled,
407+):
408+ from torchao_npu.configs import QuantV41LightningIndexerConfig, QuantV41SparseAttentionConfig
409+ from torchtitan.config.override import OverrideConfig, apply_overrides
410+ 
411+ from torchtitan_npu.config.configs import QuantizationExtensionConfig
412+ from torchtitan_npu.models.deepseek_v4_1 import model_registry
413+ from torchtitan_npu.models.deepseek_v4_1.attention import _check_indexer_teacher_pair
414+ 
415+ converted = converter_module.apply_quantization_converter(
416+ model_registry("deepseek_v4_1_debugmodel"),
417+ QuantizationExtensionConfig(
418+ enable_quantized_training=True,
419+ enable_sparse_attention_quantization=sparse_enabled,
420+ li_quantization="mxfp4" if li_enabled else None,
421+ recipe="all_mxfp8",
422+ ),
423+ model_compile_enabled=False,
424+ )
425+ apply_overrides(
426+ OverrideConfig(
427+ imports=[
428+ "torchtitan_npu.override.deepseek_v4_1.lightning_indexer.asc",
429+ "torchtitan_npu.override.deepseek_v4_1.sparse_attn.asc",
430+ ]
431+ ),
432+ converted.model,
433+ )
434+ 
435+ for layer in converted.model.layers:
436+ selector = layer.attention.indexer.selector
437+ inner_attention = layer.attention.inner_attention
438+ selector_quant = getattr(selector, "_torchao_npu_config", None)
439+ attention_quant = getattr(inner_attention, "_torchao_npu_config", None)
440+ 
441+ assert isinstance(selector_quant, QuantV41LightningIndexerConfig) is li_enabled
442+ assert isinstance(attention_quant, QuantV41SparseAttentionConfig) is sparse_enabled
443+ if inner_attention.compress_ratio > 0:
444+ _check_indexer_teacher_pair(inner_attention, layer.attention.indexer)
445+ assert type(selector).consumes_indexer_teacher
446+ assert type(inner_attention).provides_indexer_teacher
447+ # The trainer discovers instances, not configs, to assign the step denominator.
448+ selector_module = selector.build()
449+ assert isinstance(selector_module, converter_module.V41Selector)
450+ assert selector_module.consumes_indexer_teacher
451+ assert selector_module.num_global_queries is None
452+ 
453+ 
454+@pytest.mark.parametrize("li_quantization", ["mxfp8", "fp8", "hif8"])
455+def test_v41_recipe_rejects_non_mxfp4_lightning_indexer(converter_module, li_quantization):
456+ with pytest.raises(ValueError, match="supports only li_quantization='mxfp4'"):
457+ converter_module._recipe_converters(
458+ "mix",
459+ model_type="v41",
460+ enable_mxfp4_qat=False,
461+ dst_type_max=0.0,
462+ enable_fsdp_prequantize=False,
463+ model_compile_enabled=False,
464+ li_quantization=li_quantization,
465+ )
466+ 
467+ 
375@pytest.mark.parametrize("ratio", [1, 2], ids=["full-resolution", "compressed"])468@pytest.mark.parametrize("ratio", [1, 2], ids=["full-resolution", "compressed"])
376def test_converted_v41_compressor_quantizes_post_rope_and_preserves_gradients(converter_module, monkeypatch, ratio):469def test_converted_v41_compressor_quantizes_post_rope_and_preserves_gradients(converter_module, monkeypatch, ratio):
377 from torchtitan_npu.config.configs import QuantizationExtensionConfig470 from torchtitan_npu.config.configs import QuantizationExtensionConfig
@@ -19,9 +19,8 @@ gradient, so its parameters stay frozen; that is why nothing here checks an "eag
19indexer gradient" -- with the distillation loss removed there is no longer a path to one.19indexer gradient" -- with the distillation loss removed there is no longer a path to one.
20"""20"""
21 21 
22-from itertools import pairwise
23import importlib22import importlib
24-import types23+from itertools import pairwise
25 24 
26import pytest25import pytest
27import torch26import torch
@@ -5,26 +5,14 @@
5 5 
6"""DeepSeek-V4.1 LightningIndexer override: selection fused with its SLIKG backward.6"""DeepSeek-V4.1 LightningIndexer override: selection fused with its SLIKG backward.
7 7 
8-Independent of :mod:`~torchtitan_npu.override.deepseek_v4_1.sparse_attn` on purpose. The8+This entry and :mod:`~torchtitan_npu.override.deepseek_v4_1.sparse_attn` have separate
9-two are separate kernels with separate targets -- this one replaces the selection node,9+targets so TorchAO-NPU can independently replace either BF16 fallback. The resulting
10-that one the sparse core -- and a run may take either, both, or neither. They must agree10+configuration must still contain both a teacher provider and a consumer, and both sides
11-on one coordinate system (both speak document-local indices), which is a contract rather11+must use document-local indices.
12-than a shared module.
13 12 
14-The replacement drives the quantized ``ds41`` pair rather than the plain bf16 selection:13+This override drives only the BF16 ``lightning_indexer`` forward. The ds41 QLI/QSLI
15-``quant_lightning_indexer`` on the Full Mode layer that builds the candidate pool or on a14+quantized forward bridge is isolated in the optional ``torchao-npu`` package under
16-layer outside the hierarchy, and ``quant_sparse_lightning_indexer`` on a layer that searches15+``experiments/torchao-npu`` and is not selected by this override.
17-it. Which kernel runs follows from ``mode`` together with the pool capacity -- the same pair
18-the reference selector dispatches on -- so the candidate mechanism crosses the override
19-boundary with the selector instead of being bypassed.
20- 
21-The entry takes one switch, and it **defaults to the pre-quantization kernel**: the
22-quantized path currently dies on the second training step with an aicore timeout, so the
23-safe kernel is the one a run gets unless it asks for the other. A run that wants the
24-candidate pool has to say so explicitly:
25- 
26- --override.imports \
27- 'torchtitan_npu.override.deepseek_v4_1.lightning_indexer.asc={"legacy":false}'
28"""16"""
29 17 
30from typing import TYPE_CHECKING18from typing import TYPE_CHECKING
@@ -40,13 +28,9 @@ if TYPE_CHECKING:
40@override(28@override(
41 target=Selector.Config,29 target=Selector.Config,
42 exact=True,30 exact=True,
43- description=(31+ description="BF16 LightningIndexer selection fused with its SLIKG backward in one autograd.Function",
44- "LightningIndexer selection fused with its SLIKG backward in one autograd.Function "
45- "(every indexer layer); legacy=true, the default, selects the pre-quantization "
46- "kernel and legacy=false the ds41 QLI/QSLI candidate pair"
47- ),
48)32)
49-def asc(cfg: Selector.Config, legacy: bool = False) -> "AscSelector.Config":33+def asc(cfg: Selector.Config) -> "AscSelector.Config":
50 from .ascendc import AscSelector34 from .ascendc import AscSelector
51 35 
52- return derive(cfg, AscSelector.Config, legacy=legacy)36+ return derive(cfg, AscSelector.Config)
@@ -3,36 +3,17 @@
3# This source code is licensed under the BSD-style license found in the3# This source code is licensed under the BSD-style license found in the
4# LICENSE file in the root directory of this source tree.4# LICENSE file in the root directory of this source tree.
5 5 
6-"""The fused LightningIndexer selection and its SLIKG backward edge.6+"""The BF16 LightningIndexer selection fused with its SLIKG backward edge."""
7- 
8-The forward runs one of the two quantized ``ds41`` indexer kernels, chosen by the layer's
9-role in the candidate hierarchy:
10- 
11-- the pool source runs ``quant_lightning_indexer`` with a capacity, which returns its own
12- Top-K *and* the shared candidate pool;
13-- a pool searcher runs ``quant_sparse_lightning_indexer``, which scores only the pool it is
14- handed and returns its own Top-K;
15-- a layer outside the hierarchy runs ``quant_lightning_indexer`` with the pool disabled.
16- 
17-All three share one backward: SLIKG consumes the selection and the teacher, so the kernel
18-choice is a forward-only fact.
19-"""
20 7 
21from dataclasses import dataclass8from dataclasses import dataclass
22from typing import ClassVar9from typing import ClassVar
23 10 
24import torch11import torch
25-import torch_npu
26 12 
27-from torchtitan_npu.models.deepseek_v4_1.indexer import FULL, Selector13+from torchtitan_npu.models.deepseek_v4_1.indexer import Selector
28 14 
29_LAYOUT = "TND"15_LAYOUT = "TND"
30_MASK_MODE = 3 # right-down causal: entry j is complete for query t iff j < (t+1)//ratio16_MASK_MODE = 3 # right-down causal: entry j is complete for query t iff j < (t+1)//ratio
31-# The packed-MXFP4 ABI is the only value either kernel accepts; the number labels the
32-# storage format (two E2M1 values per byte plus uE8M0 scales), it is not a precision knob.
33-_QUANT_MODE = 1
34-# One E8M0 scale byte per 32 elements along the head dimension, on both operands.
35-_MX_BLOCK_SIZE = 32
36 17 
37 18 
38def _kernel_options(attention_masks, ratio):19def _kernel_options(attention_masks, ratio):
@@ -50,8 +31,7 @@ def _kernel_options(attention_masks, ratio):
50 # of its operand. Under context parallelism they carry the whole query movement:31 # of its operand. Under context parallelism they carry the whole query movement:
51 # ``seqused_q`` is this rank's chunk and ``seqused_k`` its reach into the gathered keys, so32 # ``seqused_q`` is this rank's chunk and ``seqused_k`` its reach into the gathered keys, so
52 # the selection is scored at this rank's chunk against the blocks it may read. Every33 # the selection is scored at this rank's chunk against the blocks it may read. Every
53- # operator this selector can pick takes the pair -- the bf16 V2 indexer at ``legacy=True``,34+ # operator this selector can pick takes the pair -- the BF16 indexer and SLIKG -- and at
54- # the quantized pair otherwise, and the sparse variant of the same kernel -- and at
55 # ``cp_size = 1`` each equals the corresponding boundary difference, so passing them is a35 # ``cp_size = 1`` each equals the corresponding boundary difference, so passing them is a
56 # no-op there rather than a second code path.36 # no-op there rather than a second code path.
57 seqused_q=attention_masks.kernel.q.seqused,37 seqused_q=attention_masks.kernel.q.seqused,
@@ -67,7 +47,7 @@ def _kernel_options(attention_masks, ratio):
67def _kernel_geometry(num_heads, head_dim, topk):47def _kernel_geometry(num_heads, head_dim, topk):
68 """The geometry the non-quantized metadata ops are built with.48 """The geometry the non-quantized metadata ops are built with.
69 49 
70- ``max_seqlen_q``/``max_seqlen_k`` are pinned to ``None`` because the legacy50+ ``max_seqlen_q``/``max_seqlen_k`` are pinned to ``None`` because the BF16
71 ``lightning_indexer_metadata`` takes them as optional ints; SLIKG's metadata op has the51 ``lightning_indexer_metadata`` takes them as optional ints; SLIKG's metadata op has the
72 same pair and the same reading. Passing them makes the call independent of whatever52 same pair and the same reading. Passing them makes the call independent of whatever
73 default the operator ships with.53 default the operator ships with.
@@ -82,85 +62,13 @@ def _kernel_geometry(num_heads, head_dim, topk):
82 )62 )
83 63 
84 64 
85-def _quantized_geometry(num_heads, head_dim, topk):
86- """The geometry the ``ds41`` metadata ops are built with.
87- 
88- The maximum lengths are deliberately absent rather than ``None``: these operators take
89- plain ints, whose default of ``-1`` already means "any length", and ``None`` for an
90- ``int`` is a type error.
91- """
92- return dict(
93- num_heads_q=num_heads,
94- num_heads_k=1,
95- head_dim=head_dim,
96- topk=topk,
97- )
98- 
99- 
100-def _pack_mxfp4(x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
101- """Pack one ``[T, H, D]`` indexer operand into the kernels' MXFP4 storage.
102- 
103- Returns the ``(data, descale)`` pair the operators take. ``float4_e2m1fn_x2`` is one
104- byte holding two E2M1 values, so the data view keeps its shape and only gains a uint8
105- reinterpretation; the E8M0 scales come back flat at ``D/32`` per head and the schema
106- wants them folded into ``(D/64, 2)``. The reshape is written out rather than inferred
107- so a change in the vendor quantizer's return convention fails here rather than at the
108- operator's shape check.
109- """
110- 
111- def mx_quant() -> tuple[torch.Tensor, torch.Tensor]:
112- """The vendor MX quantizer, named so the packing below reads as layout work."""
113- return torch_npu.npu_dynamic_mx_quant(
114- x.contiguous(),
115- axis=-1,
116- dst_type=torch_npu.float4_e2m1fn_x2,
117- block_size=_MX_BLOCK_SIZE,
118- round_mode="rint",
119- scale_alg=2,
120- dst_type_max=0.0,
121- )
122- 
123- rows, heads, head_dim = x.shape
124- data, scale = mx_quant()
125- return (
126- data.view(torch.uint8).reshape(rows, heads, head_dim // 2).contiguous(),
127- scale.view(torch.uint8).reshape(rows, heads, head_dim // 64, 2).contiguous(),
128- )
129- 
130- 
131-def _candidate_length(candidate_block_indices: torch.Tensor) -> torch.Tensor:
132- """The candidate table's valid prefix length, read off the block table itself.
133- 
134- ``quant_lightning_indexer`` writes ``-1`` into every slot past the row's reachable
135- block count, as a contiguous tail, so counting the non-negative entries recovers the
136- length the consumer's metadata wants. The result is shaped and typed to that contract
137- directly: ``(T1, 1)`` int32 on the table's own device.
138- 
139- This leans on the producer's fill convention, which is worth naming because the
140- consumer does not share it: ``quant_sparse_lightning_indexer`` treats
141- ``candidate_block_length`` as authoritative and *ignores* the tail, and the vendor's
142- own test for it writes junk past the length to prove the tail is never read. So the
143- inference is sound only while the table comes from ``quant_lightning_indexer`` -- which
144- is the only producer in this chain -- and it is deliberately re-derived here rather
145- than threaded so that the pool stays one cross-layer tensor.
146- """
147- return (candidate_block_indices >= 0).sum(dim=-1).to(torch.int32).contiguous()
148- 
149- 
150class _LightningIndexerTND(torch.autograd.Function):65class _LightningIndexerTND(torch.autograd.Function):
151- """The quantized ``ds41`` indexer forward, fused with the SLIKG backward.66+ """The BF16 LightningIndexer forward fused with the SLIKG backward.
152 67 
153- The kernels' contract (A5-verified): ``q`` and ``k`` are single-key-head bf16 with68+ The kernels' contract: ``q``/``k`` are BF16 with a single key head and
154- ``index_head_dim`` 128 and leave here as caller-packed MXFP4, ``w`` is float3269+ ``index_head_dim`` 128, ``w`` is float32 ``[T, Hi]``, and indices are
155- ``[T, Hi]``, the indices are document-local with ``-1`` padding, and the SLIKG metadata70+ document-local with ``-1`` padding. SLIKG requires ``topk`` to be 512 or
156- requires ``topk`` to be 512 or an integer multiple of 1024. The forward returns the71+ an integer multiple of 1024.
157- document-local indices, which the fused attention reads in that same coordinate system.
158- 
159- The *saved* operands are the bf16 tensors, not the packed ones: SLIKG differentiates
160- them, and MXFP4 is not a differentiable storage. The quantization is therefore a
161- straight-through detail of the forward -- the backward sees the values the projections
162- produced, which is the usual QAT arrangement and keeps the distillation gradient
163- attached to ``wq_b``, ``weights_proj`` and ``wk``.
164 """72 """
165 73 
166 @staticmethod74 @staticmethod
@@ -172,11 +80,6 @@ class _LightningIndexerTND(torch.autograd.Function):
172 topk,80 topk,
173 ratio,81 ratio,
174 attention_masks,82 attention_masks,
175- candidate_topk_blocks,
176- candidate_block_size,
177- is_source,
178- legacy,
179- candidate,
180 num_global_queries,83 num_global_queries,
181 ):84 ):
182 # These arrive with the batch axis already squeezed off by the caller: an85 # These arrive with the batch axis already squeezed off by the caller: an
@@ -184,117 +87,19 @@ class _LightningIndexerTND(torch.autograd.Function):
184 # was handed*, so the kernels' ``[T, H, D]`` layout has to be established outside87 # was handed*, so the kernels' ``[T, H, D]`` layout has to be established outside
185 # this node rather than inside it.88 # this node rather than inside it.
186 options = _kernel_options(attention_masks, ratio)89 options = _kernel_options(attention_masks, ratio)
187- # Which kernel runs, and what it is handed, is one three-way role. The invariant90+ li_metadata = torch.ops.cann_ops_transformer.lightning_indexer_metadata(
188- # that covers all three is hoisted here rather than restated per branch: a candidate91+ **_kernel_geometry(idx_q.shape[1], idx_q.shape[2], topk),
189- # table arrives exactly when this layer is a searcher. The source builds it and so92+ **options,
190- # may not be handed one, a layer outside the hierarchy has none to pass on, and the93+ )
191- # legacy operator has no candidate table at all.94+ topk_indices, _ = torch.ops.cann_ops_transformer.lightning_indexer(
192- expects_candidate = not legacy and candidate_topk_blocks > 0 and not is_source95+ idx_q,
193- if (candidate is not None) != expects_candidate:96+ idx_k,
194- raise ValueError(97+ idx_w,
195- "the candidate table in flight disagrees with this layer's role: "98+ topk,
196- + (99+ metadata=li_metadata,
197- "a searcher searches the pool its source built, but none was handed to it."100+ return_value=1,
198- if expects_candidate101+ **options,
199- else "only a searcher is handed one, but this layer received one."102+ )
200- )
201- )
202- 
203- candidate_out = None
204- if legacy:
205- # The pre-quantization selection: bf16 operands straight into the non-quantized
206- # operator, which has no pool to build or search. It is kept as an escape hatch
207- # -- for a geometry the quantized pair refuses, or to isolate a quantization
208- # change from a wiring change -- not as a supported configuration.
209- li_metadata = torch.ops.cann_ops_transformer.lightning_indexer_metadata(
210- **_kernel_geometry(idx_q.shape[1], idx_q.shape[2], topk),
211- **options,
212- )
213- topk_indices, _ = torch.ops.cann_ops_transformer.lightning_indexer(
214- idx_q,
215- idx_k,
216- idx_w,
217- topk,
218- metadata=li_metadata,
219- return_value=1,
220- **options,
221- )
222- else:
223- geometry = _quantized_geometry(idx_q.shape[1], idx_q.shape[2], topk)
224- idx_q_mxfp4, idx_q_scale = _pack_mxfp4(idx_q)
225- idx_k_mxfp4, idx_k_scale = _pack_mxfp4(idx_k)
226- if not expects_candidate:
227- # The producer and a layer outside the hierarchy run the same operator; what
228- # separates them is only whether this layer publishes what it built. The
229- # condition is the negation of the guard above -- a searcher is the one role
230- # that consumes -- so the two cannot disagree about which layers search.
231- li_metadata = torch.ops.cann_ops_transformer.ds41.quant_lightning_indexer_metadata(
232- **options,
233- **geometry,
234- candidate_topk_blocks=candidate_topk_blocks,
235- candidate_block_size=candidate_block_size,
236- )
237- # ``sparse_values`` is empty at ``return_value=False`` and the length is
238- # re-derived by the searcher from the table's ``-1`` tail, so neither slot is
239- # bound to a name here.
240- topk_indices, _, candidate_block_indices, _ = (
241- torch.ops.cann_ops_transformer.ds41.quant_lightning_indexer(
242- idx_q_mxfp4,
243- idx_k_mxfp4,
244- idx_w,
245- idx_q_scale,
246- idx_k_scale,
247- topk,
248- _QUANT_MODE,
249- metadata=li_metadata,
250- return_value=False,
251- candidate_topk_blocks=candidate_topk_blocks,
252- candidate_block_size=candidate_block_size,
253- **options,
254- )
255- )
256- # Guarded, not unconditional: with the pool off the operator still returns
257- # the candidate outputs, but as 1-D empties rather than a table. Publishing
258- # one would hand the next layer something that is not a pool and trip the
259- # check above, so only the producer assigns.
260- #
261- # The unsqueeze is the kernel ABI's ``[T, 1, capacity]`` becoming the
262- # model's cross-layer ``[B, L, 1, capacity]``, and it belongs *here* rather
263- # than at the caller: this is the same edge that squeezes on the way in, so
264- # both translations of the table sit next to the kernels that force them.
265- # A caller-side unsqueeze cannot tell a freshly built table from one being
266- # passed through, so it would grow the rank once per searcher layer.
267- if is_source:
268- candidate_out = candidate_block_indices.unsqueeze(0)
269- else:
270- # The candidate table arrives as the model's cross-layer tensor,
271- # ``[B, L, 1, capacity]``, and the kernel wants the row's own
272- # ``[T, 1, capacity]``.
273- block_indices = candidate.squeeze(0)
274- block_length = _candidate_length(block_indices)
275- slig_metadata = torch.ops.cann_ops_transformer.ds41.quant_sparse_lightning_indexer_metadata(
276- block_length,
277- **options,
278- **geometry,
279- quant_mode=_QUANT_MODE,
280- candidate_block_size=candidate_block_size,
281- )
282- topk_indices, _ = torch.ops.cann_ops_transformer.ds41.quant_sparse_lightning_indexer(
283- idx_q_mxfp4,
284- idx_k_mxfp4,
285- idx_w,
286- idx_q_scale,
287- block_indices,
288- block_length,
289- topk,
290- _QUANT_MODE,
291- candidate_block_size,
292- descale_k=idx_k_scale,
293- metadata=slig_metadata,
294- return_value=False,
295- **options,
296- )
297- candidate_out = candidate
298 103 
299 # The kernel's own order is unspecified, so the selection is sorted into position104 # The kernel's own order is unspecified, so the selection is sorted into position
300 # order here -- inside the Function, before anything is saved. That placement is105 # order here -- inside the Function, before anything is saved. That placement is
@@ -330,31 +135,21 @@ class _LightningIndexerTND(torch.autograd.Function):
330 # boundary tensors the graph already keeps for the backward, and the node -- and135 # boundary tensors the graph already keeps for the backward, and the node -- and
331 # with it this reference -- is released when that backward has run.136 # with it this reference -- is released when that backward has run.
332 ctx.attention_masks = attention_masks137 ctx.attention_masks = attention_masks
333- return topk_indices, topk_scores, candidate_out138+ return topk_indices, topk_scores
334 139 
335 @staticmethod140 @staticmethod
336- def backward( # pyrefly: ignore [bad-override]141+ def backward(ctx, grad_indices, attn_softmax_l1_norm): # pyrefly: ignore [bad-override]
337- ctx,
338- grad_indices,
339- attn_softmax_l1_norm,
340- grad_candidate,
341- ):
342 # The indices are integer selections: never tracked, always None. The142 # The indices are integer selections: never tracked, always None. The
343 # scores' gradient is the teacher the SLIKG kernel expects, because SLIKG143 # scores' gradient is the teacher the SLIKG kernel expects, because SLIKG
344 # applies ``dI = Z * Y - p`` itself. SMLAG's backward is what puts the raw144 # applies ``dI = Z * Y - p`` itself. SMLAG's backward is what puts the raw
345 # ``p`` on this edge; nothing else may, and a signed value here would be read145 # ``p`` on this edge; nothing else may, and a signed value here would be read
346 # as the teacher and negate the indexer's gradient.146 # as the teacher and negate the indexer's gradient.
347- #147+ del grad_indices
348- # The candidate table's gradient is ``None`` by construction too: it is an int32
349- # block table, so no graph edge ever forms on it. Both discards are named rather
350- # than elided because the two used edges are told apart by name here, and because a
351- # bare ``_`` cannot be repeated in a signature.
352- del grad_indices, grad_candidate
353 if attn_softmax_l1_norm is None:148 if attn_softmax_l1_norm is None:
354 # No teacher reached this edge, so no operand has a gradient either. The count149 # No teacher reached this edge, so no operand has a gradient either. The count
355 # is the same one the labelled tail below enumerates: one entry per forward150 # is the same one the labelled tail below enumerates: one entry per forward
356 # input, in the same order.151 # input, in the same order.
357- return (None,) * 12152+ return (None,) * 7
358 idx_q, idx_k, idx_w, topk_indices, num_global_queries = ctx.saved_tensors153 idx_q, idx_k, idx_w, topk_indices, num_global_queries = ctx.saved_tensors
359 if num_global_queries is None:154 if num_global_queries is None:
360 raise RuntimeError("Set Selector.num_global_queries before training the indexer")155 raise RuntimeError("Set Selector.num_global_queries before training the indexer")
@@ -378,13 +173,7 @@ class _LightningIndexerTND(torch.autograd.Function):
378 # ``idx_w`` arrives float32 (the kernel contract); the cast back to the173 # ``idx_w`` arrives float32 (the kernel contract); the cast back to the
379 # projection dtype happens in the eager graph outside the Function.174 # projection dtype happens in the eager graph outside the Function.
380 #175 #
381- # One gradient per forward input, in order: (idx_q, idx_k, idx_w, topk, ratio,176+ # One gradient per forward input: q, k, w, topk, ratio, masks, query count.
382- # attention_masks, candidate_topk_blocks, candidate_block_size, is_source, legacy,
383- # candidate, num_global_queries). The count is spelled out rather than padded because a padded count
384- # drifts silently in one direction only -- PyTorch ignores extra trailing entries
385- # and raises only when the list is short -- so the mismatch would surface as a
386- # confusing "expected N, got M" from the engine at some later refactor instead of
387- # here.
388 return (177 return (
389 dq,178 dq,
390 dk,179 dk,
@@ -392,64 +181,26 @@ class _LightningIndexerTND(torch.autograd.Function):
392 None, # topk181 None, # topk
393 None, # ratio182 None, # ratio
394 None, # attention_masks183 None, # attention_masks
395- None, # candidate_topk_blocks
396- None, # candidate_block_size
397- None, # is_source
398- None, # legacy
399- None, # candidate
400 None, # num_global_queries184 None, # num_global_queries
401 )185 )
402 186 
403 187 
404class AscSelector(Selector):188class AscSelector(Selector):
405- """The fused QLI/QSLI selector for the V4.1 indexer layers.189+ """The fused BF16 LI/SLIKG selector for the V4.1 indexer layers.
406- 
407- Which kernel runs is the layer's role in the candidate hierarchy, and the role is read
408- off the same config the reference selector reads it from: a Full Mode layer that carries
409- a capacity is the source, any other capacity-carrying layer is a searcher, and a layer
410- with no capacity sits outside the hierarchy. Full Mode is the discriminator because it
411- is the role that owns the compressed KV the pool indexes, so it is the only one that can
412- build a pool; a Reindex Mode layer carries a capacity but never owns the KV.
413 190 
414 It emits the kernel's own document-local ``topk_indices``. The fused attention191 It emits the kernel's own document-local ``topk_indices``. The fused attention
415 consumes that same coordinate system, so neither side translates: the selection192 consumes that same coordinate system, so neither side translates: the selection
416 crosses the model boundary exactly as the kernels selected it, and only ``-1`` marks an193 crosses the model boundary exactly as the kernels selected it, and only ``-1`` marks an
417 unused slot.194 unused slot.
418 195 
419- The pool travels as the model's cross-layer tensor, ``[B, L, 1, capacity]``, on every
420- path: :class:`_LightningIndexerTND` owns both translations, unsqueezing the kernel's own
421- ``[T, 1, capacity]`` where it produces one and squeezing it back where a searcher hands
422- it to QSLI. Keeping them on one edge is what stops the rank from growing per searcher
423- layer, since a pass-through table is indistinguishable from a fresh one at the caller.
424- Its length is not carried -- a searcher recovers it from the table's ``-1`` tail (see
425- :func:`_candidate_length`).
426- 
427 ``consumes_indexer_teacher`` is what pairs this node with the port that emits the196 ``consumes_indexer_teacher`` is what pairs this node with the port that emits the
428 teacher (``sparse_attn.asc``); see197 teacher (``sparse_attn.asc``); see
429 :func:`~torchtitan_npu.models.deepseek_v4_1.attention._check_indexer_teacher_pair`.198 :func:`~torchtitan_npu.models.deepseek_v4_1.attention._check_indexer_teacher_pair`.
430- 
431- The ``legacy`` switch swaps the whole selection back to the pre-quantization operator.
432- It is a deployment choice rather than a model fact -- see :class:`AscSelector.Config`.
433 """199 """
434 200 
435 @dataclass(kw_only=True, slots=True)201 @dataclass(kw_only=True, slots=True)
436 class Config(Selector.Config):202 class Config(Selector.Config):
437 consumes_indexer_teacher: ClassVar[bool] = True203 consumes_indexer_teacher: ClassVar[bool] = True
438- # Select the pre-quantization, pool-free ``lightning_indexer`` instead of the
439- # quantized ``ds41`` pair. The field's own default is the pool-free path, and the
440- # override entry's is the same, so a run reaches the quantized pair only by asking:
441- #
442- # --override.imports \
443- # 'torchtitan_npu.override.deepseek_v4_1.lightning_indexer.asc={"legacy":false}'
444- #
445- # The pool-free path has no candidate pool, so a run that takes it scores every
446- # visible entry on every indexer layer -- which is what the fused path did before the
447- # quantized pair landed, and is the baseline the pooled path is measured against.
448- legacy: bool = True
449- 
450- def __init__(self, config: Config):
451- super().__init__(config)
452- self.legacy = config.legacy
453 204 
454 def forward(205 def forward(
455 self,206 self,
@@ -461,11 +212,7 @@ class AscSelector(Selector):
461 candidates_BL1C: torch.Tensor | None,212 candidates_BL1C: torch.Tensor | None,
462 ) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor | None]:213 ) -> tuple[torch.Tensor, torch.Tensor | None, torch.Tensor | None]:
463 topk = self.index_topk214 topk = self.index_topk
464- # Only a Full Mode layer owns the compressed KV the pool indexes, so it is the only215+ topk_indices, topk_scores = _LightningIndexerTND.apply(
465- # role that can build one. That is the same pair -- Full Mode plus a capacity --
466- # the reference selector dispatches on, so both paths read one rule off one config.
467- is_source = self.mode is FULL and self.has_candidate_pool
468- topk_indices, topk_scores, candidate = _LightningIndexerTND.apply(
469 # The batch axis is the packed row, so it is squeezed rather than indexed: every216 # The batch axis is the packed row, so it is squeezed rather than indexed: every
470 # kernel in this path addresses one row.217 # kernel in this path addresses one row.
471 idx_q_BLHiDi.squeeze(0),218 idx_q_BLHiDi.squeeze(0),
@@ -474,22 +221,12 @@ class AscSelector(Selector):
474 topk,221 topk,
475 self.compress_ratio,222 self.compress_ratio,
476 attention_masks,223 attention_masks,
477- self.candidate_topk_blocks,
478- self.candidate_block_size,
479- is_source,
480- self.legacy,
481- candidates_BL1C,
482 self.num_global_queries,224 self.num_global_queries,
483 )225 )
484 # Two layout translations and nothing else: ``_LightningIndexerTND`` already226 # Two layout translations and nothing else: ``_LightningIndexerTND`` already
485 # emitted the selection sorted, in the kernels' ``[T, 1, K]`` layout, and the model227 # emitted the selection sorted, in the kernels' ``[T, 1, K]`` layout, and the model
486 # contract is ``[1, L, K]``. Sorting at this level instead would desynchronise the228 # contract is ``[1, L, K]``. Sorting at this level instead would desynchronise the
487 # saved indices from the teacher (see the Function).229 # saved indices from the teacher (see the Function).
488- #
489- # The candidate table needs no translation here: it is already the model's
490- # cross-layer ``[B, L, 1, capacity]`` on both paths, because the Function converts
491- # the kernel's own ``[T, 1, capacity]`` on the edge that produced it.
492 topk_indices_BLK = topk_indices.reshape(1, -1, topk)230 topk_indices_BLK = topk_indices.reshape(1, -1, topk)
493 topk_scores_BLK = topk_scores.reshape(1, -1, topk)231 topk_scores_BLK = topk_scores.reshape(1, -1, topk)
494- candidates_BL1C = candidate232+ return topk_indices_BLK, topk_scores_BLK, None
495- return topk_indices_BLK, topk_scores_BLK, candidates_BL1C