122 lines
5.6 KiB
Python
122 lines
5.6 KiB
Python
"""Trainable LiSA attention adaptor for the Qwen text reference."""
|
|
import math
|
|
|
|
import torch
|
|
from torch import nn
|
|
from torch.nn import functional as F
|
|
|
|
|
|
class LearnableSharingAttention(nn.Module):
|
|
"""Map low-rank local scores and donor logits to recipient logits."""
|
|
|
|
def __init__(self, hidden_size, heads, kv_heads, rank, theta, rotary_fraction,
|
|
width=256, bias=False):
|
|
super().__init__()
|
|
rotary_dim = int(rank * rotary_fraction)
|
|
if heads % kv_heads or not 0 < rotary_dim <= rank or rotary_dim % 2:
|
|
raise ValueError('Expected grouped query heads and a positive even rotary dimension')
|
|
self.heads, self.kv_heads, self.rank = heads, kv_heads, rank
|
|
self.rotary_dim = rotary_dim
|
|
inv_freq = theta ** (-torch.arange(0, rotary_dim, 2, dtype=torch.float32) / rotary_dim)
|
|
self.register_buffer('inv_freq', inv_freq, persistent=False)
|
|
self.q_proj = nn.Linear(hidden_size, heads * rank, bias=bias)
|
|
self.k_proj = nn.Linear(hidden_size, kv_heads * rank, bias=bias)
|
|
self.fuse = nn.Sequential(nn.Linear(2 * heads, width, bias=bias), nn.ReLU(),
|
|
nn.Linear(width, heads, bias=bias))
|
|
|
|
def rotate(self, x, position_ids):
|
|
phase = position_ids[..., None] * self.inv_freq
|
|
angle = torch.cat((phase, phase), dim=-1).unsqueeze(2)
|
|
a, b = x[..., :self.rotary_dim].chunk(2, dim=-1)
|
|
first = torch.cat((a, b), dim=-1)
|
|
rotated = torch.cat((-b, a), dim=-1)
|
|
return torch.cat((first * angle.cos() + rotated * angle.sin(),
|
|
x[..., self.rotary_dim:]), dim=-1)
|
|
|
|
def forward(self, hidden, donor, position_ids):
|
|
b, t, _ = hidden.shape
|
|
q = self.rotate(self.q_proj(hidden).reshape(b, t, self.heads, self.rank), position_ids)
|
|
k = self.rotate(self.k_proj(hidden).reshape(b, t, self.kv_heads, self.rank), position_ids)
|
|
k = k.repeat_interleave(self.heads // self.kv_heads, dim=2)
|
|
delta = torch.einsum('bthd,bshd->btsh', q, k) / math.sqrt(self.rank)
|
|
return self.fuse(torch.cat((delta, donor.permute(0, 2, 3, 1)), dim=-1)).permute(0, 3, 1, 2)
|
|
|
|
|
|
def causal_attention(scores, values, lengths):
|
|
"""Apply recipient values after causal masking of the fused scores."""
|
|
positions = torch.arange(scores.shape[-1], device=scores.device)
|
|
valid = positions[None, :] < lengths[:, None]
|
|
causal = positions[:, None] >= positions[None, :]
|
|
allowed = valid[:, None, None, :] & causal
|
|
p = scores.masked_fill(~allowed, -torch.inf).softmax(dim=-1)
|
|
repeats = scores.shape[1] // values.shape[2]
|
|
return torch.einsum('bhts,bshd->bthd', p, values.repeat_interleave(repeats, dim=2))
|
|
|
|
|
|
def huber_distillation(scores, teacher, lengths):
|
|
"""Use raw pre-softmax scores and exclude sequence padding."""
|
|
positions = torch.arange(scores.shape[-1], device=scores.device)
|
|
valid = positions[None, :] < lengths[:, None]
|
|
pairs = valid[:, None, :, None] & valid[:, None, None, :]
|
|
return F.huber_loss(scores.masked_select(pairs), teacher.detach().masked_select(pairs),
|
|
delta=1.0)
|
|
|
|
|
|
def objective(scores, teacher, lengths, language_model_loss):
|
|
kd = huber_distillation(scores, teacher, lengths)
|
|
return 0.25 * kd + 0.75 * language_model_loss, kd
|
|
|
|
|
|
class FrozenRecipient(nn.Module):
|
|
"""The recipient's unchanged gated output projection, MLP and final norm."""
|
|
|
|
def __init__(self, weights, eps):
|
|
super().__init__()
|
|
for key in ('o', 'post', 'gate', 'up', 'down', 'final'):
|
|
self.register_buffer('w_' + key, torch.as_tensor(weights[key]).detach())
|
|
self.eps = eps
|
|
|
|
def norm(self, hidden, weight):
|
|
return hidden * (hidden.square().mean(dim=-1, keepdim=True) + self.eps).rsqrt() * (1 + weight)
|
|
|
|
def forward(self, context, gate, residual):
|
|
h = residual + F.linear((context * gate.sigmoid()).flatten(-2), self.w_o)
|
|
n = self.norm(h, self.w_post)
|
|
h = h + F.linear(F.silu(F.linear(n, self.w_gate)) * F.linear(n, self.w_up), self.w_down)
|
|
return self.norm(h, self.w_final)
|
|
|
|
|
|
class _FrozenVocabularyCE(torch.autograd.Function):
|
|
"""Exact full-vocabulary CE with a streamed frozen head in both passes."""
|
|
|
|
@staticmethod
|
|
def forward(ctx, hidden, targets, vocabulary):
|
|
log_total = hidden.new_full((hidden.shape[0],), -torch.inf)
|
|
selected = hidden.new_zeros(hidden.shape[0])
|
|
for start, w in vocabulary():
|
|
logits = F.linear(hidden, w)
|
|
log_total = torch.logaddexp(log_total, logits.logsumexp(dim=-1))
|
|
belongs = (targets >= start) & (targets < start + w.shape[0])
|
|
selected[belongs] = logits[belongs, targets[belongs] - start]
|
|
ctx.save_for_backward(hidden, targets, log_total)
|
|
ctx.vocabulary = vocabulary
|
|
return (log_total - selected).mean()
|
|
|
|
@staticmethod
|
|
def backward(ctx, gradient):
|
|
hidden, targets, log_total = ctx.saved_tensors
|
|
grad_hidden = torch.zeros_like(hidden)
|
|
for start, w in ctx.vocabulary():
|
|
probs = (F.linear(hidden, w) - log_total[:, None]).exp()
|
|
belongs = (targets >= start) & (targets < start + w.shape[0])
|
|
probs[belongs, targets[belongs] - start] -= 1
|
|
grad_hidden.addmm_(probs, w)
|
|
return grad_hidden * (gradient / hidden.shape[0]), None, None
|
|
|
|
|
|
def language_model_loss(hidden, ids, lengths, vocabulary):
|
|
"""Train on all valid next-token targets, avoiding padding and final positions."""
|
|
positions = torch.arange(ids.shape[1] - 1, device=ids.device)
|
|
valid = positions[None, :] + 1 < lengths[:, None]
|
|
return _FrozenVocabularyCE.apply(hidden[:, :-1][valid], ids[:, 1:][valid], vocabulary)
|