TExcelTAD
Home › Math for Deep Learning & LLMs › Mini Project: A Character-Level Language Model in NumPy

Mini Project: A Character-Level Language Model in NumPy

This project builds a complete, if tiny, language model from nothing but NumPy, using the mathematics of the whole course: a character vocabulary (Tokenization), learned embeddings (Embeddings), an MLP over a window of previous characters (Multilayer Perceptrons), the softmax cross-entropy loss and its gradient (Softmax and Cross-Entropy Gradient), hand-written backpropagation checked against finite differences, the Adam optimizer (Adam and AdamW), perplexity on held-out text (Perplexity) and temperature sampling (Sampling).

The architecture is the classic neural probabilistic language model: concatenate the embeddings of the last CC characters, apply one ReLU hidden layer, and output logits over the vocabulary.

e=[Ext−C;…;Ext−1],h=ReLU⁡(W1e+b1),p(xt∣xt−C:t−1)=softmax⁡(W2h+b2)\mathbf{e} = [E_{x_{t-C}}; \ldots; E_{x_{t-1}}], \qquad \mathbf{h} = \operatorname{ReLU}(W_1\mathbf{e} + \mathbf{b}_1), \qquad p(x_t \mid x_{t-C:t-1}) = \operatorname{softmax}(W_2\mathbf{h} + \mathbf{b}_2)

Every code block below is self-contained, so each one rebuilds what it needs.

Step 1: Data, vocabulary and baselines

The corpus is a few short sentences. The vocabulary is its set of characters, and each training example is a window of C=4C = 4 characters with the next character as the label: the inputs shifted by one (Language Modeling). The last 10% of the windows are held out for validation. Two baselines set the bar: uniform guessing (perplexity VV) and a bigram table that only looks at the previous character.

python · try it yourself
import numpy as np

text = ("the cat sat on the mat. the dog sat on the log. the cat saw the dog. "
        "the dog saw the cat on the mat. a cat and a dog sat in the sun. "
        "the sun was on the cat. the dog ran to the log and sat. the cat ran to the mat. "
        "a dog and a cat ran in the sun. the cat sat on the log and the dog sat on the mat. ")
chars = sorted(set(text)); V = len(chars); stoi = {c: i for i, c in enumerate(chars)}
ids = np.array([stoi[c] for c in text])
C = 4                                                     # context length
X = np.array([ids[i:i + C] for i in range(len(ids) - C)]); Y = ids[C:]
n_tr = int(0.9 * len(X)); Xtr, Ytr, Xva, Yva = X[:n_tr], Y[:n_tr], X[n_tr:], Y[n_tr:]
print("vocabulary:", "".join(chars).replace(" ", "_"), f"({V} symbols)")
print("training pairs:", len(Xtr), " validation pairs:", len(Xva))
for i in range(3):
    print(repr("".join(chars[j] for j in Xtr[i])), "->", repr(chars[Ytr[i]]))
counts = np.ones((V, V)); np.add.at(counts, (Xtr[:, -1], Ytr), 1)           # bigram baseline
Pb = counts / counts.sum(1, keepdims=True)
print(f"baselines: uniform perplexity {V}, bigram perplexity {np.exp(-np.mean(np.log(Pb[Xva[:, -1], Yva]))):.2f}")
vocabulary: _.acdeghilmnorstuw (18 symbols)
training pairs: 262  validation pairs: 30
'the ' -> 'c'
'he c' -> 'a'
'e ca' -> 't'
baselines: uniform perplexity 18, bigram perplexity 4.49

Step 2: Forward, backward and a gradient check

The backward pass follows the chain from the loss to every parameter: G=1B(P−Y)G = \frac{1}{B}(P - Y) at the logits; the dense-layer rules for W2W_2, b2\mathbf{b}_2, W1W_1, b1\mathbf{b}_1 (Backpropagation Through an MLP); the ReLU mask; and finally a scatter-add of the input gradient into the rows of EE that were looked up. Before training, compare it with central differences on a few entries of every parameter. The initial loss should be close to ln⁡V\ln V, because the output layer starts with tiny weights.

python · try it yourself
import numpy as np

text = ("the cat sat on the mat. the dog sat on the log. the cat saw the dog. "
        "the dog saw the cat on the mat. a cat and a dog sat in the sun. "
        "the sun was on the cat. the dog ran to the log and sat. the cat ran to the mat. "
        "a dog and a cat ran in the sun. the cat sat on the log and the dog sat on the mat. ")
chars = sorted(set(text)); V = len(chars); stoi = {c: i for i, c in enumerate(chars)}
ids = np.array([stoi[c] for c in text])
C = 4                                                     # context length
X = np.array([ids[i:i + C] for i in range(len(ids) - C)]); Y = ids[C:]
n_tr = int(0.9 * len(X)); Xtr, Ytr, Xva, Yva = X[:n_tr], Y[:n_tr], X[n_tr:], Y[n_tr:]
rng = np.random.default_rng(0)
d, H = 10, 64
params = {"E": rng.normal(0, 1, (V, d)),
          "W1": rng.normal(0, np.sqrt(2 / (C * d)), (H, C * d)), "b1": np.zeros(H),
          "W2": rng.normal(0, 0.01, (V, H)), "b2": np.zeros(V)}
def forward(p, Xb):
    e = p["E"][Xb].reshape(len(Xb), -1)
    a = e @ p["W1"].T + p["b1"]; h = np.maximum(0, a)
    z = h @ p["W2"].T + p["b2"]
    return e, a, h, z
def loss_grads(p, Xb, Yb):
    e, a, h, z = forward(p, Xb)
    z = z - z.max(1, keepdims=True); P = np.exp(z); P /= P.sum(1, keepdims=True)
    loss = -np.mean(np.log(P[np.arange(len(Yb)), Yb]))
    G = P; G[np.arange(len(Yb)), Yb] -= 1; G /= len(Yb)
    g = {"W2": G.T @ h, "b2": G.sum(0)}
    Ga = (G @ p["W2"]) * (a > 0)
    g["W1"], g["b1"] = Ga.T @ e, Ga.sum(0)
    Ge = (Ga @ p["W1"]).reshape(len(Xb), C, d)
    gE = np.zeros_like(p["E"]); np.add.at(gE, Xb, Ge); g["E"] = gE
    return loss, g

Xb, Yb = Xtr[:8], Ytr[:8]
loss, g = loss_grads(params, Xb, Yb)
print(f"initial loss {loss:.4f} (ln V = {np.log(V):.4f})")
for k in ("E", "W1", "b1", "W2", "b2"):
    num = np.zeros_like(params[k])
    for idx in list(np.ndindex(params[k].shape))[:20]:                       # check 20 entries each
        old = params[k][idx]
        params[k][idx] = old + 1e-5; lp = loss_grads(params, Xb, Yb)[0]
        params[k][idx] = old - 1e-5; lm = loss_grads(params, Xb, Yb)[0]
        params[k][idx] = old; num[idx] = (lp - lm) / 2e-5
    mask = np.zeros(params[k].shape, bool); mask.flat[:20] = True
    err = np.max(np.abs(g[k][mask] - num[mask])) / (np.max(np.abs(num[mask])) + 1e-12)
    print(f"{k:2s}: max relative error {err:.1e}")
initial loss 2.9104 (ln V = 2.8904)
E : max relative error 2.5e-09
W1: max relative error 5.5e-09
b1: max relative error 5.8e-09
W2: max relative error 8.2e-11
b2: max relative error 1.5e-10

Step 3: Train with Adam and sample

Train on random mini-batches of 32 windows with Adam, report the validation loss and perplexity every 500 steps, and then generate text from the prompt "the " at three temperatures.

python · try it yourself
import numpy as np

text = ("the cat sat on the mat. the dog sat on the log. the cat saw the dog. "
        "the dog saw the cat on the mat. a cat and a dog sat in the sun. "
        "the sun was on the cat. the dog ran to the log and sat. the cat ran to the mat. "
        "a dog and a cat ran in the sun. the cat sat on the log and the dog sat on the mat. ")
chars = sorted(set(text)); V = len(chars); stoi = {c: i for i, c in enumerate(chars)}
ids = np.array([stoi[c] for c in text])
C = 4                                                     # context length
X = np.array([ids[i:i + C] for i in range(len(ids) - C)]); Y = ids[C:]
n_tr = int(0.9 * len(X)); Xtr, Ytr, Xva, Yva = X[:n_tr], Y[:n_tr], X[n_tr:], Y[n_tr:]
rng = np.random.default_rng(0)
d, H = 10, 64
params = {"E": rng.normal(0, 1, (V, d)),
          "W1": rng.normal(0, np.sqrt(2 / (C * d)), (H, C * d)), "b1": np.zeros(H),
          "W2": rng.normal(0, 0.01, (V, H)), "b2": np.zeros(V)}
def forward(p, Xb):
    e = p["E"][Xb].reshape(len(Xb), -1)
    a = e @ p["W1"].T + p["b1"]; h = np.maximum(0, a)
    z = h @ p["W2"].T + p["b2"]
    return e, a, h, z
def loss_grads(p, Xb, Yb):
    e, a, h, z = forward(p, Xb)
    z = z - z.max(1, keepdims=True); P = np.exp(z); P /= P.sum(1, keepdims=True)
    loss = -np.mean(np.log(P[np.arange(len(Yb)), Yb]))
    G = P; G[np.arange(len(Yb)), Yb] -= 1; G /= len(Yb)
    g = {"W2": G.T @ h, "b2": G.sum(0)}
    Ga = (G @ p["W2"]) * (a > 0)
    g["W1"], g["b1"] = Ga.T @ e, Ga.sum(0)
    Ge = (Ga @ p["W1"]).reshape(len(Xb), C, d)
    gE = np.zeros_like(p["E"]); np.add.at(gE, Xb, Ge); g["E"] = gE
    return loss, g
m = {k: np.zeros_like(v) for k, v in params.items()}; s = {k: np.zeros_like(v) for k, v in params.items()}
lr, b1, b2 = 0.01, 0.9, 0.999
def val_loss(p):
    _, _, _, z = forward(p, Xva); z = z - z.max(1, keepdims=True)
    return np.mean(np.log(np.exp(z).sum(1)) - z[np.arange(len(Yva)), Yva])
for t in range(1, 3001):
    idx = rng.integers(0, len(Xtr), 32)
    loss, g = loss_grads(params, Xtr[idx], Ytr[idx])
    for k in params:
        m[k] = b1 * m[k] + (1 - b1) * g[k]; s[k] = b2 * s[k] + (1 - b2) * g[k]**2
        params[k] -= lr * (m[k] / (1 - b1**t)) / (np.sqrt(s[k] / (1 - b2**t)) + 1e-8)
    if t % 500 == 0:
        vl = val_loss(params)
        print(f"step {t}: train loss {loss:.3f}, val loss {vl:.3f}, val perplexity {np.exp(vl):.2f}")
def sample(p, prompt, n, T, rng):
    out = [stoi[c] for c in prompt]
    for _ in range(n):
        _, _, _, z = forward(p, np.array([out[-C:]]))
        z = z[0] / T; q = np.exp(z - z.max()); q /= q.sum()
        out.append(rng.choice(V, p=q))
    return "".join(chars[i] for i in out)
for T in (0.3, 1.0, 2.0):
    print(T, repr(sample(params, "the ", 60, T, np.random.default_rng(1))))
step 500: train loss 0.333, val loss 0.606, val perplexity 1.83
step 1000: train loss 0.185, val loss 0.564, val perplexity 1.76
step 1500: train loss 0.319, val loss 0.571, val perplexity 1.77
step 2000: train loss 0.227, val loss 0.491, val perplexity 1.63
step 2500: train loss 0.151, val loss 0.478, val perplexity 1.61
step 3000: train loss 0.157, val loss 0.447, val perplexity 1.56
0.3 'the dog sat on the cat ran to the dog sat on the dog sat on the '
1.0 'the dog. the cat sat on the sun was on the cat on the mat. a dog'
2.0 'the logogat. a dog ran in the logthe mat. i the sun. the nog. th'

What the numbers say

  • The gradients are right. Relative errors around 10−910^{-9} or smaller for every parameter mean the hand-written backward pass matches the calculus (Gradient Checking).
  • The model beats both baselines by far. The validation perplexity falls from 18 (uniform) past the bigram's 4.49 to about 1.6: with four characters of context the model is, on average, about as uncertain as a choice between 1.6 characters. On such a small, repetitive corpus this mostly means it has learned its words and phrases.
  • Training loss is noisy because each step sees only 32 windows (Mini-Batch SGD); the validation loss, computed on all held-out windows, is the smoother signal. The gap between them shows mild overfitting.
  • Temperature controls variety. At T=0.3T = 0.3 the samples are nearly greedy and loop through the most common phrase. At T=1T = 1 they read like new sentences in the corpus's style. At T=2T = 2 the flattened distribution produces non-words such as "logogat".

Where to go next

  • Increase the context CC or the embedding size dd and watch the validation perplexity; at some point the tiny corpus is memorized and validation stops improving (Capacity and Overfitting).
  • Add weight decay the AdamW way, or dropout on h\mathbf{h} (Regularization).
  • Replace the fixed window by causal self-attention over the whole prefix: one head, then several, then a full transformer block.
  • Add top-p filtering to the sampler and compare with plain temperature sampling.
  • Count the parameters and FLOPs per character of your model (Counting Parameters and FLOPs).

Test yourself

Why is the initial loss close to ln⁡V\ln V?

  1. Because the corpus is small
  2. The output weights start tiny, so the first predictions are nearly uniform over the VV characters
  3. Because of Adam
  4. It is a coincidence

How does the embedding table receive its gradient?

  1. Every row is updated equally
  2. The input gradient of each looked-up row is scatter-added into that row
  3. It is not trained
  4. Through the softmax only

In the generated samples, what does a high temperature (2.0) do?

  1. Makes the text more repetitive
  2. Flattens the distribution, producing more unusual character sequences
  3. Stops generation
  4. Has no effect