"""Single-document cached decoding with each model's fixed attention path. Use caches under ``torch.inference_mode()`` and CUDA BF16 autocast. The cache capacity counts BOS as well as content tokens; exceeding it is an error. """ from __future__ import annotations from dataclasses import dataclass from typing import TYPE_CHECKING import torch from torch.nn import functional as F from torch.nn.attention import SDPBackend, sdpa_kernel from .config import BOS_ID, EOD_ID if TYPE_CHECKING: from .model import PATModel def _attention(query, key, value, *, causal: bool): """Prefill attends causally; a newly appended query sees its entire prefix.""" query = query.permute(1, 0, 2).unsqueeze(0) key = key.permute(1, 0, 2).unsqueeze(0) value = value.permute(1, 0, 2).unsqueeze(0) with sdpa_kernel(SDPBackend.FLASH_ATTENTION): output = F.scaled_dot_product_attention( query, key, value, dropout_p=0.0, is_causal=causal ) return output.squeeze(0).permute(1, 0, 2).contiguous() @dataclass class FACache: """One FA document's projected key/value history and next-token logits.""" model: PATModel keys: list[torch.Tensor] values: list[torch.Tensor] token_count: int capacity: int next_token_logits: torch.Tensor @classmethod def prefill(cls, model: PATModel, prompt_ids, *, capacity: int) -> FACache: """Encode BOS plus a nonempty text prefix, retaining every layer's KV.""" if model.config.architecture != "FA": raise ValueError("FACache requires an FA checkpoint") device = model.token_embed.weight.device if device.type != "cuda": raise RuntimeError("FA cached decoding requires CUDA FlashAttention") prompt = torch.as_tensor(prompt_ids, device=device) if prompt.ndim != 1 or prompt.dtype not in {torch.int32, torch.int64}: raise ValueError("The prompt must be a one-dimensional integer token sequence") if not prompt.numel() or bool(((prompt < 0) | (prompt >= EOD_ID)).any().item()): raise ValueError("The prompt must contain nonempty text without document or packing markers") token_count = prompt.numel() + 1 if type(capacity) is not int or not token_count <= capacity <= model.config.context_length: raise ValueError("Cache capacity must fit BOS and the prompt within context_length") tokens = torch.cat((prompt.new_tensor([BOS_ID]), prompt)).to(dtype=torch.long) positions = torch.arange(token_count, dtype=torch.long, device=device) # Inference has fixed eager projection arithmetic. Calling the class # methods also preserves it if this model was compiled for training. hidden = type(model.token_embed).forward(model.token_embed, tokens) keys, values = [], [] for layer in model.layers: query, key, value, _ = type(layer).prepare(layer, hidden, positions, positions) context = _attention(query, key, value, causal=True) hidden = type(layer).finish(layer, hidden, context, hidden.size(0)) key_cache = key.new_empty((capacity, *key.shape[1:])) value_cache = value.new_empty((capacity, *value.shape[1:])) key_cache[:token_count].copy_(key) value_cache[:token_count].copy_(value) keys.append(key_cache) values.append(value_cache) normalized = type(model.final_norm).forward(model.final_norm, hidden[-1]) logits = type(model.lm_head).forward(model.lm_head, normalized).detach().contiguous() return cls(model, keys, values, token_count, capacity, logits) def append(self, token_id: int) -> torch.Tensor: """Encode one new text token and return its next-token prediction.""" if type(token_id) is not int or not 0 <= token_id < EOD_ID: raise ValueError("Append requires one text token; stop generation when EOD is selected") if self.token_count >= self.capacity: raise ValueError("FA cache capacity exhausted") device = self.model.token_embed.weight.device token = torch.tensor([token_id], dtype=torch.long, device=device) position = torch.tensor([self.token_count], dtype=torch.long, device=device) hidden = type(self.model.token_embed).forward(self.model.token_embed, token) for index, layer in enumerate(self.model.layers): query, key, value, _ = type(layer).prepare(layer, hidden, position, position) self.keys[index][self.token_count : self.token_count + 1].copy_(key) self.values[index][self.token_count : self.token_count + 1].copy_(value) context = _attention( query, self.keys[index][: self.token_count + 1], self.values[index][: self.token_count + 1], causal=False, ) hidden = type(layer).finish(layer, hidden, context, hidden.size(0)) self.token_count += 1 normalized = type(self.model.final_norm).forward(self.model.final_norm, hidden[-1]) self.next_token_logits = ( type(self.model.lm_head).forward(self.model.lm_head, normalized).detach().contiguous() ) return self.next_token_logits def create_cache(model: PATModel, prompt_ids, capacity: int): """Prefill the fixed PAT or FA cache selected by the checkpoint geometry.""" if model.config.architecture == "FA": return FACache.prefill(model, prompt_ids, capacity=capacity) from .pat_cache import PATCache return PATCache.prefill(model, prompt_ids, capacity=capacity)