Sign in

Large language model (LLM)

Large Language Model

A language model in miniature: a GPT-style transformer that predicts the next character from the ones before it.

Overview

A language model does one thing: given a piece of text, it assigns a probability to every possible next token. Here a token is a single character. To generate text, the model predicts the next character, appends it, and repeats. Inside, each character becomes a vector, and a mechanism called attention lets each position gather information from earlier positions, weighted by how relevant they are. Stacking a few such layers lets the model pick up patterns such as: after these letters this letter usually follows. This template has the same parts as a large model but is thousands of times smaller, and it only knows the text it was trained on.

A short history

Claude Shannon studied predicting the next letter of English text in the late 1940s, and statistical language models followed for decades. The Transformer, published by Ashish Vaswani and colleagues in 2017, made it practical to train on very large corpora. OpenAI's GPT in 2018 showed that a decoder-only Transformer pretrained to predict the next token could be adapted to many tasks, and the release of ChatGPT in late 2022 brought such models into everyday use.

How it works

  1. Map each character to an integer id with CharTokenizer, then to a vector: a token embedding plus a position embedding.
  2. In each block, normalise the vectors and apply causal self-attention: every position forms a weighted mix of the vectors at itself and earlier positions.
  3. Add the result back to the input (a residual connection), normalise again, apply a small GELU feed-forward network and add again.
  4. After the last block, normalise once more and apply a linear layer that gives one score (logit) per character in the vocabulary.
  5. Turn the scores into probabilities with softmax. Train with cross-entropy against the actual next character at every position.
  6. To generate, feed the last context_size characters, pick the next one (the most likely, or a sample at a temperature), append it and repeat.

Watch out for

  • The model memorises its few hundred characters of training text. A low training loss here shows memorisation and says nothing about understanding language.
  • A character that did not occur in the training text is not in the vocabulary, so a prompt containing it raises an error.
  • The model sees at most context_size characters back. Anything earlier in the prompt has no effect on the prediction.
  • Greedy generation, at temperature 0, tends to fall into repeating loops, because the most likely continuation of a pattern is the pattern again.
  • This is a teaching-size model with about 28,000 parameters: no subword tokenizer, dropout, weight tying or key-value cache, and no pretrained knowledge.

Use cases

When to use it

To learn how a GPT works end to end, to test code that needs a real autoregressive model with a tiny footprint, or as a reference to check a framework implementation against.

In industry

Software development
Code completion and generation inside editors; GitHub Copilot is a well-known example.
Customer support
Drafting replies and answering questions from a company's help articles, usually with retrieval of the relevant passages.
Legal and professional services
Summarising long documents and extracting named fields such as parties, dates and amounts for human review.

Choosing it: what must hold

  • A task that can be expressed as reading and producing text.
  • For training from scratch, a very large corpus and a large computing budget; most projects start from a pretrained model.
  • A plan for checking outputs, because a language model can state false things fluently.

When to choose something else

IfUse instead
The task is classifying short texts into fixed labels with plenty of labelled dataNaive Bayes or logistic regression on text features, or a small fine-tuned encoder
The data is a table of numbers and categoriesGradient boosted trees such as XGBoost
You want to learn how the architecture works at small scaleThe Transformer lesson

Math foundations

  1. Input vectors

    xt=Etok[ it ]+Epos[ t ]\mathbf{x}_t = E_{\text{tok}}[\, i_t \,] + E_{\text{pos}}[\, t \,]

    Each position starts as the sum of a vector for its character and a vector for its place in the window. Without the second term the model could not tell the order of the characters.

  2. Causal self-attention

    Att⁡(Q,K,V)=softmax⁡(QK⊤dh+M)V,Mts={0s≤t−∞s>t\operatorname{Att}(Q, K, V) = \operatorname{softmax}\left( \frac{Q K^{\top}}{\sqrt{d_h}} + M \right) V, \qquad M_{ts} = \begin{cases} 0 & s \le t \\ -\infty & s > t \end{cases}

    Every position asks a question QQ, every position offers a key KK and a value VV. The match between question and key sets how much of each value is taken. The mask MM gives zero weight to later positions.

  3. One pre-norm block

    x←x+Attn⁡(LN⁡(x)),x←x+MLP⁡(LN⁡(x))\mathbf{x} \leftarrow \mathbf{x} + \operatorname{Attn}\big( \operatorname{LN}(\mathbf{x}) \big), \qquad \mathbf{x} \leftarrow \mathbf{x} + \operatorname{MLP}\big( \operatorname{LN}(\mathbf{x}) \big)

    Each sub-layer reads a normalised copy and adds its output to the running vector. The additions give gradients a direct path through the stack.

  4. Next-character distribution

    P(it+1=v∣i1,…,it)=ezt,v∑u=1∣V∣ezt,uP(i_{t+1} = v \mid i_1, \dots, i_t) = \frac{e^{z_{t,v}}}{\sum_{u=1}^{|\mathcal{V}|} e^{z_{t,u}}}

    The scores at position tt become a probability for each character of the vocabulary. Because of the mask they depend only on characters up to tt.

  5. Training loss

    L=−1T∑t=1Tlog⁡P(it+1∣i1,…,it)\mathcal{L} = -\frac{1}{T} \sum_{t=1}^{T} \log P(i_{t+1} \mid i_1, \dots, i_t)

    The average of minus the log-probability given to the true next character, in nats per character. A model that guesses uniformly scores ln⁡∣V∣\ln |\mathcal{V}|.

  6. Sampling with temperature

    Pτ(v)=ezv/τ∑uezu/τP_{\tau}(v) = \frac{e^{z_v / \tau}}{\sum_{u} e^{z_u / \tau}}

    Dividing the scores by τ\tau before the softmax sharpens the distribution for τ\tau below 1 and flattens it above 1. As τ\tau approaches 0 it picks the most likely character.

Symbols

iti_t
id of the character at position t
Etok,EposE_{\text{tok}}, E_{\text{pos}}
token and position embedding tables
Q,K,VQ, K, V
query, key and value matrices, linear maps of the normalised input
dhd_h
width of one attention head: d_model divided by n_heads
MM
the causal mask
LN⁡\operatorname{LN}
layer normalisation
zt,vz_{t,v}
logit for character v at position t
V\mathcal{V}
the vocabulary: the distinct characters of the training text
TT
number of positions in the window
τ\tau
temperature

Worked by hand

A vocabulary of three characters with logits z=(2,1,0)z = (2, 1, 0) at the last position. Compute the next-character probabilities at temperature 1 and at 0.5, and the loss if the true next character is the first.

τ=1:e2=7.389,  e1=2.718,  e0=1,sum=11.107\tau = 1: \quad e^{2} = 7.389, \; e^{1} = 2.718, \; e^{0} = 1, \quad \text{sum} = 11.107
P=(0.665,  0.245,  0.090),loss=−ln⁡0.665=0.408P = (0.665,\; 0.245,\; 0.090), \qquad \text{loss} = -\ln 0.665 = 0.408
τ=0.5:z/τ=(4,2,0),e4=54.598,  e2=7.389,  e0=1,sum=62.987\tau = 0.5: \quad z / \tau = (4, 2, 0), \quad e^{4} = 54.598, \; e^{2} = 7.389, \; e^{0} = 1, \quad \text{sum} = 62.987
P0.5=(0.867,  0.117,  0.016)P_{0.5} = (0.867,\; 0.117,\; 0.016)
uniform guess:ln⁡3=1.099\text{uniform guess:} \quad \ln 3 = 1.099

Halving the temperature moves the top character from 0.67 to 0.87 and nearly removes the last one. The loss of 0.41 is well under the 1.10 of a uniform guess, so these logits carry real information.

Visual example

Loading the example.

Try this

  • Drop the temperature to 0.2: the model repeats its favourite word.
  • Raise it to 1.6, then tighten top-p to 0.8 to cut the long tail off.
  • Press Sample a few times and read what the settings wrote.

Code sample

from impl import LLM
from config import LLMConfig

text = "the cat sat on the mat. " * 12
model = LLM(LLMConfig(context_size=24, d_model=32, n_heads=2, n_layers=2, steps=150)).fit(text)
print(round(model.loss_history[0], 2), "->", round(model.loss_history[-1], 2))   # nats per character
print(model.generate("the cat ", max_new_tokens=30))                             # continues the pattern
print(model.predict("the cat sat on the ma"))                                    # 't'
Read the implementation (265 lines)
"""LLM: a small GPT-style language model (decoder-only transformer) with a character tokenizer.

NumPy only, with the whole backward pass written by hand. It is the same architecture as a large language
model at a very small size: token and position embeddings, pre-norm blocks of causal multi-head
self-attention and a GELU feed-forward layer, a final layer norm and a linear head over the vocabulary. It is
trained to predict the next character and generates text one character at a time.
"""
from __future__ import annotations

import math

import numpy as np

try:
    from .config import LLMConfig
except ImportError:  # run from the template's own folder
    from config import LLMConfig

_C = math.sqrt(2.0 / math.pi)


class CharTokenizer:
    """Maps each distinct character of a text to an integer id and back."""

    def __init__(self, text: str) -> None:
        self.chars = sorted(set(text))
        self._ids = {c: i for i, c in enumerate(self.chars)}

    @property
    def vocab_size(self) -> int:
        return len(self.chars)

    def encode(self, text: str) -> np.ndarray:
        """Text -> (len(text),) int ids. A character that was not in the training text raises ValueError."""
        try:
            return np.array([self._ids[c] for c in text], dtype=int)
        except KeyError as e:
            raise ValueError(f"character {e.args[0]!r} is not in the vocabulary") from None

    def decode(self, ids) -> str:
        return "".join(self.chars[int(i)] for i in ids)


def _gelu(x: np.ndarray) -> np.ndarray:
    """GELU, tanh approximation (as in GPT-2)."""
    return 0.5 * x * (1.0 + np.tanh(_C * (x + 0.044715 * x**3)))


def _gelu_grad(x: np.ndarray) -> np.ndarray:
    t = np.tanh(_C * (x + 0.044715 * x**3))
    return 0.5 * (1.0 + t) + 0.5 * x * (1.0 - t**2) * _C * (1.0 + 3 * 0.044715 * x**2)


def _layer_norm(x: np.ndarray, gain: np.ndarray, bias: np.ndarray):
    """Normalise the last axis. Returns (output, cache)."""
    mu = x.mean(axis=-1, keepdims=True)
    std = np.sqrt(x.var(axis=-1, keepdims=True) + 1e-5)
    xhat = (x - mu) / std
    return gain * xhat + bias, (xhat, std)


def _layer_norm_backward(dy: np.ndarray, gain: np.ndarray, cache):
    """Returns (dx, dgain, dbias)."""
    xhat, std = cache
    dxhat = dy * gain
    dx = (dxhat - dxhat.mean(axis=-1, keepdims=True) - xhat * (dxhat * xhat).mean(axis=-1, keepdims=True)) / std
    axes = tuple(range(dy.ndim - 1))
    return dx, (dy * xhat).sum(axis=axes), dy.sum(axis=axes)


class LLM:
    """Character-level GPT. `fit(text)` trains it, `generate(prompt)` continues a prompt."""

    def __init__(self, config: LLMConfig | None = None) -> None:
        self.config = config or LLMConfig()
        self.tokenizer: CharTokenizer | None = None
        self.params: dict[str, np.ndarray] = {}
        self.loss_history: list[float] = []  # training loss (nats per character) at every step

    # ---- parameters ------------------------------------------------------------------------------------
    def _init_params(self, vocab_size: int) -> None:
        cfg = self.config
        rng = np.random.default_rng(cfg.seed)
        D = cfg.d_model
        p = {"tok_emb": rng.normal(0.0, 0.02, size=(vocab_size, D)), "pos_emb": rng.normal(0.0, 0.02, size=(cfg.context_size, D))}
        for l in range(cfg.n_layers):
            for name in ("Wq", "Wk", "Wv", "Wo"):
                p[f"h{l}.{name}"] = rng.normal(0.0, 0.02 if name != "Wo" else 0.02 / math.sqrt(2 * cfg.n_layers), size=(D, D))
                p[f"h{l}.b{name[1]}"] = np.zeros(D)
            p[f"h{l}.W1"] = rng.normal(0.0, 0.02, size=(D, 4 * D))
            p[f"h{l}.b1"] = np.zeros(4 * D)
            p[f"h{l}.W2"] = rng.normal(0.0, 0.02 / math.sqrt(2 * cfg.n_layers), size=(4 * D, D))
            p[f"h{l}.b2"] = np.zeros(D)
            for ln in ("ln1", "ln2"):
                p[f"h{l}.{ln}.g"] = np.ones(D)
                p[f"h{l}.{ln}.b"] = np.zeros(D)
        p["lnf.g"] = np.ones(D)
        p["lnf.b"] = np.zeros(D)
        p["head"] = rng.normal(0.0, 0.02, size=(D, vocab_size))
        self.params = p

    def n_parameters(self) -> int:
        return int(sum(v.size for v in self.params.values()))

    # ---- forward and backward --------------------------------------------------------------------------
    def _split(self, x: np.ndarray) -> np.ndarray:
        """(B, T, D) -> (B, heads, T, D / heads)."""
        B, T, D = x.shape
        h = self.config.n_heads
        return x.reshape(B, T, h, D // h).transpose(0, 2, 1, 3)

    @staticmethod
    def _merge(x: np.ndarray) -> np.ndarray:
        """(B, heads, T, dh) -> (B, T, D)."""
        B, h, T, dh = x.shape
        return x.transpose(0, 2, 1, 3).reshape(B, T, h * dh)

    def forward(self, ids: np.ndarray) -> tuple[np.ndarray, list]:
        """ids: (B, T) int token ids, T <= context_size. Returns (logits (B, T, vocab), cache).

        logits[b, t] scores the token that follows position t and depends only on ids[b, :t + 1].
        """
        cfg, p = self.config, self.params
        ids = np.asarray(ids, dtype=int)
        B, T = ids.shape
        if T > cfg.context_size:
            raise ValueError(f"sequence length {T} exceeds context_size {cfg.context_size}")
        dh = cfg.d_model // cfg.n_heads
        future = np.triu(np.ones((T, T), dtype=bool), k=1)  # True where a position would look ahead
        x = p["tok_emb"][ids] + p["pos_emb"][:T]
        cache = []
        for l in range(cfg.n_layers):
            a, ln1 = _layer_norm(x, p[f"h{l}.ln1.g"], p[f"h{l}.ln1.b"])
            q = self._split(a @ p[f"h{l}.Wq"] + p[f"h{l}.bq"])
            k = self._split(a @ p[f"h{l}.Wk"] + p[f"h{l}.bk"])
            v = self._split(a @ p[f"h{l}.Wv"] + p[f"h{l}.bv"])
            scores = q @ k.transpose(0, 1, 3, 2) / math.sqrt(dh)
            scores = np.where(future, -1e30, scores)
            att = np.exp(scores - scores.max(axis=-1, keepdims=True))
            att /= att.sum(axis=-1, keepdims=True)
            merged = self._merge(att @ v)
            x_mid = x + merged @ p[f"h{l}.Wo"] + p[f"h{l}.bo"]
            m, ln2 = _layer_norm(x_mid, p[f"h{l}.ln2.g"], p[f"h{l}.ln2.b"])
            pre = m @ p[f"h{l}.W1"] + p[f"h{l}.b1"]
            act = _gelu(pre)
            x_out = x_mid + act @ p[f"h{l}.W2"] + p[f"h{l}.b2"]
            cache.append((a, ln1, q, k, v, att, merged, m, ln2, pre, act))
            x = x_out
        xf, lnf = _layer_norm(x, p["lnf.g"], p["lnf.b"])
        return xf @ p["head"], [ids, cache, xf, lnf]

    def loss_and_grads(self, ids: np.ndarray, targets: np.ndarray) -> tuple[float, dict]:
        """Mean next-token cross-entropy and its gradient for every parameter.

        ids: (B, T) inputs. targets: (B, T) the token that follows each position.
        """
        cfg, p = self.config, self.params
        logits, (ids, cache, xf, lnf) = self.forward(ids)
        B, T, V = logits.shape
        dh = cfg.d_model // cfg.n_heads
        z = logits - logits.max(axis=-1, keepdims=True)
        logp = z - np.log(np.exp(z).sum(axis=-1, keepdims=True))
        rows, cols = np.arange(B)[:, None], np.arange(T)[None, :]
        loss = float(-logp[rows, cols, targets].mean())
        d = np.exp(logp)
        d[rows, cols, targets] -= 1.0
        d /= B * T
        g: dict[str, np.ndarray] = {}
        g["head"] = xf.reshape(-1, cfg.d_model).T @ d.reshape(-1, V)
        dx, g["lnf.g"], g["lnf.b"] = _layer_norm_backward(d @ p["head"].T, p["lnf.g"], lnf)
        flat = lambda t: t.reshape(-1, t.shape[-1])  # noqa: E731
        for l in range(cfg.n_layers - 1, -1, -1):
            a, ln1, q, k, v, att, merged, m, ln2, pre, act = cache[l]
            # feed-forward branch
            g[f"h{l}.W2"] = flat(act).T @ flat(dx)
            g[f"h{l}.b2"] = dx.sum(axis=(0, 1))
            dpre = (dx @ p[f"h{l}.W2"].T) * _gelu_grad(pre)
            g[f"h{l}.W1"] = flat(m).T @ flat(dpre)
            g[f"h{l}.b1"] = dpre.sum(axis=(0, 1))
            dm, g[f"h{l}.ln2.g"], g[f"h{l}.ln2.b"] = _layer_norm_backward(dpre @ p[f"h{l}.W1"].T, p[f"h{l}.ln2.g"], ln2)
            dx = dx + dm  # gradient at x_mid: residual path plus the branch
            # attention branch
            g[f"h{l}.Wo"] = flat(merged).T @ flat(dx)
            g[f"h{l}.bo"] = dx.sum(axis=(0, 1))
            dheads = self._split(dx @ p[f"h{l}.Wo"].T)
            datt = dheads @ v.transpose(0, 1, 3, 2)
            dv = att.transpose(0, 1, 3, 2) @ dheads
            dscores = att * (datt - (datt * att).sum(axis=-1, keepdims=True)) / math.sqrt(dh)
            dq = self._merge(dscores @ k)
            dk = self._merge(dscores.transpose(0, 1, 3, 2) @ q)
            dv = self._merge(dv)
            da = np.zeros_like(a)
            for name, dz in (("q", dq), ("k", dk), ("v", dv)):
                g[f"h{l}.W{name}"] = flat(a).T @ flat(dz)
                g[f"h{l}.b{name}"] = dz.sum(axis=(0, 1))
                da += dz @ p[f"h{l}.W{name}"].T
            da, g[f"h{l}.ln1.g"], g[f"h{l}.ln1.b"] = _layer_norm_backward(da, p[f"h{l}.ln1.g"], ln1)
            dx = dx + da
        g["pos_emb"] = np.zeros_like(p["pos_emb"])
        g["pos_emb"][:T] = dx.sum(axis=0)
        g["tok_emb"] = np.zeros_like(p["tok_emb"])
        np.add.at(g["tok_emb"], ids, dx)
        return loss, g

    # ---- training and generation -----------------------------------------------------------------------
    def fit(self, text: str) -> "LLM":
        """Build the character vocabulary from `text` and train on random windows of it with Adam."""
        cfg = self.config
        if len(text) < 2:
            raise ValueError("the training text must hold at least 2 characters")
        self.tokenizer = CharTokenizer(text)
        data = self.tokenizer.encode(text)
        self._init_params(self.tokenizer.vocab_size)
        T = min(cfg.context_size, len(data) - 1)
        rng = np.random.default_rng(cfg.seed + 1)
        m = {k: np.zeros_like(v) for k, v in self.params.items()}
        v = {k: np.zeros_like(p) for k, p in self.params.items()}
        offsets = np.arange(T)[None, :]
        self.loss_history = []
        for step in range(1, cfg.steps + 1):
            starts = rng.integers(0, len(data) - T, size=cfg.batch_size)[:, None]
            loss, grads = self.loss_and_grads(data[starts + offsets], data[starts + offsets + 1])
            self.loss_history.append(loss)
            norm = math.sqrt(sum(float(np.sum(gr**2)) for gr in grads.values()))
            scale = min(1.0, 1.0 / (norm + 1e-12))  # clip the gradient norm at 1
            for name, gr in grads.items():
                gr = gr * scale
                m[name] = 0.9 * m[name] + 0.1 * gr
                v[name] = 0.999 * v[name] + 0.001 * gr * gr
                self.params[name] -= cfg.learning_rate * (m[name] / (1 - 0.9**step)) / (
                    np.sqrt(v[name] / (1 - 0.999**step)) + 1e-8)
        return self

    def next_token_probs(self, prompt: str) -> dict[str, float]:
        """Probability of each character coming next after `prompt` (only its last context_size characters count)."""
        ids = self.tokenizer.encode(prompt)[-self.config.context_size:]
        logits = self.forward(ids[None, :])[0][0, -1]
        probs = np.exp(logits - logits.max())
        probs /= probs.sum()
        return {c: float(pr) for c, pr in zip(self.tokenizer.chars, probs)}

    def predict(self, prompt: str) -> str:
        """The single most likely next character after `prompt`."""
        probs = self.next_token_probs(prompt)
        return max(probs, key=probs.get)

    def generate(self, prompt: str, max_new_tokens: int = 50, temperature: float = 0.0, seed: int = 0) -> str:
        """Continue `prompt` by `max_new_tokens` characters and return prompt plus continuation.

        temperature 0 picks the most likely character each time (deterministic); above 0 it samples from the
        distribution sharpened or flattened by that temperature, using `seed`.
        """
        if not prompt:
            raise ValueError("prompt must hold at least one character")
        rng = np.random.default_rng(seed)
        ids = list(self.tokenizer.encode(prompt))
        for _ in range(max_new_tokens):
            window = np.array(ids[-self.config.context_size:])[None, :]
            logits = self.forward(window)[0][0, -1]
            if temperature <= 0:
                ids.append(int(logits.argmax()))
            else:
                probs = np.exp((logits - logits.max()) / temperature)
                ids.append(int(rng.choice(len(probs), p=probs / probs.sum())))
        return self.tokenizer.decode(ids)
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
7, run with python3 -m unittest -v

Practice

Fit LLM on the repeated sentence from the README and compare loss_history[0] with the log of tokenizer.vocab_size. Call next_token_probs("the cat sat on the ma") and read the top three characters. Then run generate with temperature 0, 0.5 and 1.5 and describe how the text changes.

Check on learning

  1. Why is the first value of the loss history close to the log of the vocabulary size?
    A way to think about it

    At the start the weights are random and small, so the logits are nearly equal. Work out the loss of a uniform distribution over the characters.

  2. What would happen during training if the causal mask were removed, and why would the trained model then be useless for generation?
    A way to think about it

    The target at each position is the next character. Check whether that character would be visible to attention without the mask, and what is available at generation time.

  3. Without the position embedding, would the model give different predictions for the prompts ab and ba? Why does that matter?
    A way to think about it

    Attention forms a weighted sum over positions. Consider which operations in the model, if any, depend on the order of the inputs.

  4. The model reaches a very low loss on its training text. Give two reasons why this does not mean it would predict new English text well.
    A way to think about it

    Compare the number of parameters with the number of training characters. Also consider what the model has never been shown.

  5. At temperature 0 the output often repeats the same phrase forever. Why does sampling at a moderate temperature break the loop?
    A way to think about it

    Greedy choice is a fixed function of the context window, so the same window always leads to the same next character. Ask what randomness changes about that.