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

52 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"""Learned non-overlapping CSA2 compression with an explicit block exchange stage.""" 

16 

17from __future__ import annotations 

18 

19from collections.abc import Callable 

20from types import SimpleNamespace 

21from typing import Any 

22 

23import torch 

24from torch import nn 

25 

26from hyper_parallel.components.modules.common.rms_norm import NativeRMSNormModule, RMSNorm 

27 

28 

29class CSA2Compressor(nn.Module): 

30 """Non-overlapping V4.1 compressed-KV producer.""" 

31 

32 def __init__(self, config: Any, compress_ratio: int, *, apply_rope: Callable) -> None: 

33 """Create the learned KV pooling projections.""" 

34 super().__init__() 

35 if compress_ratio < 1: 

36 raise ValueError(f"compress_ratio must be positive, got {compress_ratio}") 

37 self.compress_ratio = compress_ratio 

38 self.apply_rope = apply_rope 

39 self.wkv = nn.Linear(config.hidden_size, config.head_dim, bias=False) 

40 if compress_ratio > 1: 

41 self.wgate = nn.Linear(config.hidden_size, config.head_dim, bias=False) 

42 # This is a source subtree until the enclosing CSA2 family is selected. 

43 norm = NativeRMSNormModule( 

44 config=SimpleNamespace(hidden_size=config.head_dim, eps=config.rms_norm_eps), 

45 cast_order="before_weight", 

46 ) 

47 self.norm = RMSNorm(module=norm) 

48 

49 @staticmethod 

50 def pool(projected: torch.Tensor, plan: Any) -> torch.Tensor: 

51 """Pool complete document blocks in an already prepared projected buffer.""" 

52 rows = plan.indices(projected.device)[0] 

53 blocks = projected.index_select(1, rows).reshape( 

54 projected.shape[0], rows.numel() // plan.ratio, plan.ratio, projected.shape[-1], 

55 ) 

56 values, scores = blocks.chunk(2, dim=-1) 

57 return (values * scores.float().softmax(dim=2).to(values.dtype)).sum(dim=2) 

58 

59 def exchange_blocks(self, projected: torch.Tensor, block_plan: Any) -> torch.Tensor: 

60 """Keep complete local blocks in place; parallel members complete boundary blocks.""" 

61 del block_plan 

62 return projected 

63 

64 def forward( 

65 self, 

66 hidden_states: torch.Tensor, 

67 compress_position_embeddings: tuple[torch.Tensor, torch.Tensor], 

68 block_plan: Any = None, 

69 ) -> tuple[torch.Tensor, torch.Tensor]: 

70 """Return unrotated and RoPE-rotated compressed KV tensors. 

71 

72 Args: 

73 hidden_states: Decoder hidden rows to compress. 

74 compress_position_embeddings: Rotary coefficients for compressed keys. 

75 block_plan: Optional document-local grouping and cross-rank boundary plan. 

76 """ 

77 batch_size, sequence_length, _ = hidden_states.shape 

78 if self.compress_ratio == 1: 

79 latent = self.norm(self.wkv(hidden_states)) 

80 cos, sin = compress_position_embeddings 

81 rotated = self.apply_rope(latent.unsqueeze(1), cos, sin).squeeze(1) 

82 return latent, rotated 

83 

84 if block_plan is not None: 

85 projected = torch.cat((self.wkv(hidden_states), self.wgate(hidden_states)), dim=-1) 

86 projected = self.exchange_blocks(projected, block_plan) 

87 latent = self.norm(self.pool(projected, block_plan)) 

88 cos, sin = compress_position_embeddings 

89 return latent, self.apply_rope( 

90 latent.unsqueeze(1), cos, sin, 

91 ).squeeze(1) 

92 

93 usable = sequence_length - sequence_length % self.compress_ratio 

94 key_value = self.wkv(hidden_states[:, :usable]) 

95 gate = self.wgate(hidden_states[:, :usable]) 

96 key_value = key_value.view(batch_size, -1, self.compress_ratio, key_value.shape[-1]) 

97 gate = gate.view(batch_size, -1, self.compress_ratio, gate.shape[-1]) 

98 latent = self.norm((key_value * gate.float().softmax(dim=2).to(key_value.dtype)).sum(dim=2)) 

99 cos, sin = compress_position_embeddings 

100 cos = cos[:, :usable:self.compress_ratio] 

101 sin = sin[:, :usable:self.compress_ratio] 

102 rotated = self.apply_rope(latent.unsqueeze(1), cos, sin).squeeze(1) 

103 return latent, rotated