Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / quantization / quantizers / csa2 / csa2_cache.py: 95%

93 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"""CSA2 packed-cache write, decode and selected-row autograd boundaries. 

16 

17Only quantized bytes are stored. Writes and full reads pass logical floating 

18gradients through an identity STE; selected reads scatter-add duplicate rows. 

19Per-format codecs own encoding and decoding, without importing this module. 

20""" 

21 

22from typing import Any, Optional 

23 

24import torch 

25from torch import Tensor 

26 

27from hyper_parallel.components.quantization.quantizers.csa2.indexer_qk import ( 

28 dequantize_indexer_k, 

29 quantize_indexer_k, 

30) 

31from hyper_parallel.components.quantization.quantizers.csa2.main_kv import ( 

32 dequantize_main_kv, 

33 quantize_main_kv, 

34) 

35from hyper_parallel.components.quantization.quantizers.csa2.swa_kv import ( 

36 dequantize_swa_kv, 

37 quantize_swa_kv, 

38) 

39from hyper_parallel.components.quantization.tensor.csa2_cache_tensor import ( 

40 CSA2CacheFormat, 

41 CSA2CacheTensor, 

42 CSA2ScaleFormat, 

43) 

44 

45 

46class _WriteCSA2Cache(torch.autograd.Function): 

47 """Pack cache bytes while retaining an identity STE to their producer.""" 

48 

49 @staticmethod 

50 def forward(ctx: Any, value: Tensor, cache_format: CSA2CacheFormat, 

51 scale_format: CSA2ScaleFormat) -> CSA2CacheTensor: 

52 """Encode physical bytes and return a floating logical wrapper.""" 

53 del ctx 

54 if cache_format == "indexer_k": 

55 packed = quantize_indexer_k(value) 

56 elif cache_format == "main_kv": 

57 packed = quantize_main_kv(value, scale_format) 

58 else: 

59 packed = quantize_swa_kv(value, scale_format) 

60 return CSA2CacheTensor(packed, tuple(value.shape), value.dtype, 

61 cache_format, scale_format, value.requires_grad) 

62 

63 @staticmethod 

64 def backward(ctx: Any, grad_output: Tensor) -> tuple[Tensor, None, None]: 

65 """Pass consumer gradients to the floating producer without saving its data.""" 

66 del ctx 

67 return grad_output, None, None 

68 

69 

70class _ReadCSA2Cache(torch.autograd.Function): 

71 """Decode an entire cache bank with an identity STE.""" 

72 

73 @staticmethod 

74 def forward(ctx: Any, cache: CSA2CacheTensor) -> Tensor: 

75 """Decode using the format and logical dtype stored on the cache.""" 

76 del ctx 

77 width = cache.shape[-1] 

78 if cache.cache_format == "indexer_k": 

79 return dequantize_indexer_k(cache.packed, width, cache.dtype) 

80 if cache.cache_format == "main_kv": 

81 return dequantize_main_kv(cache.packed, width, cache.dtype, cache.scale_format) 

82 return dequantize_swa_kv(cache.packed, width, cache.scale_format) 

83 

84 @staticmethod 

85 def backward(ctx: Any, grad_output: Tensor) -> tuple[Tensor]: 

86 """Return floating consumer gradients to the logical cache.""" 

87 del ctx 

88 return (grad_output,) 

89 

90 

91class _ReadSelectedCSA2Cache(torch.autograd.Function): 

92 """Gather physical rows before decoding; invalid rows contribute zero.""" 

93 

94 @staticmethod 

95 def forward(ctx: Any, cache: CSA2CacheTensor, indices: Tensor) -> Tensor: 

96 """Decode selected rows, retaining indices and validity for backward.""" 

97 batch = cache.shape[0] 

98 length, width = cache.shape[-2:] 

99 valid = (indices >= 0) & (indices < length) 

100 safe = indices.long().clamp(min=0, max=max(length - 1, 0)) 

101 ctx.save_for_backward(safe, valid) 

102 ctx.bank_shape = (batch, length, width) 

103 ctx.is_swa = cache.cache_format == "swa_kv" 

104 ctx.scale_format = cache.scale_format 

105 if length == 0 or indices.numel() == 0: 

106 return torch.zeros((*indices.shape, width), dtype=cache.dtype, device=cache.device) 

107 offsets = torch.arange(batch, device=cache.device).view(-1, 1, 1) * length 

108 rows = cache.packed.reshape(batch * length, -1).index_select(0, (safe + offsets).reshape(-1)) 

109 packed = rows.reshape(*indices.shape, cache.packed.shape[-1]) 

110 decoded = (dequantize_swa_kv(packed, width, ctx.scale_format) if ctx.is_swa 

111 else dequantize_main_kv(packed, width, cache.dtype, ctx.scale_format)) 

112 return decoded.masked_fill(~valid.unsqueeze(-1), 0) 

113 

114 @staticmethod 

115 def backward(ctx: Any, grad_output: Tensor) -> tuple[Tensor, None]: 

116 """Accumulate repeated row gradients in FP32 before restoring the input dtype.""" 

117 safe, valid = ctx.saved_tensors 

118 batch, length, width = ctx.bank_shape 

119 grad_bank = torch.zeros((batch * length, width), device=grad_output.device, dtype=torch.float32) 

120 if safe.numel() and length: 

121 offsets = torch.arange(batch, device=safe.device).view(-1, 1, 1) * length 

122 row_ids = (safe + offsets).reshape(-1) 

123 grad_values = grad_output.masked_fill(~valid.unsqueeze(-1), 0).reshape(-1, width).float() 

124 grad_bank.index_add_(0, row_ids, grad_values) 

125 grad_bank = grad_bank.reshape(ctx.bank_shape).to(grad_output.dtype) 

126 return grad_bank.unsqueeze(1) if ctx.is_swa else grad_bank, None 

127 

128 

129class CSA2CacheQuantizer: 

130 """Bind a validated cache format at construction and expose autograd reads.""" 

131 

132 _DEFAULT_SCALE = {"indexer_k": "e8m0", "main_kv": "e4m3", "swa_kv": "e8m0"} 

133 _ALLOWED_SCALES = {"indexer_k": ("e8m0",), "main_kv": ("e4m3", "e8m7"), 

134 "swa_kv": ("e8m0", "e8m7")} 

135 

136 def __init__(self, cache_format: CSA2CacheFormat, 

137 scale_format: Optional[CSA2ScaleFormat] = None) -> None: 

138 """Validate the storage format and resolve its default scale format.""" 

139 if cache_format not in self._DEFAULT_SCALE: 

140 raise ValueError(f"Unsupported CSA2 cache format: {cache_format!r}.") 

141 effective_scale = self._DEFAULT_SCALE[cache_format] if scale_format is None else scale_format 

142 if effective_scale not in self._ALLOWED_SCALES[cache_format]: 

143 raise ValueError(f"Unsupported {cache_format} scale format: {effective_scale!r}.") 

144 self.cache_format = cache_format 

145 self.scale_format = effective_scale 

146 

147 def quantize(self, value: Tensor) -> CSA2CacheTensor: 

148 """Pack a producer tensor while preserving identity STE gradients.""" 

149 return _WriteCSA2Cache.apply(value, self.cache_format, self.scale_format) 

150 

151 @staticmethod 

152 def dequantize(cache: CSA2CacheTensor) -> Tensor: 

153 """Decode a full bank using the format metadata on its wrapper.""" 

154 return _ReadCSA2Cache.apply(cache) 

155 

156 @staticmethod 

157 def dequantize_selected(cache: CSA2CacheTensor, indices: Tensor) -> Tensor: 

158 """Decode [B, Q, K] row indices; invalid IDs return zero and receive no gradient.""" 

159 valid_main = cache.cache_format == "main_kv" and cache.ndim == 3 

160 valid_swa = cache.cache_format == "swa_kv" and cache.ndim == 4 and cache.shape[1] == 1 

161 if not (valid_main or valid_swa) or indices.ndim != 3: 

162 raise ValueError("Selected reads require [B, K, D] Main or [B, 1, K, D] SWA cache.") 

163 if indices.shape[0] != cache.shape[0]: 

164 raise ValueError("Selected cache indices must share the cache batch size.") 

165 if indices.dtype not in (torch.int32, torch.int64) or indices.device != cache.device: 

166 raise ValueError("Selected cache indices must be int32 or int64 on the cache device.") 

167 return _ReadSelectedCSA2Cache.apply(cache, indices) 

168 

169 

170__all__ = ["CSA2CacheQuantizer"]