27NumPy axes, broadcasting and stacks
27 NumPy axes, broadcasting and stacks
Four small functions, one level each. Each one is a move the attention and backprop lessons make in a single line: reduce over an axis and broadcast the result back, pick one entry per row, and multiply stacks of matrices. No Python loops over rows, positions or batches. Every function is a few array operations.
Set a 25-minute timer. Read one level at a time and run only its tests until they pass: pytest problems/27_numpy_axes -k level1.
Earlier levels must keep passing.
Shapes use ... for any number of leading axes (batch, heads), and a row is a slice along the last axis.
Level 1. normalize_rows(x). x is (..., n) with positive entries. Return the same shape with every row
divided by its own sum, so each row sums to 1.
Level 2. standardize(x, eps=1e-5). x is (..., n). Return the same shape with every row shifted to mean
0 and scaled to variance 1: subtract the row's mean, then divide by sqrt(var + eps), where var is the row's
mean squared deviation (what np.var computes by default). A constant row comes out as zeros, not nan. This is
LayerNorm without its learned scale and shift.
Level 3. pick(probs, labels). probs is (..., k), a distribution over k classes at every position, and
labels is an integer array with the leading shape (...), each entry in [0, k). Return each position's
probability at its label, with the shape of labels: (N, k) and (N,) give (N,), and (B, T, k) and
(B, T) give (B, T).
Level 4. cosine_scores(a, b). a is (..., n, d) and b is (..., m, d), with the same leading axes.
Return (..., n, m): entry [..., i, j] is the cosine similarity of row i of a and row j of b, their dot
product divided by both of their lengths. No row is all zeros.
Things to get right: keepdims=True on every reduction you broadcast back (the tests use square inputs, where
dropping it runs without an error), the axis each reduction runs over, integer arrays that pair up instead of
crossing, and np.swapaxes(b, -1, -2) rather than b.T, which reverses every axis of a stack.