|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 1993-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +from dataclasses import dataclass |
| 5 | + |
| 6 | +import torch |
| 7 | +from torch import nn |
| 8 | + |
| 9 | +from kvpress.presses.base_press import BasePress |
| 10 | +from kvpress.presses.scorer_press import ScorerPress |
| 11 | + |
| 12 | + |
| 13 | +@dataclass |
| 14 | +class BlockPress(BasePress): |
| 15 | + """ |
| 16 | + Simulates block prompt processing described in the KeyDiff (https://arxiv.org/abs/2504.15364). |
| 17 | + Segments input sequence into non-overlapping blocks and compresses iteratively. |
| 18 | + Keeps limited memory overhead for long context inference. |
| 19 | + """ |
| 20 | + |
| 21 | + press: ScorerPress |
| 22 | + block_size: int = 128 |
| 23 | + |
| 24 | + def __post_init__(self): |
| 25 | + assert isinstance(self.press, ScorerPress), "BlockPress requires a ScorerPress" |
| 26 | + |
| 27 | + @property |
| 28 | + def compression_ratio(self): |
| 29 | + return self.press.compression_ratio |
| 30 | + |
| 31 | + @compression_ratio.setter |
| 32 | + def compression_ratio(self, value): |
| 33 | + self.press.compression_ratio = value |
| 34 | + |
| 35 | + def compress( |
| 36 | + self, |
| 37 | + module: nn.Module, |
| 38 | + hidden_states: torch.Tensor, |
| 39 | + keys: torch.Tensor, |
| 40 | + values: torch.Tensor, |
| 41 | + attentions: torch.Tensor, |
| 42 | + kwargs: dict, |
| 43 | + ) -> tuple[torch.Tensor, torch.Tensor]: |
| 44 | + if self.press.compression_ratio == 0: |
| 45 | + return keys, values |
| 46 | + |
| 47 | + assert attentions is None, "BlockPress does not support attentions." |
| 48 | + |
| 49 | + bsz, num_key_value_heads, q_len, head_dim = keys.shape |
| 50 | + |
| 51 | + block_size = self.block_size if self.block_size < q_len else q_len |
| 52 | + n_kept = int(q_len * (1 - self.compression_ratio)) |
| 53 | + |
| 54 | + kept_indices = torch.arange(n_kept, device=keys.device).expand(bsz, num_key_value_heads, -1) |
| 55 | + |
| 56 | + # Reshape hidden states to match the kept_indices |
| 57 | + states = hidden_states.view(bsz, q_len, num_key_value_heads, -1).transpose(1, 2) |
| 58 | + |
| 59 | + for i in range(n_kept, q_len, block_size): |
| 60 | + end = min(i + block_size, q_len) |
| 61 | + current_indices = torch.arange(i, end, device=keys.device).expand(bsz, num_key_value_heads, -1) |
| 62 | + current_indices = torch.cat([kept_indices, current_indices], dim=-1) |
| 63 | + |
| 64 | + # Gather hidden states for the selected indices, then restore the shape |
| 65 | + # Check tests/presses/test_block_press.py for correctness verification of gathered hidden states |
| 66 | + current_states = states.gather(2, current_indices.unsqueeze(-1).expand(-1, -1, -1, states.shape[-1])) |
| 67 | + current_states = current_states.transpose(1, 2).reshape(bsz, -1, hidden_states.shape[-1]) |
| 68 | + |
| 69 | + scores = self.press.score( |
| 70 | + module, |
| 71 | + current_states, |
| 72 | + keys.gather(2, current_indices.unsqueeze(-1).expand(-1, -1, -1, head_dim)), |
| 73 | + values.gather(2, current_indices.unsqueeze(-1).expand(-1, -1, -1, head_dim)), |
| 74 | + attentions, |
| 75 | + kwargs, |
| 76 | + ) |
| 77 | + topk_indices = scores.topk(n_kept, dim=-1).indices |
| 78 | + kept_indices = current_indices.gather(-1, topk_indices) |
| 79 | + |
| 80 | + kept_indices = kept_indices.unsqueeze(-1).expand(-1, -1, -1, head_dim) |
| 81 | + keys = keys.gather(2, kept_indices).contiguous() |
| 82 | + values = values.gather(2, kept_indices).contiguous() |
| 83 | + |
| 84 | + return keys, values |
0 commit comments