Download modeling_tiny_gpt.py from 12somyasahu/tiny-gpt-from-scratch: direct link, hf CLI and curl.
- Browser
- Download file 8.16 kB
-
https://huggingface.co/12somyasahu/tiny-gpt-from-scratch/resolve/main/modeling_tiny_gpt.py
- Command line
-
hf download hf://12somyasahu/tiny-gpt-from-scratch/modeling_tiny_gpt.py
-
curl -L -o modeling_tiny_gpt.py https://huggingface.co/12somyasahu/tiny-gpt-from-scratch/resolve/main/modeling_tiny_gpt.py
8.16 kB
| """Standalone loader, BPE tokenizer, and TinyGPT model for the Hugging Face release.""" | |
| from __future__ import annotations | |
| from dataclasses import dataclass | |
| import json | |
| import math | |
| from pathlib import Path | |
| import re | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| PRETOKEN_RE = re.compile(r" ?[A-Za-z]+| ?[0-9]+| ?[^\sA-Za-z0-9]+|\s+") | |
| EOS_TOKEN = "<|endoftext|>" | |
| def _merge_tuple(seq: tuple[int, ...], pair: tuple[int, int], new_id: int) -> tuple[int, ...]: | |
| out: list[int] = [] | |
| i = 0 | |
| n = len(seq) | |
| a, b = pair | |
| while i < n: | |
| if i + 1 < n and seq[i] == a and seq[i + 1] == b: | |
| out.append(new_id) | |
| i += 2 | |
| else: | |
| out.append(seq[i]) | |
| i += 1 | |
| return tuple(out) | |
| class BPETokenizer: | |
| """Byte-level BPE tokenizer.""" | |
| def __init__(self, merges: dict[tuple[int, int], int], vocab_size: int = 4096) -> None: | |
| self.eos_token = EOS_TOKEN | |
| self.eos_id = 256 | |
| self.vocab_size = vocab_size | |
| self.merges = merges | |
| self.vocab: dict[int, bytes] = {i: bytes([i]) for i in range(256)} | |
| self.vocab[self.eos_id] = self.eos_token.encode("utf-8") | |
| for (a, b), new_id in sorted(self.merges.items(), key=lambda kv: kv[1]): | |
| self.vocab[new_id] = self.vocab[a] + self.vocab[b] | |
| def _encode_chunk(self, chunk_bytes: bytes) -> tuple[int, ...]: | |
| ids = tuple(chunk_bytes) | |
| while len(ids) >= 2: | |
| best_pair: tuple[int, int] | None = None | |
| best_rank = float("inf") | |
| for i in range(len(ids) - 1): | |
| p = (ids[i], ids[i + 1]) | |
| rank = self.merges.get(p) | |
| if rank is not None and rank < best_rank: | |
| best_rank = rank | |
| best_pair = p | |
| if best_pair is None: | |
| break | |
| ids = _merge_tuple(ids, best_pair, int(best_rank)) | |
| return ids | |
| def encode(self, text: str) -> list[int]: | |
| if not text: | |
| return [] | |
| tokens: list[int] = [] | |
| parts = text.split(self.eos_token) | |
| for part_idx, part in enumerate(parts): | |
| if part: | |
| for chunk in PRETOKEN_RE.findall(part): | |
| tokens.extend(self._encode_chunk(chunk.encode("utf-8"))) | |
| if part_idx < len(parts) - 1: | |
| tokens.append(self.eos_id) | |
| return tokens | |
| def decode(self, ids: list[int], skip_special_tokens: bool = False) -> str: | |
| raw_bytes = bytearray() | |
| for idx in ids: | |
| if skip_special_tokens and idx == self.eos_id: | |
| continue | |
| raw_bytes.extend(self.vocab.get(int(idx), b"")) | |
| return raw_bytes.decode("utf-8", errors="replace") | |
| def load(cls, path: str | Path) -> "BPETokenizer": | |
| payload = json.loads(Path(path).read_text(encoding="utf-8")) | |
| merges = {(int(a), int(b)): int(new_id) for a, b, new_id in payload["merges"]} | |
| return cls(merges=merges, vocab_size=int(payload["vocab_size"])) | |
| class ModelConfig: | |
| vocab_size: int = 4096 | |
| context_length: int = 256 | |
| n_layer: int = 6 | |
| n_head: int = 6 | |
| n_embd: int = 384 | |
| dropout: float = 0.1 | |
| class CausalSelfAttention(nn.Module): | |
| def __init__(self, cfg: ModelConfig) -> None: | |
| super().__init__() | |
| self.n_head = cfg.n_head | |
| self.n_embd = cfg.n_embd | |
| self.head_dim = cfg.n_embd // cfg.n_head | |
| self.c_attn = nn.Linear(cfg.n_embd, 3 * cfg.n_embd, bias=False) | |
| self.c_proj = nn.Linear(cfg.n_embd, cfg.n_embd, bias=False) | |
| self.attn_dropout = nn.Dropout(cfg.dropout) | |
| self.resid_dropout = nn.Dropout(cfg.dropout) | |
| mask = torch.tril(torch.ones(cfg.context_length, cfg.context_length)) | |
| self.register_buffer("causal_mask", mask.view(1, 1, cfg.context_length, cfg.context_length)) | |
| def forward(self, x: torch.Tensor) -> torch.Tensor: | |
| B, T, C = x.shape | |
| q, k, v = self.c_attn(x).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) | |
| att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(self.head_dim)) | |
| att = att.masked_fill(self.causal_mask[:, :, :T, :T] == 0, float("-inf")) | |
| att = self.attn_dropout(F.softmax(att, dim=-1)) | |
| y = (att @ v).transpose(1, 2).contiguous().view(B, T, C) | |
| return self.resid_dropout(self.c_proj(y)) | |
| class MLP(nn.Module): | |
| def __init__(self, cfg: ModelConfig) -> None: | |
| super().__init__() | |
| self.c_fc = nn.Linear(cfg.n_embd, 4 * cfg.n_embd, bias=False) | |
| self.c_proj = nn.Linear(4 * cfg.n_embd, cfg.n_embd, bias=False) | |
| self.dropout = nn.Dropout(cfg.dropout) | |
| def forward(self, x: torch.Tensor) -> torch.Tensor: | |
| return self.dropout(self.c_proj(F.gelu(self.c_fc(x), approximate="tanh"))) | |
| class TransformerBlock(nn.Module): | |
| def __init__(self, cfg: ModelConfig) -> None: | |
| super().__init__() | |
| self.ln_1 = nn.LayerNorm(cfg.n_embd) | |
| self.attn = CausalSelfAttention(cfg) | |
| self.ln_2 = nn.LayerNorm(cfg.n_embd) | |
| self.mlp = MLP(cfg) | |
| def forward(self, x: torch.Tensor) -> torch.Tensor: | |
| x = x + self.attn(self.ln_1(x)) | |
| x = x + self.mlp(self.ln_2(x)) | |
| return x | |
| class TinyGPT(nn.Module): | |
| def __init__(self, cfg: ModelConfig) -> None: | |
| super().__init__() | |
| self.cfg = cfg | |
| self.wte = nn.Embedding(cfg.vocab_size, cfg.n_embd) | |
| self.wpe = nn.Embedding(cfg.context_length, cfg.n_embd) | |
| self.drop = nn.Dropout(cfg.dropout) | |
| self.blocks = nn.ModuleList([TransformerBlock(cfg) for _ in range(cfg.n_layer)]) | |
| self.ln_f = nn.LayerNorm(cfg.n_embd) | |
| self.lm_head = nn.Linear(cfg.n_embd, cfg.vocab_size, bias=False) | |
| self.wte.weight = self.lm_head.weight | |
| def forward(self, idx: torch.Tensor) -> torch.Tensor: | |
| B, T = idx.shape | |
| pos = torch.arange(0, T, dtype=torch.long, device=idx.device) | |
| x = self.drop(self.wte(idx) + self.wpe(pos)) | |
| for block in self.blocks: | |
| x = block(x) | |
| return self.lm_head(self.ln_f(x)) | |
| def generate( | |
| self, | |
| idx: torch.Tensor, | |
| max_new_tokens: int, | |
| temperature: float = 0.8, | |
| top_k: int | None = 40, | |
| eos_id: int | None = 256, | |
| ) -> torch.Tensor: | |
| self.eval() | |
| for _ in range(max_new_tokens): | |
| logits = self(idx[:, -self.cfg.context_length :])[:, -1, :] | |
| if temperature <= 0.0: | |
| next_id = torch.argmax(logits, dim=-1, keepdim=True) | |
| else: | |
| logits = logits / temperature | |
| if top_k is not None and top_k > 0: | |
| k = min(top_k, logits.size(-1)) | |
| top_vals, _ = torch.topk(logits, k) | |
| logits = logits.masked_fill(logits < top_vals[:, [-1]], float("-inf")) | |
| next_id = torch.multinomial(F.softmax(logits, dim=-1), num_samples=1) | |
| idx = torch.cat((idx, next_id), dim=1) | |
| if eos_id is not None and (next_id == eos_id).all(): | |
| break | |
| return idx | |
| def load_from_folder(folder: str | Path, device: str | torch.device = "cpu") -> tuple[TinyGPT, BPETokenizer]: | |
| """Load TinyGPT weights (no optimizer state), config, and BPE tokenizer from a release folder.""" | |
| root = Path(folder) | |
| raw_cfg = json.loads((root / "config.json").read_text(encoding="utf-8")) | |
| cfg = ModelConfig( | |
| vocab_size=raw_cfg["vocab_size"], | |
| context_length=raw_cfg["context_length"], | |
| n_layer=raw_cfg["n_layer"], | |
| n_head=raw_cfg["n_head"], | |
| n_embd=raw_cfg["n_embd"], | |
| dropout=raw_cfg.get("dropout", 0.1), | |
| ) | |
| model = TinyGPT(cfg).to(device) | |
| state_dict = torch.load(root / "model.pt", map_location=device, weights_only=True) | |
| model.load_state_dict(state_dict) | |
| model.eval() | |
| tokenizer = BPETokenizer.load(root / "tokenizer.json") | |
| return model, tokenizer | |