Getting Shapes Right
Most bugs in ML interview code are shape bugs, and the worst ones raise no error. A sum over the wrong axis, a
broadcast that builds an (n, n) matrix, or a reshape that scrambles heads all produce arrays of plausible size
and numbers that look fine. The model then trains a little worse, or not at all, and you find out in minute 40.
The fix is a handful of habits that cost a few seconds each. Interviewers notice them, too: writing shapes as you go is the most visible sign that a candidate has written this kind of code before.
Name Every Dimension
Give every dimension a one-letter name and use the same names everywhere: B batch, T sequence length, D
model width, H heads, C classes, n examples, d features, k clusters or neighbors. Unpack them at the
top of each function, and write the shape of every new array in a comment. Then a mismatch is visible on the page
before you run anything.
import numpy as np
def layer_norm(x: np.ndarray, gain: np.ndarray, eps: float = 1e-5) -> np.ndarray:
B, T, D = x.shape # name every dimension once
assert gain.shape == (D,), gain.shape
mu = x.mean(axis=-1, keepdims=True) # (B, T, 1)
var = x.var(axis=-1, keepdims=True) # (B, T, 1)
out = (x - mu) / np.sqrt(var + eps) * gain # (B, T, D)
assert out.shape == (B, T, D)
return out
Say the names out loud as you write them ("x is batch by time by width"). It settles conventions with the
interviewer early, such as whether a weight is (D_in, D_out) or PyTorch's (D_out, D_in), and it gives you
words to use when you explain the code later.
Assert at the Boundaries
Put assert statements where shapes enter and leave a function, not on every line. Inputs are where wrong
assumptions arrive (a (n,) label vector passed as (n, 1), a mask with the wrong axis order), and outputs are
where your own mistakes surface. An assert with the actual shape in its message turns a confusing failure ten
lines later into an exact one.
def cross_entropy(logits: np.ndarray, y: np.ndarray) -> float:
n, C = logits.shape
assert y.shape == (n,), f"labels should be ({n},), got {y.shape}"
s = logits - logits.max(axis=1, keepdims=True) # (n, C)
log_p = s - np.log(np.exp(s).sum(axis=1, keepdims=True)) # (n, C)
return float(-log_p[np.arange(n), y].mean())
logits = np.array([[2.0, 0.0, 0.0], [0.0, 0.0, 3.0]])
assert np.isclose(cross_entropy(logits, np.array([0, 2])), 0.1672, atol=1e-4)
try:
cross_entropy(logits, np.array([[0], [2]])) # a column of labels
except AssertionError as e:
print(e) # labels should be (2,), got (2, 1)
Without the assert, the column of labels would index log_p[np.arange(2), y] as a (2, 2) array, and the mean
would quietly average the wrong entries. Asserts are cheap enough to leave in interview code; mention that in
production you would turn the hot-path ones into tests.
Broadcasting Bugs
A broadcasting bug is a missing or wrong axis that NumPy fills in for you. The rules are covered in
NumPy Essentials; the dangerous case is a square shape, where a mistake that would
error on (2, 3) runs on (3, 3). Here is a softmax without keepdims:
def softmax_bug(z: np.ndarray) -> np.ndarray: # (n, C)
e = np.exp(z - z.max(axis=-1)) # (n, C) - (n,): lines n up with C
return e / e.sum(axis=-1)
z = np.random.default_rng(0).normal(size=(3, 3))
print(softmax_bug(z).sum(axis=-1).round(2)) # rows don't sum to 1, and no error
try:
softmax_bug(np.zeros((2, 3)))
except ValueError as e:
print("(2, 3):", e)
On the (3, 3) input the row sums come out as 0.92, 0.74 and 2.46, and nothing complains; on (2, 3) the same
code fails at once. Three bugs of this kind come up again and again:
- Missing
keepdims. Symptom: rows that don't sum to 1, or a normalization that mixes examples. Fix:keepdims=Trueon every reduction that is combined with its input. (n, 1)against(n,). Symptom: a loss that is too large and won't fall, from an(n, n)difference. Fix: flatten predictions to(n,)or reshape targets to(n, 1), and assert the result's shape.- Reducing over the batch. Symptom: one example's output changes when other examples in the batch change.
Fix: reduce over the feature axis with
axis=-1; only BatchNorm reduces over the batch, on purpose.
Reshape Versus Transpose
reshape reinterprets the same numbers in memory order, while transpose moves axes. Reshape can safely split
or merge only axes that are next to each other; to change their order, transpose. The standard trap is splitting
attention heads: (B, T, H * dh) must become (B, T, H, dh) and then move H forward, and a direct reshape to
(B, H, T, dh) has the right shape and the wrong contents.
B, T, H, dh = 2, 4, 3, 5
x = np.random.default_rng(1).normal(size=(B, T, H * dh)) # (B, T, H*dh)
right = x.reshape(B, T, H, dh).transpose(0, 2, 1, 3) # (B, H, T, dh)
wrong = x.reshape(B, H, T, dh) # same shape, scrambled
assert right.shape == wrong.shape == (B, H, T, dh)
assert np.allclose(right[0, 1, 2], x[0, 2, 5:10]) # head 1 of token 2: features 5..9
assert not np.allclose(wrong[0, 1, 2], x[0, 2, 5:10])
assert np.array_equal(right.transpose(0, 2, 1, 3).reshape(B, T, H * dh), x) # and back
The wrong version mixes features from different tokens into each head, so attention still runs and the model
still trains, just badly. In PyTorch there is one more wrinkle: after a transpose the tensor is no longer
contiguous, and .view refuses to merge its axes.
import torch
t = torch.arange(24.0).reshape(2, 3, 4).transpose(1, 2) # (2, 4, 3), not contiguous
try:
t.view(2, 12)
except RuntimeError as e:
print("view:", str(e)[:50])
assert t.reshape(2, 12).shape == (2, 12) # copies when it has to
assert torch.equal(t.contiguous().view(2, 12), t.reshape(2, 12))
Use .reshape, or .contiguous().view(...) if you want the copy to be explicit. The
multi-head attention write-up uses exactly this split and merge.
Test on Tiny Inputs
Run every function on a tiny input before the real one, with sizes that all differ, such as (2, 3, 4), so a
swapped axis either errors or gives a visibly wrong shape. Then check one value you can compute by hand, and one
property that must hold. Testing on a (2, 3) input takes seconds; debugging a (64, 512, 768) one takes the
rest of the round.
x = np.arange(24, dtype=float).reshape(2, 3, 4) # (B, T, D): no two sizes equal
out = layer_norm(x, np.ones(4))
assert out.shape == (2, 3, 4)
row = np.array([0.0, 1.0, 2.0, 3.0]) # x[0, 0], by hand: mean 1.5, var 1.25
assert np.allclose(out[0, 0], (row - 1.5) / np.sqrt(1.25 + 1e-5))
assert np.allclose(out.mean(axis=-1), 0) # property: each row is centered
x2 = x.copy()
x2[1] += 100.0 # change only example 1
assert np.allclose(layer_norm(x2, np.ones(4))[0], out[0]) # example 0 must not notice
The last check is the batch-independence test, and it catches a reduction over the wrong axis even when every shape is right. Similar one-line properties exist for most model parts: a causal output must not change when a later token changes, softmax rows must sum to 1, a permutation of the batch must permute the output. For a backward pass, add a gradient check.
Key Takeaways
- Name every dimension, unpack them at the top of each function, and comment the shape of every new array.
- Assert shapes where they enter and leave a function, with the actual shape in the message.
- Square shapes hide broadcasting bugs. Use
keepdims=Trueand test on sizes that all differ. reshapesplits and merges neighboring axes;transposemoves them. Split heads withreshape(B, T, H, dh).transpose(0, 2, 1, 3).- In PyTorch, use
.reshapeor.contiguous().viewafter a transpose. - Test on a tiny input: one value by hand, one property, and the batch-independence check.