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.

(a,b)=arg⁡max⁡(a, b)count⁡(a,b),new id=256,257,…(a, b) = \arg\max_{(a,\, b)} \operatorname{count}(a, b), \qquad \text{new id} = 256, 257, \ldots

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. QK⊤QK^\top scores how much each token attends to the others; dividing by dk\sqrt{d_k} keeps the softmax from saturating. The causal mask MM sets future positions to −∞-\infty. Heads split dd into hh slices of size dk=d/hd_k = d/h that run in parallel.

Attention(Q,K,V)=softmax ⁣(QK⊤dk+M)V\mathrm{Attention}(Q, K, V) = \mathrm{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}} + M\right) V
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 4d4d and back. Normalising before each sublayer and adding a residual keeps gradients flowing through deep stacks.

x←x+Attn(LN(x)),x←x+MLP(LN(x))x \leftarrow x + \mathrm{Attn}(\mathrm{LN}(x)), \qquad x \leftarrow x + \mathrm{MLP}(\mathrm{LN}(x))
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 x

Model

Embed each token and its position, run LL blocks, normalise, and project to vocabulary logits.

h0=Etok[xt]+Epos[t],z=LN(hL) Wouth_0 = E_{\text{tok}}[x_t] + E_{\text{pos}}[t], \qquad z = \mathrm{LN}(h_L)\, W_{\text{out}}
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 tt predicts token t+1t+1, so inputs and targets are the same sequence shifted by one.

L=−1T∑t=1Tlog⁡pθ(xt+1∣x≤t)\mathcal{L} = -\frac{1}{T} \sum_{t=1}^{T} \log p_\theta(x_{t+1} \mid x_{\le t})
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 zz at the last position, sample, append, repeat. Temperature τ<1\tau < 1 sharpens the distribution; τ→0\tau \to 0 is greedy decoding.

pi=exp⁡(zi/τ)∑jexp⁡(zj/τ)p_i = \frac{\exp(z_i / \tau)}{\sum_j \exp(z_j / \tau)}
@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