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 for logits that would overflow a naive softmax (Overflow and a Stable Softmax).
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:
cross-entropy: 1.9146Solution
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 and , the upstream gradient is . Write the gradients with respect to and and check them against finite differences (Backpropagation Through an MLP).
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:
dW correct: True db correct: TrueSolution
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).
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:
root-mean-square activation after 30 layers: 1.100e+00Solution
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 (Adam and AdamW).
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:
w after 500 steps: [ 3. -1.]Solution
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).
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:
earlier outputs unchanged: TrueSolution
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 and check that each normalized token (with ) has root mean square 1 and that scaling the input changes nothing (Layer Normalization and RMSNorm).
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:
rms per token: [1. 1. 1. 1.]
scale invariant: TrueSolution
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).
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:
NLL 1.0822 nats/token, perplexity 2.951 (uniform: 10)Solution
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 , zero the rest and renormalize (Sampling).
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:
kept tokens: [1 3 4 5 6] filtered: [0. 0.43 0. 0.269 0.161 0.086 0.054]Solution
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 ?
- Biases are always summed
- The same bias is added to every example in the batch (fan-out)
- To normalize the gradient
- Because of ReLU
In Exercise 5, what does adding above the diagonal achieve?
- It scales the scores
- Future positions get (numerically) zero attention weight
- It normalizes the values
- It adds position information
In Exercise 7, a perplexity well below the vocabulary size means…
- the model is worse than uniform guessing
- the model assigns the actual tokens more probability than uniform guessing would
- the logits overflowed
- nothing