Download src/pat/model.py from ICLRPAT27/PAT-code: direct link, hf CLI and curl.
- Browser
- Download file 12.4 kB
-
https://huggingface.co/ICLRPAT27/PAT-code/resolve/main/src/pat/model.py
- Command line
-
hf download hf://ICLRPAT27/PAT-code/src/pat/model.py
-
curl -L -o model.py https://huggingface.co/ICLRPAT27/PAT-code/resolve/main/src/pat/model.py
12.4 kB
| """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 | |
| 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 | |
| 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, | |
| ) | |
| 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() | |