102 lines
4.8 KiB
Python
102 lines
4.8 KiB
Python
"""Incremental full-attention sites for measuring LiSA's real K/V allocation.
|
|
|
|
The scheduler supplies the earlier full-attention site's raw score row for
|
|
the same query. This file measures an attention site, excluding GDN, MLP,
|
|
embedding, and scheduler overhead.
|
|
"""
|
|
import math
|
|
|
|
import torch
|
|
|
|
from crossqkv.lisa_tail import TorchTail, rotate
|
|
|
|
|
|
class AttentionSiteCache:
|
|
def __init__(self, tail: TorchTail, layer, batch_size, capacity, adapter=None,
|
|
dtype=torch.float32):
|
|
self.tail, self.adapter = tail, adapter
|
|
self.name = f'layers.{layer}.self_attn.'
|
|
self.heads = tail.c['num_attention_heads']
|
|
self.kv_heads = tail.c['num_key_value_heads']
|
|
self.head_dim = tail.c['head_dim']
|
|
self.key_dim = adapter.rank if adapter is not None else self.head_dim
|
|
self.capacity = capacity
|
|
self.next_position = 0
|
|
self.k = torch.empty(batch_size, capacity, self.kv_heads, self.key_dim, dtype=dtype)
|
|
self.v = torch.empty(batch_size, capacity, self.kv_heads, self.head_dim, dtype=dtype)
|
|
rp = tail.c['rope_parameters']
|
|
n = int(self.head_dim * rp['partial_rotary_factor'])
|
|
self.rotary_frequency = rp['rope_theta'] ** (-torch.arange(0, n, 2, dtype=dtype) / n)
|
|
|
|
def reset(self):
|
|
self.next_position = 0
|
|
|
|
@property
|
|
def allocated_bytes(self):
|
|
return {'k': self.k.numel()*self.k.element_size(),
|
|
'v': self.v.numel()*self.v.element_size()}
|
|
|
|
def native_rotate(self, x, position):
|
|
angle = self.rotary_frequency * position
|
|
a, b = x[..., :2*len(angle)].chunk(2, -1)
|
|
angle = torch.cat((angle, angle))
|
|
return torch.cat((torch.cat((a, b), -1)*angle.cos()
|
|
+ torch.cat((-b, a), -1)*angle.sin(),
|
|
x[..., 2*len(self.rotary_frequency):]), -1)
|
|
|
|
@torch.no_grad()
|
|
def prefill(self, h):
|
|
"""Populate K/V from a fresh prefix without scoring its queries."""
|
|
n = h.shape[1]
|
|
if h.shape[0] != self.k.shape[0] or n > self.capacity:
|
|
raise ValueError('Prefix does not fit the attention cache')
|
|
base, name = self.tail, self.name
|
|
if self.adapter is None:
|
|
rp = base.c['rope_parameters']
|
|
k = base.linear(h, name+'k_proj').unflatten(-1, (self.kv_heads, self.head_dim))
|
|
k = rotate(base.norm(k, name+'k_norm'), rp['rope_theta'], rp['partial_rotary_factor'])
|
|
else:
|
|
a = self.adapter
|
|
k = a.k_proj(h).unflatten(-1, (self.kv_heads, self.key_dim))
|
|
k = a.rotate(k, torch.arange(n, device=h.device)[None, :])
|
|
self.k[:, :n].copy_(k)
|
|
self.v[:, :n].copy_(base.linear(h, name+'v_proj').unflatten(-1, (self.kv_heads, self.head_dim)))
|
|
self.next_position = n
|
|
|
|
@torch.no_grad()
|
|
def step(self, h, donor=None):
|
|
"""h has shape (batch, 1, hidden). Return output and unmasked score row."""
|
|
pos = self.next_position
|
|
if h.shape[:2] != (self.k.shape[0], 1) or pos >= self.capacity:
|
|
raise ValueError('Wrong input shape or full attention cache')
|
|
if self.adapter is not None and (donor is None or
|
|
donor.shape != (len(h), self.heads, 1, pos+1)):
|
|
raise ValueError('LiSA requires the upstream score row for its full prefix')
|
|
base = self.tail
|
|
name = self.name
|
|
if self.adapter is None:
|
|
packed = base.linear(h, name+'q_proj').unflatten(-1, (self.heads, 2*self.head_dim))
|
|
q, gate = packed.chunk(2, -1)
|
|
k = base.linear(h, name+'k_proj').unflatten(-1, (self.kv_heads, self.head_dim))
|
|
q = self.native_rotate(base.norm(q, name+'q_norm'), pos)
|
|
k = self.native_rotate(base.norm(k, name+'k_norm'), pos)
|
|
else:
|
|
a = self.adapter
|
|
position = torch.tensor([[pos]], device=h.device)
|
|
q = a.rotate(a.q_proj(h).unflatten(-1, (self.heads, self.key_dim)), position)
|
|
k = a.rotate(a.k_proj(h).unflatten(-1, (self.kv_heads, self.key_dim)), position)
|
|
gate = base.gate_only(h, name)
|
|
v = base.linear(h, name+'v_proj').unflatten(-1, (self.kv_heads, self.head_dim))
|
|
self.k[:, pos:pos+1].copy_(k)
|
|
self.v[:, pos:pos+1].copy_(v)
|
|
self.next_position += 1
|
|
groups = self.heads // self.kv_heads
|
|
keys = self.k[:, :pos+1].repeat_interleave(groups, 2)
|
|
values = self.v[:, :pos+1].repeat_interleave(groups, 2)
|
|
scores = torch.einsum('bthd,bshd->bhts', q, keys) / math.sqrt(self.key_dim)
|
|
if self.adapter is not None:
|
|
both = torch.cat((scores, donor), dim=1).permute(0, 2, 3, 1)
|
|
scores = self.adapter.fuse(both).permute(0, 3, 1, 2)
|
|
context = torch.einsum('bhts,bshd->bthd', scores.softmax(-1), values)
|
|
return base.linear((context * gate.sigmoid()).flatten(-2), name+'o_proj'), scores
|