"""Transformer decoder-only (estilo GPT) para os modelos de 1M a 33M. Escolhas: - pré-norma com RMSNorm, sem bias nas camadas lineares; - posição com RoPE (não gasta parâmetros, ao contrário de embeddings de posição); - MLP com GELU e expansão 4x, para valer a conta 12 x camadas x dim² por bloco; - embeddings de entrada e saída compartilhados (tied), como no TinyStories; - atenção causal com F.scaled_dot_product_attention (usa FlashAttention se houver). """ from __future__ import annotations import json import math from dataclasses import asdict, dataclass from pathlib import Path import torch import torch.nn as nn import torch.nn.functional as F @dataclass class GPTConfig: name: str = "custom" vocab_size: int = 8192 block_size: int = 1024 n_layer: int = 8 n_head: int = 4 n_embd: int = 256 dropout: float = 0.0 rope_theta: float = 10000.0 # hiperparâmetros de treino sugeridos (lidos pelo 05_pretrain.py) lr: float = 1e-3 @classmethod def load(cls, path: str | Path) -> "GPTConfig": d = json.loads(Path(path).read_text(encoding="utf-8")) return cls(**{k: v for k, v in d.items() if k in cls.__dataclass_fields__}) def to_dict(self) -> dict: return asdict(self) class RMSNorm(nn.Module): def __init__(self, dim: int, eps: float = 1e-6): super().__init__() self.eps = eps self.weight = nn.Parameter(torch.ones(dim)) def forward(self, x): return x * torch.rsqrt(x.float().pow(2).mean(-1, keepdim=True) + self.eps).type_as(x) * self.weight def rope_cache(seq_len: int, head_dim: int, theta: float, device=None): inv = 1.0 / (theta ** (torch.arange(0, head_dim, 2, device=device).float() / head_dim)) t = torch.arange(seq_len, device=device).float() freqs = torch.outer(t, inv) # (T, hd/2) return freqs.cos(), freqs.sin() def apply_rope(x, cos, sin): # x: (B, H, T, hd) x1, x2 = x[..., 0::2], x[..., 1::2] cos, sin = cos[None, None, : x.size(2)], sin[None, None, : x.size(2)] out = torch.stack((x1 * cos - x2 * sin, x1 * sin + x2 * cos), dim=-1) return out.flatten(-2).type_as(x) class Attention(nn.Module): def __init__(self, cfg: GPTConfig): super().__init__() assert cfg.n_embd % cfg.n_head == 0 self.n_head = cfg.n_head self.qkv = nn.Linear(cfg.n_embd, 3 * cfg.n_embd, bias=False) self.proj = nn.Linear(cfg.n_embd, cfg.n_embd, bias=False) self.dropout = cfg.dropout def forward(self, x, cos, sin): B, T, C = x.shape q, k, v = self.qkv(x).split(C, dim=2) q, k, v = (t.view(B, T, self.n_head, C // self.n_head).transpose(1, 2) for t in (q, k, v)) q, k = apply_rope(q, cos, sin), apply_rope(k, cos, sin) y = F.scaled_dot_product_attention(q, k, v, is_causal=True, dropout_p=self.dropout if self.training else 0.0) return self.proj(y.transpose(1, 2).contiguous().view(B, T, C)) class MLP(nn.Module): def __init__(self, cfg: GPTConfig): super().__init__() self.fc = nn.Linear(cfg.n_embd, 4 * cfg.n_embd, bias=False) self.proj = nn.Linear(4 * cfg.n_embd, cfg.n_embd, bias=False) self.drop = nn.Dropout(cfg.dropout) def forward(self, x): return self.drop(self.proj(F.gelu(self.fc(x)))) class Block(nn.Module): def __init__(self, cfg: GPTConfig): super().__init__() self.ln1, self.attn = RMSNorm(cfg.n_embd), Attention(cfg) self.ln2, self.mlp = RMSNorm(cfg.n_embd), MLP(cfg) def forward(self, x, cos, sin): x = x + self.attn(self.ln1(x), cos, sin) return x + self.mlp(self.ln2(x)) class GPT(nn.Module): def __init__(self, cfg: GPTConfig): super().__init__() self.cfg = cfg self.wte = nn.Embedding(cfg.vocab_size, cfg.n_embd) self.drop = nn.Dropout(cfg.dropout) self.blocks = nn.ModuleList(Block(cfg) for _ in range(cfg.n_layer)) self.ln_f = RMSNorm(cfg.n_embd) self.lm_head = nn.Linear(cfg.n_embd, cfg.vocab_size, bias=False) self.lm_head.weight = self.wte.weight # tied embeddings cos, sin = rope_cache(cfg.block_size, cfg.n_embd // cfg.n_head, cfg.rope_theta) self.register_buffer("rope_cos", cos, persistent=False) self.register_buffer("rope_sin", sin, persistent=False) self.apply(self._init) for n, p in self.named_parameters(): # escala residual (GPT-2) if n.endswith("proj.weight"): nn.init.normal_(p, mean=0.0, std=0.02 / math.sqrt(2 * cfg.n_layer)) @staticmethod def _init(m): if isinstance(m, (nn.Linear, nn.Embedding)): nn.init.normal_(m.weight, mean=0.0, std=0.02) def num_params(self, non_embedding: bool = False) -> int: n = sum(p.numel() for p in self.parameters()) # pesos compartilhados contam uma vez return n - self.wte.weight.numel() if non_embedding else n def flops_per_token(self) -> float: """Aproximação de treino (forward + backward): 6N + 12·L·T·d da atenção.""" c = self.cfg return 6 * self.num_params() + 12 * c.n_layer * c.block_size * c.n_embd def forward(self, idx, targets=None, ignore_index: int = -100): T = idx.size(1) assert T <= self.cfg.block_size, f"sequência {T} > block_size {self.cfg.block_size}" x = self.drop(self.wte(idx)) for b in self.blocks: x = b(x, self.rope_cos, self.rope_sin) logits = self.lm_head(self.ln_f(x)) if targets is None: return logits, None loss = F.cross_entropy(logits.float().view(-1, logits.size(-1)), targets.reshape(-1), ignore_index=ignore_index) return logits, loss def configure_optimizer(self, lr: float, weight_decay: float, betas=(0.9, 0.95), device_type="cuda"): decay = [p for p in self.parameters() if p.dim() >= 2] no_decay = [p for p in self.parameters() if p.dim() < 2] groups = [{"params": decay, "weight_decay": weight_decay}, {"params": no_decay, "weight_decay": 0.0}] return torch.optim.AdamW(groups, lr=lr, betas=betas, fused=device_type == "cuda") @torch.no_grad() def generate(self, idx, max_new_tokens: int, temperature: float = 0.8, top_k: int | None = 50, stop_id: int | None = None): for _ in range(max_new_tokens): ctx = idx[:, -self.cfg.block_size:] logits, _ = self(ctx) logits = logits[:, -1, :].float() if temperature <= 0: nxt = logits.argmax(-1, keepdim=True) else: logits = logits / temperature if top_k: v, _ = torch.topk(logits, min(top_k, logits.size(-1))) logits[logits < v[:, [-1]]] = -float("inf") nxt = torch.multinomial(F.softmax(logits, dim=-1), 1) idx = torch.cat((idx, nxt), dim=1) if stop_id is not None and (nxt == stop_id).all(): break return idx def load_checkpoint(path: str | Path, device="cpu") -> tuple[GPT, dict]: ck = torch.load(path, map_location=device, weights_only=False) model = GPT(GPTConfig(**ck["config"])) sd = {k.removeprefix("_orig_mod."): v for k, v in ck["model"].items()} model.load_state_dict(sd) return model.to(device), ck