"""Differentiable Qwen text tail with streamed frozen weights and LiSA sites.""" import math import torch from torch import nn from torch.nn import functional as F from torch.utils.checkpoint import checkpoint from crossqkv.lisa_train import causal_attention from functional.model import PREFIX def weight_chunks(tensor, start, end, rows=512): width = tensor.shape[1] for lo in range(start, end, rows): hi = min(lo + rows, end) yield torch.from_numpy(tensor.read(slice(lo * width, hi * width)).reshape(hi-lo, width)) tensor.evict() class FrozenLinear(torch.autograd.Function): """Read only the requested output rows and stream them again for dX.""" @staticmethod def forward(ctx, hidden, weight, start, end): ctx.weight, ctx.start, ctx.end = weight, start, end return torch.cat([F.linear(hidden, w) for w in weight_chunks(weight, start, end)], dim=-1) @staticmethod def backward(ctx, grad): out = grad.new_zeros((*grad.shape[:-1], ctx.weight.shape[1])) lo = 0 for w in weight_chunks(ctx.weight, ctx.start, ctx.end): hi = lo + len(w) out = out + grad[..., lo:hi] @ w lo = hi return out, None, None, None def rotate(x, theta, fraction): d = int(x.shape[-1] * fraction) inv = theta ** (-torch.arange(0, d, 2, dtype=x.dtype, device=x.device) / d) phase = torch.arange(x.shape[1], dtype=x.dtype, device=x.device)[:, None] * inv angle = torch.cat((phase, phase), dim=-1)[None, :, None, :] a, b = x[..., :d].chunk(2, dim=-1) return torch.cat((x[..., :d] * angle.cos() + torch.cat((-b, a), -1) * angle.sin(), x[..., d:]), dim=-1) def gated_delta(q, k, v, g, beta): q = q * (q.square().sum(-1, keepdim=True) + 1e-6).rsqrt() / math.sqrt(q.shape[-1]) k = k * (k.square().sum(-1, keepdim=True) + 1e-6).rsqrt() state = v.new_zeros(v.shape[0], v.shape[2], k.shape[-1], v.shape[-1]) rows = [] for i in range(v.shape[1]): qt, kt, vt = q[:, i], k[:, i], v[:, i] state = state * g[:, i, :, None, None].exp() delta = (vt - (state * kt.unsqueeze(-1)).sum(-2)) * beta[:, i, :, None] state = state + kt.unsqueeze(-1) * delta.unsqueeze(-2) rows.append((state * qt.unsqueeze(-1)).sum(-2)) return torch.stack(rows, dim=1) class TorchTail(nn.Module): """Inputs start immediately before the first trainable recipient.""" def __init__(self, source_model, start, adapters=None): super().__init__() self.source = source_model self.c = source_model.config self.eps = source_model.eps self.start = start self.adapters = nn.ModuleDict({str(k): v for k, v in (adapters or {}).items()}) self._small = {} def small(self, name): if name not in self._small: self._small[name] = torch.from_numpy(self.source.small(name)) return self._small[name] def linear(self, h, name, start=0, end=None): t = self.source.tensors[PREFIX + name + '.weight'] return FrozenLinear.apply(h, t, start, t.shape[0] if end is None else end) def norm(self, x, name, centered=True): w = self.small(name + '.weight') return x * (x.square().mean(-1, keepdim=True) + self.eps).rsqrt() * (1+w if centered else w) def gate_only(self, h, name): heads, dim = self.c['num_attention_heads'], self.c['head_dim'] return torch.stack([self.linear(h, name+'q_proj', (2*j+1)*dim, (2*j+2)*dim) for j in range(heads)], dim=2) def native_scores(self, q, h, name): c = self.c k = self.linear(h, name+'k_proj').unflatten(-1, (c['num_key_value_heads'], c['head_dim'])) params = c['rope_parameters'] q = rotate(self.norm(q, name+'q_norm'), params['rope_theta'], params['partial_rotary_factor']) k = rotate(self.norm(k, name+'k_norm'), params['rope_theta'], params['partial_rotary_factor']) k = k.repeat_interleave(q.shape[2] // k.shape[2], dim=2) return torch.einsum('bthd,bshd->bhts', q, k) / math.sqrt(q.shape[-1]) def full(self, h, layer, donor, lengths, mode, recipients, keep_teacher): c = self.c heads, kv_heads, dim = c['num_attention_heads'], c['num_key_value_heads'], c['head_dim'] name = f'layers.{layer}.self_attn.' shared = layer in recipients and mode != 'native' if not shared or keep_teacher: packed = self.linear(h, name+'q_proj').unflatten(-1, (heads, 2*dim)) q, gate = packed.chunk(2, dim=-1) if shared: with torch.no_grad(): native = self.native_scores(q, h, name) else: native = self.native_scores(q, h, name) else: gate = self.gate_only(h, name) native = None if not shared: scores = native elif mode == 'direct': scores = donor elif mode == 'lisa': pos = torch.arange(h.shape[1], device=h.device)[None, :] scores = self.adapters[str(layer)](h, donor, pos) elif mode == 'linear': matrix = self.adapters[str(layer)] scores = matrix(donor.permute(0, 2, 3, 1)).permute(0, 3, 1, 2) else: raise ValueError(f'Unknown mode {mode}') v = self.linear(h, name+'v_proj').unflatten(-1, (kv_heads, dim)) out = causal_attention(scores, v, lengths) * gate.sigmoid() return self.linear(out.flatten(-2), name+'o_proj'), scores, native def linear_attention(self, x, layer): p = f'layers.{layer}.linear_attn.' c = self.c kh, vh = c['linear_num_key_heads'], c['linear_num_value_heads'] kd, vd = c['linear_key_head_dim'], c['linear_value_head_dim'] projected = self.linear(x, p+'in_proj_qkv').transpose(1, 2) kernel = self.small(p+'conv1d.weight') convolved = F.conv1d(projected, kernel, padding=kernel.shape[-1]-1, groups=projected.shape[1])[..., :x.shape[1]] q, k, v = F.silu(convolved.transpose(1, 2)).split((kh*kd, kh*kd, vh*vd), dim=-1) q = q.unflatten(-1, (kh, kd)).repeat_interleave(vh//kh, dim=2) k = k.unflatten(-1, (kh, kd)).repeat_interleave(vh//kh, dim=2) v = v.unflatten(-1, (vh, vd)) gate = self.linear(x, p+'in_proj_z').unflatten(-1, (vh, vd)) beta = self.linear(x, p+'in_proj_b').sigmoid() a = self.linear(x, p+'in_proj_a') g = -self.small(p+'A_log').exp() * F.softplus(a + self.small(p+'dt_bias')) out = gated_delta(q, k, v, g, beta) return self.linear((self.norm(out, p+'norm', centered=False)*F.silu(gate)).flatten(-2), p+'out_proj') def forward(self, h, donor, lengths, mode, recipients, keep_teacher=False): side = {} for layer, kind in enumerate(self.c['layer_types'][self.start:], self.start): p = f'layers.{layer}.' n = self.norm(h, p+'input_layernorm') if kind == 'full_attention': out, donor, native = self.full(n, layer, donor, lengths, mode, recipients, keep_teacher) side[layer] = (donor, native) elif torch.is_grad_enabled() and n.requires_grad: out = checkpoint(self.linear_attention, n, layer, use_reentrant=True) else: out = self.linear_attention(n, layer) h = h + out n = self.norm(h, p+'post_attention_layernorm') x = F.silu(self.linear(n, p+'mlp.gate_proj')) * self.linear(n, p+'mlp.up_proj') h = h + self.linear(x, p+'mlp.down_proj') return self.norm(h, 'norm'), side