Skip to content

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.

Applied ~12 min6 steps

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

Read first

01

Name every axis

Read

A 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:

WhereContract
Image batch entering a CNNB × C × H × W (channels first)
Sequence batch entering an RNNB × T × F
Logits leaving a classifierB × K
Targets for cross-entropyB 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?

2
5
8
2
3

Bug

Each tensor carries axis names that every step checks.

  1. input x(2, 5, 8)(batch, time, feature)ok
  2. x @ W_qkv(2, 5, 24)(batch, time, 3·feature)ok
  3. split into 2 heads(2, 5, 2, 4)(batch, time, head, head_dim)ok
  4. transpose(2, 2, 5, 4)(batch, head, time, head_dim)ok
  5. q @ kᵀ / √d(2, 2, 5, 5)(batch, head, query, key)ok
  6. + mask(2, 2, 5, 5)mask (batch, 1, 1, key)ok
  7. softmax over keys(2, 2, 5, 5)rows sum to 1ok
  8. @ v, merge heads(2, 5, 8)(batch, time, feature)ok
  9. mean over time(2, 8)(batch, feature)ok
  10. @ W_out(2, 3)(batch, class)ok
  11. 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.

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.

02

A bug that runs

Explore
Python
import 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 it
R
set.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 it

In 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.

03

Flatten order and channel layout

Read

Two 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.

04

Which one is safe?

Predict

Predict first

An image x has shape 32 × 32 × 3 (height, width, channels). Which call gives a correct 3 × 32 × 32 channels-first array?

x.reshape(3, 32, 32)x.transpose(2, 0, 1)Both give the same 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.

05

Check: shape contracts

Checkpoint

Check 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.

06

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; reshape only reinterprets memory.

Concepts in this lesson