Shape contracts: catching silent tensor bugs
Most neural-network bugs don't crash. Name every axis, check shapes where data enters and between layers, and learn the three silent traps — broadcasting, flatten order and channel layout.
You will be able to
- Write a shape contract for each layer boundary of a small network
- Spot a broadcasting bug that returns a wrong number without an error
- Explain why flatten order differs between Python and R
- Tell channels-first from channels-last layouts and convert between them
Name every axis
ReadA tensorTensorAn array with any number of axes, such as batch × channels × height × width. Its shape is part of the data contract. is a grid of numbers whose axes mean something: rows of a batch, channels, height, width, time steps, features. A shape contractShape contractA stated, checked rule for every array's shape and meaning (rows, channels, steps) at each layer boundary. writes those meanings down at every layer boundary, then checks them in code:
| Where | Contract |
|---|---|
| Image batch entering a CNN | B × C × H × W (channels first) |
| Sequence batch entering an RNN | B × T × F |
| Logits leaving a classifier | B × K |
| Targets for cross-entropy | B integers in 0 … K − 1 |
A wrong shape that happens to be legal doesn't raise an error. It computes something else.
Pick a bug: some stop with an error, others run quietly with wrong numbers.
DExplorable · Shape contracts
Which tensor bugs stop with an error, and which run quietly and give wrong answers?
Bug
Each tensor carries axis names that every step checks.
- input x(2, 5, 8)(batch, time, feature)ok
- x @ W_qkv(2, 5, 24)(batch, time, 3·feature)ok
- split into 2 heads(2, 5, 2, 4)(batch, time, head, head_dim)ok
- transpose(2, 2, 5, 4)(batch, head, time, head_dim)ok
- q @ kᵀ / √d(2, 2, 5, 5)(batch, head, query, key)ok
- + mask(2, 2, 5, 5)mask (batch, 1, 1, key)ok
- softmax over keys(2, 2, 5, 5)rows sum to 1ok
- @ v, merge heads(2, 5, 8)(batch, time, feature)ok
- mean over time(2, 8)(batch, feature)ok
- @ W_out(2, 3)(batch, class)ok
- loss against B labels(2)one row per exampleok
Logits move by up to 0.0000 on the same random arrays. Correct logits for sequence 1: 0.381, −0.378, 0.251.
- Errors
- 0
- Silent problems
- 0
- Logit change
- 0.000
- Puzzle: Find a bug and sizes that run without any error but change the logits.
Every step's shape matches its contract, from (2, 5, 8) to (2, 3) logits. Pick a bug to see which ones a shape check catches.
A bug that runs
Exploreimport numpy as np
rng = np.random.default_rng(0)
y = rng.normal(size=100) # targets, shape (100,)
pred = y[:, None] + 0.1 # predictions, shape (100, 1): off by 0.1 everywhere
print("loss as written:", np.mean((pred - y) ** 2)) # (100, 1) − (100,) → (100, 100)!
print("loss intended: ", np.mean((pred[:, 0] - y) ** 2)) # 0.01
print("contract holds: ", pred.shape == y.shape) # False: the check exposes itset.seed(0)
y <- rnorm(100) # targets, length 100
pred <- matrix(y + 0.1, ncol = 1) # predictions, 100 × 1
y_half <- y[1:50] # a bug upstream lost half the targets
d <- pred - y_half # no error, no warning: R recycles the 50 values
cat("loss as written:", mean(d^2), "\n")
cat("loss intended: ", mean((pred[, 1] - y)^2), "\n")
cat("contract holds: ", length(y_half) == nrow(pred), "\n") # FALSE: the check exposes itIn Python, subtracting a (100,) vector from a (100, 1) column broadcastsBroadcastingStretching a smaller array along missing or size-1 axes so element-wise math works, without copying it. to a 100 × 100 table of every prediction minus every target, and the "loss" is far from the intended 0.01. R doesn't broadcast, but it recycles a short vector without a word. Neither program crashes; only the contract check notices.
Flatten order and channel layout
ReadTwo more traps move numbers to the wrong place without an error.
Flatten order. NumPy and torch flatten row by row (row-major); R stores matrices column by column, so as.vector(m) reads down the columns. The CodeSplash CNN expects pixel columns in reading order, row 1 left to right, then row 2. In R, transpose before flattening an image row by row.
Channel layout. Torch wants B × C × H × W (channels first); many image libraries return H × W × C. A reshape from one to the other keeps the numbers in memory order and scrambles the image. Use a transpose (permute), then check one pixel by hand.
Which one is safe?
PredictPredict first
An image x has shape 32 × 32 × 3 (height, width, channels). Which call gives a correct 3 × 32 × 32 channels-first array?
Reveal
x.transpose(2, 0, 1) moves the channel axis to the front and keeps every pixel's three values together. reshape only reinterprets the same memory, so its first "channel" is a mix of all three colors from the top rows.
Check: shape contracts
CheckpointCheck yourself
In NumPy, predictions of shape (64, 1) minus targets of shape (64,) gives what shape?
Show the answer
Answer: a
Broadcasting stretches the column across 64 columns and the vector down 64 rows. Squeeze the predictions or reshape the targets first.
Check yourself
In R, m is the 2 × 2 matrix with rows (1, 2) and (3, 4). What does as.vector(m) return?
Show the answer
Answer: a
R stores matrices by column. as.vector(t(m)) gives the row-by-row order NumPy uses.
Check yourself
A cross-entropy loss gets logits of shape B × K and one-hot targets of shape B × K where it expects B class indices. Which outcome is most dangerous?
Show the answer
Answer: a
Some libraries accept both forms with different meanings. State the target contract and assert it.
Check yourself
Where do shape assertions catch the most bugs for the least code?
Show the answer
Answer: a
Inputs and hand-written boundaries are where layouts, flatten orders and broadcasting slip. Library internals are already tested.
Recap
Recap- Name every axis and check shapes where data enters and between your own layers.
- Broadcasting (NumPy, torch) and recycling (R) turn wrong shapes into wrong numbers, not errors.
- Python flattens row-major, R column-major; torch is channels first, many image readers channels last.
- Use transposes to reorder axes;
reshapeonly reinterprets memory.
Concepts in this lesson