Merged
feat: add mixed quantized DeepSeek V4.1 sparse attention #861
zx1029Add on Sep 20
feat: add mixed quantized DeepSeek V4.1 sparse attention #861
Merged
Total: 12 files changed+858-13
| @@ -1,6 +1,6 @@ | |||
| 1 | # 快速上手 | 1 | # 快速上手 |
| 2 | 2 | ||
| 3 | -参考 [软件安装](./installation.md) 准备环境后,进入 `torchtitan-npu` 仓库根目录。除另有说明外,本文中的相对路径和命令均以仓库根目录为基准。本文先以 DeepSeek V3 说明通用启动方式,再给出 DeepSeek-V4 多卡训练和 TorchAO-NPU 低精度训练入口。 | 3 | +参考 [软件安装](./installation.md) 准备环境后,进入 `torchtitan-npu` 仓库根目录。除另有说明外,本文中的相对路径和命令均以仓库根目录为基准。本文先以 DeepSeek V3 说明通用启动方式,再给出 DeepSeek-V4/V4.1 多卡训练和 TorchAO-NPU 低精度训练入口。 |
| 4 | 4 | ||
| 5 | ## 数据准备 | 5 | ## 数据准备 |
| 6 | 6 | ||
| @@ -174,6 +174,32 @@ LI Q/K 量化可通过以下参数单独选择,必须同时启用低精度训 | |||
| 174 | 174 | ||
| 175 | 启动日志中出现 `Applied TorchAO-NPU recipe=...` 表示低精度 recipe 已生效。 | 175 | 启动日志中出现 `Applied TorchAO-NPU recipe=...` 表示低精度 recipe 已生效。 |
| 176 | 176 | ||
| 177 | +### DeepSeek-V4.1 TorchAO-NPU 低精度训练 | ||
| 178 | + | ||
| 179 | +DeepSeek-V4.1 复用上述 TorchAO-NPU 低精度入口。除启用量化训练和选择 `recipe` 外,增加 | ||
| 180 | +`--extension.quantization.enable-sparse-attention-quantization`,将 V4.1 的稀疏 attention | ||
| 181 | +替换为混合量化路径;该开关需要与 | ||
| 182 | +`--extension.quantization.enable-quantized-training` 同时传入。当前入口面向 A5(Ascend 950)硬件: | ||
| 183 | +> [!NOTE] | ||
| 184 | +> 启用 'enable-sparse-attention-quantization' 会对KV做 'mxfp8_bf16' 和 'mxfp4_bf16' 量化,需要参考 [Ascend C 自定义算子编译安装说明](https://gitcode.com/cann/cann-recipes-infer/blob/master/ops/ascendc/README.md) 编译并安装 'kv_compress_epilog_v2' 算子,注意添加自定义算子环境变量。 | ||
| 185 | + | ||
| 186 | +deepseek v4.1 模型做低精预训练可运行以下脚本: | ||
| 187 | + | ||
| 188 | +```bash | ||
| 189 | +HF_ASSETS_PATH=/path/to/DeepSeek-V41_tokenizer \ | ||
| 190 | +bash examples/deepseek_v4_1/debug/deepseek_v4_1_flash_8p_cpt_4k_a5.sh | ||
| 191 | +``` | ||
| 192 | + | ||
| 193 | +deepseek v4.1 模型做QAT训练可运行以下脚本: | ||
| 194 | + | ||
| 195 | +```bash | ||
| 196 | +HF_ASSETS_PATH=/path/to/DeepSeek-V41_tokenizer \ | ||
| 197 | +bash examples/deepseek_v4_1/debug/deepseek_v4_1_flash_8p_qat_4k_a5.sh | ||
| 198 | +``` | ||
| 199 | + | ||
| 200 | +不使能 `enable-sparse-attention-quantization` 时,`recipe` 仍会量化匹配的权重和其他模块,V4.1 稀疏 attention 保持原始路径。启动日志中的 | ||
| 201 | +`sparse_attention_quantization=True` 可用于确认该开关已生效。 | ||
| 202 | + | ||
| 177 | ### 排查启动报错:查看更多 rank 日志 | 203 | ### 排查启动报错:查看更多 rank 日志 |
| 178 | 204 | ||
| 179 | > [!TIP] | 205 | > [!TIP] |
| @@ -27,4 +27,11 @@ if [[ "${USE_GOLDEN:-0}" != "1" ]]; then | |||
| 27 | torchtitan_npu.override.deepseek_v4_1.mhc.asc_sinkhorn}" | 27 | torchtitan_npu.override.deepseek_v4_1.mhc.asc_sinkhorn}" |
| 28 | fi | 28 | fi |
| 29 | 29 | ||
| 30 | -exec bash "${SCRIPT_DIR}/deepseek_v4_1_flash_8p_cpt_4k_a3.sh" "$@" | 30 | +QUANTIZATION_ARGS=( |
| 31 | + --extension.quantization.enable-quantized-training | ||
| 32 | + --extension.quantization.recipe all_block_fp8 | ||
| 33 | +) | ||
| 34 | + | ||
| 35 | +exec bash "${SCRIPT_DIR}/deepseek_v4_1_flash_8p_cpt_4k_a3.sh" \ | ||
| 36 | + "${QUANTIZATION_ARGS[@]}" \ | ||
| 37 | + "$@" \ | ||
| @@ -0,0 +1,26 @@ | |||
| 1 | +#!/usr/bin/env bash | ||
| 2 | +# Copyright (c) 2026 Huawei Technologies Co., Ltd. All Rights Reserved. | ||
| 3 | +# | ||
| 4 | +# This source code is licensed under the BSD-style license found in the | ||
| 5 | +# LICENSE file in the root directory of this source tree. | ||
| 6 | + | ||
| 7 | +# 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 entrypoint | ||
| 9 | +# only supplies A5-specific runtime and fused-operator settings. | ||
| 10 | +# 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 5 | ||
| 12 | + | ||
| 13 | +set -euo pipefail | ||
| 14 | + | ||
| 15 | +SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" | ||
| 16 | + | ||
| 17 | +QUANTIZATION_ARGS=( | ||
| 18 | + --extension.quantization.enable-quantized-training | ||
| 19 | + --extension.quantization.recipe all_block_fp8 | ||
| 20 | + --extension.quantization.enable-mxfp4-qat | ||
| 21 | + --extension.quantization.enable-sparse-attention-quantization | ||
| 22 | +) | ||
| 23 | + | ||
| 24 | +exec bash "${SCRIPT_DIR}/deepseek_v4_1_flash_8p_cpt_4k_a5.sh" \ | ||
| 25 | + "${QUANTIZATION_ARGS[@]}" \ | ||
| 26 | + "$@" \ | ||
| @@ -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_npu.quantized_modules import v41_sparse_attention as sparse_attention | ||
| 11 | + | ||
| 12 | + | ||
| 13 | +def test_quantized_cache_width_for_v41_head(): | ||
| 14 | + assert sparse_attention._quantized_cache_width(512, 32, "mxfp8_bf16") == 544 | ||
| 15 | + assert sparse_attention._quantized_cache_width(512, 16, "mxfp4_bf16") == 320 | ||
| 16 | + assert sparse_attention._quantized_cache_width(128, 32, "mxfp8_bf16") == 160 | ||
| 17 | + assert sparse_attention._quantized_cache_width(128, 16, "mxfp4_bf16") == 96 | ||
| 18 | + | ||
| 19 | + | ||
| 20 | +@pytest.mark.parametrize("head_dim", [64, 65, 127, 513]) | ||
| 21 | +def test_quantized_cache_width_rejects_unsupported_head_dim(head_dim): | ||
| 22 | + with pytest.raises(ValueError, match="head_dim > 64 and divisible by 64"): | ||
| 23 | + sparse_attention._quantized_cache_width(head_dim) | ||
| 24 | + | ||
| 25 | + | ||
| 26 | +def test_localize_indices_preserves_document_local_entries(): | ||
| 27 | + """Global top-k coordinates outside a query document are invalidated.""" | ||
| 28 | + topk_indices = torch.tensor([[0, 1, 3], [1, 2, 3], [2, 4, 5]], dtype=torch.int64) | ||
| 29 | + doc_ids = torch.tensor([0, 0, 1], dtype=torch.int64) | ||
| 30 | + cu_cmp = torch.tensor([0, 2, 5], dtype=torch.int64) | ||
| 31 | + | ||
| 32 | + localized = sparse_attention._localize_indices(topk_indices, doc_ids, cu_cmp) | ||
| 33 | + | ||
| 34 | + expected = torch.tensor([[0, 1, -1], [1, -1, -1], [0, 2, 3]], dtype=torch.int64) | ||
| 35 | + assert torch.equal(localized, expected) | ||
| 36 | + | ||
| 37 | + | ||
| 38 | +def _fake_mla_apply(captured): | ||
测试用 _fake_mla_apply 替换了 _SparseMLA.apply,现有 UT 无法触达_SparseMLA.forward/backward 内部,建议补充测试用例 ![]() ![]() | |||
| 39 | + def apply(q, swa_k, cmp_k, indices, sinks, cu_q, cu_cmp, remainder, scale, ratio, window): | ||
| 40 | + captured.update( | ||
| 41 | + q=q, | ||
| 42 | + swa_k=swa_k, | ||
| 43 | + cmp_k=cmp_k, | ||
| 44 | + indices=indices, | ||
| 45 | + sinks=sinks, | ||
| 46 | + cu_q=cu_q, | ||
| 47 | + cu_cmp=cu_cmp, | ||
| 48 | + remainder=remainder, | ||
| 49 | + scale=scale, | ||
| 50 | + ratio=ratio, | ||
| 51 | + window=window, | ||
| 52 | + ) | ||
| 53 | + lse = torch.zeros((1, q.shape[0], q.shape[1]), dtype=q.dtype, device=q.device) | ||
| 54 | + return q, lse | ||
| 55 | + | ||
| 56 | + return staticmethod(apply) | ||
| 57 | + | ||
| 58 | + | ||
| 59 | +@pytest.mark.parametrize( | ||
| 60 | + ("ratio", "with_shared", "cmp_tokens"), | ||
| 61 | + [(0, False, 0), (1, True, 4), (2, True, 2)], | ||
| 62 | + ids=["window-only", "full-resolution-shared-kv", "compressed-shared-kv"], | ||
| 63 | +) | ||
| 64 | +def test_sparse_mla_forward_backward_uses_quantized_forward_and_original_backward( | ||
| 65 | + monkeypatch, ratio, with_shared, cmp_tokens | ||
| 66 | +): | ||
| 67 | + """Exercise the custom autograd function around mocked NPU kernel boundaries.""" | ||
| 68 | + device = "npu" | ||
| 69 | + q = torch.ones((4, 2, 4), device=device, dtype=torch.bfloat16, requires_grad=True) | ||
| 70 | + swa_k = torch.ones((4, 1, 4), device=device, dtype=torch.bfloat16, requires_grad=True) | ||
| 71 | + cmp_k = ( | ||
| 72 | + torch.ones((cmp_tokens, 1, 4), device=device, dtype=torch.bfloat16, requires_grad=True) if with_shared else None | ||
| 73 | + ) | ||
| 74 | + indices = torch.zeros((4, 1, 2), device=device, dtype=torch.int32) if with_shared else None | ||
| 75 | + sinks = torch.ones((2,), device=device, dtype=torch.float32, requires_grad=True) | ||
| 76 | + cu_q = torch.tensor([0, 4], device=device, dtype=torch.int32) | ||
| 77 | + cu_cmp = torch.tensor([0, cmp_tokens], device=device, dtype=torch.int32) if with_shared else None | ||
| 78 | + remainder = torch.zeros((1,), device=device, dtype=torch.int32) if ratio > 1 else None | ||
| 79 | + forward_metadata = torch.tensor([7], device=device, dtype=torch.int32) | ||
| 80 | + grad_metadata = torch.tensor([9], device=device, dtype=torch.int32) | ||
| 81 | + metadata_calls = [] | ||
| 82 | + quantize_calls = [] | ||
| 83 | + forward_kwargs = {} | ||
| 84 | + lse = torch.zeros((1, q.shape[0], q.shape[1]), device=device, dtype=q.dtype) | ||
| 85 | + | ||
| 86 | + def metadata(*args, **kwargs): | ||
| 87 | + metadata_calls.append((args, kwargs)) | ||
| 88 | + return forward_metadata if len(metadata_calls) == 1 else grad_metadata | ||
| 89 | + | ||
| 90 | + def fake_quantize(kv, quant_group_size, quant_mode): | ||
| 91 | + quantize_calls.append((kv, quant_group_size, quant_mode)) | ||
| 92 | + return kv + 1 | ||
| 93 | + | ||
| 94 | + def sparse_flash_mla(q_input, **kwargs): | ||
| 95 | + forward_kwargs.update(kwargs) | ||
| 96 | + return q_input + 1, lse | ||
| 97 | + | ||
| 98 | + def sparse_flash_mla_grad(q_input, grad_output, output, saved_lse, **kwargs): | ||
| 99 | + assert q_input is q | ||
| 100 | + assert output.shape == q.shape | ||
| 101 | + assert saved_lse is lse | ||
| 102 | + torch.testing.assert_close(grad_output, torch.ones_like(q)) | ||
| 103 | + assert kwargs["ori_kv"] is swa_k | ||
| 104 | + assert kwargs["cmp_kv"] is cmp_k | ||
| 105 | + assert kwargs["cmp_sparse_indices"] is indices | ||
| 106 | + assert kwargs["sinks"] is sinks | ||
| 107 | + assert kwargs["metadata"] is grad_metadata | ||
| 108 | + assert kwargs["cmp_residual_kv"] is remainder | ||
| 109 | + assert kwargs["softmax_scale"] == 0.5 | ||
| 110 | + assert kwargs["cmp_ratio"] == max(ratio, 1) | ||
| 111 | + return ( | ||
| 112 | + torch.full_like(q, 2), | ||
| 113 | + torch.full_like(swa_k, 3), | ||
| 114 | + torch.full_like(cmp_k, 4) if cmp_k is not None else None, | ||
| 115 | + torch.full_like(sinks, 5), | ||
| 116 | + None, | ||
| 117 | + None, | ||
| 118 | + ) | ||
| 119 | + | ||
| 120 | + monkeypatch.setattr(sparse_attention, "sparse_flash_mla_metadata", metadata) | ||
| 121 | + monkeypatch.setattr(sparse_attention, "sparse_flash_mla_grad_metadata", metadata) | ||
| 122 | + monkeypatch.setattr(sparse_attention, "_fake_quantize_kv", fake_quantize) | ||
| 123 | + monkeypatch.setattr(torch.ops.cann_ops_transformer, "sparse_flash_mla", sparse_flash_mla) | ||
| 124 | + monkeypatch.setattr(torch.ops.cann_ops_transformer, "sparse_flash_mla_grad", sparse_flash_mla_grad) | ||
| 125 | + | ||
| 126 | + output, returned_lse = sparse_attention._SparseMLA.apply( | ||
| 127 | + q, | ||
| 128 | + swa_k, | ||
| 129 | + cmp_k, | ||
| 130 | + indices, | ||
| 131 | + sinks, | ||
| 132 | + cu_q, | ||
| 133 | + cu_cmp, | ||
| 134 | + remainder, | ||
| 135 | + 0.5, | ||
| 136 | + ratio, | ||
| 137 | + 2, | ||
| 138 | + ) | ||
| 139 | + | ||
| 140 | + assert returned_lse is lse | ||
| 141 | + assert not returned_lse.requires_grad | ||
| 142 | + assert len(quantize_calls) == (2 if with_shared else 1) | ||
| 143 | + assert quantize_calls[0][1:] == (32, "mxfp8_bf16") | ||
| 144 | + if with_shared: | ||
| 145 | + assert quantize_calls[1][1:] == (16, "mxfp4_bf16") | ||
| 146 | + torch.testing.assert_close(forward_kwargs["ori_kv"], swa_k + 1) | ||
| 147 | + if with_shared: | ||
| 148 | + torch.testing.assert_close(forward_kwargs["cmp_kv"], cmp_k + 1) | ||
| 149 | + else: | ||
| 150 | + assert forward_kwargs["cmp_kv"] is None | ||
| 151 | + assert forward_kwargs["metadata"] is forward_metadata | ||
| 152 | + assert forward_kwargs["cmp_sparse_indices"] is indices | ||
| 153 | + assert forward_kwargs["sinks"] is sinks | ||
| 154 | + assert forward_kwargs["cmp_residual_kv"] is remainder | ||
| 155 | + assert len(metadata_calls) == 2 | ||
| 156 | + | ||
| 157 | + output.sum().backward() | ||
| 158 | + torch.testing.assert_close(q.grad, torch.full_like(q, 2)) | ||
| 159 | + torch.testing.assert_close(swa_k.grad, torch.full_like(swa_k, 3)) | ||
| 160 | + torch.testing.assert_close(sinks.grad, torch.full_like(sinks, 5)) | ||
| 161 | + if with_shared: | ||
| 162 | + torch.testing.assert_close(cmp_k.grad, torch.full_like(cmp_k, 4)) | ||
| 163 | + | ||
| 164 | + | ||
| 165 | +def test_forward_ratio_zero_passes_window_only_inputs_to_mla(monkeypatch): | ||
| 166 | + captured = {} | ||
| 167 | + monkeypatch.setattr(sparse_attention._SparseMLA, "apply", _fake_mla_apply(captured)) | ||
| 168 | + | ||
| 169 | + device = "npu" | ||
| 170 | + q = torch.randn((1, 4, 2, 512), device=device, dtype=torch.bfloat16) | ||
| 171 | + swa_k = torch.randn((1, 4, 512), device=device, dtype=torch.bfloat16) | ||
| 172 | + metadata = SimpleNamespace( | ||
| 173 | + cu_seq_q=torch.tensor([0, 4], device=device, dtype=torch.int32), | ||
| 174 | + doc_ids_BL=torch.zeros(4, device=device, dtype=torch.int32), | ||
| 175 | + ) | ||
| 176 | + module = sparse_attention.QuantV41SparseAttention( | ||
| 177 | + window_size=3, | ||
| 178 | + softmax_scale=0.125, | ||
| 179 | + compress_ratio=0, | ||
| 180 | + ) | ||
| 181 | + | ||
| 182 | + output, teacher_lse = module( | ||
| 183 | + q, | ||
| 184 | + swa_k, | ||
| 185 | + None, | ||
| 186 | + attention_masks=metadata, | ||
| 187 | + topk_indices=None, | ||
| 188 | + attn_sink=torch.zeros(2, device=device, dtype=torch.float32), | ||
| 189 | + wants_teacher=True, | ||
| 190 | + ) | ||
| 191 | + | ||
| 192 | + assert output.shape == q.shape | ||
| 193 | + assert teacher_lse.shape == (1, 2, 4) | ||
| 194 | + assert captured["cmp_k"] is None | ||
| 195 | + assert captured["indices"] is None | ||
| 196 | + assert captured["cu_cmp"] is None | ||
| 197 | + assert captured["ratio"] == 0 | ||
| 198 | + assert captured["window"] == 3 | ||
| 199 | + | ||
| 200 | + | ||
| 201 | +def test_forward_ratio_one_uses_full_resolution_shared_kv_without_residual(monkeypatch): | ||
| 202 | + captured = {} | ||
| 203 | + monkeypatch.setattr(sparse_attention._SparseMLA, "apply", _fake_mla_apply(captured)) | ||
| 204 | + | ||
| 205 | + device = "npu" | ||
| 206 | + q = torch.randn((1, 4, 2, 512), device=device, dtype=torch.bfloat16) | ||
| 207 | + swa_k = torch.randn((1, 4, 512), device=device, dtype=torch.bfloat16) | ||
| 208 | + cmp_k = torch.randn((1, 4, 512), device=device, dtype=torch.bfloat16) | ||
| 209 | + metadata = SimpleNamespace( | ||
| 210 | + cu_seq_q=torch.tensor([0, 4], device=device, dtype=torch.int32), | ||
| 211 | + doc_ids_BL=torch.zeros(4, device=device, dtype=torch.int32), | ||
| 212 | + ) | ||
| 213 | + module = sparse_attention.QuantV41SparseAttention( | ||
| 214 | + window_size=3, | ||
| 215 | + softmax_scale=0.125, | ||
| 216 | + compress_ratio=1, | ||
| 217 | + ) | ||
| 218 | + | ||
| 219 | + output, teacher_lse = module( | ||
| 220 | + q, | ||
| 221 | + swa_k, | ||
| 222 | + cmp_k, | ||
| 223 | + attention_masks=metadata, | ||
| 224 | + topk_indices=torch.zeros((1, 4, 2), device=device, dtype=torch.int64), | ||
| 225 | + attn_sink=torch.zeros(2, device=device, dtype=torch.float32), | ||
| 226 | + wants_teacher=True, | ||
| 227 | + ) | ||
| 228 | + | ||
| 229 | + assert output.shape == q.shape | ||
| 230 | + assert teacher_lse.shape == (1, 2, 4) | ||
| 231 | + assert captured["cu_cmp"].tolist() == [0, 4] | ||
| 232 | + assert captured["remainder"] is None | ||
| 233 | + assert captured["cmp_k"].shape == (4, 1, 512) | ||
| 234 | + | ||
| 235 | + | ||
| 236 | +def test_forward_ratio_two_localizes_and_compacts_indices(monkeypatch): | ||
| 237 | + captured = {} | ||
| 238 | + monkeypatch.setattr(sparse_attention._SparseMLA, "apply", _fake_mla_apply(captured)) | ||
| 239 | + | ||
| 240 | + device = "npu" | ||
| 241 | + q = torch.randn((1, 4, 2, 512), device=device, dtype=torch.bfloat16) | ||
| 242 | + swa_k = torch.randn((1, 4, 512), device=device, dtype=torch.bfloat16) | ||
| 243 | + cmp_k = torch.randn((1, 2, 512), device=device, dtype=torch.bfloat16) | ||
| 244 | + metadata = SimpleNamespace( | ||
| 245 | + cu_seq_q=torch.tensor([0, 2, 4], device=device, dtype=torch.int32), | ||
| 246 | + doc_ids_BL=torch.tensor([0, 0, 1, 1], device=device, dtype=torch.int32), | ||
| 247 | + ) | ||
| 248 | + topk_indices = torch.tensor( | ||
| 249 | + [[[0, 1], [1, 0], [1, 0], [0, 1]]], | ||
| 250 | + device=device, | ||
| 251 | + dtype=torch.int64, | ||
| 252 | + ) | ||
| 253 | + module = sparse_attention.QuantV41SparseAttention( | ||
| 254 | + window_size=5, | ||
| 255 | + softmax_scale=0.25, | ||
| 256 | + compress_ratio=2, | ||
| 257 | + ) | ||
| 258 | + | ||
| 259 | + output, teacher_lse = module( | ||
| 260 | + q, | ||
| 261 | + swa_k, | ||
| 262 | + cmp_k, | ||
| 263 | + attention_masks=metadata, | ||
| 264 | + topk_indices=topk_indices, | ||
| 265 | + attn_sink=torch.zeros(2, device=device, dtype=torch.float32), | ||
| 266 | + wants_teacher=True, | ||
| 267 | + ) | ||
| 268 | + | ||
| 269 | + assert output.shape == q.shape | ||
| 270 | + assert teacher_lse.shape == (1, 2, 4) | ||
| 271 | + assert captured["cu_cmp"].tolist() == [0, 1, 2] | ||
| 272 | + assert captured["remainder"].tolist() == [0, 0] | ||
| 273 | + assert captured["indices"].shape == (4, 1, 2) | ||
| 274 | + assert captured["indices"].tolist() == [[[0, -1]], [[0, -1]], [[0, -1]], [[0, -1]]] | ||
| 275 | + assert captured["cmp_k"].shape == (2, 1, 512) | ||
| 276 | + assert captured["ratio"] == 2 | ||
| @@ -3,12 +3,18 @@ | |||
| 3 | # This source code is licensed under the BSD-style license found in the | 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. | 4 | # LICENSE file in the root directory of this source tree. |
| 5 | 5 | ||
| 6 | -from torchao_npu.configs import ModuleSwapConfig, ParamSwapConfig, QuantLightningIndexerConfig | 6 | +from torchao_npu.configs import ( |
| 7 | + ModuleSwapConfig, | ||
| 8 | + ParamSwapConfig, | ||
| 9 | + QuantLightningIndexerConfig, | ||
| 10 | + QuantV41SparseAttentionConfig, | ||
| 11 | +) | ||
| 7 | 12 | ||
| 8 | __all__ = [ | 13 | __all__ = [ |
| 9 | "ModuleSwapConfig", | 14 | "ModuleSwapConfig", |
| 10 | "ParamSwapConfig", | 15 | "ParamSwapConfig", |
| 11 | "QuantLightningIndexerConfig", | 16 | "QuantLightningIndexerConfig", |
| 17 | + "QuantV41SparseAttentionConfig", | ||
| 12 | ] | 18 | ] |
| 13 | 19 | ||
| 14 | 20 | ||
| @@ -6,12 +6,17 @@ | |||
| 6 | """Public quantization configurations for torchao-npu.""" | 6 | """Public quantization configurations for torchao-npu.""" |
| 7 | 7 | ||
| 8 | from torchao_npu.configs.module_swap import ModuleSwapConfig | 8 | from torchao_npu.configs.module_swap import ModuleSwapConfig |
| 9 | -from torchao_npu.configs.module_swap_configs import QuantLightningIndexerConfig, quant_mode_for_config | 9 | +from torchao_npu.configs.module_swap_configs import ( |
| 10 | + QuantLightningIndexerConfig, | ||
| 11 | + QuantV41SparseAttentionConfig, | ||
| 12 | + quant_mode_for_config, | ||
| 13 | +) | ||
| 10 | from torchao_npu.configs.param_swap import ParamSwapConfig | 14 | from torchao_npu.configs.param_swap import ParamSwapConfig |
| 11 | 15 | ||
| 12 | __all__ = [ | 16 | __all__ = [ |
| 13 | "ModuleSwapConfig", | 17 | "ModuleSwapConfig", |
| 14 | "ParamSwapConfig", | 18 | "ParamSwapConfig", |
| 15 | "QuantLightningIndexerConfig", | 19 | "QuantLightningIndexerConfig", |
| 20 | + "QuantV41SparseAttentionConfig", | ||
| 16 | "quant_mode_for_config", | 21 | "quant_mode_for_config", |
| 17 | ] | 22 | ] |
| @@ -5,9 +5,10 @@ | |||
| 5 | 5 | ||
| 6 | """Concrete module-swap quantization configs.""" | 6 | """Concrete module-swap quantization configs.""" |
| 7 | 7 | ||
| 8 | -__all__ = ["QuantLightningIndexerConfig", "quant_mode_for_config"] | 8 | +__all__ = ["QuantLightningIndexerConfig", "QuantV41SparseAttentionConfig", "quant_mode_for_config"] |
| 9 | 9 | ||
| 10 | from torchao_npu.configs.module_swap_configs.quant_lightning_indexer import ( | 10 | from torchao_npu.configs.module_swap_configs.quant_lightning_indexer import ( |
| 11 | QuantLightningIndexerConfig, | 11 | QuantLightningIndexerConfig, |
| 12 | quant_mode_for_config, | 12 | quant_mode_for_config, |
| 13 | ) | 13 | ) |
| 14 | +from torchao_npu.configs.module_swap_configs.quant_v41_sparse_attention import QuantV41SparseAttentionConfig | ||
| @@ -0,0 +1,36 @@ | |||
| 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 V4.1 sparse attention quantization path.""" | ||
| 7 | + | ||
| 8 | +__all__ = ["QuantV41SparseAttentionConfig"] | ||
| 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 QuantV41SparseAttentionConfig(ModuleSwapConfig): | ||
| 21 | + """Install mixed quant sparse attention with FP8 SWA_KV / FP4 CMP_KV and BF16 scales.""" | ||
| 22 | + | ||
| 23 | + | ||
| 24 | +@register_quantize_module_handler(QuantV41SparseAttentionConfig) | ||
| 25 | +def _quant_v41_sparse_attention_transform(module, config: QuantV41SparseAttentionConfig): | ||
| 26 | + from torchao_npu.quantized_modules.v41_sparse_attention import QuantV41SparseAttention | ||
| 27 | + | ||
| 28 | + # Keep the host forward's validation and distillation loss wiring intact. | ||
| 29 | + if not hasattr(module, "_torchao_npu_original_compute_attention"): | ||
| 30 | + module._torchao_npu_original_compute_attention = module._compute_attention | ||
| 31 | + if config.step == QATStep.PREPARE: | ||
| 32 | + module._torchao_npu_module_swap_config = config | ||
| 33 | + module._compute_attention = MethodType(QuantV41SparseAttention.forward, module) | ||
| 34 | + else: | ||
| 35 | + module._compute_attention = module._torchao_npu_original_compute_attention | ||
| 36 | + return module | ||
| @@ -0,0 +1,300 @@ | |||
| 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 | +"""V4.1 sparse attention using the mixed-quantization MLA kernel. | ||
| 6 | + | ||
| 7 | +The host retains validation and distillation wiring. This module packs both | ||
| 8 | +KV streams with ``kv_compress_epilog`` and feeds the resulting byte cache to | ||
| 9 | +``mixed_quant_sparse_flash_mla``. The mixed kernel currently has no backward | ||
| 10 | +operator, so backward uses original BF16 KV with the quantized output/LSE. | ||
| 11 | +This is an approximate gradient, not an exact derivative of the quantized | ||
| 12 | +forward or a dequantized-KV STE. | ||
| 13 | +""" | ||
| 14 | + | ||
| 15 | +__all__ = ["QuantV41SparseAttention"] | ||
| 16 | + | ||
| 17 | +import custom_ops # noqa: F401 # pyrefly: ignore[missing-import] | ||
| 18 | +import torch | ||
| 19 | +import torch_npu | ||
| 20 | +from cann_ops_transformer import sparse_flash_mla_grad_metadata, sparse_flash_mla_metadata | ||
| 21 | + | ||
| 22 | +from torchao_npu.quantization.quant_primitives.mx_bf16 import dequantize_mx_bf16 | ||
| 23 | + | ||
| 24 | +try: | ||
| 25 | + _IS_A5 = torch_npu.npu.get_device_name().startswith("Ascend950") | ||
| 26 | +except (AttributeError, TypeError): | ||
| 27 | + _IS_A5 = False | ||
| 28 | + | ||
| 29 | + | ||
| 30 | +def _kernel_options(cu_q, cu_cmp, remainder, ratio, window): | ||
| 31 | + return dict( | ||
| 32 | + cu_seqlens_q=cu_q, | ||
| 33 | + cu_seqlens_ori_kv=cu_q, | ||
| 34 | + cu_seqlens_cmp_kv=cu_cmp, | ||
| 35 | + cmp_residual_kv=remainder, | ||
| 36 | + cmp_ratio=max(ratio, 1), | ||
| 37 | + ori_mask_mode=4, | ||
| 38 | + cmp_mask_mode=0 if _IS_A5 and cu_cmp is None else 3, | ||
| 39 | + ori_win_left=window - 1, | ||
| 40 | + ori_win_right=0, | ||
| 41 | + layout_q="TND", | ||
| 42 | + layout_kv="TND", | ||
| 43 | + ) | ||
| 44 | + | ||
| 45 | + | ||
| 46 | +_ROPE_HEAD_DIM = 64 | ||
| 47 | + | ||
| 48 | + | ||
| 49 | +def _align_up(value: int, alignment: int) -> int: | ||
| 50 | + """Round ``value`` up to the next multiple of ``alignment``.""" | ||
| 51 | + return (value + alignment - 1) // alignment * alignment | ||
| 52 | + | ||
| 53 | + | ||
| 54 | +def _quantized_cache_width(head_dim: int, quant_group_size: int = 32, quant_mode: str = "mxfp8_bf16") -> int: | ||
| 55 | + """Return the 32-byte-aligned row width for a kv-compress layout.""" | ||
| 56 | + if head_dim <= _ROPE_HEAD_DIM or head_dim % 64: | ||
| 57 | + raise ValueError("quantized V4.1 KV requires head_dim > 64 and divisible by 64") | ||
| 58 | + if quant_mode not in ("mxfp8_bf16", "mxfp4_bf16"): | ||
| 59 | + raise ValueError(f"unsupported quantization mode: {quant_mode}") | ||
| 60 | + if quant_group_size <= 0 or head_dim % quant_group_size: | ||
| 61 | + raise ValueError("quant_group_size must be positive and divide head_dim") | ||
| 62 | + data_col = head_dim if quant_mode == "mxfp8_bf16" else head_dim // 2 | ||
| 63 | + scale_bytes = (head_dim // quant_group_size) * 2 | ||
| 64 | + concat_col = data_col + scale_bytes | ||
| 65 | + return _align_up(concat_col, 32) | ||
| 66 | + | ||
| 67 | + | ||
| 68 | +def _fake_quantize_kv(kv: torch.Tensor, quant_group_size=32, quant_mode="mxfp8_bf16") -> torch.Tensor: | ||
| 69 | + """Pack a BF16 ``[tokens, 1, head_dim]`` KV stream into the mixed layout.""" | ||
| 70 | + if kv.ndim != 3 or kv.shape[1] != 1: | ||
似乎应该用全0Tensor (torch.zeros)进行初始化? ![]() ![]() | |||
| 71 | + raise ValueError(f"quantized V4.1 KV must have shape [T, 1, D], got {tuple(kv.shape)}") | ||
| 72 | + tokens, _, head_dim = kv.shape | ||
| 73 | + cache_width = _quantized_cache_width(head_dim, quant_group_size, quant_mode) | ||
| 74 | + # kv_compress_epilog has a paged-cache interface. A one-token block per | ||
| 75 | + # row gives a contiguous TND view while retaining the required 4-D cache. | ||
| 76 | + cache_dtype = torch.float8_e4m3fn if quant_mode == "mxfp8_bf16" else torch.uint8 | ||
| 77 | + cache = torch.zeros((tokens, cache_width), dtype=cache_dtype, device=kv.device) | ||
| 78 | + | ||
| 79 | + slot_mapping = torch.arange(tokens, dtype=torch.int32, device=kv.device) | ||
| 80 | + torch.ops.custom.kv_compress_epilog_v2.default( | ||
| 81 | + cache, | ||
| 82 | + kv.reshape(tokens, head_dim), | ||
| 83 | + slot_mapping, | ||
| 84 | + quant_group_size=quant_group_size, | ||
| 85 | + quant_mode=quant_mode, | ||
| 86 | + round_scale=False, | ||
| 87 | + ) | ||
| 88 | + | ||
| 89 | + qdq_cache = dequantize_mx_bf16( | ||
| 90 | + cache, | ||
| 91 | + d=head_dim, | ||
| 92 | + quant_mode=quant_mode, | ||
| 93 | + group_size=quant_group_size, | ||
| 94 | + fp8_dtype=torch.float8_e4m3fn if quant_mode == "mxfp8_bf16" else None, | ||
| 95 | + ) | ||
| 96 | + | ||
| 97 | + return qdq_cache.reshape(tokens, 1, head_dim).contiguous() | ||
| 98 | + | ||
| 99 | + | ||
| 100 | +class _SparseMLA(torch.autograd.Function): | ||
| 101 | + @staticmethod | ||
| 102 | + def forward( # pyrefly: ignore [bad-override] | ||
| 103 | + ctx, | ||
| 104 | + q, | ||
| 105 | + swa_k, | ||
| 106 | + cmp_k, | ||
| 107 | + indices, | ||
| 108 | + sinks, | ||
| 109 | + cu_q, | ||
| 110 | + cu_cmp, | ||
| 111 | + cmp_residual_kv, | ||
| 112 | + softmax_scale, | ||
| 113 | + ratio, | ||
| 114 | + window_size, | ||
| 115 | + ): | ||
| 116 | + options = _kernel_options(cu_q, cu_cmp, cmp_residual_kv, ratio, window_size) | ||
| 117 | + # K can differ between the candidate and indexer paths. Use the actual | ||
| 118 | + # supplied shape rather than assuming the LI configuration's top-k. | ||
| 119 | + geometry = dict( | ||
| 120 | + ori_topk=0, | ||
| 121 | + cmp_topk=0 if indices is None else indices.shape[-1], | ||
| 122 | + has_ori_kv=True, | ||
| 123 | + has_cmp_kv=cmp_k is not None, | ||
| 124 | + ) | ||
| 125 | + smla_metadata = sparse_flash_mla_metadata( | ||
| 126 | + q.shape[1], | ||
| 127 | + 1, | ||
| 128 | + q.shape[2], | ||
| 129 | + ori_topk_length=None, | ||
| 130 | + cmp_topk_length=None, | ||
| 131 | + **options, | ||
| 132 | + **geometry, | ||
| 133 | + ) | ||
| 134 | + smla_grad_metadata = sparse_flash_mla_grad_metadata(q.shape[1], 1, q.shape[2], **options, **geometry) | ||
| 135 | + | ||
| 136 | + qdq_swa_k = _fake_quantize_kv(swa_k, quant_group_size=32, quant_mode="mxfp8_bf16") | ||
| 137 | + qdq_cmp_k = None if cmp_k is None else _fake_quantize_kv(cmp_k, quant_group_size=16, quant_mode="mxfp4_bf16") | ||
| 138 | + | ||
| 139 | + output, lse = torch.ops.cann_ops_transformer.sparse_flash_mla( | ||
| 140 | + q, | ||
| 141 | + ori_kv=qdq_swa_k, | ||
| 142 | + cmp_kv=qdq_cmp_k, | ||
| 143 | + cmp_sparse_indices=indices, | ||
| 144 | + ori_block_table=None, | ||
| 145 | + cmp_block_table=None, | ||
| 146 | + sinks=sinks, | ||
| 147 | + metadata=smla_metadata, | ||
| 148 | + softmax_scale=softmax_scale, | ||
| 149 | + return_softmax_lse=True, | ||
| 150 | + **options, | ||
| 151 | + ) | ||
| 152 | + | ||
| 153 | + ctx.save_for_backward( | ||
| 154 | + q, | ||
| 155 | + swa_k, | ||
| 156 | + cmp_k, | ||
| 157 | + indices, | ||
| 158 | + sinks, | ||
| 159 | + cu_q, | ||
| 160 | + cu_cmp, | ||
| 161 | + cmp_residual_kv, | ||
| 162 | + output, | ||
| 163 | + lse, | ||
| 164 | + smla_grad_metadata, | ||
| 165 | + ) | ||
| 166 | + ctx.softmax_scale, ctx.ratio, ctx.window_size = softmax_scale, ratio, window_size | ||
| 167 | + # The teacher consumes the LSE as a detached constant. | ||
| 168 | + ctx.mark_non_differentiable(lse) | ||
| 169 | + return output, lse | ||
| 170 | + | ||
| 171 | + @staticmethod | ||
| 172 | + def backward(ctx, grad_output, grad_lse): # pyrefly: ignore [bad-override] | ||
| 173 | + del grad_lse # the LSE is a teacher signal, never a loss input | ||
| 174 | + # A single read of the saved tensors: eager AC recomputation must see | ||
| 175 | + # the same native metadata the forward produced. | ||
| 176 | + q, swa_k, cmp_k, indices, sink, cu_q, cu_cmp, cmp_residual_kv, output, lse, metadata = ctx.saved_tensors | ||
| 177 | + dq, dswa_k, dcmp_k, dsink, _, _ = torch.ops.cann_ops_transformer.sparse_flash_mla_grad( | ||
| 178 | + q, | ||
| 179 | + grad_output.contiguous(), | ||
| 180 | + output, | ||
| 181 | + lse, | ||
| 182 | + ori_kv=swa_k, | ||
| 183 | + cmp_kv=cmp_k, | ||
| 184 | + ori_sparse_indices=None, | ||
| 185 | + cmp_sparse_indices=indices, | ||
| 186 | + sinks=sink, | ||
| 187 | + metadata=metadata, | ||
| 188 | + seqused_q=None, | ||
| 189 | + seqused_ori_kv=None, | ||
| 190 | + seqused_cmp_kv=None, | ||
| 191 | + ori_topk_length=None, | ||
| 192 | + cmp_topk_length=None, | ||
| 193 | + softmax_scale=ctx.softmax_scale, | ||
| 194 | + **_kernel_options(cu_q, cu_cmp, cmp_residual_kv, ctx.ratio, ctx.window_size), | ||
| 195 | + ) | ||
| 196 | + return dq, dswa_k, dcmp_k if cmp_k is not None else None, None, dsink, None, None, None, None, None, None | ||
| 197 | + | ||
| 198 | + | ||
| 199 | +def _localize_indices(topk_indices: torch.Tensor, doc_ids_BL: torch.Tensor, cu_cmp: torch.Tensor) -> torch.Tensor: | ||
| 200 | + """Global compressed-pool coordinates into the query's own document-local grid. | ||
| 201 | + | ||
| 202 | + Entries outside the query's document become ``-1``; the caller compacts them. | ||
| 203 | + The shared ``topk_indices``/``topk_scores`` are never modified in place. | ||
| 204 | + """ | ||
| 205 | + starts = cu_cmp.to(dtype=torch.long, device=topk_indices.device) | ||
| 206 | + doc_ids = doc_ids_BL.reshape(-1) | ||
| 207 | + doc_start = starts[doc_ids].unsqueeze(-1) | ||
| 208 | + doc_end = starts[doc_ids + 1].unsqueeze(-1) | ||
| 209 | + indices = topk_indices.reshape(-1, topk_indices.shape[-1]).to(torch.long) | ||
| 210 | + valid = (indices >= doc_start) & (indices < doc_end) | ||
| 211 | + return torch.where(valid, indices - doc_start, -1).view_as(topk_indices) | ||
| 212 | + | ||
| 213 | + | ||
| 214 | +class QuantV41SparseAttention(torch.nn.Module): | ||
| 215 | + """Sparse computation installed at the host's ``_compute_attention`` seam. | ||
| 216 | + | ||
| 217 | + The host supplies window_size, softmax_scale and compress_ratio when the | ||
| 218 | + module-swap handler binds this forward method to it. | ||
| 219 | + """ | ||
| 220 | + | ||
| 221 | + def __init__(self, *, window_size: int, softmax_scale: float, compress_ratio: int): | ||
| 222 | + super().__init__() | ||
| 223 | + self.window_size = window_size | ||
| 224 | + self.softmax_scale = softmax_scale | ||
| 225 | + self.compress_ratio = compress_ratio | ||
| 226 | + | ||
| 227 | + def forward( | ||
| 228 | + self, | ||
| 229 | + q, | ||
| 230 | + swa_k, | ||
| 231 | + cmp_k, | ||
| 232 | + *, | ||
| 233 | + attention_masks, | ||
| 234 | + topk_indices, | ||
| 235 | + attn_sink, | ||
| 236 | + wants_teacher, | ||
| 237 | + ): | ||
| 238 | + metadata = attention_masks | ||
| 239 | + ratio = self.compress_ratio | ||
| 240 | + if ratio not in (0, 1, 2): | ||
| 241 | + raise ValueError(f"V4.1 fused sparse attention supports ratios 0/1/2, got {ratio}") | ||
| 242 | + if q.ndim != 4 or q.shape[0] != 1 or swa_k.shape != (1, q.shape[1], q.shape[-1]): | ||
| 243 | + raise ValueError("V4.1 SMLA requires CP1 packed Q [1,S,H,D] and original KV [1,S,D]") | ||
| 244 | + if q.shape[-1] != 512: | ||
| 245 | + raise ValueError("mixed quant V4.1 SMLA requires head_dim=512 with 64 trailing RoPE channels") | ||
| 246 | + if attn_sink is None: | ||
| 247 | + raise ValueError("V4.1 SMLA requires per-head attention sinks") | ||
| 248 | + if q.dtype != torch.bfloat16 or swa_k.dtype != q.dtype: | ||
| 249 | + raise ValueError("V4.1 SMLA requires BF16 Q/KV; no implicit precision conversion") | ||
| 250 | + cu_q = metadata.cu_seq_q | ||
| 251 | + if cu_q is None: | ||
| 252 | + raise ValueError("V4.1 SMLA requires the packed document boundaries (cu_seq_q metadata)") | ||
| 253 | + shared = cu_cmp = remainder = indices = None | ||
| 254 | + if ratio == 0: | ||
| 255 | + if cmp_k is not None: | ||
| 256 | + raise ValueError("window-only ratio 0 must not receive a second KV stream") | ||
| 257 | + else: | ||
| 258 | + if ( | ||
| 259 | + cmp_k is None | ||
| 260 | + or cmp_k.ndim != 3 | ||
| 261 | + or cmp_k.shape[0] != 1 | ||
| 262 | + or cmp_k.shape[-1] != q.shape[-1] | ||
| 263 | + or cmp_k.dtype != q.dtype | ||
| 264 | + ): | ||
| 265 | + raise ValueError("ratio 1/2 requires a BF16 second KV stream [1,N,D]") | ||
| 266 | + if topk_indices is None: | ||
| 267 | + raise ValueError("ratio 1/2 fused attention requires the model's selection indices") | ||
| 268 | + if ratio == 1 and cmp_k.shape != swa_k.shape: | ||
| 269 | + raise ValueError("ratio 1 requires full-resolution shared KV") | ||
| 270 | + # Per-document alignment makes every document's compressed length | ||
| 271 | + # exactly cu_q // ratio, with no residual groups to carry. | ||
| 272 | + cu_cmp = cu_q // ratio | ||
| 273 | + remainder = torch.zeros_like(cu_cmp[1:]) if ratio > 1 else None | ||
| 274 | + shared = cmp_k.flatten(0, 1) | ||
| 275 | + # TND kernels consume document-local indices; cu_cmp supplies the | ||
| 276 | + # document offsets. Preserve the reference cross-document mask. | ||
| 277 | + local = _localize_indices(topk_indices, metadata.doc_ids_BL, cu_cmp) | ||
| 278 | + # Packed documents can leave leading/interleaved invalid slots; | ||
| 279 | + # compact them without changing the selected keys or their order. | ||
| 280 | + order = (local < 0).to(torch.int32).argsort(dim=-1, stable=True) | ||
| 281 | + indices = local.gather(-1, order).flatten(0, 1).to(torch.int32).unsqueeze(1).contiguous() | ||
| 282 | + shared = shared.unsqueeze(1).contiguous() | ||
| 283 | + output, lse = _SparseMLA.apply( | ||
| 284 | + q.flatten(0, 1).contiguous(), | ||
| 285 | + swa_k.flatten(0, 1).unsqueeze(1).contiguous(), | ||
| 286 | + shared, | ||
| 287 | + indices, | ||
| 288 | + attn_sink.float(), | ||
| 289 | + cu_q, | ||
| 290 | + cu_cmp, | ||
| 291 | + remainder, | ||
| 292 | + self.softmax_scale, | ||
| 293 | + ratio, | ||
| 294 | + self.window_size, | ||
| 295 | + ) | ||
| 296 | + out = output.reshape_as(q) | ||
| 297 | + if not wants_teacher: | ||
| 298 | + return out, None | ||
| 299 | + # The kernel returns the LSE as [1, S, H]; the teacher reads [B, H, L]. | ||
| 300 | + return out, lse.transpose(1, 2) | ||
| @@ -20,7 +20,7 @@ wrappers and NPU kernels continue to come from the separately installed | |||
| 20 | from __future__ import annotations | 20 | from __future__ import annotations |
| 21 | 21 | ||
| 22 | from dataclasses import dataclass, field, replace | 22 | from dataclasses import dataclass, field, replace |
| 23 | -from typing import TYPE_CHECKING, Annotated, Protocol, cast | 23 | +from typing import TYPE_CHECKING, Annotated, Literal, Protocol, cast |
| 24 | 24 | ||
| 25 | import torch | 25 | import torch |
| 26 | import tyro | 26 | import tyro |
| @@ -46,6 +46,7 @@ from torchtitan_npu.models.common.metadata_extension import ( | |||
| 46 | LightningIndexerMetadata, | 46 | LightningIndexerMetadata, |
| 47 | ) | 47 | ) |
| 48 | from torchtitan_npu.models.deepseek_v4.compressor import LightningIndexer | 48 | from torchtitan_npu.models.deepseek_v4.compressor import LightningIndexer |
| 49 | +from torchtitan_npu.models.deepseek_v4_1.attention import CompressedSparseInnerAttention2 | ||
| 49 | from torchtitan_npu.override.common.swiglu_group.ascendc import AscGroupedExperts, _ensure_cann_ops_loaded | 50 | from torchtitan_npu.override.common.swiglu_group.ascendc import AscGroupedExperts, _ensure_cann_ops_loaded |
| 50 | from torchtitan_npu.patches.torchtitan.models.common.linear import BatchedLinear | 51 | from torchtitan_npu.patches.torchtitan.models.common.linear import BatchedLinear |
| 51 | 52 | ||
| @@ -110,6 +111,7 @@ _DEFAULT_TARGET_CONFIG_TYPES = ( | |||
| 110 | GroupedExperts.Config, | 111 | GroupedExperts.Config, |
| 111 | LightningIndexer.Config, | 112 | LightningIndexer.Config, |
| 112 | LightningIndexerMetadata.Config, | 113 | LightningIndexerMetadata.Config, |
| 114 | + CompressedSparseInnerAttention2.Config, | ||
| 113 | ) | 115 | ) |
| 114 | 116 | ||
| 115 | 117 | ||
| @@ -269,10 +271,39 @@ _DSV4_CONFIG_FILTERS = { | |||
| 269 | "lightning_indexer_metadata": match_config_fqn_suffix(".lightning_indexer_metadata"), | 271 | "lightning_indexer_metadata": match_config_fqn_suffix(".lightning_indexer_metadata"), |
| 270 | } | 272 | } |
| 271 | 273 | ||
| 274 | +_DSV41_CONFIG_FILTERS = { | ||
| 275 | + # V4.1 keeps the V4 attention and MoE config-tree suffixes for the dense | ||
| 276 | + # parameter quantizers; only the sparse core has a new module boundary. | ||
| 277 | + "dense": _DSV4_CONFIG_FILTERS["dense"], | ||
| 278 | + "routed_expert": _DSV4_CONFIG_FILTERS["routed_expert"], | ||
| 279 | + "sparse_attention": match_config_fqn_suffix(".attention.inner_attention"), | ||
| 280 | +} | ||
| 281 | + | ||
| 282 | +_ModelType = Literal["v4", "v41"] | ||
| 283 | +_CONFIG_FILTERS_BY_MODEL_TYPE: dict[_ModelType, dict[str, ConfigFilterFn]] = { | ||
| 284 | + "v4": _DSV4_CONFIG_FILTERS, | ||
| 285 | + "v41": _DSV41_CONFIG_FILTERS, | ||
| 286 | +} | ||
| 287 | +_MODEL_TYPE_BY_MODEL_NAME: dict[str, _ModelType] = { | ||
| 288 | + "deepseek_v4": "v4", | ||
| 289 | + "deepseek_v4_1": "v41", | ||
| 290 | +} | ||
| 291 | + | ||
| 272 | 292 | ||
| 273 | _SUPPORTED_RECIPES = ("all_mxfp8", "mix", "all_block_fp8") | 293 | _SUPPORTED_RECIPES = ("all_mxfp8", "mix", "all_block_fp8") |
| 274 | 294 | ||
| 275 | 295 | ||
| 296 | +def _model_type_for_spec(model_spec: ModelSpec) -> _ModelType: | ||
| 297 | + """Return the quantization family recorded by the model registry.""" | ||
| 298 | + try: | ||
| 299 | + return _MODEL_TYPE_BY_MODEL_NAME[model_spec.name] | ||
| 300 | + except KeyError as exc: | ||
| 301 | + raise ValueError( | ||
| 302 | + "TorchAO-NPU quantization supports DeepSeek V4 and V4.1 model specs, " | ||
| 303 | + f"got {getattr(model_spec, 'name', type(model_spec).__qualname__)!r}" | ||
| 304 | + ) from exc | ||
| 305 | + | ||
| 306 | + | ||
| 276 | def _prepare_quant_lightning_indexer_inputs( | 307 | def _prepare_quant_lightning_indexer_inputs( |
| 277 | module, | 308 | module, |
| 278 | idx_q: torch.Tensor, | 309 | idx_q: torch.Tensor, |
| @@ -433,6 +464,8 @@ def _quantization_converter( | |||
| 433 | def _recipe_converters( | 464 | def _recipe_converters( |
| 434 | recipe: str, | 465 | recipe: str, |
| 435 | *, | 466 | *, |
| 467 | + model_type: _ModelType, | ||
| 468 | + enable_sparse_attention_quantization: bool = False, | ||
| 436 | enable_mxfp4_qat: bool, | 469 | enable_mxfp4_qat: bool, |
| 437 | dst_type_max: float, | 470 | dst_type_max: float, |
| 438 | fsdp_prequantize: bool, | 471 | fsdp_prequantize: bool, |
| @@ -441,13 +474,17 @@ def _recipe_converters( | |||
| 441 | li_kernel_config: LightningIndexerKernelConfig | None = None, | 474 | li_kernel_config: LightningIndexerKernelConfig | None = None, |
| 442 | ) -> list[QuantizationConverter.Config]: | 475 | ) -> list[QuantizationConverter.Config]: |
| 443 | converters: list[QuantizationConverter.Config] | 476 | converters: list[QuantizationConverter.Config] |
| 444 | - dense_filter = _DSV4_CONFIG_FILTERS["dense"] | 477 | + try: |
| 478 | + filters = _CONFIG_FILTERS_BY_MODEL_TYPE[model_type] | ||
| 479 | + except KeyError as exc: | ||
| 480 | + raise ValueError(f"unsupported DeepSeek model type {model_type!r}; expected 'v4' or 'v41'") from exc | ||
| 481 | + dense_filter = filters["dense"] | ||
| 445 | 482 | ||
| 446 | if recipe == "all_mxfp8": | 483 | if recipe == "all_mxfp8": |
| 447 | converters = [ | 484 | converters = [ |
| 448 | _quantization_converter( | 485 | _quantization_converter( |
| 449 | _mxfp8_param_swap(), | 486 | _mxfp8_param_swap(), |
| 450 | - any_config_filter(dense_filter, _DSV4_CONFIG_FILTERS["routed_expert"]), | 487 | + any_config_filter(dense_filter, filters["routed_expert"]), |
| 451 | model_compile_enabled=model_compile_enabled, | 488 | model_compile_enabled=model_compile_enabled, |
| 452 | ) | 489 | ) |
| 453 | ] | 490 | ] |
| @@ -473,7 +510,7 @@ def _recipe_converters( | |||
| 473 | ), | 510 | ), |
| 474 | _quantization_converter( | 511 | _quantization_converter( |
| 475 | routed_config, | 512 | routed_config, |
| 476 | - _DSV4_CONFIG_FILTERS["routed_expert"], | 513 | + filters["routed_expert"], |
| 477 | model_compile_enabled=model_compile_enabled, | 514 | model_compile_enabled=model_compile_enabled, |
| 478 | ), | 515 | ), |
| 479 | ] | 516 | ] |
| @@ -487,19 +524,36 @@ def _recipe_converters( | |||
| 487 | converters.append( | 524 | converters.append( |
| 488 | _quantization_converter( | 525 | _quantization_converter( |
| 489 | li_config, | 526 | li_config, |
| 490 | - _DSV4_CONFIG_FILTERS["lightning_indexer"], | 527 | + filters["lightning_indexer"], |
| 491 | model_compile_enabled=model_compile_enabled, | 528 | model_compile_enabled=model_compile_enabled, |
| 492 | ) | 529 | ) |
| 493 | ) | 530 | ) |
| 494 | converters.append( | 531 | converters.append( |
| 495 | _quantization_converter( | 532 | _quantization_converter( |
| 496 | None, | 533 | None, |
| 497 | - _DSV4_CONFIG_FILTERS["lightning_indexer_metadata"], | 534 | + filters["lightning_indexer_metadata"], |
| 498 | model_compile_enabled=model_compile_enabled, | 535 | model_compile_enabled=model_compile_enabled, |
| 499 | replacement_config_type=_QuantizedLightningIndexerMetadataAdapter.Config, | 536 | replacement_config_type=_QuantizedLightningIndexerMetadataAdapter.Config, |
| 500 | replacement_kwargs={"quant_mode": li_config.quant_mode}, | 537 | replacement_kwargs={"quant_mode": li_config.quant_mode}, |
| 501 | ) | 538 | ) |
| 502 | ) | 539 | ) |
| 540 | + if enable_sparse_attention_quantization: | ||
| 541 | + if "sparse_attention" in filters: | ||
| 542 | + from torchao_npu.configs import QuantV41SparseAttentionConfig | ||
| 543 | + | ||
| 544 | + converters.append( | ||
| 545 | + _quantization_converter( | ||
| 546 | + QuantV41SparseAttentionConfig(), | ||
| 547 | + filters["sparse_attention"], | ||
| 548 | + model_compile_enabled=model_compile_enabled, | ||
| 549 | + ) | ||
| 550 | + ) | ||
| 551 | + else: | ||
| 552 | + logger.warning( | ||
| 553 | + "Sparse attention quantization is enabled, but model type %s has no " | ||
| 554 | + "sparse_attention filter; skipping the sparse attention replacement.", | ||
| 555 | + model_type, | ||
| 556 | + ) | ||
| 503 | return converters | 557 | return converters |
| 504 | 558 | ||
| 505 | 559 | ||
| @@ -546,11 +600,16 @@ def apply_quantization_converter( | |||
| 546 | return model_spec | 600 | return model_spec |
| 547 | quantization_config.validate() | 601 | quantization_config.validate() |
| 548 | 602 | ||
| 603 | + model_config = model_spec.model | ||
| 604 | + model_type = _model_type_for_spec(model_spec) | ||
| 605 | + | ||
| 549 | li_kernel_config = ( | 606 | li_kernel_config = ( |
| 550 | _get_li_kernel_config(model_spec.model) if quantization_config.li_quantization is not None else None | 607 | _get_li_kernel_config(model_spec.model) if quantization_config.li_quantization is not None else None |
| 551 | ) | 608 | ) |
| 552 | converters = _recipe_converters( | 609 | converters = _recipe_converters( |
| 553 | quantization_config.recipe, | 610 | quantization_config.recipe, |
| 611 | + model_type=model_type, | ||
| 612 | + enable_sparse_attention_quantization=quantization_config.enable_sparse_attention_quantization, | ||
| 554 | enable_mxfp4_qat=quantization_config.enable_mxfp4_qat, | 613 | enable_mxfp4_qat=quantization_config.enable_mxfp4_qat, |
| 555 | dst_type_max=quantization_config.dst_type_max, | 614 | dst_type_max=quantization_config.dst_type_max, |
| 556 | fsdp_prequantize=quantization_config.fsdp_prequantize, | 615 | fsdp_prequantize=quantization_config.fsdp_prequantize, |
| @@ -560,13 +619,14 @@ def apply_quantization_converter( | |||
| 560 | ) | 619 | ) |
| 561 | validate_converter_order(converters) | 620 | validate_converter_order(converters) |
| 562 | 621 | ||
| 563 | - model_config = model_spec.model | ||
| 564 | for converter_config in converters: | 622 | for converter_config in converters: |
| 565 | model_config = converter_config.build().convert(model_config) | 623 | model_config = converter_config.build().convert(model_config) |
| 566 | 624 | ||
| 567 | logger.info( | 625 | logger.info( |
| 568 | - "Applied TorchAO-NPU recipe=%s, mxfp4_qat=%s, li_quantization=%s, dst_type_max=%s, fsdp_prequantize=%s", | 626 | + "Applied TorchAO-NPU recipe=%s, sparse_attention_quantization=%s, mxfp4_qat=%s, " |
| 627 | + "li_quantization=%s, dst_type_max=%s, fsdp_prequantize=%s", | ||
| 569 | quantization_config.recipe, | 628 | quantization_config.recipe, |
| 629 | + quantization_config.enable_sparse_attention_quantization, | ||
| 570 | quantization_config.enable_mxfp4_qat, | 630 | quantization_config.enable_mxfp4_qat, |
| 571 | quantization_config.li_quantization, | 631 | quantization_config.li_quantization, |
| 572 | quantization_config.dst_type_max, | 632 | quantization_config.dst_type_max, |
| @@ -6,6 +6,7 @@ | |||
| 6 | """CPU coverage for converter selection and weight-wrapper dispatch to NPU ops.""" | 6 | """CPU coverage for converter selection and weight-wrapper dispatch to NPU ops.""" |
| 7 | 7 | ||
| 8 | import importlib | 8 | import importlib |
| 9 | +import logging | ||
| 9 | import sys | 10 | import sys |
| 10 | from dataclasses import dataclass | 11 | from dataclasses import dataclass |
| 11 | from types import ModuleType, SimpleNamespace | 12 | from types import ModuleType, SimpleNamespace |
| @@ -141,6 +142,106 @@ def test_quantization_converter_preserves_li_metadata_replacement(converter_modu | |||
| 141 | assert not quantization_calls | 142 | assert not quantization_calls |
| 142 | 143 | ||
| 143 | 144 | ||
| 145 | +@pytest.mark.parametrize( | ||
| 146 | + ("model_type", "expect_sparse_attention_converter"), | ||
| 147 | + [("v4", False), ("v41", True)], | ||
| 148 | +) | ||
| 149 | +def test_recipe_converters_select_filters_for_model_type( | ||
| 150 | + converter_module, model_type, expect_sparse_attention_converter | ||
| 151 | +): | ||
| 152 | + converters = converter_module._recipe_converters( | ||
| 153 | + "mix", | ||
| 154 | + model_type=model_type, | ||
| 155 | + enable_sparse_attention_quantization=True, | ||
| 156 | + enable_mxfp4_qat=False, | ||
| 157 | + dst_type_max=0.0, | ||
| 158 | + fsdp_prequantize=False, | ||
| 159 | + model_compile_enabled=False, | ||
| 160 | + ) | ||
| 161 | + | ||
| 162 | + sparse_attention_converters = [ | ||
| 163 | + converter | ||
| 164 | + for converter in converters | ||
| 165 | + if converter.filter_fn is converter_module._DSV41_CONFIG_FILTERS["sparse_attention"] | ||
| 166 | + ] | ||
| 167 | + assert bool(sparse_attention_converters) is expect_sparse_attention_converter | ||
| 168 | + | ||
| 169 | + | ||
| 170 | +def test_recipe_converters_warn_when_sparse_attention_filter_is_unavailable(converter_module, caplog): | ||
| 171 | + with caplog.at_level(logging.WARNING): | ||
| 172 | + converters = converter_module._recipe_converters( | ||
| 173 | + "mix", | ||
| 174 | + model_type="v4", | ||
| 175 | + enable_sparse_attention_quantization=True, | ||
| 176 | + enable_mxfp4_qat=False, | ||
| 177 | + dst_type_max=0.0, | ||
| 178 | + fsdp_prequantize=False, | ||
| 179 | + model_compile_enabled=False, | ||
| 180 | + ) | ||
| 181 | + | ||
| 182 | + assert "model type v4 has no sparse_attention filter" in caplog.text | ||
| 183 | + assert not any( | ||
| 184 | + converter.filter_fn is converter_module._DSV41_CONFIG_FILTERS["sparse_attention"] for converter in converters | ||
| 185 | + ) | ||
| 186 | + | ||
| 187 | + | ||
| 188 | +def test_model_type_rejects_unknown_model_spec_name(converter_module): | ||
| 189 | + with pytest.raises(ValueError, match=r"supports DeepSeek V4 and V4\.1 model specs"): | ||
| 190 | + converter_module._model_type_for_spec(SimpleNamespace(name="deepseek_v3", model=object())) | ||
| 191 | + | ||
| 192 | + | ||
| 193 | +def test_model_type_comes_from_model_spec_name(converter_module): | ||
| 194 | + assert converter_module._model_type_for_spec(SimpleNamespace(name="deepseek_v4", model=object())) == "v4" | ||
| 195 | + assert converter_module._model_type_for_spec(SimpleNamespace(name="deepseek_v4_1", model=object())) == "v41" | ||
| 196 | + | ||
| 197 | + | ||
| 198 | +def test_recipe_converters_reject_unknown_model_type(converter_module): | ||
| 199 | + with pytest.raises(ValueError, match="unsupported DeepSeek model type"): | ||
| 200 | + converter_module._recipe_converters( | ||
| 201 | + "mix", | ||
| 202 | + model_type="v3", # type: ignore[arg-type] | ||
| 203 | + enable_mxfp4_qat=False, | ||
| 204 | + dst_type_max=0.0, | ||
| 205 | + fsdp_prequantize=False, | ||
| 206 | + model_compile_enabled=False, | ||
| 207 | + ) | ||
| 208 | + | ||
| 209 | + | ||
| 210 | +@pytest.mark.parametrize( | ||
| 211 | + ("model_name", "expected_model_type"), | ||
| 212 | + [("deepseek_v4", "v4"), ("deepseek_v4_1", "v41")], | ||
| 213 | +) | ||
| 214 | +def test_apply_quantization_converter_passes_model_type(converter_module, monkeypatch, model_name, expected_model_type): | ||
| 215 | + @dataclass(frozen=True) | ||
| 216 | + class FakeModelSpec: | ||
| 217 | + name: str | ||
| 218 | + model: object | ||
| 219 | + | ||
| 220 | + quantization_config = SimpleNamespace( | ||
| 221 | + enable_quantized_training=True, | ||
| 222 | + enable_sparse_attention_quantization=False, | ||
| 223 | + recipe="mix", | ||
| 224 | + enable_mxfp4_qat=False, | ||
| 225 | + dst_type_max=0.0, | ||
| 226 | + fsdp_prequantize=False, | ||
| 227 | + li_quantization=None, | ||
| 228 | + validate=lambda: None, | ||
| 229 | + ) | ||
| 230 | + calls = [] | ||
| 231 | + monkeypatch.setattr(converter_module, "_recipe_converters", lambda *args, **kwargs: calls.append(kwargs) or []) | ||
| 232 | + monkeypatch.setattr(converter_module, "validate_converter_order", lambda converters: None) | ||
| 233 | + | ||
| 234 | + model_spec = FakeModelSpec(name=model_name, model=object()) | ||
| 235 | + converted = converter_module.apply_quantization_converter( | ||
| 236 | + model_spec, | ||
| 237 | + quantization_config, | ||
| 238 | + model_compile_enabled=False, | ||
| 239 | + ) | ||
| 240 | + | ||
| 241 | + assert converted is not model_spec | ||
| 242 | + assert calls[0]["model_type"] == expected_model_type | ||
| 243 | + | ||
| 244 | + | ||
| 144 | def test_parameter_quantization_skips_li_metadata(converter_module, quantization_calls): | 245 | def test_parameter_quantization_skips_li_metadata(converter_module, quantization_calls): |
| 145 | from interfaces.torchao_converter import _mxfp8_param_swap | 246 | from interfaces.torchao_converter import _mxfp8_param_swap |
| 146 | 247 | ||
| @@ -109,6 +109,7 @@ class QuantizationExtensionConfig: | |||
| 109 | """ | 109 | """ |
| 110 | 110 | ||
| 111 | enable_quantized_training: bool = False | 111 | enable_quantized_training: bool = False |
| 112 | + enable_sparse_attention_quantization: bool = False | ||
| 112 | recipe: QuantizationRecipe = "mix" | 113 | recipe: QuantizationRecipe = "mix" |
| 113 | enable_mxfp4_qat: bool = False | 114 | enable_mxfp4_qat: bool = False |
| 114 | li_quantization: LIQuantization | None = None | 115 | li_quantization: LIQuantization | None = None |


有必要新增这个脚本吗?直接用deepseek_v4_1_flash_8p_cpt_4k_a5.sh?或者加上qat参数后调deepseek_v4_1_flash_8p_cpt_4k_a5.sh?