Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / modules / attention / compressed_sparse_attention2 / quantize_compressed_sparse_attention2.py: 100%

54 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-12-05 05:12 +0800

1# Copyright 2026 Huawei Technologies Co., Ltd 

2# 

3# Licensed under the Apache License, Version 2.0 (the "License"); 

4# you may not use this file except in compliance with the License. 

5# You may obtain a copy of the License at 

6# 

7# http://www.apache.org/licenses/LICENSE-2.0 

8# 

9# Unless required by applicable law or agreed to in writing, software 

10# distributed under the License is distributed on an "AS IS" BASIS, 

11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

12# See the License for the specific language governing permissions and 

13# limitations under the License. 

14# ============================================================================ 

15"""Bind CSA2 low-precision policies before local, TP and CP execution. 

16 

17The family variants inherit this layer, so packing occurs at producer hooks 

18before transport. Each build binds its own config; disabled policies leave 

19the base hooks unchanged. Main KV is packed once and shared by consumers. 

20""" 

21 

22from __future__ import annotations 

23 

24from typing import Any 

25 

26from torch import Tensor 

27 

28from hyper_parallel.components.quantization.config import ( 

29 CSA2MainKVFormat, 

30 CSA2SWAKVFormat, 

31 LowPrecisionConfig, 

32) 

33from hyper_parallel.components.quantization.quantizers.csa2 import ( 

34 CSA2CacheQuantizer, 

35 indexer_qk_quantize_dequantize, 

36) 

37from hyper_parallel.components.quantization.tensor.csa2_cache_tensor import CSA2CacheTensor 

38from .compressed_sparse_attention2 import CompressedSparseAttention2Module 

39 

40 

41class MainKVQATStrategy: 

42 """Pack a Full owner Main KV for sharing across consumer layers.""" 

43 

44 def __init__(self, format_config: CSA2MainKVFormat) -> None: 

45 """Bind a Main KV cache quantizer from the configured format.""" 

46 if not isinstance(format_config, CSA2MainKVFormat): 

47 raise TypeError("MainKVQATStrategy requires a CSA2MainKVFormat.") 

48 self.format_config = format_config 

49 self.quantizer = CSA2CacheQuantizer("main_kv", format_config.scale_format) 

50 

51 def quantize(self, compressed_kv: Tensor) -> Tensor: 

52 """Keep a physical FP4 cache while preserving STE gradients to the producer.""" 

53 return self.quantizer.quantize(compressed_kv) 

54 

55 

56class SWAKVQATStrategy: 

57 """Pack local SWA KV before attention consumption.""" 

58 

59 def __init__(self, format_config: CSA2SWAKVFormat) -> None: 

60 """Bind a SWA KV cache quantizer from the configured format.""" 

61 if not isinstance(format_config, CSA2SWAKVFormat): 

62 raise TypeError("SWAKVQATStrategy requires a CSA2SWAKVFormat.") 

63 self.format_config = format_config 

64 self.quantizer = CSA2CacheQuantizer("swa_kv", format_config.scale_format) 

65 

66 def quantize(self, kv: Tensor) -> Tensor: 

67 """Hold local SWA KV in physical FP8 form until attention reads it.""" 

68 return self.quantizer.quantize(kv) 

69 

70 

71class IndexerQATPolicy: 

72 """Apply MXFP4 query QDQ and pack each Full layer's shared key once. 

73 

74 Selection and KL decode the same bytes that the shared state publishes. 

75 The query round trip and cache boundaries both preserve identity STE gradients. 

76 """ 

77 

78 def __init__(self) -> None: 

79 """Bind the fixed Indexer K cache quantizer.""" 

80 self._quantizer = CSA2CacheQuantizer("indexer_k") 

81 

82 def quantize_query(self, query: Tensor) -> Tensor: 

83 """Apply MXFP4 QDQ after RoPE, preserving an identity STE gradient.""" 

84 return indexer_qk_quantize_dequantize(query) 

85 

86 def pack_owned_key(self, key: Tensor) -> tuple[Tensor, Tensor]: 

87 """Pack once and decode the same bytes for scoring and KL. 

88 

89 Returns: 

90 The differentiable decoded key and its packed shared cache. 

91 """ 

92 cache = self._quantizer.quantize(key) 

93 return CSA2CacheQuantizer.dequantize(cache), cache 

94 

95 

96class QuantizeCompressedSparseAttention2Module(CompressedSparseAttention2Module): 

97 """Bind producer-side CSA2 policies for local and parallel variants.""" 

98 

99 def __init__(self, *args: Any, low_precision: LowPrecisionConfig | None = None, 

100 **kwargs: Any) -> None: 

101 """Construct the attention module and bind the configured quantization policies.""" 

102 super().__init__(*args, **kwargs) 

103 self._main_kv_qat_strategy = None 

104 self._swa_kv_qat_strategy = None 

105 if low_precision is not None: 

106 if low_precision.main_kv is not None: 

107 self._main_kv_qat_strategy = MainKVQATStrategy(low_precision.main_kv) 

108 if low_precision.swa_kv is not None: 

109 self._swa_kv_qat_strategy = SWAKVQATStrategy(low_precision.swa_kv) 

110 if low_precision.indexer_qk is not None and self.is_index_source: 

111 self.indexer.set_qk_policy(IndexerQATPolicy()) 

112 

113 def set_main_kv_qat_strategy(self, strategy: MainKVQATStrategy | None) -> None: 

114 """Bind or clear the Main KV strategy on an existing module.""" 

115 self._main_kv_qat_strategy = strategy 

116 

117 def set_swa_kv_qat_strategy(self, strategy: SWAKVQATStrategy | None) -> None: 

118 """Bind or clear the SWA KV strategy on an existing module.""" 

119 self._swa_kv_qat_strategy = strategy 

120 

121 def _apply_swa_kv_qat(self, key_value: Tensor) -> Tensor: 

122 """Pack local SWA KV when its policy is enabled.""" 

123 return self._swa_kv_qat_strategy.quantize(key_value) if self._swa_kv_qat_strategy is not None else key_value 

124 

125 def _apply_main_kv_qat(self, compressed: Tensor) -> Tensor: 

126 """Pack Main KV once, preserving already-packed CP or shared banks.""" 

127 if self._main_kv_qat_strategy is None or isinstance(compressed, CSA2CacheTensor): 

128 return compressed 

129 return self._main_kv_qat_strategy.quantize(compressed) 

130 

131 

132__all__ = [ 

133 "MainKVQATStrategy", 

134 "SWAKVQATStrategy", 

135 "IndexerQATPolicy", 

136 "QuantizeCompressedSparseAttention2Module", 

137]