|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 1993-2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +from io import StringIO |
| 5 | +from dataclasses import dataclass, field |
| 6 | +from contextlib import contextmanager |
| 7 | + |
| 8 | +import torch |
| 9 | +import requests # type: ignore[import-untyped] |
| 10 | +import numpy as np |
| 11 | + |
| 12 | +from kvpress.presses.base_press import BasePress |
| 13 | + |
| 14 | + |
| 15 | +PATTERNS_DICT = { |
| 16 | + "togethercomputer/Llama-2-7B-32K-Instruct": "Llama-2-7B-32K-Instruct/lr%3D0.02-reg%3D0.05-ctx%3D1000_32000-multi_passkey10", # noqa: E501 |
| 17 | + "gradientai//Llama-3-8B-Instruct-Gradient-1048k": "Llama-3-8B-Instruct-Gradient-1048k/lr%3D0.02-reg%3D0.05-ctx%3D1000_32000-multi_passkey10", # noqa: E501 |
| 18 | + "gradientai//Llama-3-8B-Instruct-Gradient-4194k": "Llama-3-8B-Instruct-Gradient-4194k/lr%3D0.02-reg%3D0.05-ctx%3D1000_32000-multi_passkey10", # noqa: E501 |
| 19 | + "meta-llama/Meta-Llama-3.1-8B-Instruct": "Meta-Llama-3.1-8B-Instruct/lr=0.02-reg=0.05-ctx=1000_128000-multi_passkey10", # noqa: E501 |
| 20 | + "mistralai/Mistral-7B-Instruct-v0.2": "Mistral-7B-Instruct-v0.2/lr%3D0.02-reg%3D0.05-ctx%3D1000_32000-multi_passkey10", # noqa: E501 |
| 21 | + "mistralai/Mistral-7B-Instruct-v0.3": "Mistral-7B-Instruct-v0.3/lr%3D0.02-reg%3D0.05-ctx%3D1000_32000-multi_passkey10", # noqa: E501 |
| 22 | +} |
| 23 | + |
| 24 | + |
| 25 | +@dataclass |
| 26 | +class DuoAttentionPress(BasePress): |
| 27 | + """ |
| 28 | + Implements DuoAttention (https://arxiv.org/abs/2410.10819) |
| 29 | +
|
| 30 | + Splits attention heads into two types: |
| 31 | + - Retrieval heads: use the full KV cache |
| 32 | + - Streaming heads: use only sink and recent tokens. |
| 33 | +
|
| 34 | + Head classification is based on scores loaded from https://github.com/mit-han-lab/duo-attention/ |
| 35 | + The higher the head_compression_ratio, the more streaming heads are used. |
| 36 | + """ |
| 37 | + |
| 38 | + head_compression_ratio: float = 0.0 |
| 39 | + compression_ratio_: float = field(init=False, default=None) |
| 40 | + recent_size: int = field(init=False, default=None) |
| 41 | + sink_size: int = field(init=False, default=None) |
| 42 | + streaming_mask: torch.Tensor = field(init=False, default=None) |
| 43 | + |
| 44 | + def __post_init_from_model__(self, model): |
| 45 | + """ |
| 46 | + Initialize sink_size, recent_size, and streaming_mask from a model |
| 47 | + """ |
| 48 | + # Load attention pattern from the DuoAttention repo |
| 49 | + self.sink_size, self.recent_size, head_scores = self.load_attention_pattern(model) |
| 50 | + |
| 51 | + # Define retrieval and streaming heads through a binary mask |
| 52 | + n_pruned = round(head_scores.size * self.head_compression_ratio) |
| 53 | + self.streaming_mask = torch.zeros(head_scores.shape, dtype=bool, device=model.device) |
| 54 | + if n_pruned > 0: |
| 55 | + indices = np.argsort(head_scores, axis=None)[:n_pruned] |
| 56 | + self.streaming_mask[np.unravel_index(indices, head_scores.shape)] = True |
| 57 | + |
| 58 | + @property |
| 59 | + def compression_ratio(self) -> float: |
| 60 | + assert self.compression_ratio_ is not None, "Forward pass must be run to compute the compression ratio" |
| 61 | + return self.compression_ratio_ |
| 62 | + |
| 63 | + @compression_ratio.setter |
| 64 | + def compression_ratio(self, value): |
| 65 | + raise AttributeError(f"compression ratio cannot be set for {type(self).__name__}") |
| 66 | + |
| 67 | + def compress(self, module, hidden_states, keys, values, attentions, kwargs): |
| 68 | + |
| 69 | + assert module.config._attn_implementation != "eager", "eager mode not supported" |
| 70 | + q_len = hidden_states.shape[1] |
| 71 | + |
| 72 | + if (self.head_compression_ratio > 0) or (q_len > (self.sink_size + self.recent_size)): |
| 73 | + |
| 74 | + # Save indices to mask during the attention mechanism. Please refer to attention_patch.py for more details |
| 75 | + masked_keys = torch.zeros_like(keys[..., 0], dtype=torch.bool) |
| 76 | + masked_keys[:, self.streaming_mask[module.layer_idx], self.sink_size : -self.recent_size] = True |
| 77 | + module.masked_key_indices = torch.nonzero(masked_keys, as_tuple=True) |
| 78 | + |
| 79 | + # Compute the compression ratio |
| 80 | + self.compression_ratio_ = self.streaming_mask.float().mean().item() |
| 81 | + self.compression_ratio_ *= 1 - (self.sink_size + self.recent_size) / q_len |
| 82 | + |
| 83 | + return keys, values |
| 84 | + |
| 85 | + @staticmethod |
| 86 | + def load_attention_pattern(model): |
| 87 | + """ |
| 88 | + Load the attention pattern from the DuoAttention repo |
| 89 | + """ |
| 90 | + |
| 91 | + assert ( |
| 92 | + model.config.name_or_path in PATTERNS_DICT |
| 93 | + ), f"Checkpoint {model.config.name_or_path} not in {list(PATTERNS_DICT.keys())}" |
| 94 | + base_url = "https://raw.githubusercontent.com/mit-han-lab/duo-attention/refs/heads/main/attn_patterns" |
| 95 | + url = f"{base_url}/{PATTERNS_DICT[model.config.name_or_path]}/" |
| 96 | + |
| 97 | + # Load config |
| 98 | + config = requests.get(url + "config.json").json() |
| 99 | + |
| 100 | + # Load head scores and clip as in duo_attn.utils.load_attn_pattern |
| 101 | + text = requests.get(url + "full_attention_heads.tsv").text |
| 102 | + head_scores = np.loadtxt(StringIO(text), dtype=float, delimiter="\t") |
| 103 | + head_scores = np.clip(head_scores, 0, 1) |
| 104 | + |
| 105 | + return config["sink_size"], config["recent_size"], head_scores |
| 106 | + |
| 107 | + @contextmanager |
| 108 | + def __call__(self, model): |
| 109 | + self.__post_init_from_model__(model) |
| 110 | + with super().__call__(model): |
| 111 | + yield |
0 commit comments