All courses
Courses › How LLMs really work · foundation

Vectorized numpy

Apply operations to whole arrays, broadcast across shapes, and reduce with sum/mean/max along an axis.

Builds on: numpy arrays and shapes

▶ Watch this lesson Start the whole course

What the animation says

Why not a loop?

Here's a table of numbers: a thousand rows, five hundred twelve columns. We want three things: multiply everything by ten, subtract each column's average, and find each row's largest value. With Python loops, that's nested for statements over half a million entries. Slow, and easy to get an index wrong. Numpy lets you write each step as one line about the whole table. The looping still happens, but inside numpy's fast built-in routines, not in slow Python steps.

Elementwise and the stamp

Let's shrink the table to two rows and three columns, holding one through six. X times ten works position by position. Every entry is multiplied, and you wrote no loop. Adding two arrays of the same shape also pairs entries, position by position. Now subtract a single row of three numbers. Numpy reuses that row, like a stamp pressed onto every row. But what if you subtract two numbers instead, one meant for each row? What happens?

Line shapes up from the right

It's an error. Numpy lines shapes up from the right. Write two, three above two. The rightmost sizes, three and two, are compared. They differ, and neither is one, so it fails. The rule: each pair must be equal, or one of them must be one. A missing size counts as one. Two, three with just three: the threes match, the missing size becomes one, and the result is two by three. So subtracting a row of three column averages works: each row loses its own column's average.

Reductions collapse an axis

Reductions like sum, mean and max collapse one axis. Summing along axis zero adds down each column. One plus four is five, then seven, then nine. Shape three. Axis zero disappears from the shape. One number per column remains. Mean along axis zero divides by the two rows: two and a half, three and a half, four and a half. Those are the averages we used. Your turn. Which arrow shows how a sum along axis one adds?

keepdims: keep the slot

Now subtract each row's maximum from that row. Max along axis one gives three and six, shape two. Lined up from the right against two, three, that's the same error as before. Add keepdims equals true. The collapsed axis stays, as size one. Shape two by one. From the right: three against one, so the one stretches across the columns. Two against two matches. So what is the first row of X minus this row maximum?

The whole picture

Minus two, minus one, zero. The second row, four, five, six minus six, gives the same. Three ideas. Write the operation for the whole array, and let numpy do the looping. Match shapes from the right: sizes equal or one, and ones get stretched. Reducing along an axis removes that axis from the shape. And use keepdims when you want to combine the result with the original array again.

Why not just write a loop?

Suppose a table of numbers has shape (1000, 512): 1000 rows, 512 columns. You want to multiply everything by 10, subtract each column's average, then find each row's largest value. With Python loops, that is nested `for` statements over about half a million entries: slow and easy to get wrong. How can you say "do this to the whole table" in one line and have it run fast?

Whole-array ops, stretching, collapsing

Three ideas cover most of it. - **Elementwise**: `X * 10` or `X + Y` (same shape) works position by position. You write no loop; numpy does the looping internally, in its own fast built-in routines rather than slow Python steps. - **Broadcasting**: if one shape is "smaller", numpy reuses it along the missing or size-1 directions, like a stamp pressed onto every row. - **Reduction**: `sum`, `mean` and `max` along one axis collapse that axis. Each line of entries along it becomes a single number, so you get one result per remaining position.

The exact rules

**Broadcasting:** 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). The result takes the larger size. So (2,3) with (3,) gives (2,3), but (2,3) with (2,) is an error, since 3 ≠ 2. **Reduction:** for $X$ of shape $(T,d)$, `X.sum(axis=0)` gives $s_j=\sum_i X_{ij}$, shape $(d,)$. The chosen axis disappears; `keepdims=True` keeps it as size 1.

Worked by hand

$X=\begin{bmatrix}1&2&3\\4&5&6\end{bmatrix}$, shape (2,3). - `X.sum(axis=0)` adds down the columns: $[5,7,9]$, shape (3,). - `X.sum(axis=1)` adds across the rows: $[6,15]$, shape (2,). - `X.mean(axis=0)` $=[2.5,3.5,4.5]$. - `X - X.mean(axis=0)`: (2,3) minus (3,) reuses the row of averages for each row, giving $\begin{bmatrix}-1.5&-1.5&-1.5\\1.5&1.5&1.5\end{bmatrix}$.

Try it, including keepdims

`X.max(axis=1)` has shape (2,), which does not line up with (2,3) from the right. `keepdims=True` gives shape (2,1). The 1 then stretches across the columns, so each row has its own maximum subtracted from it.
import numpy as np
X = np.array([[1., 2., 3.],
              [4., 5., 6.]])         # shape (2, 3)
print(X * 10)                        # every entry times 10
col_mean = X.mean(axis=0)            # shape (3,): [2.5 3.5 4.5]
print(X - col_mean)                  # (2,3) - (3,) -> (2,3)
row_max = X.max(axis=1, keepdims=True)  # shape (2,1): [[3.],[6.]]
print(X - row_max)                   # [[-2. -1.  0.] [-2. -1.  0.]]
print(X.sum(axis=1))                 # [ 6. 15.]

Remember

Write the operation for the whole array and let numpy do the looping. Shapes are matched from the right: sizes must be equal or 1, and size-1 directions get stretched. Reducing along an axis removes that axis from the shape. Use `keepdims=True` when you want to combine the result with the original array again.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.