AI from scratch · Toolkit 1 · Stage 4: the engineer's toolkit

NumPy in depth

Every model on this path has been NumPy underneath: a batch is an array, a layer is a matrix product, a loss is a mean. Start 2 showed that arrays do arithmetic without loops. This lesson is the rest of what you need to write array code that is fast and right: how shapes combine, when two names share one array, how to turn any loop into array operations, one notation for every sum over indices, and how much memory it all takes. Most bugs in ML code are shape bugs, and most of them are silent.

1. Shapes and axes

An array's shape lists its sizes, outermost first. A table of 5 rides with 3 numbers each (km, minutes, passengers) has shape (5, 3): 5 rows, 3 columns. In ML the habit is rows are examples, columns are features, so a batch of 64 photos of 28 × 28 pixels is (64, 28, 28).

Many functions take an axis: the one that gets used up. X.mean(axis=0) averages down the rows, leaving one number per column (the average ride); X.mean(axis=1) averages across each row, one number per ride. Leave the axis out and everything is averaged into one number.

A batch X has shape (1000, 20): 1,000 examples, 20 features. What shape is X.mean(axis=0)?

Axis 0 (the 1,000 examples) is used up, leaving one mean per feature: the average example. That's the first half of standardizing a table.

An axis is a direction through the array; a reduction along it uses it up, and rows-are-examples is the convention everything assumes.

2. Broadcasting: how different shapes combine

X - X.mean(axis=0) subtracts a (3,) array from a (5, 3) one, and it works: the 3 means are subtracted from every row. That's broadcasting, and it follows one rule:

Line the shapes up from the right. Each pair of sizes must be equal, or one of them must be 1. A missing size counts as 1. Size-1 axes are stretched to match.

Pick two shapes and see what happens. Faded cells are stretched copies: NumPy doesn't actually make them.

What shape is A + B when A is (4, 1) and B is (3,)?

From the right: 1 vs 3 → 3; 4 vs (missing = 1) → 4. Every row of A gets every element of B: a 4 × 3 table. That's exactly the trap in the box above when you didn't mean it.

Broadcasting lines shapes up from the right and stretches every size-1 axis for free, so one rule covers "subtract the column means" and "build a whole table".

Why broadcasting costs no memory
  1. An array is a flat block of numbers plus a stride per axis: how many bytes to jump to get to the next index along that axis.
  2. A (4, 3) array of 8-byte floats has strides (24, 8): next column is 8 bytes on, next row is 3 numbers (24 bytes) on.
  3. Stretching a size-1 axis just sets its stride to 0: "the next index along this axis is the same number again".
  4. So B of shape (3,) seen as (4, 3) has strides (0, 8): every row reads the same three numbers, and no copies are made. np.broadcast_to(B, (4, 3)).strides shows it.
  5. The rule lines up from the right because the last axis is the one stored side by side in memory: a 1-D array most naturally matches a row, which is what "subtract the column means" needs.

3. Views and copies: two names, one array

Slicing an array doesn't copy it. first_rows = X[:2] is a view: a new name looking at the same memory. Change the view and the original changes. That makes slicing instant even on a huge array, and it's a classic bug. Indexing with a list or a mask (fancy indexing) makes a copy instead, because the chosen items aren't evenly spaced in memory any more.

batch = data[:64], then batch -= batch.mean(). What happened to data?

In-place operations (-=, [...] =) write into the shared memory. If the next epoch slices data again, those rows get centered twice. Use batch = data[:64] - data[:64].mean() (a new array) or .copy().

A slice is a window onto the same memory; a list or a mask makes a copy; and an in-place change through a window changes the original.

4. Turning any loop into array code

Almost every loop over numbers has an array version, built from a few moves:

The loop doesThe array way
The same arithmetic on each itemWrite it once on the whole array: a * km + b
if on each itemA mask and np.where(cond, if_true, if_false), or np.clip for limits
Keep only some itemsx[x > 0]
A running totalnp.cumsum
Every pair of two listsBroadcasting a column against a row: a[:, None] - b[None, :]
Count per categorynp.bincount, or np.unique(..., return_counts=True)
Sort by somethingnp.argsort: the positions in sorted order

The pairs move is the one that unlocks kNN, clustering and attention: every distance between 500 points and 400 others, as one (500, 400) table.

On a laptop the broadcast version is about 58 times faster; the box prints what your browser gets. The loop asks Python about every one of the 200,000 pairs; the array version asks once.

Which array expression replaces this loop? for i in range(len(x)): y[i] = x[i] if x[i] > 0 else 0.1 * x[i]

An if on each item is a mask plus np.where. This one is the "leaky ReLU" activation.

A loop over numbers becomes array code through a handful of moves: whole-array arithmetic, masks with np.where, cumsum, argsort, and a column against a row for every pair.

5. einsum: one notation for every sum over indices

Matrix products, dot products, traces, batch products: they're all "multiply matching entries and add some indices up". np.einsum writes exactly that. You name each axis with a letter; letters that appear in the inputs but not after the arrow get summed.

\[ C_{ik} = \sum_j A_{ij} B_{jk} \quad\Longleftrightarrow\quad \texttt{np.einsum("ij,jk->ik", A, B)} \]

What does np.einsum("ij,ij->", A, B) compute?

Both letters appear in the inputs and neither after the arrow, so both are summed: \(\sum_{i,j} A_{ij} B_{ij}\). That's the "Frobenius inner product", the dot product of two matrices treated as long vectors.

einsum names each axis with a letter, multiplies matching entries, and sums every letter missing after the arrow.

6. Memory and number types

Each number takes a fixed number of bytes set by its dtype: 8 for float64 (NumPy's default), 4 for float32 (what deep learning uses), 2 for float16. So an array's memory is just its size times that. Estimate before you allocate: it's the cheapest bug catch there is.

A dataset of 1,000,000 examples with 1,000 features each, stored as float32. About how many gigabytes? (A whole number.)

\(10^6 \times 10^3 \times 4 \text{ bytes} = 4 \times 10^9\) bytes = 4 GB. As float64 it would be 8 GB, more than many laptops can spare: load it in chunks, or keep float32.

Memory is size times bytes per number: estimate it before you allocate, and remember float32 keeps only about seven digits.

Where it breaks: silent shapes, slow drift, sudden memory

7. What to carry forward

All lessons: AI from scratch. The NumPy user guide's pages on broadcasting and on copies and views go further.

Last updated