import json import torch import torch.nn as nn from torch.nn import functional as F class Block(nn.Module): def __init__(self, cfg): super().__init__() n_embd = cfg["n_embd"] self.n_head = cfg["n_head"] self.dropout = cfg["dropout"] self.ln1 = nn.LayerNorm(n_embd) self.qkv = nn.Linear(n_embd, 3 * n_embd) self.proj = nn.Linear(n_embd, n_embd) self.ln2 = nn.LayerNorm(n_embd) self.mlp = nn.Sequential( nn.Linear(n_embd, 4 * n_embd), nn.GELU(), nn.Linear(4 * n_embd, n_embd), nn.Dropout(self.dropout)) self.drop = nn.Dropout(self.dropout) def forward(self, x): B, T, C = x.shape h = self.n_head q, k, v = self.qkv(self.ln1(x)).split(C, dim=2) q = q.view(B, T, h, C // h).transpose(1, 2) k = k.view(B, T, h, C // h).transpose(1, 2) v = v.view(B, T, h, C // h).transpose(1, 2) y = F.scaled_dot_product_attention( q, k, v, is_causal=True, dropout_p=self.dropout if self.training else 0.0) y = y.transpose(1, 2).contiguous().view(B, T, C) x = x + self.drop(self.proj(y)) x = x + self.mlp(self.ln2(x)) return x class TinyGPT(nn.Module): def __init__(self, cfg): super().__init__() self.cfg = cfg self.tok = nn.Embedding(cfg["vocab_size"], cfg["n_embd"]) self.pos = nn.Embedding(cfg["block_size"], cfg["n_embd"]) self.blocks = nn.Sequential(*[Block(cfg) for _ in range(cfg["n_layer"])]) self.ln_f = nn.LayerNorm(cfg["n_embd"]) self.head = nn.Linear(cfg["n_embd"], cfg["vocab_size"]) def forward(self, idx, targets=None): B, T = idx.shape x = self.tok(idx) + self.pos(torch.arange(T, device=idx.device)) logits = self.head(self.ln_f(self.blocks(x))) loss = None if targets is not None: loss = F.cross_entropy( logits.view(-1, self.cfg["vocab_size"]), targets.view(-1)) return logits, loss @torch.no_grad() def generate(self, idx, max_new_tokens, temperature=0.8): for _ in range(max_new_tokens): logits, _ = self(idx[:, -self.cfg["block_size"]:]) probs = F.softmax(logits[:, -1, :] / temperature, dim=-1) idx = torch.cat([idx, torch.multinomial(probs, 1)], dim=1) return idx def load_model(weights_path="tinygpt.pt", device="cpu"): cfg = json.load(open("config.json")) chars = json.load(open("vocab.json"))["chars"] model = TinyGPT(cfg).to(device) sd = torch.load(weights_path, map_location=device) # accept either a plain state_dict or a checkpoint dict that wraps one for key in ("model", "model_state_dict", "state_dict"): if isinstance(sd, dict) and key in sd: sd = sd[key] break model.load_state_dict(sd) model.eval() return model, chars