TExcelTAD
Home › Math for Deep Learning & LLMs › Deep Learning Math Exercises

Deep Learning Math Exercises

Time to practise the whole course. Each exercise has a starter program that runs but does not do the job yet. Replace the TODO parts, press ▶ Run, and compare your result with the expected output. The output block under each starter shows what the unfinished starter prints.

Tip: Write down the shape of every array before you write code. Most deep-learning bugs are shape bugs, and a gradient always has the shape of the thing it differentiates.

# Exercise Practises
1 Stable cross-entropy from logits log-sum-exp, numerical stability
2 Backprop through a dense ReLU layer matrix gradients, gradient checking
3 Variance-preserving initialization He initialization
4 Implement Adam optimizers, bias correction
5 Causal self-attention attention, masking
6 RMSNorm normalization
7 Perplexity of a model cross-entropy, perplexity
8 Nucleus (top-p) filtering sampling

Exercise 1: Stable cross-entropy from logits

Compute the mean cross-entropy 1B∑b(LSE⁡(zb)−zb,yb)\frac{1}{B}\sum_b\left(\operatorname{LSE}(\mathbf{z}_b) - z_{b,y_b}\right) for logits that would overflow a naive softmax (Overflow and a Stable Softmax).

python · try it yourself
import numpy as np

Z = np.array([[1000.0, 998.0, 990.0], [-5.0, 2.0, 0.5]])
y = np.array([1, 2])
def lse(Z):
    return np.zeros(len(Z))          # TODO: m + log(sum(exp(Z - m))) with m the row maximum
loss = np.mean(lse(Z) - Z[np.arange(len(y)), y])
print(f"cross-entropy: {loss:.4f}")
cross-entropy: -499.2500

Expected output when solved:

text
cross-entropy: 1.9146
Solution
python · try it yourself
import numpy as np

Z = np.array([[1000.0, 998.0, 990.0], [-5.0, 2.0, 0.5]])
y = np.array([1, 2])
def lse(Z):
    m = Z.max(axis=1)
    return m + np.log(np.sum(np.exp(Z - m[:, None]), axis=1))
loss = np.mean(lse(Z) - Z[np.arange(len(y)), y])
print(f"cross-entropy: {loss:.4f}")
cross-entropy: 1.9146

Exercise 2: Backprop through a dense ReLU layer

For H=ReLU⁡(XWT+b)H = \operatorname{ReLU}(XW^T + \mathbf{b}) and L=12∑H2\mathcal{L} = \frac{1}{2}\sum H^2, the upstream gradient is HH. Write the gradients with respect to WW and b\mathbf{b} and check them against finite differences (Backpropagation Through an MLP).

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
X, W, b = rng.normal(size=(6, 4)), rng.normal(size=(3, 4)), rng.normal(size=3)
L = lambda W, b: 0.5 * np.sum(np.maximum(0, X @ W.T + b) ** 2)
A = X @ W.T + b; H = np.maximum(0, A)
G = np.zeros_like(A)                  # TODO: dL/dA = H * (A > 0)
gW, gb = np.zeros_like(W), np.zeros_like(b)   # TODO: G^T X and the column sums of G
numW = np.array([[(L(W + e, b) - L(W - e, b)) / 2e-6 for e in E] for E in np.eye(12).reshape(3, 4, 3, 4) * 1e-6])
numb = np.array([(L(W, b + e) - L(W, b - e)) / 2e-6 for e in np.eye(3) * 1e-6])
print("dW correct:", np.allclose(gW, numW, atol=1e-5), " db correct:", np.allclose(gb, numb, atol=1e-5))
dW correct: False  db correct: False

Expected output when solved:

text
dW correct: True  db correct: True
Solution
python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
X, W, b = rng.normal(size=(6, 4)), rng.normal(size=(3, 4)), rng.normal(size=3)
L = lambda W, b: 0.5 * np.sum(np.maximum(0, X @ W.T + b) ** 2)
A = X @ W.T + b; H = np.maximum(0, A)
G = H * (A > 0)
gW, gb = G.T @ X, G.sum(axis=0)
numW = np.array([[(L(W + e, b) - L(W - e, b)) / 2e-6 for e in E] for E in np.eye(12).reshape(3, 4, 3, 4) * 1e-6])
numb = np.array([(L(W, b + e) - L(W, b - e)) / 2e-6 for e in np.eye(3) * 1e-6])
print("dW correct:", np.allclose(gW, numW, atol=1e-5), " db correct:", np.allclose(gb, numb, atol=1e-5))
dW correct: True  db correct: True

Exercise 3: Variance-preserving initialization

Choose the weight standard deviation so that a 30-layer ReLU network keeps the activation scale of order 1 (Initialization).

python · try it yourself
import numpy as np

rng = np.random.default_rng(1)
n, L = 256, 30
std = 1.0                             # TODO: He initialization, sqrt(2 / n)
h = rng.normal(size=(500, n))
for _ in range(L):
    h = np.maximum(0, h @ rng.normal(0, std, (n, n)))
print(f"root-mean-square activation after {L} layers: {np.sqrt(np.mean(h**2)):.3e}")
root-mean-square activation after 30 layers: 4.461e+31

Expected output when solved:

text
root-mean-square activation after 30 layers: 1.100e+00
Solution
python · try it yourself
import numpy as np

rng = np.random.default_rng(1)
n, L = 256, 30
std = np.sqrt(2 / n)
h = rng.normal(size=(500, n))
for _ in range(L):
    h = np.maximum(0, h @ rng.normal(0, std, (n, n)))
print(f"root-mean-square activation after {L} layers: {np.sqrt(np.mean(h**2)):.3e}")
root-mean-square activation after 30 layers: 1.100e+00

Exercise 4: Implement Adam

Complete one Adam step (moments, bias correction, update) and minimize f(w)=(w1−3)2+10(w2+1)2f(\mathbf{w}) = (w_1 - 3)^2 + 10(w_2 + 1)^2 (Adam and AdamW).

python · try it yourself
import numpy as np

grad = lambda w: np.array([2 * (w[0] - 3), 20 * (w[1] + 1)])
w, m, v = np.zeros(2), np.zeros(2), np.zeros(2)
lr, b1, b2, eps = 0.1, 0.9, 0.999, 1e-8
for t in range(1, 501):
    g = grad(w)
    # TODO: update m and v, compute the bias-corrected m_hat and v_hat, and step w
print("w after 500 steps:", np.round(w, 3))
w after 500 steps: [0. 0.]

Expected output when solved:

text
w after 500 steps: [ 3. -1.]
Solution
python · try it yourself
import numpy as np

grad = lambda w: np.array([2 * (w[0] - 3), 20 * (w[1] + 1)])
w, m, v = np.zeros(2), np.zeros(2), np.zeros(2)
lr, b1, b2, eps = 0.1, 0.9, 0.999, 1e-8
for t in range(1, 501):
    g = grad(w)
    m = b1 * m + (1 - b1) * g
    v = b2 * v + (1 - b2) * g * g
    m_hat, v_hat = m / (1 - b1**t), v / (1 - b2**t)
    w = w - lr * m_hat / (np.sqrt(v_hat) + eps)
print("w after 500 steps:", np.round(w, 3))
w after 500 steps: [ 3. -1.]

Exercise 5: Causal self-attention

Add the causal mask so that each position attends only to itself and earlier positions, and check that changing the last token leaves the earlier outputs unchanged (Causal Masking).

python · try it yourself
import numpy as np

rng = np.random.default_rng(2)
n, d = 5, 4
Wq, Wk, Wv = (rng.normal(size=(d, d)) for _ in range(3))
def attn(X):
    S = (X @ Wq) @ (X @ Wk).T / np.sqrt(d)
    # TODO: add a mask with -1e9 above the diagonal
    A = np.exp(S - S.max(1, keepdims=True)); A /= A.sum(1, keepdims=True)
    return A @ (X @ Wv)
X = rng.normal(size=(n, d)); X2 = X.copy(); X2[-1] += 5
print("earlier outputs unchanged:", np.allclose(attn(X)[:-1], attn(X2)[:-1]))
earlier outputs unchanged: False

Expected output when solved:

text
earlier outputs unchanged: True
Solution
python · try it yourself
import numpy as np

rng = np.random.default_rng(2)
n, d = 5, 4
Wq, Wk, Wv = (rng.normal(size=(d, d)) for _ in range(3))
def attn(X):
    S = (X @ Wq) @ (X @ Wk).T / np.sqrt(d)
    S = S + np.triu(np.full((n, n), -1e9), k=1)
    A = np.exp(S - S.max(1, keepdims=True)); A /= A.sum(1, keepdims=True)
    return A @ (X @ Wv)
X = rng.normal(size=(n, d)); X2 = X.copy(); X2[-1] += 5
print("earlier outputs unchanged:", np.allclose(attn(X)[:-1], attn(X2)[:-1]))
earlier outputs unchanged: True

Exercise 6: RMSNorm

Implement RMSNorm with gain γ\boldsymbol{\gamma} and check that each normalized token (with γ=1\boldsymbol{\gamma} = \mathbf{1}) has root mean square 1 and that scaling the input changes nothing (Layer Normalization and RMSNorm).

python · try it yourself
import numpy as np

rng = np.random.default_rng(3)
X = rng.normal(2.0, 3.0, size=(4, 8)); gamma = np.ones(8)
def rmsnorm(X, gamma, eps=1e-6):
    return X                          # TODO: gamma * X / sqrt(mean(X^2 over the last axis) + eps)
Y = rmsnorm(X, gamma)
print("rms per token:", np.round(np.sqrt(np.mean(Y**2, axis=1)), 4))
print("scale invariant:", np.allclose(rmsnorm(7 * X, gamma), Y))
rms per token: [4.0187 4.4024 3.5538 3.6391]
scale invariant: False

Expected output when solved:

text
rms per token: [1. 1. 1. 1.]
scale invariant: True
Solution
python · try it yourself
import numpy as np

rng = np.random.default_rng(3)
X = rng.normal(2.0, 3.0, size=(4, 8)); gamma = np.ones(8)
def rmsnorm(X, gamma, eps=1e-6):
    return gamma * X / np.sqrt(np.mean(X**2, axis=-1, keepdims=True) + eps)
Y = rmsnorm(X, gamma)
print("rms per token:", np.round(np.sqrt(np.mean(Y**2, axis=1)), 4))
print("scale invariant:", np.allclose(rmsnorm(7 * X, gamma), Y))
rms per token: [1. 1. 1. 1.]
scale invariant: True

Exercise 7: Perplexity of a model

Given the logits a model produced at each position and the actual next tokens, compute the mean negative log-likelihood and the perplexity (Perplexity).

python · try it yourself
import numpy as np

rng = np.random.default_rng(4)
T, V = 50, 10
logits = rng.normal(size=(T, V)); targets = rng.integers(0, V, T)
logits[np.arange(T), targets] += 2.0            # the model favors the right token a little
nll = 0.0                                       # TODO: mean of logsumexp(logits) - logits[target]
print(f"NLL {nll:.4f} nats/token, perplexity {np.exp(nll):.3f} (uniform: {V})")
NLL 0.0000 nats/token, perplexity 1.000 (uniform: 10)

Expected output when solved:

text
NLL 1.0822 nats/token, perplexity 2.951 (uniform: 10)
Solution
python · try it yourself
import numpy as np

rng = np.random.default_rng(4)
T, V = 50, 10
logits = rng.normal(size=(T, V)); targets = rng.integers(0, V, T)
logits[np.arange(T), targets] += 2.0
m = logits.max(axis=1)
lse = m + np.log(np.sum(np.exp(logits - m[:, None]), axis=1))
nll = np.mean(lse - logits[np.arange(T), targets])
print(f"NLL {nll:.4f} nats/token, perplexity {np.exp(nll):.3f} (uniform: {V})")
NLL 1.0822 nats/token, perplexity 2.951 (uniform: 10)

Exercise 8: Nucleus (top-p) filtering

Keep the smallest set of most likely tokens whose total probability reaches p=0.9p = 0.9, zero the rest and renormalize (Sampling).

python · try it yourself
import numpy as np

probs = np.array([0.05, 0.4, 0.02, 0.25, 0.15, 0.08, 0.05])
def top_p(probs, p):
    q = probs.copy()                  # TODO: sort descending, cumulative sum, keep up to p, renormalize
    return q
q = top_p(probs, 0.9)
print("kept tokens:", np.flatnonzero(q), " filtered:", np.round(q, 3))
kept tokens: [0 1 2 3 4 5 6]  filtered: [0.05 0.4  0.02 0.25 0.15 0.08 0.05]

Expected output when solved:

text
kept tokens: [1 3 4 5 6]  filtered: [0.    0.43  0.    0.269 0.161 0.086 0.054]
Solution
python · try it yourself
import numpy as np

probs = np.array([0.05, 0.4, 0.02, 0.25, 0.15, 0.08, 0.05])
def top_p(probs, p):
    order = np.argsort(probs)[::-1]
    cum = np.cumsum(probs[order])
    keep = order[:np.searchsorted(cum, p) + 1]
    q = np.zeros_like(probs); q[keep] = probs[keep]
    return q / q.sum()
q = top_p(probs, 0.9)
print("kept tokens:", np.flatnonzero(q), " filtered:", np.round(q, 3))
kept tokens: [1 3 4 5 6]  filtered: [0.    0.43  0.    0.269 0.161 0.086 0.054]

Test yourself

In Exercise 2, why is the bias gradient a sum over the rows of GG?

  1. Biases are always summed
  2. The same bias is added to every example in the batch (fan-out)
  3. To normalize the gradient
  4. Because of ReLU

In Exercise 5, what does adding −109-10^9 above the diagonal achieve?

  1. It scales the scores
  2. Future positions get (numerically) zero attention weight
  3. It normalizes the values
  4. It adds position information

In Exercise 7, a perplexity well below the vocabulary size means…

  1. the model is worse than uniform guessing
  2. the model assigns the actual tokens more probability than uniform guessing would
  3. the logits overflowed
  4. nothing