Tensor Shapes and Broadcasting: Reading the Dimensions of a Model
Read array shapes with confidence, apply the broadcasting rules, and catch the silent shape bugs that corrupt a loss without raising errors.
Key takeaways
- A shape is only useful when you know what each axis stands for, such as batch, tokens or channels.
- Broadcasting compares shapes from the right, and two lengths are compatible if they are equal or one of them is 1.
- Subtracting an array of shape (n,) from one of shape (n, 1) silently produces an n by n result.
- Reshaping and transposing can give the same shape with the values in different places.
- Shape comments, assertions and unequal test sizes catch errors early.
In machine learning code, a tensor is a multidimensional array of numbers, and its shape lists the length of each axis. If you can say what every axis means at every line, most dimension errors disappear and model code becomes much easier to read.
Broadcasting is the rule that lets arrays of different shapes combine in element-wise operations. It saves code and memory, and it is also the source of bugs that run without any error and give wrong numbers.
Naming the axes
A single number has shape (). A vector has shape (d,). A table has shape (n, d). Higher-dimensional tensors add axes for structure.
| Data | Typical shape | Axes |
|---|---|---|
| Tabular batch | (B, d) | batch, features |
| Image batch, channels first | (B, C, H, W) | batch, channels, height, width |
| Image batch, channels last | (B, H, W, C) | batch, height, width, channels |
| Token IDs | (B, T) | batch, tokens |
| Token vectors | (B, T, d) | batch, tokens, embedding width |
| Attention weights | (B, h, T, T) | batch, heads, query position, key position |
Libraries differ in their default image layout. PyTorch layers conventionally expect channels first, while Keras commonly uses channels last. Check the documentation for the layer you call.
Following shapes through a model
Walk a batch of 32 token sequences of length 20 through a toy text classifier with embedding width 64 and 5 classes.
token IDs (32, 20)
embedding lookup (32, 20, 64)
dense layer, 64 → 64 (32, 20, 64) last axis transformed
average over tokens (axis 1) (32, 64)
output layer, 64 → 5 (32, 5) one score per class A dense layer acts on the last axis and leaves earlier axes alone. A reduction such as a mean removes the axis you reduce over. If sequences are padded to a common length, a plain average would include the padding, so you need a mask of shape (32, 20) and a division by the count of real tokens.
The broadcasting rules
NumPy, PyTorch and related libraries follow essentially the same rules for element-wise operations.
- Line up the two shapes at their right ends.
- If one shape is shorter, treat its missing leading axes as length 1.
- For each axis, the lengths must be equal, or one of them must be 1.
- The result takes the larger length on each axis, and the length-1 side is repeated along it.
| Left | Right | Result |
|---|---|---|
| (32, 10) | (10,) | (32, 10) |
| (32, 10) | (32, 1) | (32, 10) |
| (3, 1) | (4,) | (3, 4) |
| (8, 1, 6, 1) | (7, 1, 5) | (8, 7, 6, 5) |
| (3,) | (4,) | error |
| (32, 10) | (32,) | error |
The last row surprises people. Alignment starts at the right, so the 32 is compared with 10. To apply one value per row, give the vector shape (32, 1).
The repetition is conceptual. Libraries do not normally copy the data to perform it, although the output itself takes memory.
The silent bug in a loss function
Suppose a model returns predictions with shape (n, 1) and your targets have shape (n,). Subtracting them broadcasts to (n, n): every prediction minus every target.
import numpy as np
y_hat = np.array([[1.0], [2.0], [3.0]]) # shape (3, 1)
y = np.array([1.0, 2.0, 3.0]) # shape (3,)
wrong = ((y_hat - y) ** 2).mean() # averages a (3, 3) array
right = ((y_hat[:, 0] - y) ** 2).mean() # averages a (3,) array
print((y_hat - y).shape, round(wrong, 3), right) The predictions are perfect, so the correct mean squared error is 0. The broken version reports about 1.333. Training on that loss pushes every prediction toward the average target, and the symptom looks like a model that refuses to learn. It belongs near the top of any list for debugging a model that will not learn.
The fix is to make the shapes match on purpose, then assert it: assert y_hat.shape == y.shape.
Axes in reductions
For X with shape (n, d), the axis argument names the axis that disappears.
| Call | Result shape | Meaning |
|---|---|---|
X.mean(axis=0) | (d,) | one mean per feature |
X.mean(axis=1) | (n,) | one mean per example |
X.mean(axis=1, keepdims=True) | (n, 1) | per example, ready to broadcast |
X.mean() | () | a single number |
Subtracting X.mean(axis=0) centers each feature. Subtracting X.mean(axis=1, keepdims=True) centers each row. Both run, and only one is what you meant. With real data, compute feature means on the training split and reuse them elsewhere.
A softmax has the same trap. Applied over the class axis, each example's outputs sum to 1. Applied over the batch axis, the numbers still look like probabilities but compare unrelated examples.
Matrix products and extra axes
The @ operator multiplies matrices using the last two axes and broadcasts any axes before them. The inner lengths must match.
Multi-head attention shows this well. Start with token vectors of shape (B, T, d) and h heads, with d divisible by h.
project to queries (B, T, d)
reshape to split heads (B, T, h, d/h)
swap the token and head axes (B, h, T, d/h)
keys, prepared the same way (B, h, T, d/h)
Q @ Kᵀ over the last two axes (B, h, T, T)
softmax over the last axis, @ V (B, h, T, d/h)
swap back and merge heads (B, T, d) The walkthrough of queries, keys and values shows what the numbers mean.
When products get hard to read, einsum notation names each index. np.einsum("bhqd,bhkd->bhqk", Q, K) states that you sum over d and keep batch, head, query and key positions.
Weight shapes and parameter counts
Shapes also describe a layer's parameters, and conventions differ. For a dense layer mapping d_in features to d_out, some libraries store the weight with shape (d_in, d_out) and compute XW. Others, including PyTorch's linear layer, store (d_out, d_in) and compute X Wᵀ. The math is identical, but loading weights from one convention into the other requires a transpose.
A square weight matrix is the dangerous case. If d_in equals d_out, a missing transpose raises no error and the model simply produces nonsense. Compare outputs on a fixed input after any conversion.
A two-dimensional convolution adds more axes. In PyTorch's convention its weight has shape (C_out, C_in, K, K). A layer with 3 input channels, 16 output channels and 3 by 3 kernels holds 16 · 3 · 3 · 3 = 432 weights plus 16 biases.
The output's spatial size follows from the kernel, stride and padding. With input size H, kernel K, padding P on each side and stride S, and no dilation, it is the floor of (H + 2P − K) / S, plus 1. For H = 32, K = 3, P = 1 and S = 2 that gives the floor of 15.5, plus 1, which is 16. Convolution computed by hand works through more cases.
Reshape is not transpose
Reshape keeps the elements in their existing order and regroups them. Transpose changes which axis is which.
A = np.arange(6).reshape(2, 3)
print(A.tolist()) # [[0, 1, 2], [3, 4, 5]]
print(A.T.tolist()) # [[0, 3], [1, 4], [2, 5]]
print(A.reshape(3, 2).tolist()) # [[0, 1], [2, 3], [4, 5]] Both of the last two have shape (3, 2), so no error will warn you if you pick the wrong one. In the attention example above, going directly from (B, T, d) to (B, h, T, d/h) with a single reshape would scramble tokens and features. Some libraries also distinguish between operations that return a view of the same memory and operations that copy, so modifying one array in place can change another.
Memory costs of expanded shapes
Broadcasting makes pairwise computations short to write. For A of shape (n, d) and B of shape (m, d), the expression A[:, None, :] - B[None, :, :] has shape (n, m, d).
With n = m = 10,000 and d = 100 in 64-bit floats, that is 10¹⁰ numbers, about 80 GB. Process the data in chunks, or expand the squared distance into dot products so that the three-dimensional array never exists. Vectorization in NumPy covers these patterns.
Habits that prevent shape bugs
- Comment the shape beside each line that changes it.
- Assert shapes at the boundaries of functions, especially before losses.
- Test with axis lengths that all differ, such as B = 2, T = 3, h = 4 and d = 8, so that a swapped axis raises an error.
- Check that changing one example in a batch leaves other examples' outputs unchanged, unless a layer such as batch normalization in training mode is meant to mix them.
- Prefer explicit
keepdimsand explicit new axes to relying on lucky alignment.
When an error does appear, read the two shapes in the message and work backward to the first line where an axis stopped meaning what you expected. Unit tests for tensor code make that line easier to find.
Common questions
What is the difference between rank and dimension?
In array code, the "rank" or number of dimensions often means the number of axes. In linear algebra, rank means the number of independent rows or columns. Read the context.
Is shape (n,) the same as (n, 1)?
No. They hold the same count of values but behave differently under broadcasting, matrix multiplication and many library functions.