TExcelTAD
Home › Math for Deep Learning & LLMs › Deep Learning Math with NumPy

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∈RB×dX \in \mathbb{R}^{B \times d} X.shape == (B, d)
a dense layer H=XWT+bTH = XW^T + \mathbf{b}^T (rows are examples) H = X @ W.T + b
an elementwise activation σ(H)\sigma(H) np.maximum(0, H), np.tanh(H)
logits to probabilities softmax⁡\operatorname{softmax} along the class axis exp(z - max) / sum over axis=-1
a loss averaged over the batch 1B∑bℓb\frac{1}{B}\sum_b \ell_b loss.mean()
a parameter update θ←θ−η∇L\boldsymbol{\theta} \leftarrow \boldsymbol{\theta} - \eta\nabla\mathcal{L} 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.

python · try it yourself
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).

python · try it yourself
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:

python · try it yourself
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 explicit PRNGKey and NumPy's default_rng(seed) all make runs reproducible.
  • Frameworks replace the hand-written backward lines with loss.backward() or jax.grad, built on the same chain rule (Building a Tiny Autodiff Engine).
  • Mixed-precision training keeps a float32 master copy of the weights while computing in 16-bit.

Exercises

Exercise 1: Layer shapes

XX is (64,100)(64, 100) and a layer has WW of shape (50,100)(50, 100). What is the output shape, and what is the shape of the gradient with respect to WW?

Answer

Output (64,50)(64, 50); gradient (50,100)(50, 100).

Solution

XWTXW^T is (64×100)(100×50)(64 \times 100)(100 \times 50). A gradient always has the shape of the parameter, so ∂L/∂W\partial\mathcal{L}/\partial W is (50,100)(50, 100); it is computed as GTXG^TX with GG of shape (64,50)(64, 50).

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: 7×109⋅4=2.8×10107 \times 10^9 \cdot 4 = 2.8 \times 10^{10} bytes. bfloat16 uses 2 bytes, half of that.

Exercise 3: Batch gradient (code)

For H=XWTH = XW^T and upstream gradient G=∂L/∂HG = \partial\mathcal{L}/\partial H, the weight gradient is GTXG^TX. Verify it numerically for L=∑H2/2\mathcal{L} = \sum H^2/2.

Answer

The formula matches the numerical gradient.

Solution

For L=12∑H2\mathcal{L} = \frac{1}{2}\sum H^2 the upstream gradient is G=HG = H.

python · try it yourself
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 WW of shape (out, in) computes…

  1. WXWX
  2. XWT+bXW^T + \mathbf{b}
  3. XTWX^TW
  4. WTXTW^TX^T

About how many significant decimal digits does float32 carry?

  1. 3
  2. 7
  3. 16
  4. 32

The four steps of a training iteration are…

  1. forward, loss, backward, update
  2. load, save, print, exit
  3. update, forward, loss, backward
  4. sample, sort, loss, update