1/26
Learn

Four functions, four array moves

Model coding rounds ask you to write attention, a small GPT or backprop in NumPy or PyTorch. Most lines of those programs make one of a few array moves: reduce along an axis and use the result on the same table, pick one entry per row, add an axis, or multiply stacks of matrices. A wrong move often runs with no error. This lesson's practice problem puts the moves in four small functions:

Write four NumPy functions with no Python loops over rows, positions or batches. ... means any number of leading axes, like a batch and heads.

  1. normalize_rows(x): x is (..., n) with positive entries. Return the same shape, with each row divided by its own sum.
  2. standardize(x, eps=1e-5): return the same shape, with each row shifted to mean 0 and divided by sqrt(var + eps), where var is the row's variance.
  3. pick(probs, labels): probs is (..., k), and labels holds one class number per row, shape (...). Return each row's probability at its label.
  4. cosine_scores(a, b): a is (..., n, d) and b is (..., m, d). Return (..., n, m): the cosine similarity of every row of a with every row of b.
CallReturns
normalize_rows([[1, 3], [2, 2]])[[0.25, 0.75], [0.5, 0.5]]
standardize([[1, 2, 3]])[[-1.22, 0, 1.22]], rounded
pick([[0.7, 0.2, 0.1], [0.1, 0.8, 0.1]], [0, 1])[0.7, 0.8]
cosine_scores([[1, 0]], [[2, 0], [0, 3]])[[1, 0]]

The tests use square inputs on purpose. On a square table, a missing keepdims runs with no error and gives wrong numbers. By the end of Part 2 you'll see why, and you'll spot it on sight.

This lesson teaches the moves one at a time on one small table, students' scores on three tests: shapes and axes, keepdims, broadcasting, picking entries, and @ on stacks. Thirteen steps end with a small task in the editor. The whole problem comes back at the end, as the lesson's practice, from a blank file.