LLMs
Simply, a large language model is a function with millions of learned numbers inside it.
Tokenization
The model reads integers, not text so we start from UTF-8 bytes, so ids 0–255 can spell any string in any language. Byte-pair encoding (BPE) then grows the vocabulary: count every adjacent pair of ids, replace the most frequent pair with a new id, and repeat until the vocabulary reaches its target size. Common chunks like the or ing end up as single tokens, so the same text takes fewer, more meaningful steps.
Training produces an ordered list of merges. Encoding replays them on new text, always applying the earliest-learned merge first. Decoding looks up each id's bytes and joins them.
from collections import Counter
def get_pairs(ids):
return Counter(zip(ids, ids[1:]))
def merge(ids, pair, new_id): # replace each occurrence, left to right
out, i = [], 0
while i < len(ids):
if i + 1 < len(ids) and (ids[i], ids[i + 1]) == pair:
out.append(new_id)
i += 2
else:
out.append(ids[i])
i += 1
return out
def train(text, vocab_size):
ids, merges = list(text.encode('utf-8')), {}
for new_id in range(256, vocab_size):
pairs = get_pairs(ids)
if not pairs:
break
pair = max(pairs, key=pairs.get) # most frequent pair
ids = merge(ids, pair, new_id)
merges[pair] = new_id
return merges # {(a, b): new_id}, in the order learned
def encode(text, merges):
ids = list(text.encode('utf-8'))
while len(ids) >= 2:
pairs = get_pairs(ids)
pair = min(pairs, key=lambda p: merges.get(p, float('inf')))
if pair not in merges: # nothing left to merge
break
ids = merge(ids, pair, merges[pair])
return ids
def decode(ids, merges):
vocab = {i: bytes([i]) for i in range(256)}
for (a, b), new_id in merges.items():
vocab[new_id] = vocab[a] + vocab[b]
return b''.join(vocab[i] for i in ids).decode('utf-8', errors='replace')Vocabulary size is a trade-off. More merges mean shorter sequences, but a larger embedding table and rarer tokens that each get less training. Some data needs almost none: chess moves written as 1.e4 e5 2.Nf3 use only 33 distinct characters, so one token per character works fine.
Causal self-attention
Each token emits a query, key and value. scores how much each token attends to the others; dividing by keeps the softmax from saturating. The causal mask sets future positions to . Heads split into slices of size that run in parallel.
import torch
import torch.nn as nn
import torch.nn.functional as F
class Attention(nn.Module):
def __init__(self, d, h):
super().__init__()
self.h = h
self.qkv = nn.Linear(d, 3 * d)
self.out = nn.Linear(d, d)
def forward(self, x): # (B, T, d)
B, T, d = x.shape
q, k, v = self.qkv(x).split(d, dim=-1)
q, k, v = (t.view(B, T, self.h, -1).transpose(1, 2)
for t in (q, k, v)) # (B, h, T, d/h)
att = q @ k.transpose(-2, -1) / (d // self.h) ** 0.5 # (B, h, T, T)
future = torch.triu(torch.ones(T, T, dtype=torch.bool,
device=x.device), diagonal=1)
att = att.masked_fill(future, float('-inf')).softmax(dim=-1)
y = (att @ v).transpose(1, 2).reshape(B, T, d) # merge heads
return self.out(y)Block
Attention mixes information across tokens; the MLP transforms each token on its own, expanding to and back. Normalising before each sublayer and adding a residual keeps gradients flowing through deep stacks.
class Block(nn.Module):
def __init__(self, d, h):
super().__init__()
self.ln1, self.ln2 = nn.LayerNorm(d), nn.LayerNorm(d)
self.attn = Attention(d, h)
self.mlp = nn.Sequential(nn.Linear(d, 4 * d), nn.GELU(),
nn.Linear(4 * d, d))
def forward(self, x):
x = x + self.attn(self.ln1(x))
x = x + self.mlp(self.ln2(x))
return xModel
Embed each token and its position, run blocks, normalise, and project to vocabulary logits.
class GPT(nn.Module):
def __init__(self, vocab, d=256, h=4, layers=4, max_len=512):
super().__init__()
self.max_len = max_len
self.tok = nn.Embedding(vocab, d)
self.pos = nn.Embedding(max_len, d)
self.blocks = nn.Sequential(*[Block(d, h) for _ in range(layers)])
self.ln = nn.LayerNorm(d)
self.head = nn.Linear(d, vocab, bias=False)
def forward(self, idx): # (B, T) token ids
pos = torch.arange(idx.shape[1], device=idx.device)
x = self.tok(idx) + self.pos(pos)
return self.head(self.ln(self.blocks(x))) # (B, T, vocab)Loss
Next-token prediction: position predicts token , so inputs and targets are the same sequence shifted by one.
def loss_fn(model, tokens): # (B, T + 1)
inputs, targets = tokens[:, :-1], tokens[:, 1:]
logits = model(inputs)
return F.cross_entropy(logits.flatten(0, 1), targets.flatten())Generate
Take the logits at the last position, sample, append, repeat. Temperature sharpens the distribution; is greedy decoding.
@torch.no_grad()
def generate(model, idx, n, temperature=1.0):
for _ in range(n):
logits = model(idx[:, -model.max_len:])[:, -1] / temperature
next_id = torch.multinomial(logits.softmax(dim=-1), 1)
idx = torch.cat([idx, next_id], dim=1)
return idx