-
-
Save oniani/c8a346c59b2330869febc4c9c36b45fb to your computer and use it in GitHub Desktop.
Pretraining a GPT-Style Autoregressive Transformer from Scratch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| import string | |
| from dataclasses import dataclass | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| import urllib.request | |
| class CharacterLevelTokenizer: | |
| """A character-level tokenizer that treats individual characters as tokens.""" | |
| def __init__(self, text: str = string.printable) -> None: | |
| """Builds the vocabulary from the given text.""" | |
| self.vocab: list[str] = sorted(set(text)) | |
| self.vocab_size: int = len(self.vocab) | |
| self.char_to_token: dict[str, int] = {char: idx for idx, char in enumerate(self.vocab)} | |
| def encode(self, text: str) -> list[int]: | |
| """Converts a string into a list of token IDs.""" | |
| return [self.char_to_token[char] for char in text] | |
| def decode(self, token_ids: list[int]) -> str: | |
| """Converts a list of token IDs back into a string.""" | |
| return "".join(self.vocab[token_id] for token_id in token_ids) | |
| @dataclass(frozen=True) # We like our dataclasses frozen! | |
| class Config: | |
| """Transformer config.""" | |
| vocab_size: int # Tokenizer vocabulary size | |
| block_size: int # Max sequence length (context window) | |
| n_layer: int # Number of transformer layers | |
| n_head: int # Attention heads per layer | |
| n_embd: int # Embedding dimension (must be divisible by `n_head`) | |
| dropout: float # Dropout probability | |
| bias: bool # Whether `nn.Linear` and `nn.LayerNorm` use bias | |
| @property | |
| def head_size(self) -> int: | |
| """Returns the per-head dimension (embedding is split evenly across attention heads).""" | |
| return self.n_embd // self.n_head | |
| class Transformer(nn.Module): | |
| """Autoregressive transformer language model.""" | |
| def __init__(self, cfg: Config) -> None: | |
| """Initializes the building blocks of the transformer.""" | |
| super().__init__() | |
| self.block_size = cfg.block_size | |
| self.tok_emb_table = nn.Embedding(cfg.vocab_size, cfg.n_embd) | |
| self.pos_emb_table = nn.Embedding(cfg.block_size, cfg.n_embd) | |
| self.blocks = nn.Sequential(*[Block(cfg) for _ in range(cfg.n_layer)]) | |
| self.ln = nn.LayerNorm(cfg.n_embd, bias=cfg.bias) | |
| self.proj = nn.Linear(cfg.n_embd, cfg.vocab_size) | |
| # Weight tying: reduces the total number of parameters without degrading accuracy | |
| # Reference: https://arxiv.org/abs/1608.05859 | |
| self.proj.weight = self.tok_emb_table.weight | |
| def forward(self, token_ids: torch.Tensor, targets: torch.Tensor | None = None) -> tuple: | |
| """Computes logits and optional loss.""" | |
| B, T = token_ids.shape | |
| tok_emb = self.tok_emb_table(token_ids) | |
| pos_emb = self.pos_emb_table(torch.arange(T, device=token_ids.device)) | |
| emb = tok_emb + pos_emb | |
| out = self.ln(self.blocks(emb)) | |
| if targets is None: | |
| logits = self.proj(out[:, [-1], :]) # Last-token projection with time dimension | |
| loss = None | |
| else: | |
| logits = self.proj(out) | |
| loss = F.cross_entropy(logits.view(B * T, -1), targets.view(-1)) | |
| return logits, loss | |
| @torch.no_grad() | |
| def generate( | |
| self, | |
| token_ids: torch.Tensor, | |
| max_new_token_ids: int, | |
| temperature: float = 0.7, | |
| top_k: int | None = None, | |
| ) -> torch.Tensor: | |
| """Generates tokens IDs autoregressively.""" | |
| self.eval() | |
| for _ in range(max_new_token_ids): | |
| logits, _ = self(token_ids[:, -self.block_size :]) | |
| logits = logits[:, -1, :] / temperature | |
| if top_k is not None: | |
| k = min(top_k, logits.size(-1)) | |
| threshold = torch.topk(logits, k).values[:, [-1]] | |
| logits[logits < threshold] = -float("inf") | |
| probs = torch.softmax(logits, dim=-1) | |
| next_token = torch.multinomial(probs, num_samples=1) | |
| token_ids = torch.cat((token_ids, next_token), dim=1) | |
| return token_ids | |
| class AttentionHead(nn.Module): | |
| """A single causal self-attention head.""" | |
| def __init__(self, cfg: Config) -> None: | |
| """Initializes QKV projection and dropout, and cache causal mask to avoid recomputing it.""" | |
| super().__init__() | |
| self.qkv = nn.Linear(cfg.n_embd, 3 * cfg.head_size, bias=cfg.bias) | |
| self.dropout = nn.Dropout(cfg.dropout) | |
| self.register_buffer("mask", torch.tril(torch.ones(cfg.block_size, cfg.block_size))) | |
| def forward(self, x: torch.Tensor) -> torch.Tensor: | |
| """Computes masked single-head self-attention for the input tensor.""" | |
| _, T, D = x.shape | |
| q, k, v = self.qkv(x).split(self.qkv.out_features // 3, dim=-1) | |
| attn_scores = q @ k.transpose(-2, -1) | |
| attn_scores = attn_scores * D**-0.5 # Prevent softmax from blowing up | |
| attn_scores = attn_scores.masked_fill(self.mask[:T, :T] == 0, float("-inf")) # Mask future tokens | |
| attn_weights = torch.softmax(attn_scores, dim=-1) | |
| attn_weights = self.dropout(attn_weights) | |
| return attn_weights @ v | |
| class MultiHeadAttention(nn.Module): | |
| """A Multi-Head Attention (MHA).""" | |
| def __init__(self, cfg: Config) -> None: | |
| """Initializes multi-head self-attention with output projection and dropout.""" | |
| super().__init__() | |
| self.heads = nn.ModuleList([AttentionHead(cfg) for _ in range(cfg.n_head)]) | |
| self.proj = nn.Linear(cfg.n_embd, cfg.n_embd) | |
| self.dropout = nn.Dropout(cfg.dropout) | |
| def forward(self, x: torch.Tensor) -> torch.Tensor: | |
| """Computes masked multi-head self-attention for the input tensor.""" | |
| out = torch.cat([head(x) for head in self.heads], dim=-1) | |
| out = self.dropout(self.proj(out)) | |
| return out | |
| class Block(nn.Module): | |
| """Transformer block.""" | |
| def __init__(self, cfg: Config) -> None: | |
| """Initializes a transformer block.""" | |
| super().__init__() | |
| self.ln1 = nn.LayerNorm(cfg.n_embd, bias=cfg.bias) | |
| self.mha = MultiHeadAttention(cfg) | |
| self.ln2 = nn.LayerNorm(cfg.n_embd, bias=cfg.bias) | |
| self.mlp = nn.Sequential( | |
| nn.Linear(cfg.n_embd, 2 * cfg.n_embd, bias=cfg.bias), # Flexible: can change to e.g. `4 * cfg.n_embd` | |
| nn.GELU(), | |
| nn.Linear(2 * cfg.n_embd, cfg.n_embd, bias=cfg.bias), | |
| nn.Dropout(cfg.dropout), | |
| ) | |
| def forward(self, x: torch.Tensor) -> torch.Tensor: | |
| """Performs a forward pass: attention + MLP with residuals and layer norms.""" | |
| x = x + self.mha(self.ln1(x)) | |
| x = x + self.mlp(self.ln2(x)) | |
| return x | |
| def sample_batch(data: torch.Tensor, batch_size: int, block_size: int) -> tuple: | |
| """Randomly samples training sequences for Next-Token Prediction (NTP).""" | |
| idxs = torch.randint(len(data) - block_size, (batch_size,)) # Random starting positions | |
| token_ids = torch.stack([data[idx : idx + block_size] for idx in idxs]) # Input sequences | |
| targets = torch.stack([data[idx + 1 : idx + block_size + 1] for idx in idxs]) # Same sequences shifted by +1 (NTP) | |
| return token_ids, targets | |
| with urllib.request.urlopen("https://www.gutenberg.org/cache/epub/84/pg84.txt") as f: # Read Frankenstein | |
| text = f.read().decode("utf-8") | |
| tokenizer = CharacterLevelTokenizer(text) | |
| device = torch.device("cuda:0" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu") | |
| cfg = Config(vocab_size=tokenizer.vocab_size, block_size=32, n_layer=4, n_head=4, n_embd=64, dropout=0.0, bias=False) | |
| max_steps, log_interval, batch_size, learning_rate = 2_000, 10, 256, 1e-3 | |
| data = torch.tensor(tokenizer.encode(text), device=device) | |
| model = Transformer(cfg).to(device).train() | |
| n_params, adamw_params, muon_params = 0, [], [] | |
| for param in model.parameters(): | |
| n_params += param.numel() | |
| (adamw_params if param.ndim < 2 else muon_params).append(param) | |
| print(f"Model parameters: {n_params:,}\n") | |
| adamw = torch.optim.AdamW(adamw_params, lr=3e-4, betas=(0.9, 0.95), eps=1e-8, weight_decay=0.01) | |
| muon = torch.optim.Muon(muon_params, lr=0.02, momentum=0.95, weight_decay=0.1) | |
| for step in range(1, max_steps + 1): | |
| token_ids, targets = sample_batch(data, batch_size, cfg.block_size) | |
| adamw.zero_grad() | |
| muon.zero_grad() | |
| _, loss = model(token_ids, targets) | |
| loss.backward() | |
| adamw.step() | |
| muon.step() | |
| if step % log_interval == 0: | |
| print(f"\rStep {step}/{max_steps} ({step / max_steps:.2%}) | Loss: {loss.item():.4f} ", end="", flush=True) | |
| # Seed the model with the prompt "I am" to kick off text generation | |
| token_ids = torch.tensor(tokenizer.encode("I am"), device=device).reshape(1, -1) | |
| output = model.generate(token_ids, max_new_token_ids=512)[0] | |
| print(f"\n\nOUTPUT:\n\n{tokenizer.decode(output.tolist())}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment