Deep Learning Math with NumPy
Deep-learning frameworks are, at their core, array libraries with automatic gradients and GPU kernels. Everything in this course can be done with NumPy arrays and hand-written gradients, which is slower but shows exactly what happens. This lesson sets the conventions: batch-first shapes, float32 versus float64, and seeded randomness.
Conventions used in this course
| Concept | Math | NumPy |
|---|---|---|
| a batch of inputs | X.shape == (B, d) |
|
| a dense layer | (rows are examples) | H = X @ W.T + b |
| an elementwise activation | np.maximum(0, H), np.tanh(H) |
|
| logits to probabilities | along the class axis | exp(z - max) / sum over axis=-1 |
| a loss averaged over the batch | loss.mean() |
|
| a parameter update | W -= lr * gW |
Weight matrices are stored as (out, in), like PyTorch's nn.Linear, so a single example is transformed by W @ x and a batch by X @ W.T.
import numpy as np
rng = np.random.default_rng(0)
B, d_in, d_out = 8, 5, 3
X = rng.normal(size=(B, d_in))
W = rng.normal(size=(d_out, d_in)); b = np.zeros(d_out)
H = X @ W.T + b
print("batch:", X.shape, "-> layer output:", H.shape)
print("row 0 equals W @ x0:", np.allclose(H[0], W @ X[0] + b))batch: (8, 5) -> layer output: (8, 3)
row 0 equals W @ x0: True
float32 by default
GPUs train in 32-bit (or 16-bit) floats. NumPy defaults to 64-bit. The difference is invisible for most examples in this course, but it matters for precision, memory and speed: a float32 has about 7 significant decimal digits, a float64 about 16 (Floating Point).
import numpy as np
a64 = np.ones(1_000_000, dtype=np.float64) * 0.1
a32 = a64.astype(np.float32)
print("memory float64:", a64.nbytes // 1_000_000, "MB float32:", a32.nbytes // 1_000_000, "MB")
print("float32 epsilon:", np.finfo(np.float32).eps, " float64 epsilon:", np.finfo(np.float64).eps)
print("1 + 1e-8 in float32 == 1:", np.float32(1) + np.float32(1e-8) == np.float32(1))memory float64: 8 MB float32: 4 MB
float32 epsilon: 1.1920929e-07 float64 epsilon: 2.220446049250313e-16
1 + 1e-8 in float32 == 1: True
Training-loop skeleton
Every training example in this course follows the same four lines: forward pass, loss, backward pass, update. Here is the skeleton on the simplest model, linear regression, with the gradient written by hand:
import numpy as np
rng = np.random.default_rng(1)
X = rng.normal(size=(256, 2)); y = X @ np.array([3.0, -2.0]) + 0.5
w, b, lr = np.zeros(2), 0.0, 0.1
for step in range(101):
pred = X @ w + b # forward
loss = np.mean((pred - y) ** 2) # loss
g = 2 * (pred - y) / len(y) # backward: dloss/dpred
gw, gb = X.T @ g, g.sum()
w, b = w - lr * gw, b - lr * gb # update
if step % 25 == 0:
print(f"step {step:3d} loss {loss:.6f}")
print("learned:", np.round(w, 4), round(b, 4))step 0 loss 12.535873
step 25 loss 0.000455
step 50 loss 0.000000
step 75 loss 0.000000
step 100 loss 0.000000
learned: [ 3. -2.] 0.5
In software
- PyTorch's
torch.manual_seed, JAX's explicitPRNGKeyand NumPy'sdefault_rng(seed)all make runs reproducible. - Frameworks replace the hand-written backward lines with
loss.backward()orjax.grad, built on the same chain rule (Building a Tiny Autodiff Engine). - Mixed-precision training keeps a
float32master copy of the weights while computing in 16-bit.
Exercises
Exercise 1: Layer shapes
is and a layer has of shape . What is the output shape, and what is the shape of the gradient with respect to ?
Answer
Output ; gradient .
Solution
is . A gradient always has the shape of the parameter, so is ; it is computed as with of shape .
Exercise 2: Memory of a model
How many megabytes do the weights of a 7-billion-parameter model take in float32, and in bfloat16?
Answer
28,000 MB (28 GB) and 14,000 MB (14 GB).
Solution
4 bytes per float32 parameter: bytes. bfloat16 uses 2 bytes, half of that.
Exercise 3: Batch gradient (code)
For and upstream gradient , the weight gradient is . Verify it numerically for .
Answer
The formula matches the numerical gradient.
Solution
For the upstream gradient is .
import numpy as np
rng = np.random.default_rng(2)
X, W = rng.normal(size=(4, 3)), rng.normal(size=(2, 3))
L = lambda W: 0.5 * np.sum((X @ W.T) ** 2)
G = X @ W.T
num = np.zeros_like(W)
for i in range(2):
for j in range(3):
E = np.zeros_like(W); E[i, j] = 1e-6
num[i, j] = (L(W + E) - L(W - E)) / 2e-6
print(np.allclose(G.T @ X, num, atol=1e-6))True
Test yourself
With examples as rows, a dense layer with weights of shape (out, in) computes…
About how many significant decimal digits does float32 carry?
- 3
- 7
- 16
- 32
The four steps of a training iteration are…
- forward, loss, backward, update
- load, save, print, exit
- update, forward, loss, backward
- sample, sort, loss, update