File size: 12,369 Bytes
643267a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 | """Minimal PAT/FA decoder with document-local training and text inference."""
from __future__ import annotations
import math
from collections.abc import Sequence
from dataclasses import dataclass
import torch
from torch import nn
from torch.nn import functional as F
from torch.utils.checkpoint import checkpoint
from .attention import DecoderLayer, MemoryTransition, full_attention
from .config import EOD_ID, PATConfig
from .packing import PackedBatch, pack_pieces
@dataclass
class ModelOutput:
loss_sum: torch.Tensor
token_count: int
lexical_loss_sum: torch.Tensor
lexical_token_count: int
targets: torch.Tensor
logits: torch.Tensor | None = None
@property
def loss(self) -> torch.Tensor:
return self.loss_sum / self.token_count
class PATModel(nn.Module):
"""The fixed publication decoder; ``architecture`` selects PAT or FA."""
def __init__(self, config: PATConfig) -> None:
super().__init__()
self.config = config
self.token_embed = nn.Embedding(config.vocab_size, config.d_model)
self.final_norm = nn.LayerNorm(config.d_model, eps=1e-6)
self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)
self.layers = nn.ModuleList(DecoderLayer(config, i) for i in range(config.n_layers))
self.transitions = nn.ModuleDict(
{
str(i): MemoryTransition(config, i)
for i in range(config.n_layers - 1)
if config.memory_slots[i] != config.memory_slots[i + 1]
}
)
self._initialize()
self.lm_head.weight = self.token_embed.weight
self._components_compiled = False
def _initialize(self) -> None:
for module in self.modules():
if isinstance(module, (nn.Linear, nn.Embedding)):
nn.init.normal_(module.weight, mean=0, std=0.02)
if isinstance(module, nn.Linear) and module.bias is not None:
nn.init.zeros_(module.bias)
elif isinstance(module, nn.LayerNorm):
nn.init.ones_(module.weight)
nn.init.zeros_(module.bias)
scale = 0.02 / math.sqrt(2 * self.config.n_layers)
for layer in self.layers:
nn.init.normal_(layer.out_proj.weight, mean=0, std=scale)
nn.init.normal_(layer.mlp[2].weight, mean=0, std=scale)
def compile_components(self) -> None:
"""Compile projection and feed-forward components used by training."""
if self._components_compiled:
return
self.token_embed.forward = torch.compile(self.token_embed.forward, dynamic=True)
self.final_norm.forward = torch.compile(self.final_norm.forward, dynamic=True)
if self.config.architecture == "FA":
self.lm_head.forward = torch.compile(self.lm_head.forward, dynamic=True)
for index, layer in enumerate(self.layers):
# The first PAT layer preserves explicit low-precision casts; the
# later layers retain the producer's ordinary compiler arithmetic.
options = (
{"emulate_precision_casts": True}
if self.config.architecture == "PAT" and index == 0
else None
)
layer.prepare = torch.compile(layer.prepare, dynamic=True, options=options)
layer.prepare_with_memory = torch.compile(
layer.prepare_with_memory, dynamic=True, fullgraph=True
)
layer.finish = torch.compile(layer.finish, dynamic=True)
for transition in self.transitions.values():
transition.forward = torch.compile(transition.forward, dynamic=True, fullgraph=True)
self._components_compiled = True
def _pat_hidden(self, batch: PackedBatch, physical_hidden: torch.Tensor) -> torch.Tensor:
from .kernels.attention import KernelConfig, attention, bind_plan, materialize_layout
cfg = self.config
kernel = KernelConfig(cfg.chunk_size, cfg.max_memory_size, warps=2)
geometry = batch.geometry(cfg)
signatures = tuple(
(width, cfg.memory_slots[max(0, i - 1)]) for i, width in enumerate(cfg.memory_slots)
)
layouts = {
signature: materialize_layout(
geometry, local_slots=signature[0], global_slots=signature[1], config=kernel
)
for signature in dict.fromkeys(signatures)
}
first = layouts[signatures[0]]
hidden = physical_hidden.index_select(0, first.canonical_order)
lexical_count = first.total_lexical_tokens
previous_summary = None
for index, layer in enumerate(self.layers):
materialized = layouts[signatures[index]]
def run_layer(
current, source, layer=layer, materialized=materialized, first_layer=index == 0
):
positions = materialized.canonical_positions
key_positions = materialized.canonical_key_positions
if first_layer:
query, key, value, _ = layer.prepare(current, positions, key_positions)
memory_key = key.new_empty((0, cfg.n_heads, cfg.head_dim))
memory_value = memory_key
else:
if source.numel() == 0:
combined, start = current, lexical_count
else:
combined, start = torch.cat((current, source), dim=0), current.size(0)
query, key, value, _, memory_key, memory_value = layer.prepare_with_memory(
combined,
positions,
combined[: current.size(0)],
combined[:start],
materialized.layout.memory_positions,
key_positions,
)
plan = bind_plan(
materialized,
heads=cfg.n_heads,
head_dim=cfg.head_dim,
dtype=query.dtype,
config=kernel,
layer_zero=first_layer,
)
context = attention(
q_canonical=query,
k_memory=memory_key,
v_memory=memory_value,
k_token_canonical=key,
v_token_canonical=value,
scale=cfg.head_dim**-0.5,
plan=plan,
)
return layer.finish(current, context, lexical_count)
source = hidden.new_empty((0,)) if previous_summary is None else previous_summary
previous_summary = None
if self.training and torch.is_grad_enabled():
hidden = checkpoint(run_layer, hidden, source, use_reentrant=False)
else:
hidden = run_layer(hidden, source)
if str(index) in self.transitions:
previous_summary = hidden[lexical_count:]
summary = previous_summary.reshape(
geometry.row_count, cfg.memory_slots[index], cfg.d_model
)
transitioned = (
self.transitions[str(index)](summary).reshape(-1, cfg.d_model).to(hidden.dtype)
)
hidden = torch.cat((hidden[:lexical_count], transitioned), dim=0)
return hidden[:lexical_count]
def hidden_states(
self,
pieces: Sequence[torch.Tensor],
document_ends: Sequence[bool] | None = None,
*,
for_inference: bool = False,
):
"""Return final normalized lexical states and their supervision map."""
if self.token_embed.weight.device.type != "cuda":
raise RuntimeError("PAT and FA require CUDA; there is no CPU attention implementation")
self.compile_components()
batch = pack_pieces(
pieces,
self.config,
device=self.token_embed.weight.device,
document_ends=document_ends,
for_inference=for_inference,
)
hidden = self.token_embed(batch.token_ids)
if self.config.architecture == "PAT":
hidden = self._pat_hidden(batch, hidden)
else:
positions = torch.cat(
[torch.arange(length, device=hidden.device) for length in batch.piece_lengths]
)
for layer in self.layers:
def run_layer(current, layer=layer):
query, key, value, _ = layer.prepare(current, positions, positions)
context = full_attention(
query, key, value, batch.piece_lengths, self.config.context_length
)
return layer.finish(current, context, current.size(0))
if self.training and torch.is_grad_enabled():
hidden = checkpoint(run_layer, hidden, use_reentrant=False)
else:
hidden = run_layer(hidden)
return self.final_norm(hidden), batch
def forward(
self,
pieces: Sequence[torch.Tensor],
document_ends: Sequence[bool] | None = None,
return_logits: bool = False,
) -> ModelOutput:
hidden, batch = self.hidden_states(pieces, document_ends)
if not batch.token_count:
raise ValueError("training needs at least one target token")
selected = hidden.index_select(0, batch.source_indices)
if self.config.architecture == "PAT" and self.training:
from .losses import pat_training_loss
loss_sum, lexical_sum = pat_training_loss(selected, self.lm_head.weight, batch.targets)
logits = None
if return_logits:
logits = torch.cat(
[
self.lm_head(selected[start : start + self.config.ce_chunk_size])
for start in range(0, batch.token_count, self.config.ce_chunk_size)
]
)
return ModelOutput(
loss_sum,
batch.token_count,
lexical_sum,
batch.lexical_token_count,
batch.targets,
logits,
)
logits_parts = []
loss_sum = selected.new_zeros((), dtype=torch.float32)
lexical_loss_sum = loss_sum.detach().clone()
for start in range(0, batch.token_count, self.config.ce_chunk_size):
states = selected[start : start + self.config.ce_chunk_size]
labels = batch.targets[start : start + self.config.ce_chunk_size]
def loss_chunk(states, labels):
logits = self.lm_head(states)
losses = F.cross_entropy(logits, labels, reduction="none")
return losses.sum(), losses[labels.ne(EOD_ID)].sum()
if torch.is_grad_enabled():
summed, lexical = checkpoint(loss_chunk, states, labels, use_reentrant=False)
else:
summed, lexical = loss_chunk(states, labels)
loss_sum = loss_sum + summed
lexical_loss_sum = lexical_loss_sum + lexical.detach()
if return_logits:
logits_parts.append(self.lm_head(states))
return ModelOutput(
loss_sum,
batch.token_count,
lexical_loss_sum,
batch.lexical_token_count,
batch.targets,
torch.cat(logits_parts) if return_logits else None,
)
@torch.no_grad()
def next_token_logits(self, tokens: torch.Tensor) -> torch.Tensor:
"""Teacher-forced diagnostic using the compiled training arithmetic.
Use ``pat.generate.generate`` or ``pat.inference.create_cache`` for
text generation. Cached decoding preserves the original inference
arithmetic, which can differ near chunk boundaries from this full-
prefix diagnostic. No artificial document end is appended here.
"""
if tokens.numel() and bool(tokens.eq(EOD_ID).any().item()):
raise ValueError("a generation prefix must be an open document without EOD")
hidden, _ = self.hidden_states([tokens], document_ends=[False], for_inference=True)
return self.lm_head(hidden[-1]).float()
|