"""Causal (grouped-query) self-attention on top of torch's scaled_dot_product_attention. SDPA picks the best available backend at runtime (cuDNN / memory-efficient / flash / math); nothing here requires a specific kernel, so CPU and any CUDA build work. """ from __future__ import annotations import torch import torch.nn as nn import torch.nn.functional as F from .config import ModelConfig from .layers import apply_rope class KVCache: """Pre-allocated per-layer key/value buffers stored with n_kv_heads (GQA saves cache memory).""" def __init__(self, cfg: ModelConfig, batch: int, max_len: int, device, dtype): shape = (batch, cfg.n_kv_heads, max_len, cfg.head_dim) self.k = [torch.zeros(shape, device=device, dtype=dtype) for _ in range(cfg.n_layers)] self.v = [torch.zeros(shape, device=device, dtype=dtype) for _ in range(cfg.n_layers)] self.max_len = max_len class Attention(nn.Module): def __init__(self, cfg: ModelConfig): super().__init__() self.n_heads, self.n_kv, self.hd = cfg.n_heads, cfg.n_kv_heads, cfg.head_dim self.wq = nn.Linear(cfg.d_model, cfg.n_heads * cfg.head_dim, bias=False) self.wk = nn.Linear(cfg.d_model, cfg.n_kv_heads * cfg.head_dim, bias=False) self.wv = nn.Linear(cfg.d_model, cfg.n_kv_heads * cfg.head_dim, bias=False) self.wo = nn.Linear(cfg.n_heads * cfg.head_dim, cfg.d_model, bias=False) def forward(self, x, cos, sin, cache: KVCache | None = None, layer: int = 0, start: int = 0) -> torch.Tensor: B, L, _ = x.shape q = self.wq(x).view(B, L, self.n_heads, self.hd).transpose(1, 2) k = self.wk(x).view(B, L, self.n_kv, self.hd).transpose(1, 2) v = self.wv(x).view(B, L, self.n_kv, self.hd).transpose(1, 2) q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin) if cache is not None: cache.k[layer][:, :, start : start + L] = k cache.v[layer][:, :, start : start + L] = v k, v = cache.k[layer][:, :, : start + L], cache.v[layer][:, :, : start + L] if self.n_kv != self.n_heads: # expand KV groups; works with every SDPA backend k = k.repeat_interleave(self.n_heads // self.n_kv, dim=1) v = v.repeat_interleave(self.n_heads // self.n_kv, dim=1) if L == 1: # single decode step attends to the whole cache o = F.scaled_dot_product_attention(q, k, v) elif start == 0: o = F.scaled_dot_product_attention(q, k, v, is_causal=True) else: # chunk appended after a cached prefix: causal w.r.t. absolute positions mask = torch.ones(L, start + L, dtype=torch.bool, device=x.device).tril(diagonal=start) o = F.scaled_dot_product_attention(q, k, v, attn_mask=mask) return self.wo(o.transpose(1, 2).reshape(B, L, -1))