PAT-code / src /pat /attention.py
ICLRPAT27's picture
Publish reviewed PAT training and inference supplement
643267a verified
Raw History Blame Contribute Delete
8.73 kB
"""Shared decoder layers and the two fixed attention implementations."""
from __future__ import annotations
import math
import torch
from torch import nn
from torch.nn import functional as F
from torch.nn.attention import SDPBackend, sdpa_kernel
from .config import PATConfig
from .rotary import RotaryEmbedding, normalize_key, normalize_query
class SwiGLU(nn.Module):
def forward(self, values: torch.Tensor) -> torch.Tensor:
gate, value = values.chunk(2, dim=-1)
return F.silu(gate) * value
class DecoderLayer(nn.Module):
"""Pre-LayerNorm attention and SwiGLU.
The packed projection stores Q, K, V in that order. Later PAT layers
compute Q only for current rows, and K/V for current and summary sources.
Summary rows skip the feed-forward sublayer. FA keeps its producer's
separate Q/K/V projections, so importing a checkpoint preserves GEMMs.
"""
def __init__(self, config: PATConfig, index: int) -> None:
super().__init__()
width = config.d_model
self.n_heads, self.head_dim = config.n_heads, config.head_dim
self.qk_norm_eps = 1e-6
self.norm1 = nn.LayerNorm(width, eps=1e-6)
self.is_pat = config.architecture == "PAT"
if self.is_pat:
self.qkv_proj = nn.Linear(width, 3 * width)
else:
self.q_proj = nn.Linear(width, width)
self.k_proj = nn.Linear(width, width)
self.v_proj = nn.Linear(width, width)
self.out_proj = nn.Linear(width, width)
self.qk_log_scale = nn.Parameter(
torch.full((config.n_heads,), math.log(config.qk_scale(index)), dtype=torch.float32)
)
self.norm2 = nn.LayerNorm(width, eps=1e-6)
base = round(width * config.ffw_mult_by_layer[index])
inner = max(8, round((2.0 / 3.0) * base / 8) * 8)
self.mlp = nn.Sequential(nn.Linear(width, 2 * inner), SwiGLU(), nn.Linear(inner, width))
self.rope = RotaryEmbedding(config.head_dim)
def prepare(self, hidden, positions, key_positions):
normalized = self.norm1(hidden)
token_count = int(hidden.size(0))
if self.is_pat:
q_projected, k_projected, v_projected = self.qkv_proj(normalized).split(
self.n_heads * self.head_dim, dim=-1
)
q = q_projected.view(token_count, self.n_heads, self.head_dim)
k = k_projected.view(token_count, self.n_heads, self.head_dim)
v = v_projected.view(token_count, self.n_heads, self.head_dim)
else:
q = self.q_proj(normalized).view(token_count, self.n_heads, self.head_dim)
k = self.k_proj(normalized).view(token_count, self.n_heads, self.head_dim)
v = self.v_proj(normalized).view(token_count, self.n_heads, self.head_dim)
raw_key = k
if self.is_pat:
q = self.rope(q, positions)
k = self.rope(k, key_positions)
else:
q, k = self.rope.apply_pair(q, k, positions)
q = normalize_query(q, self.qk_log_scale, self.head_dim, self.qk_norm_eps)
k = normalize_key(k, self.qk_norm_eps)
# Preserve the producer's compile outputs, including the raw key view.
# Removing that view changes saved-intermediate rounding in backward.
return q.contiguous(), k.contiguous(), v.contiguous(), raw_key
def prepare_with_memory(
self, combined, positions, current_marker, memory_marker, memory_positions, key_positions
):
current_tokens = int(current_marker.size(0))
memory_start = int(memory_marker.size(0))
total_tokens = int(combined.size(0))
normalized = self.norm1(combined)
width = self.n_heads * self.head_dim
q_projected = F.linear(
normalized[:current_tokens], self.qkv_proj.weight[:width], self.qkv_proj.bias[:width]
)
kv = F.linear(normalized, self.qkv_proj.weight[width:], self.qkv_proj.bias[width:])
k_projected, v_projected = kv.split(width, dim=-1)
q_raw = q_projected.view(current_tokens, self.n_heads, self.head_dim)
k_raw_all = k_projected.view(total_tokens, self.n_heads, self.head_dim)
value_all = v_projected.view(total_tokens, self.n_heads, self.head_dim)
k_raw = k_raw_all[:current_tokens]
value = value_all[:current_tokens]
query = self.rope(q_raw, positions)
key = self.rope(k_raw, key_positions)
query = normalize_query(query, self.qk_log_scale, self.head_dim, self.qk_norm_eps)
key = normalize_key(key, self.qk_norm_eps)
memory_positions = memory_positions.to(device=k_raw_all.device)
memory_key = self.rope(k_raw_all[memory_start:], memory_positions)
memory_key = normalize_key(memory_key, self.qk_norm_eps)
return (
query.contiguous(),
key.contiguous(),
value.contiguous(),
k_raw,
memory_key.contiguous(),
value_all[memory_start:].contiguous(),
)
def finish(self, residual, context, lexical_tokens):
hidden = residual + self.out_proj(context.reshape(context.size(0), -1)).to(residual.dtype)
if not self.is_pat:
return hidden + self.mlp(self.norm2(hidden))
lexical = hidden[:lexical_tokens]
lexical = lexical + self.mlp(self.norm2(lexical)).to(hidden.dtype)
return torch.cat((lexical, hidden[lexical_tokens:]), dim=0)
class MemoryTransition(nn.Module):
"""Learned interval-overlap map, independent for each attention head."""
def __init__(self, config: PATConfig, boundary: int) -> None:
super().__init__()
fan_in, fan_out = config.memory_slots[boundary : boundary + 2]
source = torch.arange(fan_in, dtype=torch.float64, device="cpu")
target = torch.arange(fan_out, dtype=torch.float64, device="cpu")
overlap = (
torch.minimum((target[:, None] + 1) / fan_out, (source[None, :] + 1) / fan_in)
- torch.maximum(target[:, None] / fan_out, source[None, :] / fan_in)
).clamp_min(0)
matrix = overlap * fan_out
if fan_in > 1:
generator = torch.Generator(device="cpu").manual_seed(
(config.seed + 1_000_003 * (boundary + 1)) % ((1 << 63) - 1)
)
noise = torch.randn(
matrix.shape, generator=generator, dtype=torch.float64, device="cpu"
)
centered = noise - noise.mean(dim=1, keepdim=True)
noise = centered * (
torch.linalg.vector_norm(matrix, dim=1, keepdim=True)
/ torch.linalg.vector_norm(centered, dim=1, keepdim=True)
)
matrix = matrix + 0.01 * noise
self.matrix = nn.Parameter(matrix.float().unsqueeze(0).repeat(config.n_heads, 1, 1))
def forward(self, summaries: torch.Tensor) -> torch.Tensor:
rows, width, features = summaries.shape
groups = self.matrix.size(0)
grouped = summaries.reshape(rows, width, groups, features // groups)
matrix = self.matrix.to(device=summaries.device, dtype=summaries.dtype)
return (
torch.einsum("goi,rigd->rogd", matrix, grouped)
.reshape(rows, self.matrix.size(1), features)
.contiguous()
)
def full_attention(q, k, v, piece_lengths: tuple[int, ...], context_length: int):
"""Piece-local causal FlashAttention, with a fixed sliding window."""
if q.device.type != "cuda":
raise RuntimeError("FA requires CUDA FlashAttention")
if q.dtype not in {torch.float16, torch.bfloat16}:
raise RuntimeError("FA requires BF16 or FP16 autocast")
maximum = max(piece_lengths)
equal = len(set(piece_lengths)) == 1
if equal and maximum <= context_length:
shape = (len(piece_lengths), maximum, q.size(1), q.size(2))
query, key, value = (x.reshape(shape).permute(0, 2, 1, 3) for x in (q, k, v))
with sdpa_kernel(SDPBackend.FLASH_ATTENTION):
result = F.scaled_dot_product_attention(
query, key, value, dropout_p=0.0, is_causal=True
)
return result.permute(0, 2, 1, 3).reshape_as(q).contiguous()
from torch.nn.attention.varlen import varlen_attn
offsets = [0]
for length in piece_lengths:
offsets.append(offsets[-1] + length)
offsets = torch.tensor(offsets, device=q.device, dtype=torch.int32)
window = (context_length - 1, 0) if maximum > context_length else (-1, 0)
return varlen_attn(
q.contiguous(),
k.contiguous(),
v.contiguous(),
offsets,
offsets,
max_q=maximum,
max_k=maximum,
window_size=window,
).contiguous()