Merged
feat: DeepSeek V4.1 main KV 的C4复用 #899
feat: DeepSeek V4.1 main KV 的C4复用 #899
Merged
wanghui0Add on Sep 22
Total: 14 files changed+480-140
@@ -0,0 +1,61 @@
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+import pytest
7+import torch
8+from torchao_npu.ops.kv_cache_fake_quant import fake_quantize_mx_bf16
9+ 
10+ 
11+@pytest.mark.parametrize("shape", [(2, 3, 32), (6, 1, 32)], ids=["compressor", "smla"])
12+def test_kv_fake_quantize_decodes_packed_cache_and_preserves_ste(monkeypatch, shape):
13+ x = torch.linspace(-1, 1, 192, dtype=torch.bfloat16).reshape(shape).requires_grad_()
14+ seen = []
15+ 
16+ def packed_fp4_encoder(cache, rows, slots, *, quant_group_size, quant_mode, round_scale):
17+ seen.append(rows.detach().clone())
18+ assert cache.dtype == torch.uint8
19+ assert cache.shape == (6, 32)
20+ assert torch.equal(slots, torch.arange(6, dtype=torch.int32))
21+ assert (quant_group_size, quant_mode, round_scale) == (16, "mxfp4_bf16", False)
22+ # E2M1 low-first pair [0.5, 1.0], with two distinct BF16 group scales.
23+ cache[:, :16] = 0x21
24+ cache[:, 16:20] = torch.tensor([[0.5, 2.0]], dtype=torch.bfloat16).view(torch.uint8)
25+ 
26+ monkeypatch.setattr(torch.ops.custom.kv_compress_epilog_v2, "default", packed_fp4_encoder)
27+ 
28+ result = fake_quantize_mx_bf16(x)
29+ 
30+ expected = torch.tensor([0.25, 0.5] * 8 + [1.0, 2.0] * 8, dtype=x.dtype).repeat(6).reshape(shape)
31+ assert len(seen) == 1
32+ assert torch.equal(seen[0], x.detach().reshape(6, 32))
33+ assert result.shape == x.shape
34+ assert result.dtype == x.dtype
35+ assert torch.equal(result, expected)
36+ grad = torch.linspace(-0.5, 0.5, x.numel(), dtype=x.dtype).reshape_as(x)
37+ result.backward(grad)
38+ assert torch.equal(x.grad, grad)
39+ 
40+ 
41+@pytest.mark.parametrize(
42+ ("quant_mode", "group_size"),
43+ [("mxfp4_bf16", 16), ("mxfp8_bf16", 32)],
44+ ids=["main-kv-fp4", "swa-fp8"],
45+)
46+def test_kv_fake_quantize_real_epilog_round_trip_and_backward(quant_mode, group_size):
47+ x = torch.tensor([0.5, 1.0, 2.0], device="npu", dtype=torch.bfloat16)[:, None].repeat(1, 512)
48+ x.requires_grad_()
49+ 
50+ result = fake_quantize_mx_bf16(x, quant_group_size=group_size, quant_mode=quant_mode)
51+ 
52+ # FP8 round_scale=False uses amax / 448 stored as BF16; FP4 powers of two
53+ # are exact. Account for BF16 rounding of FP8's stored group scale.
54+ expected = (
55+ x.detach() if quant_mode == "mxfp4_bf16" else (x.detach().float() / 448).bfloat16().float().mul(448).bfloat16()
56+ )
57+ assert result.dtype == x.dtype
58+ assert torch.equal(result, expected)
59+ upstream = torch.linspace(-1, 1, x.numel(), device=x.device, dtype=x.dtype).reshape_as(x)
60+ result.backward(upstream)
61+ assert torch.equal(x.grad, upstream)
@@ -0,0 +1,80 @@
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+import torch
7+from torchao.quantization.qat import QATStep
8+from torchao.quantization.quant_api import quantize_
9+from torchao_npu.configs import QuantCompressorConfig
10+ 
11+ 
12+class _CompressorHost(torch.nn.Module):
13+ """Small host with distinct latent/rotated outputs and a shared-KV branch."""
14+ 
15+ def __init__(self, is_source=True):
16+ super().__init__()
17+ self.is_source = is_source
18+ self.weight = torch.nn.Parameter(torch.tensor(2.0, dtype=torch.bfloat16))
19+ 
20+ def forward(self, x, positions, cmp_k=None):
21+ if not self.is_source:
22+ return cmp_k, None
23+ latent = x * self.weight
24+ return latent + positions.unsqueeze(-1), latent
25+ 
26+ 
27+def test_quant_compressor_preserves_latent_parameters_and_ste(monkeypatch):
28+ module = _CompressorHost()
29+ original_weight = module.weight
30+ original_keys = tuple(module.state_dict())
31+ original_forward = module.forward
32+ quantize_(module, QuantCompressorConfig(), filter_fn=lambda candidate, _: candidate is module)
33+ # Preparing twice must not wrap an already swapped forward recursively.
34+ quantize_(module, QuantCompressorConfig(), filter_fn=lambda candidate, _: candidate is module)
35+ captured = []
36+ 
37+ def encode(cache, rows, slots, **kwargs):
38+ captured.append(rows.clone())
39+ assert kwargs["quant_mode"] == "mxfp4_bf16"
40+ assert kwargs["quant_group_size"] == 16
41+ cache[:, :16] = 0x21
42+ cache[:, 16:20] = torch.tensor([[0.5, 2.0]], dtype=torch.bfloat16).view(torch.uint8)
43+ 
44+ monkeypatch.setattr(torch.ops.custom.kv_compress_epilog_v2, "default", encode)
45+ x = torch.linspace(0.125, 1, 64, dtype=torch.bfloat16).reshape(1, 2, 32).requires_grad_()
46+ positions = torch.tensor([[0, 2]], dtype=torch.bfloat16)
47+ 
48+ main_kv, latent = module(x, positions)
49+ 
50+ assert module.weight is original_weight
51+ assert tuple(module.state_dict()) == original_keys
52+ assert module._torchao_npu_original_forward == original_forward
53+ assert len(captured) == 1
54+ assert torch.equal(captured[0], (x.detach() * 2 + positions.unsqueeze(-1)).reshape(2, 32))
55+ assert torch.equal(latent, x.detach() * 2)
56+ expected = torch.tensor([0.25, 0.5] * 8 + [1.0, 2.0] * 8, dtype=x.dtype).repeat(2).reshape_as(x)
57+ assert main_kv.dtype == x.dtype
58+ assert torch.equal(main_kv, expected)
59+ (main_kv.float().sum() + 3 * latent.float().sum()).backward()
60+ assert torch.equal(x.grad, torch.full_like(x, 8))
61+ assert torch.equal(module.weight.grad, (x.detach() * 4).sum())
62+ 
63+ reuser = _CompressorHost(is_source=False)
64+ quantize_(reuser, QuantCompressorConfig(), filter_fn=lambda candidate, _: candidate is reuser)
65+ shared, shared_latent = reuser(x, positions, main_kv)
66+ assert shared is main_kv
67+ assert shared_latent is None
68+ assert len(captured) == 1
69+ 
70+ 
71+def test_quant_compressor_convert_restores_host_forward():
72+ module = _CompressorHost()
73+ quantize_(module, QuantCompressorConfig(), filter_fn=lambda candidate, _: candidate is module)
74+ quantize_(module, QuantCompressorConfig(step=QATStep.CONVERT), filter_fn=lambda candidate, _: candidate is module)
75+ x = torch.ones((1, 1, 32), dtype=torch.bfloat16)
76+ 
77+ main_kv, latent = module(x, torch.tensor([[3]], dtype=torch.bfloat16))
78+ 
79+ assert torch.equal(main_kv, x * 5)
80+ assert torch.equal(latent, x * 2)
@@ -10,19 +10,6 @@ import torch
10from torchao_npu.quantized_modules import v41_sparse_attention as sparse_attention10from torchao_npu.quantized_modules import v41_sparse_attention as sparse_attention
11 11 
12 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- 
26def test_localize_indices_preserves_document_local_entries():13def test_localize_indices_preserves_document_local_entries():
27 """Global top-k coordinates outside a query document are invalidated."""14 """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)15 topk_indices = torch.tensor([[0, 1, 3], [1, 2, 3], [2, 4, 5]], dtype=torch.int64)
@@ -31,7 +18,7 @@ def test_localize_indices_preserves_document_local_entries():
31 18 
32 localized = sparse_attention._localize_indices(topk_indices, doc_ids, cu_cmp)19 localized = sparse_attention._localize_indices(topk_indices, doc_ids, cu_cmp)
33 20 
34- expected = torch.tensor([[0, 1, -1], [1, -1, -1], [0, 2, 3]], dtype=torch.int64)21+ expected = torch.tensor([[0, 1, -1], [1, -1, -1], [0, 2, -1]], dtype=torch.int64)
35 assert torch.equal(localized, expected)22 assert torch.equal(localized, expected)
36 23 
37 24 
@@ -61,11 +48,11 @@ def _fake_mla_apply(captured):
61 [(0, False, 0), (1, True, 4), (2, True, 2)],48 [(0, False, 0), (1, True, 4), (2, True, 2)],
62 ids=["window-only", "full-resolution-shared-kv", "compressed-shared-kv"],49 ids=["window-only", "full-resolution-shared-kv", "compressed-shared-kv"],
63)50)
64-def test_sparse_mla_forward_backward_uses_quantized_forward_and_original_backward(51+def test_sparse_mla_quantizes_only_swa_and_preserves_main_kv_in_both_passes(
65 monkeypatch, ratio, with_shared, cmp_tokens52 monkeypatch, ratio, with_shared, cmp_tokens
66):53):
67 """Exercise the custom autograd function around mocked NPU kernel boundaries."""54 """Exercise the custom autograd function around mocked NPU kernel boundaries."""
68- device = "npu"55+ device = "cpu"
69 q = torch.ones((4, 2, 4), device=device, dtype=torch.bfloat16, requires_grad=True)56 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)57 swa_k = torch.ones((4, 1, 4), device=device, dtype=torch.bfloat16, requires_grad=True)
71 cmp_k = (58 cmp_k = (
@@ -100,7 +87,9 @@ def test_sparse_mla_forward_backward_uses_quantized_forward_and_original_backwar
100 assert output.shape == q.shape87 assert output.shape == q.shape
101 assert saved_lse is lse88 assert saved_lse is lse
102 torch.testing.assert_close(grad_output, torch.ones_like(q))89 torch.testing.assert_close(grad_output, torch.ones_like(q))
103- assert kwargs["ori_kv"] is swa_k90+ assert kwargs["ori_kv"] is forward_kwargs["ori_kv"]
91+ assert kwargs["ori_kv"] is not swa_k
92+ torch.testing.assert_close(kwargs["ori_kv"], torch.full_like(swa_k, 2))
104 assert kwargs["cmp_kv"] is cmp_k93 assert kwargs["cmp_kv"] is cmp_k
105 assert kwargs["cmp_sparse_indices"] is indices94 assert kwargs["cmp_sparse_indices"] is indices
106 assert kwargs["sinks"] is sinks95 assert kwargs["sinks"] is sinks
@@ -119,7 +108,7 @@ def test_sparse_mla_forward_backward_uses_quantized_forward_and_original_backwar
119 108 
120 monkeypatch.setattr(sparse_attention, "sparse_flash_mla_metadata", metadata)109 monkeypatch.setattr(sparse_attention, "sparse_flash_mla_metadata", metadata)
121 monkeypatch.setattr(sparse_attention, "sparse_flash_mla_grad_metadata", metadata)110 monkeypatch.setattr(sparse_attention, "sparse_flash_mla_grad_metadata", metadata)
122- monkeypatch.setattr(sparse_attention, "_fake_quantize_kv", fake_quantize)111+ monkeypatch.setattr(sparse_attention, "fake_quantize_mx_bf16", fake_quantize)
123 monkeypatch.setattr(torch.ops.cann_ops_transformer, "sparse_flash_mla", sparse_flash_mla)112 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)113 monkeypatch.setattr(torch.ops.cann_ops_transformer, "sparse_flash_mla_grad", sparse_flash_mla_grad)
125 114 
@@ -139,15 +128,11 @@ def test_sparse_mla_forward_backward_uses_quantized_forward_and_original_backwar
139 128 
140 assert returned_lse is lse129 assert returned_lse is lse
141 assert not returned_lse.requires_grad130 assert not returned_lse.requires_grad
142- assert len(quantize_calls) == (2 if with_shared else 1)131+ assert len(quantize_calls) == 1
132+ assert quantize_calls[0][0] is swa_k
143 assert quantize_calls[0][1:] == (32, "mxfp8_bf16")133 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)134 torch.testing.assert_close(forward_kwargs["ori_kv"], swa_k + 1)
147- if with_shared:135+ assert forward_kwargs["cmp_kv"] is cmp_k
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_metadata136 assert forward_kwargs["metadata"] is forward_metadata
152 assert forward_kwargs["cmp_sparse_indices"] is indices137 assert forward_kwargs["cmp_sparse_indices"] is indices
153 assert forward_kwargs["sinks"] is sinks138 assert forward_kwargs["sinks"] is sinks
@@ -6,6 +6,7 @@
6from torchao_npu.configs import (6from torchao_npu.configs import (
7 ModuleSwapConfig,7 ModuleSwapConfig,
8 ParamSwapConfig,8 ParamSwapConfig,
9+ QuantCompressorConfig,
9 QuantLightningIndexerConfig,10 QuantLightningIndexerConfig,
10 QuantV41SparseAttentionConfig,11 QuantV41SparseAttentionConfig,
11)12)
@@ -13,6 +14,7 @@ from torchao_npu.configs import (
13__all__ = [14__all__ = [
14 "ModuleSwapConfig",15 "ModuleSwapConfig",
15 "ParamSwapConfig",16 "ParamSwapConfig",
17+ "QuantCompressorConfig",
16 "QuantLightningIndexerConfig",18 "QuantLightningIndexerConfig",
17 "QuantV41SparseAttentionConfig",19 "QuantV41SparseAttentionConfig",
18]20]
@@ -7,6 +7,7 @@
7 7 
8from torchao_npu.configs.module_swap import ModuleSwapConfig8from 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 QuantLightningIndexerConfig,11 QuantLightningIndexerConfig,
11 QuantV41SparseAttentionConfig,12 QuantV41SparseAttentionConfig,
12 quant_mode_for_config,13 quant_mode_for_config,
@@ -16,6 +17,7 @@ from torchao_npu.configs.param_swap import ParamSwapConfig
16__all__ = [17__all__ = [
17 "ModuleSwapConfig",18 "ModuleSwapConfig",
18 "ParamSwapConfig",19 "ParamSwapConfig",
20+ "QuantCompressorConfig",
19 "QuantLightningIndexerConfig",21 "QuantLightningIndexerConfig",
20 "QuantV41SparseAttentionConfig",22 "QuantV41SparseAttentionConfig",
21 "quant_mode_for_config",23 "quant_mode_for_config",
@@ -5,8 +5,14 @@
5 5 
6"""Concrete module-swap quantization configs."""6"""Concrete module-swap quantization configs."""
7 7 
8-__all__ = ["QuantLightningIndexerConfig", "QuantV41SparseAttentionConfig", "quant_mode_for_config"]8+__all__ = [
9+ "QuantCompressorConfig",
10+ "QuantLightningIndexerConfig",
11+ "QuantV41SparseAttentionConfig",
12+ "quant_mode_for_config",
13+]
9 14 
15+from torchao_npu.configs.module_swap_configs.quant_compressor import QuantCompressorConfig
10from torchao_npu.configs.module_swap_configs.quant_lightning_indexer import (16from torchao_npu.configs.module_swap_configs.quant_lightning_indexer import (
11 QuantLightningIndexerConfig,17 QuantLightningIndexerConfig,
12 quant_mode_for_config,18 quant_mode_for_config,
@@ -0,0 +1,40 @@
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 main-KV FP4 fake quantization."""
7+ 
8+from dataclasses import dataclass
9+from types import MethodType
10+ 
11+from torchao.quantization.qat import QATStep
12+from torchao.quantization.transform_module import register_quantize_module_handler
13+ 
14+from torchao_npu.configs.module_swap import ModuleSwapConfig
15+ 
16+ 
17+@dataclass(kw_only=True, slots=True)
18+class QuantCompressorConfig(ModuleSwapConfig):
19+ """Quantize post-RoPE main KV as MXFP4 with BF16 group scales."""
20+ 
21+ group_size: int = 16
22+ 
23+ def __post_init__(self) -> None:
24+ ModuleSwapConfig.__post_init__(self)
25+ if self.group_size not in (16, 32):
26+ raise ValueError("QuantCompressorConfig requires group_size=16 or 32")
27+ 
28+ 
29+@register_quantize_module_handler(QuantCompressorConfig)
30+def _quant_compressor_transform(module, config: QuantCompressorConfig):
31+ from torchao_npu.quantized_modules.compressor import QuantCompressor
32+ 
33+ if not hasattr(module, "_torchao_npu_original_forward"):
34+ module._torchao_npu_original_forward = module.forward
35+ if config.step == QATStep.PREPARE:
36+ module._torchao_npu_module_swap_config = config
37+ module.forward = MethodType(QuantCompressor.forward, module)
38+ else:
39+ module.forward = module._torchao_npu_original_forward
40+ return module
@@ -18,7 +18,7 @@ from torchao_npu.configs.module_swap import ModuleSwapConfig
18 18 
19@dataclass(kw_only=True, slots=True)19@dataclass(kw_only=True, slots=True)
20class QuantV41SparseAttentionConfig(ModuleSwapConfig):20class QuantV41SparseAttentionConfig(ModuleSwapConfig):
21- """Install mixed quant sparse attention with FP8 SWA_KV / FP4 CMP_KV and BF16 scales."""21+ """Install FP8 SWA fake quantization; main KV is supplied by QuantCompressor."""
22 22 
23 23 
24@register_quantize_module_handler(QuantV41SparseAttentionConfig)24@register_quantize_module_handler(QuantV41SparseAttentionConfig)
@@ -0,0 +1,55 @@
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+"""KV cache fake quantization with BF16 group scales."""
7+ 
8+import custom_ops # noqa: F401 # pyrefly: ignore[missing-import]
9+import torch
10+ 
11+from torchao_npu.quantization.quant_primitives.mx_bf16 import dequantize_mx_bf16, kv_cache_layout
12+ 
13+ 
14+class _MXBF16FakeQuantize(torch.autograd.Function):
15+ @staticmethod
16+ def forward(ctx, kv, quant_group_size, quant_mode): # pyrefly: ignore [bad-override]
17+ if kv.dtype != torch.bfloat16 or kv.ndim < 2:
18+ raise ValueError("KV cache quantization requires BF16 input with shape [..., head_dim]")
19+ head_dim = kv.shape[-1]
20+ _, _, _, cache_width = kv_cache_layout(head_dim, quant_mode, quant_group_size)
21+ rows = kv.reshape(-1, head_dim).contiguous()
22+ cache_dtype = torch.float8_e4m3fn if quant_mode == "mxfp8_bf16" else torch.uint8
23+ cache = torch.zeros((rows.shape[0], cache_width), dtype=cache_dtype, device=kv.device)
24+ slots = torch.arange(rows.shape[0], dtype=torch.int32, device=kv.device)
25+ torch.ops.custom.kv_compress_epilog_v2.default( # pyrefly: ignore [missing-attribute]
26+ cache,
27+ rows,
28+ slots,
29+ quant_group_size=quant_group_size,
30+ quant_mode=quant_mode,
31+ round_scale=False,
32+ )
33+ return dequantize_mx_bf16(
34+ cache,
35+ d=head_dim,
36+ quant_mode=quant_mode,
37+ group_size=quant_group_size,
38+ output_dtype=kv.dtype,
39+ ).reshape_as(kv)
40+ 
41+ @staticmethod
42+ def backward(ctx, grad_output): # pyrefly: ignore [bad-override]
43+ return grad_output, None, None
44+ 
45+ 
46+def fake_quantize_mx_bf16(
47+ kv: torch.Tensor,
48+ *,
49+ quant_group_size: int = 16,
50+ quant_mode: str = "mxfp4_bf16",
51+) -> torch.Tensor:
52+ """Quantize/dequantize KV, preserving its shape/dtype with an identity STE."""
53+ if quant_mode not in ("mxfp4_bf16", "mxfp8_bf16"):
54+ raise ValueError(f"unsupported KV quantization mode: {quant_mode}")
55+ return _MXBF16FakeQuantize.apply(kv, quant_group_size, quant_mode)
@@ -0,0 +1,30 @@
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+"""Post-RoPE main-KV fake quantization for source compressors."""
7+ 
8+from collections.abc import Callable
9+ 
10+import torch
11+ 
12+from torchao_npu.configs.module_swap_configs.quant_compressor import QuantCompressorConfig
13+from torchao_npu.ops.kv_cache_fake_quant import fake_quantize_mx_bf16
14+ 
15+ 
16+class QuantCompressor(torch.nn.Module):
17+ """Forward behavior installed on the original Compressor instance."""
18+ 
19+ _torchao_npu_original_forward: Callable[..., tuple[torch.Tensor | None, torch.Tensor | None]]
20+ _torchao_npu_module_swap_config: QuantCompressorConfig
21+ 
22+ def forward(self, x_BLD, positions_BL, cmp_k=None):
23+ main_kv, latent = self._torchao_npu_original_forward(x_BLD, positions_BL, cmp_k)
24+ # Reusing layers must return the same shared tensor without another Q/DQ.
25+ if not self.is_source:
26+ return main_kv, latent
27+ if main_kv is None:
28+ raise RuntimeError("A source compressor must return main KV")
29+ config = self._torchao_npu_module_swap_config
30+ return fake_quantize_mx_bf16(main_kv, quant_group_size=config.group_size), latent
@@ -2,24 +2,21 @@
2#2#
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-"""V4.1 sparse attention using the mixed-quantization MLA kernel.5+"""V4.1 sparse attention with FP8 SWA fake quantization.
6 6 
7-The host retains validation and distillation wiring. This module packs both7+Main KV arrives already fake-quantized by the source Compressor and is shared
8-KV streams with ``kv_compress_epilog`` and feeds the resulting byte cache to8+by all consuming layers. Forward and backward use the same fake-quantized
9-``mixed_quant_sparse_flash_mla``. The mixed kernel currently has no backward9+main KV and SWA values. SWA gradients pass directly to the original input
10-operator, so backward uses original BF16 KV with the quantized output/LSE.10+with an identity STE.
11-This is an approximate gradient, not an exact derivative of the quantized
12-forward or a dequantized-KV STE.
13"""11"""
14 12 
15__all__ = ["QuantV41SparseAttention"]13__all__ = ["QuantV41SparseAttention"]
16 14 
17-import custom_ops # noqa: F401 # pyrefly: ignore[missing-import]
18import torch15import torch
19import torch_npu16import torch_npu
20from cann_ops_transformer import sparse_flash_mla_grad_metadata, sparse_flash_mla_metadata17from cann_ops_transformer import sparse_flash_mla_grad_metadata, sparse_flash_mla_metadata
21 18 
22-from torchao_npu.quantization.quant_primitives.mx_bf16 import dequantize_mx_bf1619+from torchao_npu.ops.kv_cache_fake_quant import fake_quantize_mx_bf16
23 20 
24try:21try:
25 _IS_A5 = torch_npu.npu.get_device_name().startswith("Ascend950")22 _IS_A5 = torch_npu.npu.get_device_name().startswith("Ascend950")
@@ -27,76 +24,22 @@ except (AttributeError, TypeError):
27 _IS_A5 = False24 _IS_A5 = False
28 25 
29 26 
30-def _kernel_options(cu_q, cu_cmp, remainder, ratio, window):27+def _kernel_options(cu_seqlens_q, cu_seqlens_cmp_kv, cmp_residual_kv, ratio, window_size):
31 return dict(28 return dict(
32- cu_seqlens_q=cu_q,29+ cu_seqlens_q=cu_seqlens_q,
33- cu_seqlens_ori_kv=cu_q,30+ cu_seqlens_ori_kv=cu_seqlens_q,
34- cu_seqlens_cmp_kv=cu_cmp,31+ cu_seqlens_cmp_kv=cu_seqlens_cmp_kv,
35- cmp_residual_kv=remainder,32+ cmp_residual_kv=cmp_residual_kv,
36 cmp_ratio=max(ratio, 1),33 cmp_ratio=max(ratio, 1),
37 ori_mask_mode=4,34 ori_mask_mode=4,
38- cmp_mask_mode=0 if _IS_A5 and cu_cmp is None else 3,35+ cmp_mask_mode=0 if _IS_A5 and cu_seqlens_cmp_kv is None else 3,
39- ori_win_left=window - 1,36+ ori_win_left=window_size - 1,
40 ori_win_right=0,37 ori_win_right=0,
41 layout_q="TND",38 layout_q="TND",
42 layout_kv="TND",39 layout_kv="TND",
43 )40 )
44 41 
45 42 
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:
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- 
100class _SparseMLA(torch.autograd.Function):43class _SparseMLA(torch.autograd.Function):
101 @staticmethod44 @staticmethod
102 def forward( # pyrefly: ignore [bad-override]45 def forward( # pyrefly: ignore [bad-override]
@@ -104,21 +47,21 @@ class _SparseMLA(torch.autograd.Function):
104 q,47 q,
105 swa_k,48 swa_k,
106 cmp_k,49 cmp_k,
107- indices,50+ cmp_sparse_indices,
108 sinks,51 sinks,
109- cu_q,52+ cu_seqlens_q,
110- cu_cmp,53+ cu_seqlens_cmp_kv,
111 cmp_residual_kv,54 cmp_residual_kv,
112 softmax_scale,55 softmax_scale,
113 ratio,56 ratio,
114 window_size,57 window_size,
115 ):58 ):
116- options = _kernel_options(cu_q, cu_cmp, cmp_residual_kv, ratio, window_size)59+ options = _kernel_options(cu_seqlens_q, cu_seqlens_cmp_kv, cmp_residual_kv, ratio, window_size)
117 # K can differ between the candidate and indexer paths. Use the actual60 # K can differ between the candidate and indexer paths. Use the actual
118 # supplied shape rather than assuming the LI configuration's top-k.61 # supplied shape rather than assuming the LI configuration's top-k.
119 geometry = dict(62 geometry = dict(
120 ori_topk=0,63 ori_topk=0,
121- cmp_topk=0 if indices is None else indices.shape[-1],64+ cmp_topk=0 if cmp_sparse_indices is None else cmp_sparse_indices.shape[-1],
122 has_ori_kv=True,65 has_ori_kv=True,
123 has_cmp_kv=cmp_k is not None,66 has_cmp_kv=cmp_k is not None,
124 )67 )
@@ -133,14 +76,13 @@ class _SparseMLA(torch.autograd.Function):
133 )76 )
134 smla_grad_metadata = sparse_flash_mla_grad_metadata(q.shape[1], 1, q.shape[2], **options, **geometry)77 smla_grad_metadata = sparse_flash_mla_grad_metadata(q.shape[1], 1, q.shape[2], **options, **geometry)
135 78 
136- qdq_swa_k = _fake_quantize_kv(swa_k, quant_group_size=32, quant_mode="mxfp8_bf16")79+ qdq_swa_k = fake_quantize_mx_bf16(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 80 
139 output, lse = torch.ops.cann_ops_transformer.sparse_flash_mla(81 output, lse = torch.ops.cann_ops_transformer.sparse_flash_mla(
140 q,82 q,
141 ori_kv=qdq_swa_k,83 ori_kv=qdq_swa_k,
142- cmp_kv=qdq_cmp_k,84+ cmp_kv=cmp_k,
143- cmp_sparse_indices=indices,85+ cmp_sparse_indices=cmp_sparse_indices,
144 ori_block_table=None,86 ori_block_table=None,
145 cmp_block_table=None,87 cmp_block_table=None,
146 sinks=sinks,88 sinks=sinks,
@@ -152,12 +94,12 @@ class _SparseMLA(torch.autograd.Function):
152 94 
153 ctx.save_for_backward(95 ctx.save_for_backward(
154 q,96 q,
155- swa_k,97+ qdq_swa_k,
156 cmp_k,98 cmp_k,
157- indices,99+ cmp_sparse_indices,
158 sinks,100 sinks,
159- cu_q,101+ cu_seqlens_q,
160- cu_cmp,102+ cu_seqlens_cmp_kv,
161 cmp_residual_kv,103 cmp_residual_kv,
162 output,104 output,
163 lse,105 lse,
@@ -173,36 +115,51 @@ class _SparseMLA(torch.autograd.Function):
173 del grad_lse # the LSE is a teacher signal, never a loss input115 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 see116 # A single read of the saved tensors: eager AC recomputation must see
175 # the same native metadata the forward produced.117 # 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_tensors118+ (
177- dq, dswa_k, dcmp_k, dsink, _, _ = torch.ops.cann_ops_transformer.sparse_flash_mla_grad(119+ q,
120+ qdq_swa_k,
121+ cmp_k,
122+ cmp_sparse_indices,
123+ sinks,
124+ cu_seqlens_q,
125+ cu_seqlens_cmp_kv,
126+ cmp_residual_kv,
127+ output,
128+ lse,
129+ smla_grad_metadata,
130+ ) = ctx.saved_tensors
131+ dq, dswa_k, dcmp_k, dsinks, _, _ = torch.ops.cann_ops_transformer.sparse_flash_mla_grad(
178 q,132 q,
179 grad_output.contiguous(),133 grad_output.contiguous(),
180 output,134 output,
181 lse,135 lse,
182- ori_kv=swa_k,136+ ori_kv=qdq_swa_k,
183 cmp_kv=cmp_k,137 cmp_kv=cmp_k,
184 ori_sparse_indices=None,138 ori_sparse_indices=None,
185- cmp_sparse_indices=indices,139+ cmp_sparse_indices=cmp_sparse_indices,
186- sinks=sink,140+ sinks=sinks,
187- metadata=metadata,141+ metadata=smla_grad_metadata,
188 seqused_q=None,142 seqused_q=None,
189 seqused_ori_kv=None,143 seqused_ori_kv=None,
190 seqused_cmp_kv=None,144 seqused_cmp_kv=None,
191 ori_topk_length=None,145 ori_topk_length=None,
192 cmp_topk_length=None,146 cmp_topk_length=None,
193 softmax_scale=ctx.softmax_scale,147 softmax_scale=ctx.softmax_scale,
194- **_kernel_options(cu_q, cu_cmp, cmp_residual_kv, ctx.ratio, ctx.window_size),148+ **_kernel_options(cu_seqlens_q, cu_seqlens_cmp_kv, cmp_residual_kv, ctx.ratio, ctx.window_size),
195 )149 )
196- return dq, dswa_k, dcmp_k if cmp_k is not None else None, None, dsink, None, None, None, None, None, None150+ # SWA Q/DQ runs inside this custom forward; apply its identity STE here.
151+ return dq, dswa_k, dcmp_k if cmp_k is not None else None, None, dsinks, None, None, None, None, None, None
197 152 
198 153 
199-def _localize_indices(topk_indices: torch.Tensor, doc_ids_BL: torch.Tensor, cu_cmp: torch.Tensor) -> torch.Tensor:154+def _localize_indices(
155+ topk_indices: torch.Tensor, doc_ids_BL: torch.Tensor, cu_seqlens_cmp_kv: torch.Tensor
156+) -> torch.Tensor:
200 """Global compressed-pool coordinates into the query's own document-local grid.157 """Global compressed-pool coordinates into the query's own document-local grid.
201 158 
202 Entries outside the query's document become ``-1``; the caller compacts them.159 Entries outside the query's document become ``-1``; the caller compacts them.
203 The shared ``topk_indices``/``topk_scores`` are never modified in place.160 The shared ``topk_indices``/``topk_scores`` are never modified in place.
204 """161 """
205- starts = cu_cmp.to(dtype=torch.long, device=topk_indices.device)162+ starts = cu_seqlens_cmp_kv.to(dtype=torch.long, device=topk_indices.device)
206 doc_ids = doc_ids_BL.reshape(-1)163 doc_ids = doc_ids_BL.reshape(-1)
207 doc_start = starts[doc_ids].unsqueeze(-1)164 doc_start = starts[doc_ids].unsqueeze(-1)
208 doc_end = starts[doc_ids + 1].unsqueeze(-1)165 doc_end = starts[doc_ids + 1].unsqueeze(-1)
@@ -247,10 +204,10 @@ class QuantV41SparseAttention(torch.nn.Module):
247 raise ValueError("V4.1 SMLA requires per-head attention sinks")204 raise ValueError("V4.1 SMLA requires per-head attention sinks")
248 if q.dtype != torch.bfloat16 or swa_k.dtype != q.dtype:205 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")206 raise ValueError("V4.1 SMLA requires BF16 Q/KV; no implicit precision conversion")
250- cu_q = metadata.cu_seq_q207+ cu_seqlens_q = metadata.cu_seq_q
251- if cu_q is None:208+ if cu_seqlens_q is None:
252 raise ValueError("V4.1 SMLA requires the packed document boundaries (cu_seq_q metadata)")209 raise ValueError("V4.1 SMLA requires the packed document boundaries (cu_seq_q metadata)")
253- shared = cu_cmp = remainder = indices = None210+ cmp_k_tnd = cu_seqlens_cmp_kv = cmp_residual_kv = cmp_sparse_indices = None
254 if ratio == 0:211 if ratio == 0:
255 if cmp_k is not None:212 if cmp_k is not None:
256 raise ValueError("window-only ratio 0 must not receive a second KV stream")213 raise ValueError("window-only ratio 0 must not receive a second KV stream")
@@ -268,27 +225,27 @@ class QuantV41SparseAttention(torch.nn.Module):
268 if ratio == 1 and cmp_k.shape != swa_k.shape:225 if ratio == 1 and cmp_k.shape != swa_k.shape:
269 raise ValueError("ratio 1 requires full-resolution shared KV")226 raise ValueError("ratio 1 requires full-resolution shared KV")
270 # Per-document alignment makes every document's compressed length227 # Per-document alignment makes every document's compressed length
271- # exactly cu_q // ratio, with no residual groups to carry.228+ # exactly cu_seqlens_q // ratio, with no residual groups to carry.
272- cu_cmp = cu_q // ratio229+ cu_seqlens_cmp_kv = cu_seqlens_q // ratio
273- remainder = torch.zeros_like(cu_cmp[1:]) if ratio > 1 else None230+ cmp_residual_kv = torch.zeros_like(cu_seqlens_cmp_kv[1:]) if ratio > 1 else None
274- shared = cmp_k.flatten(0, 1)231+ cmp_k_tnd = cmp_k.flatten(0, 1)
275- # TND kernels consume document-local indices; cu_cmp supplies the232+ # TND kernels consume document-local indices; cu_seqlens_cmp_kv supplies the
276 # document offsets. Preserve the reference cross-document mask.233 # document offsets. Preserve the reference cross-document mask.
277- local = _localize_indices(topk_indices, metadata.doc_ids_BL, cu_cmp)234+ local = _localize_indices(topk_indices, metadata.doc_ids_BL, cu_seqlens_cmp_kv)
278 # Packed documents can leave leading/interleaved invalid slots;235 # Packed documents can leave leading/interleaved invalid slots;
279 # compact them without changing the selected keys or their order.236 # compact them without changing the selected keys or their order.
280 order = (local < 0).to(torch.int32).argsort(dim=-1, stable=True)237 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()238+ cmp_sparse_indices = local.gather(-1, order).flatten(0, 1).to(torch.int32).unsqueeze(1).contiguous()
282- shared = shared.unsqueeze(1).contiguous()239+ cmp_k_tnd = cmp_k_tnd.unsqueeze(1).contiguous()
283 output, lse = _SparseMLA.apply(240 output, lse = _SparseMLA.apply(
284 q.flatten(0, 1).contiguous(),241 q.flatten(0, 1).contiguous(),
285 swa_k.flatten(0, 1).unsqueeze(1).contiguous(),242 swa_k.flatten(0, 1).unsqueeze(1).contiguous(),
286- shared,243+ cmp_k_tnd,
287- indices,244+ cmp_sparse_indices,
288 attn_sink.float(),245 attn_sink.float(),
289- cu_q,246+ cu_seqlens_q,
290- cu_cmp,247+ cu_seqlens_cmp_kv,
291- remainder,248+ cmp_residual_kv,
292 self.softmax_scale,249 self.softmax_scale,
293 ratio,250 ratio,
294 self.window_size,251 self.window_size,
@@ -47,6 +47,7 @@ from torchtitan_npu.models.common.metadata_extension import (
47)47)
48from torchtitan_npu.models.deepseek_v4.compressor import LightningIndexer48from torchtitan_npu.models.deepseek_v4.compressor import LightningIndexer
49from torchtitan_npu.models.deepseek_v4_1.attention import CompressedSparseInnerAttention249from torchtitan_npu.models.deepseek_v4_1.attention import CompressedSparseInnerAttention2
50+from torchtitan_npu.models.deepseek_v4_1.compressor import Compressor as V41Compressor
50from torchtitan_npu.override.common.swiglu_group.ascendc import AscGroupedExperts, _ensure_cann_ops_loaded51from torchtitan_npu.override.common.swiglu_group.ascendc import AscGroupedExperts, _ensure_cann_ops_loaded
51from torchtitan_npu.patches.torchtitan.models.common.linear import BatchedLinear52from torchtitan_npu.patches.torchtitan.models.common.linear import BatchedLinear
52 53 
@@ -112,11 +113,12 @@ _DEFAULT_TARGET_CONFIG_TYPES = (
112 LightningIndexer.Config,113 LightningIndexer.Config,
113 LightningIndexerMetadata.Config,114 LightningIndexerMetadata.Config,
114 CompressedSparseInnerAttention2.Config,115 CompressedSparseInnerAttention2.Config,
116+ V41Compressor.Config,
115)117)
116 118 
117 119 
118def _get_npu_quantized_module_cls(parent_cls: type[Module]) -> type[Module]:120def _get_npu_quantized_module_cls(parent_cls: type[Module]) -> type[Module]:
119- """Create a parameter-quantized subclass while preserving host behavior.121+ """Create a quantized subclass while preserving host behavior.
120 122 
121 The generated class inherits the concrete config owner so custom forward123 The generated class inherits the concrete config owner so custom forward
122 methods and config fields remain intact. Standard GroupedExperts and124 methods and config fields remain intact. Standard GroupedExperts and
@@ -131,7 +133,7 @@ def _get_npu_quantized_module_cls(parent_cls: type[Module]) -> type[Module]:
131 class NpuQuantizedModule(parent_cls): # type: ignore[valid-type, misc]133 class NpuQuantizedModule(parent_cls): # type: ignore[valid-type, misc]
132 @dataclass(kw_only=True, slots=True)134 @dataclass(kw_only=True, slots=True)
133 class Config(parent_config_cls): # type: ignore[misc, valid-type]135 class Config(parent_config_cls): # type: ignore[misc, valid-type]
134- # ParamSwapConfig contains Python objects and is supplied by the136+ # TorchAO configs contain Python objects and are supplied by the
135 # recipe, not by Tyro CLI parsing or config serialization.137 # recipe, not by Tyro CLI parsing or config serialization.
136 _torchao_npu_config: Annotated[AOBaseConfig | None, tyro.conf.Suppress] = None138 _torchao_npu_config: Annotated[AOBaseConfig | None, tyro.conf.Suppress] = None
137 139 
@@ -271,11 +273,19 @@ _DSV4_CONFIG_FILTERS = {
271 "lightning_indexer_metadata": match_config_fqn_suffix(".lightning_indexer_metadata"),273 "lightning_indexer_metadata": match_config_fqn_suffix(".lightning_indexer_metadata"),
272}274}
273 275 
276+_v41_compressor_fqn_filter = match_config_fqn_suffix(".attention.compressor")
277+ 
278+ 
279+def _is_v41_kv_source(config: Module.Config, fqn: str) -> bool:
280+ return _v41_compressor_fqn_filter(config, fqn) and isinstance(config, V41Compressor.Config) and config.is_source
281+ 
282+ 
274_DSV41_CONFIG_FILTERS = {283_DSV41_CONFIG_FILTERS = {
275 # V4.1 keeps the V4 attention and MoE config-tree suffixes for the dense284 # 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.285+ # parameter quantizers and adds Compressor/sparse-attention module swaps.
277 "dense": _DSV4_CONFIG_FILTERS["dense"],286 "dense": _DSV4_CONFIG_FILTERS["dense"],
278 "routed_expert": _DSV4_CONFIG_FILTERS["routed_expert"],287 "routed_expert": _DSV4_CONFIG_FILTERS["routed_expert"],
288+ "compressor": _is_v41_kv_source,
279 "sparse_attention": match_config_fqn_suffix(".attention.inner_attention"),289 "sparse_attention": match_config_fqn_suffix(".attention.inner_attention"),
280}290}
281 291 
@@ -539,8 +549,15 @@ def _recipe_converters(
539 )549 )
540 if enable_sparse_attention_quantization:550 if enable_sparse_attention_quantization:
541 if "sparse_attention" in filters:551 if "sparse_attention" in filters:
542- from torchao_npu.configs import QuantV41SparseAttentionConfig552+ from torchao_npu.configs import QuantCompressorConfig, QuantV41SparseAttentionConfig
543 553 
554+ converters.append(
555+ _quantization_converter(
556+ QuantCompressorConfig(),
557+ filters["compressor"],
558+ model_compile_enabled=model_compile_enabled,
559+ )
560+ )
544 converters.append(561 converters.append(
545 _quantization_converter(562 _quantization_converter(
546 QuantV41SparseAttentionConfig(),563 QuantV41SparseAttentionConfig(),
@@ -318,3 +318,107 @@ def test_quantized_experts_preserve_wrappers_through_forward(monkeypatch, conver
318 torch.testing.assert_close(weight, scores)318 torch.testing.assert_close(weight, scores)
319 assert group_index is None319 assert group_index is None
320 assert clamp_limit == -1.0320 assert clamp_limit == -1.0
321+ 
322+ 
323+@pytest.mark.parametrize("enabled", [False, True], ids=["disabled", "enabled"])
324+def test_v41_recipe_couples_source_compressor_and_sparse_attention(converter_module, enabled):
325+ from torchao_npu.configs import QuantCompressorConfig, QuantV41SparseAttentionConfig
326+ 
327+ from torchtitan_npu.config.configs import QuantizationExtensionConfig
328+ from torchtitan_npu.models.deepseek_v4_1 import model_registry
329+ 
330+ spec = model_registry("deepseek_v4_1_debugmodel")
331+ converted = converter_module.apply_quantization_converter(
332+ spec,
333+ QuantizationExtensionConfig(
334+ enable_quantized_training=True,
335+ enable_sparse_attention_quantization=enabled,
336+ recipe="all_mxfp8",
337+ ),
338+ model_compile_enabled=False,
339+ )
340+ 
341+ for layer in converted.model.layers:
342+ compressor = layer.attention.compressor
343+ compressor_quant = getattr(compressor, "_torchao_npu_config", None)
344+ attention_quant = getattr(layer.attention.inner_attention, "_torchao_npu_config", None)
345+ if enabled and compressor.is_source:
346+ assert isinstance(compressor_quant, QuantCompressorConfig)
347+ assert compressor_quant.group_size == 16
348+ assert type(compressor)._owner.__name__ == "NpuQuantizedCompressor"
349+ else:
350+ assert compressor_quant is None
351+ assert isinstance(attention_quant, QuantV41SparseAttentionConfig) is enabled
352+ 
353+ 
354+@pytest.mark.parametrize("ratio", [1, 2], ids=["full-resolution", "compressed"])
355+def test_converted_v41_compressor_quantizes_post_rope_and_preserves_gradients(converter_module, monkeypatch, ratio):
356+ from torchtitan_npu.config.configs import QuantizationExtensionConfig
357+ from torchtitan_npu.models.deepseek_v4_1 import model_registry
358+ 
359+ reference_spec = model_registry("deepseek_v4_1_debugmodel")
360+ converted = converter_module.apply_quantization_converter(
361+ model_registry("deepseek_v4_1_debugmodel"),
362+ QuantizationExtensionConfig(
363+ enable_quantized_training=True,
364+ enable_sparse_attention_quantization=True,
365+ recipe="all_mxfp8",
366+ ),
367+ model_compile_enabled=False,
368+ )
369+ layer_id = next(
370+ i
371+ for i, layer in enumerate(reference_spec.model.layers)
372+ if layer.attention.compressor.is_source and layer.attention.compressor.compress_ratio == ratio
373+ )
374+ with torch.random.fork_rng(devices=[]):
375+ torch.manual_seed(17)
376+ reference = reference_spec.model.layers[layer_id].attention.compressor.build()
377+ reference.init_states(buffer_device=torch.device("cpu"))
378+ reference.to(dtype=torch.bfloat16)
379+ quantized = converted.model.layers[layer_id].attention.compressor.build()
380+ quantized.init_states(buffer_device=torch.device("cpu"))
381+ quantized.to(dtype=torch.bfloat16)
382+ quantized.load_state_dict(reference.state_dict())
383+ captured = []
384+ d = reference_spec.model.layers[layer_id].attention.compressor.wkv.out_features
385+ 
386+ def encode(cache, rows, slots, **kwargs):
387+ captured.append(rows.detach().clone())
388+ assert kwargs["quant_group_size"] == 16
389+ assert kwargs["quant_mode"] == "mxfp4_bf16"
390+ cache[:, : d // 2] = 0x21
391+ scales = torch.full((rows.shape[0], d // 16), 0.5, dtype=torch.bfloat16)
392+ cache[:, d // 2 : d // 2 + 2 * (d // 16)] = scales.view(torch.uint8)
393+ 
394+ monkeypatch.setattr(torch.ops.custom.kv_compress_epilog_v2, "default", encode)
395+ dim = reference_spec.model.dim
396+ x_ref = torch.linspace(-1, 1, 4 * dim, dtype=torch.bfloat16).reshape(1, 4, dim).requires_grad_()
397+ x_quant = x_ref.detach().clone().requires_grad_()
398+ positions = torch.arange(4).unsqueeze(0)
399+ 
400+ expected_kv, expected_latent = reference(x_ref, positions)
401+ actual_kv, actual_latent = quantized(x_quant, positions)
402+ 
403+ assert len(captured) == 1
404+ assert torch.equal(captured[0], expected_kv.detach().reshape(-1, d))
405+ assert torch.equal(actual_latent, expected_latent)
406+ expected_qdq = torch.tensor([0.25, 0.5], dtype=actual_kv.dtype).repeat(actual_kv.numel() // 2).reshape_as(actual_kv)
407+ assert torch.equal(actual_kv, expected_qdq)
408+ assert actual_kv.dtype == expected_kv.dtype
409+ reuser = converted.model.layers[layer_id + 1].attention.compressor.build()
410+ shared, latent = reuser(x_quant, positions, actual_kv)
411+ assert shared is actual_kv
412+ assert latent is None
413+ assert len(captured) == 1
414+ 
415+ kv_grad = torch.linspace(-0.5, 0.5, actual_kv.numel()).reshape_as(actual_kv)
416+ latent_grad = torch.linspace(0.25, 0.75, actual_latent.numel()).reshape_as(actual_latent)
417+ ((expected_kv.float() * kv_grad).sum() + (expected_latent.float() * latent_grad).sum()).backward()
418+ ((actual_kv.float() * kv_grad).sum() + (actual_latent.float() * latent_grad).sum()).backward()
419+ torch.testing.assert_close(x_quant.grad, x_ref.grad, rtol=0, atol=0)
420+ for (_, parameter), (_, reference_parameter) in zip(
421+ quantized.named_parameters(), reference.named_parameters(), strict=True
422+ ):
423+ assert parameter.grad is not None
424+ torch.testing.assert_close(parameter.grad, reference_parameter.grad, rtol=0, atol=0)
@@ -110,6 +110,7 @@ class QuantizationExtensionConfig:
110 110 
111 enable_quantized_training: bool = False111 enable_quantized_training: bool = False
112 enable_sparse_attention_quantization: bool = False112 enable_sparse_attention_quantization: bool = False
113+ """V4.1 source-Compressor FP4 Q/DQ and sparse-attention SWA FP8 Q/DQ."""
113 recipe: QuantizationRecipe = "mix"114 recipe: QuantizationRecipe = "mix"
114 enable_mxfp4_qat: bool = False115 enable_mxfp4_qat: bool = False
115 li_quantization: LIQuantization | None = None116 li_quantization: LIQuantization | None = None