import math import torch import torch.nn as nn import torch.nn.functional as F class Config: vocab_size = 50257 n_layer = 30 n_head = 25 n_embd = 1600 block_size = 512 dropout = 0.1 bias = True class CausalSelfAttention(nn.Module): def __init__(self, config): super().__init__() assert config.n_embd % config.n_head == 0 self.n_head = config.n_head self.n_embd = config.n_embd self.head_dim = config.n_embd // config.n_head self.dropout = config.dropout self.qkv = nn.Linear(config.n_embd, 3 * config.n_embd, bias=config.bias) self.proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias) self.resid_dropout = nn.Dropout(config.dropout) def forward(self, x): B, T, C = x.shape qkv = self.qkv(x) q, k, v = qkv.split(self.n_embd, dim=2) q = q.view(B, T, self.n_head, self.head_dim).transpose(1, 2) k = k.view(B, T, self.n_head, self.head_dim).transpose(1, 2) v = v.view(B, T, self.n_head, self.head_dim).transpose(1, 2) # Fused, memory-efficient attention (flash-attention-style kernel). # Replaces the old manual QK^T + mask + softmax, which builds the full # attention matrix explicitly and gets memory-expensive fast at this scale. y = F.scaled_dot_product_attention( q, k, v, attn_mask=None, dropout_p=self.dropout if self.training else 0.0, is_causal=True, # handles the causal mask internally, no manual buffer needed ) y = y.transpose(1, 2).contiguous().view(B, T, C) y = self.resid_dropout(self.proj(y)) return y class MLP(nn.Module): def __init__(self, config): super().__init__() self.fc1 = nn.Linear(config.n_embd, 4 * config.n_embd, bias=config.bias) self.act = nn.GELU() self.fc2 = nn.Linear(4 * config.n_embd, config.n_embd, bias=config.bias) self.dropout = nn.Dropout(config.dropout) def forward(self, x): return self.dropout(self.fc2(self.act(self.fc1(x)))) class Block(nn.Module): def __init__(self, config): super().__init__() self.ln1 = nn.LayerNorm(config.n_embd) self.attn = CausalSelfAttention(config) self.ln2 = nn.LayerNorm(config.n_embd) self.mlp = MLP(config) def forward(self, x): x = x + self.attn(self.ln1(x)) x = x + self.mlp(self.ln2(x)) return x class B24GPT(nn.Module): def __init__(self, config): super().__init__() self.config = config self.tok_emb = nn.Embedding(config.vocab_size, config.n_embd) self.pos_emb = nn.Embedding(config.block_size, config.n_embd) self.drop = nn.Dropout(config.dropout) self.blocks = nn.ModuleList([Block(config) for _ in range(config.n_layer)]) self.ln_f = nn.LayerNorm(config.n_embd) self.head = nn.Linear(config.n_embd, config.vocab_size, bias=False) self.tok_emb.weight = self.head.weight self.apply(self._init_weights) def _init_weights(self, module): if isinstance(module, nn.Linear): nn.init.normal_(module.weight, mean=0.0, std=0.02) if module.bias is not None: nn.init.zeros_(module.bias) elif isinstance(module, nn.Embedding): nn.init.normal_(module.weight, mean=0.0, std=0.02) def forward(self, idx, targets=None): B, T = idx.shape assert T <= self.config.block_size, "sequence longer than block_size" pos = torch.arange(0, T, device=idx.device).unsqueeze(0) x = self.drop(self.tok_emb(idx) + self.pos_emb(pos)) for block in self.blocks: x = torch.utils.checkpoint.checkpoint(block, x, use_reentrant=False) \ if self.training else block(x) x = self.ln_f(x) logits = self.head(x) loss = None if targets is not None: loss = F.cross_entropy( logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1 ) return logits, loss def num_params(self): n = sum(p.numel() for p in self.parameters()) n -= self.tok_emb.weight.numel() return n