"""A tiny word/punctuation-level causal Transformer used for Victus research experiments.""" from __future__ import annotations import torch from torch import nn class VictusTinyLM(nn.Module): def __init__( self, vocab_size: int, block_size: int = 128, d_model: int = 96, n_heads: int = 4, n_layers: int = 3, dropout: float = 0.08, ) -> None: super().__init__() if d_model % n_heads != 0: raise ValueError("d_model must be divisible by n_heads") self.block_size = block_size self.token_embedding = nn.Embedding(vocab_size, d_model) self.position_embedding = nn.Embedding(block_size, d_model) layer = nn.TransformerEncoderLayer( d_model=d_model, nhead=n_heads, dim_feedforward=d_model * 4, dropout=dropout, activation="gelu", batch_first=True, norm_first=True, ) self.transformer = nn.TransformerEncoder( layer, num_layers=n_layers, enable_nested_tensor=False, ) self.final_norm = nn.LayerNorm(d_model) self.lm_head = nn.Linear(d_model, vocab_size, bias=False) self.apply(self._init_weights) @staticmethod def _init_weights(module: nn.Module) -> None: if isinstance(module, (nn.Linear, nn.Embedding)): nn.init.normal_(module.weight, mean=0.0, std=0.02) if isinstance(module, nn.Linear) and module.bias is not None: nn.init.zeros_(module.bias) def forward(self, token_ids: torch.Tensor) -> torch.Tensor: _, length = token_ids.shape if length > self.block_size: raise ValueError(f"Sequence length {length} exceeds block size {self.block_size}") positions = torch.arange(length, device=token_ids.device) x = self.token_embedding(token_ids) + self.position_embedding(positions)[None, :, :] # True entries are masked, so each position can only attend to itself and the past. causal_mask = torch.triu( torch.ones(length, length, dtype=torch.bool, device=token_ids.device), diagonal=1, ) x = self.transformer(x, mask=causal_mask, is_causal=True) return self.lm_head(self.final_norm(x)) @torch.no_grad() def generate( self, token_ids: torch.Tensor, max_new_tokens: int = 180, temperature: float = 0.8, top_k: int = 30, ) -> torch.Tensor: if temperature <= 0: raise ValueError("temperature must be greater than zero") self.eval() for _ in range(max_new_tokens): context = token_ids[:, -self.block_size :] logits = self(context)[:, -1, :] / temperature if top_k > 0: k = min(top_k, logits.shape[-1]) threshold = torch.topk(logits, k).values[:, [-1]] logits = logits.masked_fill(logits < threshold, float("-inf")) probabilities = torch.softmax(logits, dim=-1) next_token = torch.multinomial(probabilities, num_samples=1) token_ids = torch.cat((token_ids, next_token), dim=1) return token_ids