| import math |
| import torch |
| import time |
| import matplotlib.pyplot as plt |
| import numpy as np |
| from typing import List, Tuple, Dict |
|
|
| |
| |
| |
|
|
| def compute_attention_scores(query_states, key_states_cpu, pooling="max"): |
| """ |
| query_states: [q_len, q_heads, head_dim] on GPU |
| key_states_cpu: [kv_len, kv_heads, head_dim] on CPU |
| """ |
|
|
| q_len, q_heads, head_dim = query_states.shape |
| kv_len, kv_heads, _ = key_states_cpu.shape |
| query_group_size = q_heads // kv_heads |
|
|
| device = query_states.device |
|
|
| |
|
|
| if query_group_size == 1: |
| chunk_size = 12150 |
|
|
| attn_weights = torch.empty(kv_heads, q_len, kv_len, device=device, dtype=query_states.dtype) |
|
|
| for i in range(0, kv_len, chunk_size): |
| end_i = min(i + chunk_size, kv_len) |
| k_chunk = key_states_cpu[i:end_i].to(device) |
|
|
| attn_chunk = torch.bmm( |
| query_states.transpose(0, 1), |
| k_chunk.transpose(1, 2) |
| ) / math.sqrt(head_dim) |
|
|
| attn_weights[:, :, i:end_i] = attn_chunk |
| del k_chunk, attn_chunk |
|
|
| return attn_weights |
|
|
| else: |
| |
| |
| query_states = query_states.view(q_len, kv_heads, query_group_size, head_dim) |
| |
| query_states = query_states.permute(1, 2, 0, 3).contiguous() |
|
|
| if pooling == "mean": |
| attn_weights_sum = None |
| count = 0 |
| elif pooling == "max": |
| attn_weights_max = None |
| else: |
| raise ValueError("Pooling method not supported") |
|
|
| for g in range(query_group_size): |
| q_group = query_states[:, g, :, :] |
|
|
| chunk_size = 12150 |
| group_attn = torch.empty(kv_heads, q_len, kv_len, device=device, dtype=query_states.dtype) |
|
|
| for i in range(0, kv_len, chunk_size): |
| end_i = min(i + chunk_size, kv_len) |
| k_chunk = key_states_cpu[i:end_i].to(device) |
| k_chunk = k_chunk.permute(1, 2, 0) |
| attn_chunk = torch.bmm(q_group, k_chunk) / math.sqrt(head_dim) |
| group_attn[:, :, i:end_i] = attn_chunk |
| del k_chunk, attn_chunk |
|
|
| |
| if pooling == "mean": |
| if attn_weights_sum is None: |
| attn_weights_sum = group_attn |
| else: |
| attn_weights_sum += group_attn |
| count += 1 |
| elif pooling == "max": |
| if attn_weights_max is None: |
| attn_weights_max = group_attn |
| else: |
| attn_weights_max = torch.max(attn_weights_max, group_attn) |
|
|
| del group_attn |
|
|
| if pooling == "mean": |
| attn_weights = attn_weights_sum / count |
| del attn_weights_sum |
| elif pooling == "max": |
| attn_weights = attn_weights_max |
| del attn_weights_max |
|
|
| return attn_weights |
|
|
|
|
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| |
|
|
| |
| |
|
|
| |
| |
|
|
|
|
| def cal_similarity( |
| key_states, |
| ): |
| |
| k = key_states.permute(1, 0, 2).to('cuda') |
| H, L, D = k.shape |
|
|
| |
| k_norm = k / (k.norm(dim=-1, keepdim=True) + 1e-8) |
|
|
| |
| k_sum = k_norm.sum(dim=1) |
|
|
| |
| |
| |
| dot_with_sum = torch.bmm(k_norm, k_sum.unsqueeze(-1)).squeeze(-1) |
|
|
| |
| |
| if L == 1: |
| mean_sim = torch.zeros(H, 1, device=k.device) |
| else: |
| mean_sim = (dot_with_sum - 1.0) / L |
|
|
| avg_sim = mean_sim |
|
|
| |
| result = avg_sim.softmax(dim=-1).to('cpu') |
|
|
| return result |
|
|
|
|
| class ChunkKVRangeTracker: |
| def __init__(self, total_cache_len: int, clip_token_nums: int, max_batch_size: int): |
| self.total_cache_len = total_cache_len |
| self.clip_token_nums = clip_token_nums |
| self.max_batch_size = max_batch_size |
| self.tokens_per_chunk = clip_token_nums * max_batch_size |
| self.chunk_ranges: Dict[int, Tuple[int, int]] = {} |
| self.next_free_idx = 0 |
| self.registered_chunks_ordered: List[int] = [] |
|
|
| def register_chunks(self, chunk_ids: List[int]): |
| """Batch register multiple chunks and allocate original space""" |
| for cid in chunk_ids: |
| if cid in self.chunk_ranges: |
| continue |
| start = self.next_free_idx |
| end = start + self.tokens_per_chunk |
| if end > self.total_cache_len: |
| import pdb; pdb.set_trace() |
| raise ValueError("KV cache is full") |
| self.chunk_ranges[cid] = (start, end) |
| self.registered_chunks_ordered.append(cid) |
| self.next_free_idx = end |
|
|
| def get_range(self, chunk_id: int) -> Tuple[int, int]: |
| if chunk_id not in self.chunk_ranges: |
| raise KeyError(f"Chunk {chunk_id} not registered. Call register_chunks first.") |
| return self.chunk_ranges[chunk_id] |
|
|
| def get_all_ranges_previous(self, current_chunk_ids: List[int]) -> List[Tuple[int, int]]: |
| |
| ranges = [] |
| if len(current_chunk_ids) > 0: |
| min_chunk_id = min(current_chunk_ids) |
| for cid in self.registered_chunks_ordered: |
| if cid >= min_chunk_id: |
| continue |
| ranges.append(self.chunk_ranges[cid]) |
| else: |
| |
| for cid in self.registered_chunks_ordered: |
| ranges.append(self.chunk_ranges[cid]) |
| return ranges |
|
|
| def get_all_chunk_ids(self) -> List[int]: |
| return self.registered_chunks_ordered.copy() |
| |
| def update_ranges_after_compression(self, new_ranges: Dict[int, Tuple[int, int]]): |
| """Update each chunk's range based on actual compressed length""" |
| |
| for cid, (start, end) in new_ranges.items(): |
| if cid in self.chunk_ranges: |
| self.chunk_ranges[cid] = (start, end) |
|
|
| |
| if new_ranges: |
| self.next_free_idx = max(end for start, end in new_ranges.values()) |
| else: |
| self.next_free_idx = 0 |