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

56 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"""NPU SWA KV E4M3 storage with group-32 E8M0 or BF16 scales. 

16 

17E8M0 uses the native CUBALS MX codec. BF16 scales use grouped normalization 

18and 32-byte aligned rows. Decoding returns BF16 attention values. 

19""" 

20 

21from importlib import import_module 

22 

23import torch 

24from torch import Tensor 

25 

26from hyper_parallel.components.quantization.config import ( 

27 FP8_E4M3_MAX, 

28 MX_BLOCK_SIZE_32, 

29 MX_SCALE_ALG_CUBALS, 

30 MX_SCALE_SLOTS, 

31 SWA_KV_GROUP_SIZE, 

32) 

33 

34_E8M0_NAN_SCALE = 255 

35_BF16_SCALE_BYTES = 2 

36_BF16_CACHE_ROW_ALIGNMENT = 32 

37 

38 

39def _scale_slots(width: int) -> int: 

40 """Round group-32 E8M0 scale slots to the native two-slot ABI.""" 

41 groups = width // SWA_KV_GROUP_SIZE 

42 return (groups + MX_SCALE_SLOTS - 1) // MX_SCALE_SLOTS * MX_SCALE_SLOTS 

43 

44 

45def _swa_row_bytes(width: int, scale_format: str) -> int: 

46 """Count SWA data and scale bytes, including BF16-scale row padding.""" 

47 if scale_format == "e8m0": 

48 return width + _scale_slots(width) 

49 payload = width + _BF16_SCALE_BYTES * width // SWA_KV_GROUP_SIZE 

50 return (payload + _BF16_CACHE_ROW_ALIGNMENT - 1) // _BF16_CACHE_ROW_ALIGNMENT * _BF16_CACHE_ROW_ALIGNMENT 

51 

52 

53def quantize_swa_kv(kv: Tensor, scale_format: str = "e8m0") -> Tensor: 

54 """Encode SWA KV rows as E4M3 values with group-32 E8M0 or BF16 scales.""" 

55 width = kv.shape[-1] 

56 if width <= 0 or width % SWA_KV_GROUP_SIZE: 

57 raise ValueError("SWA KV last axis must be positive and divisible by 32.") 

58 if kv.numel() == 0: 

59 return torch.empty((*kv.shape[:-1], _swa_row_bytes(width, scale_format)), 

60 dtype=torch.uint8, device=kv.device) 

61 if scale_format == "e8m0": 

62 flat = kv.reshape(-1, width).contiguous() 

63 npu = import_module("torch_npu") 

64 data, scale = npu.npu_dynamic_mx_quant( 

65 flat, dst_type=torch.float8_e4m3fn, block_size=MX_BLOCK_SIZE_32, 

66 scale_alg=MX_SCALE_ALG_CUBALS, 

67 ) 

68 return torch.cat((data.view(torch.uint8).reshape(*kv.shape[:-1], width), 

69 scale.reshape(*kv.shape[:-1], -1)), dim=-1) 

70 grouped = kv.float().reshape(*kv.shape[:-1], width // SWA_KV_GROUP_SIZE, SWA_KV_GROUP_SIZE) 

71 amax = torch.nan_to_num(grouped.abs(), nan=float("inf")).amax(dim=-1) 

72 scale = (amax / FP8_E4M3_MAX).clamp_min(torch.finfo(torch.bfloat16).tiny).to(torch.bfloat16) 

73 normalized = (grouped / scale.float().unsqueeze(-1)).clamp(-FP8_E4M3_MAX, FP8_E4M3_MAX) 

74 data = normalized.to(torch.float8_e4m3fn) 

75 packed = torch.cat((data.view(torch.uint8).reshape(*kv.shape[:-1], width), scale.view(torch.uint8)), dim=-1) 

76 padding = _swa_row_bytes(width, scale_format) - packed.shape[-1] 

77 return torch.nn.functional.pad(packed, (0, padding)) if padding else packed 

78 

79 

80def dequantize_swa_kv(packed: Tensor, logical_width: int, scale_format: str = "e8m0") -> Tensor: 

81 """Decode packed SWA rows to BF16 using the selected scale format.""" 

82 if logical_width <= 0 or logical_width % SWA_KV_GROUP_SIZE: 

83 raise ValueError("SWA KV logical width must be positive and divisible by 32.") 

84 if packed.numel() == 0: 

85 return torch.empty((*packed.shape[:-1], logical_width), dtype=torch.bfloat16, device=packed.device) 

86 data = packed[..., :logical_width].contiguous() 

87 if scale_format == "e8m0": 

88 slots = _scale_slots(logical_width) 

89 scale = packed[..., logical_width:logical_width + slots] 

90 scale = scale.reshape(*data.shape[:-1], slots // MX_SCALE_SLOTS, MX_SCALE_SLOTS) 

91 npu = import_module("torch_npu") 

92 values = npu.npu_anti_mx_quant( 

93 data.reshape(-1, logical_width).view(torch.float8_e4m3fn), 

94 scale.reshape(-1, slots // MX_SCALE_SLOTS, MX_SCALE_SLOTS).contiguous(), 

95 src_type=torch.float8_e4m3fn, dst_type=15, # BF16 output 

96 ) 

97 groups = logical_width // SWA_KV_GROUP_SIZE 

98 invalid_scale = scale.reshape(*packed.shape[:-1], slots)[..., :groups] == _E8M0_NAN_SCALE 

99 decoded = values.reshape(*packed.shape[:-1], groups, SWA_KV_GROUP_SIZE) 

100 # Native E4M3 anti-MX maps NaN scales to zero; retain the overflow signal. 

101 decoded.masked_fill_(invalid_scale.unsqueeze(-1), float("nan")) 

102 return decoded.reshape(*packed.shape[:-1], logical_width) 

103 scale_bytes = _BF16_SCALE_BYTES * logical_width // SWA_KV_GROUP_SIZE 

104 scales = packed[..., logical_width:logical_width + scale_bytes].contiguous().view(torch.bfloat16) 

105 values = data.view(torch.float8_e4m3fn).to(torch.bfloat16) 

106 return (values.reshape(*data.shape[:-1], logical_width // SWA_KV_GROUP_SIZE, SWA_KV_GROUP_SIZE) 

107 * scales.unsqueeze(-1)).reshape(*data.shape[:-1], logical_width) 

108 

109 

110__all__ = ["quantize_swa_kv", "dequantize_swa_kv"]