Skip to content
Mathematical foundations Foundation 20 min read

Tensors, shapes and broadcasting

In deep learning code a "tensor" is an n-dimensional array with a shape, and the shape is the type system that NumPy and PyTorch never check for you. Learn to read shapes, predict what broadcasting will do, and write contractions with einsum, and you will find most bugs before they run.

10,000 ft

Every input, activation, weight and gradient in a neural network is a tensor: a batch of images is (N, C, H, W), a batch of token sequences flowing through a transformer is (B, T, D), an attention score table is (B, H, T, T). Frameworks (NumPy, PyTorch, JAX, MLX) share almost identical shape semantics, so this page is the grammar of all model code. Shapes also decide cost: the memory of a tensor is the product of its dimensions times the bytes per element, which is why a single \(T\times T\) dimension made long-context attention expensive until kernels such as FlashAttention stopped materialising it (KV cache and efficient attention). Linear algebra (matrices) tells you what an operation means; this page tells you how it is laid out, batched and broadcast in real code.

2,000 ft

A tensor has a shape (sizes of its axes) and, in memory, strides (how many bytes to jump per step along each axis). Reshapes and transposes usually just change the strides: no data moves. Broadcasting lets an operation between tensors of different shapes proceed by aligning shapes from the right and stretching any axis of size 1, again without copying. Batched matmul applies a matrix product over all leading axes at once. einsum names every axis with a letter and states the whole operation as "multiply along shared letters, sum the ones that disappear". The diagram follows one transformer attention layer by shape.

One attention layer, followed by shape
One attention layer, followed by shape. token ids (B, T), embeddings (B, T, D), Q, K, V = x·W (B, T, D), split heads (B, H, T, D/H), QKᵀ/√d (B, H, T, T), softmax·V, merge heads (B, T, D), logits (B, T, V), lookup, matmul, reshape + transpose, batched matmul, many layers, then unembedOne attention layer, followed by shape. token ids (B, T), embeddings (B, T, D), Q, K, V = x·W (B, T, D), split heads (B, H, T, D/H), QKᵀ/√d (B, H, T, T), softmax·V, merge heads (B, T, D), logits (B, T, V), lookup, matmul, reshape + transpose, batched matmul, many layers, then unembed

Ground level

What "tensor" means here

In deep learning, a tensor is an array of numbers arranged along some number of axes (also called dimensions; the number of axes is the tensor's rank or ndim). Its shape lists the size of each axis.

ndim Name Example shape What it holds
0 scalar () a loss value
1 vector (768,) one token's embedding
2 matrix (768, 3072) an MLP weight
3 3-D tensor (32, 1024, 768) a batch of 32 sequences of 1,024 tokens, width 768
4 4-D tensor (32, 3, 224, 224) 32 RGB images, channels first (PyTorch's NCHW)
4 4-D tensor (32, 12, 1024, 1024) attention scores: batch, heads, query, key

Two meanings of 'tensor'

In physics and mathematics a tensor is a multilinear map whose components transform in a specific way when you change coordinates; a matrix is the components of a rank-2 tensor in some basis. Deep learning borrowed the word to mean "n-dimensional array" and kept almost nothing else. The useful idea that did survive is contraction: summing over a shared index, which generalises matrix multiplication and which einsum writes directly.

Conventions to know:

  • The last axis is the feature axis in most code. nn.Linear in PyTorch and x @ W in NumPy act on the last axis and treat every leading axis as batch.
  • The first axis is usually the batch. Some sequence code puts time first; always check.
  • Image layout differs by framework: PyTorch defaults to channels-first (N, C, H, W); TensorFlow and JAX image code often use channels-last (N, H, W, C), which also tends to be faster on modern GPUs.

Memory: strides, views and copies

A tensor's numbers sit in one flat block of memory. The strides say how many bytes to step to move one position along each axis. For a contiguous float32 array of shape (2, 3, 4) in row-major (C) order, the strides are (48, 16, 4): moving one step along the last axis moves 4 bytes (one float), along the middle axis 4 floats = 16 bytes, along the first axis 3×4 floats = 48 bytes. In general, element [i, j, k] lives at byte offset \(i\,s_0 + j\,s_1 + k\,s_2\).

That indirection makes many operations free:

  • Transpose / permute just reorders the strides. Transposing the last two axes of our array gives shape (2, 4, 3) with strides (48, 4, 16): same memory, read in a different order. The result is a view, and it is no longer contiguous (C-ordered).
  • Slicing with steps (x[:, ::2]) multiplies a stride; still a view.
  • Reshape is a view when the new shape can be expressed with strides over the existing layout, and must copy otherwise (for example reshaping a transposed array). PyTorch's view refuses to copy and errors; reshape copies silently when needed; .contiguous() forces a compact copy.
  • Broadcasting uses a stride of 0: the same memory is reused for every position along a stretched axis. np.broadcast_to([1, 2, 3], (4, 3)) has strides (0, 8).

Views alias memory

Because views share memory, writing into a view writes into the original. a = x[0]; a[:] = 0 zeroes the first row of x. In PyTorch, in-place operations on views of tensors that autograd needs can raise errors or, worse, change results. When in doubt, .copy() (NumPy) or .clone() (PyTorch).

Reductions and axes

x.sum(axis=k) removes axis k by summing along it; keepdims=True keeps it with size 1 so the result still broadcasts against x. Softmax over the last axis is the canonical example:

e = np.exp(x - x.max(axis=-1, keepdims=True))   # keepdims: (..., 1) broadcasts against (..., n)
p = e / e.sum(axis=-1, keepdims=True)

Without keepdims the max would have shape (...,) and line up against the wrong axis, or fail. (Subtracting the max is the log-sum-exp stability trick; see numerical computing.)

Broadcasting: the rules

When an element-wise operation combines tensors of different shapes, NumPy, PyTorch, JAX and MLX all apply the same three rules (NumPy docs, PyTorch docs):

  1. Align shapes on the right. If one tensor has fewer axes, pad its shape with 1s on the left.
  2. Two sizes on the same axis are compatible if they are equal or one of them is 1.
  3. An axis of size 1 is stretched to match the other. The result's size on each axis is the larger one.

If any axis is incompatible, the operation raises an error. Worked cases:

a b result why
(32, 768) (768,) (32, 768) bias added to every row
(3, 1) (1, 4) (3, 4) an "outer" sum: both stretch
(8, 12, 1024, 1024) (1024, 1024) (8, 12, 1024, 1024) one causal mask for every batch and head
(8, 1, 1, 1024) (8, 12, 1024, 1024) (8, 12, 1024, 1024) a per-sequence padding mask over keys
(5, 4) (5,) error right-aligned: 4 vs 5
(5, 4) (5, 1) (5, 4) the fix: make it a column
0001122331010111213202021222300001011021030201202203a: (3, 1)b: (1, 4)a + b: (3, 4)+=
Broadcasting (3, 1) + (1, 4). Each size-1 axis is stretched (faded cells) to match the other array, then the addition is element-wise. In memory nothing is copied: the stretched axis has stride 0.

The silent (n,) versus (n, 1) bug

Targets of shape (3,) minus predictions of shape (3, 1) broadcast to a (3, 3) matrix of every target minus every prediction. Mean-squaring that gives a plausible number and no error. With targets (1, 2, 3) and predictions (1.1, 1.9, 3.2) the correct MSE is 0.02; the broadcast version reports 1.42 (Build it). Models still train on such a loss, just badly. Defences: assert shapes, squeeze model outputs deliberately, and keep the feature axis explicit.

Batched matrix multiplication

@ (np.matmul, torch.matmul) treats the last two axes as matrices and broadcasts every leading axis. So:

  • (B, T, D) @ (D, F) → (B, T, F): a linear layer applied to every token of every sequence. The weight is broadcast over (B, T).
  • (B, H, T, Dh) @ (B, H, Dh, T) → (B, H, T, T): attention scores for every batch item and head at once.
  • (B, H, T, T) @ (B, H, T, Dh) → (B, H, T, Dh): weighted sum of values.

The rule for the last two axes is the matrix rule: (…, m, k) @ (…, k, n) → (…, m, n), with the inner k matching. FLOPs are \(2mkn\) times the product of the batch axes.

Splitting heads: reshape plus transpose

Multi-head attention (multi-head attention) takes Q of shape (B, T, D) and treats it as H independent heads of width Dh = D / H:

  1. reshape(B, T, H, Dh): split the last axis into (H, Dh). A free view, because the head's features are contiguous within each token.
  2. transpose(0, 2, 1, 3) → (B, H, T, Dh): move heads next to batch so the matmul treats (B, H) as batch axes. Another view, now non-contiguous.

Merging is the reverse: transpose back to (B, T, H, Dh), then reshape to (B, T, D). The reshape now has to copy, because the data is no longer laid out token-by-token, and this is exactly where PyTorch code calls .contiguous(). Getting the order wrong (reshaping (B, T, D) straight to (B, H, T, Dh)) runs without error and scrambles tokens across heads.

einsum: name every axis

einsum describes a tensor operation by labelling axes with letters. The rule is short: letters in the inputs that also appear in the output are kept; letters that appear in the inputs but not in the output are multiplied along and summed out. It is Einstein's 1916 summation convention, made executable.

Operation einsum Shapes
dot product "i,i->" (n,), (n,) → ()
outer product "i,j->ij" (m,), (n,) → (m, n)
matrix–vector "ij,j->i" (m, n), (n,) → (m,)
matmul "ik,kj->ij" (m, k), (k, n) → (m, n)
transpose "ij->ji" (m, n) → (n, m)
trace "ii->" (n, n) → ()
batched linear layer "btd,df->btf" (B, T, D), (D, F) → (B, T, F)
attention scores "bhqd,bhkd->bhqk" (B, H, T, Dh) ×2 → (B, H, T, T)
weighted values "bhqk,bhkd->bhqd" (B, H, T, T), (B, H, T, Dh) → (B, H, T, Dh)

The attention line is worth reading slowly: b and h are kept (batch axes), q and k are kept (the output is a query × key table), and d disappears, so it is summed: each score is a dot product over head features. No transposes needed, because the letters say which axes pair up. einops (Rogozhnikov, ICLR 2022) extends the idea to reshapes: rearrange(q, "b t (h d) -> b h t d", h=H) states the head split, and checks it.

Shapes decide memory

The bytes a tensor occupies are the product of its shape times bytes per element (4 for float32, 2 for bfloat16/float16, 1 for int8). That arithmetic explains a lot of systems design. An attention score tensor for batch 8, 32 heads and 8,192 tokens in 16-bit precision is

\[ 8 \times 32 \times 8192 \times 8192 \times 2\ \text{bytes} = 34{,}359{,}738{,}368\ \text{bytes} = 32\ \text{GiB}, \]

for one layer, before the softmax output and gradients. FlashAttention (Dao et al., 2022) computes exactly the same result in tiles that never write that (B, H, T, T) tensor to GPU main memory. The quadratic \(T\times T\) axis pair is the reason "long context" is a research area (long context).

Shape discipline

Habits that experienced practitioners actually use:

  • Comment shapes on every line of model code: # (B, T, D). It costs nothing and is the single most effective debugging habit.
  • Assert shapes at module boundaries (assert x.shape == (B, T, D)); use type-annotation libraries such as jaxtyping to put shapes in signatures.
  • Prefer einsum/einops for anything beyond a plain matmul: named axes make the intent checkable.
  • Use distinct sizes in tests. If B = T = D = 4, a transposed axis passes silently. With B, T, D, H = 2, 5, 16, 4 (as in Build it) a wrong axis order usually raises an error.
  • Overfit one batch before training at scale: shape bugs that broadcast silently show up as a loss that will not go to zero (training recipe).

History

From index notation to array programming

Gregorio Ricci-Curbastro and Tullio Levi-Civita set out tensor calculus in 1900; Albert Einstein introduced the convention of summing over repeated indices in his 1916 paper on general relativity, to stop writing summation signs. Kenneth Iverson's APL (described in A Programming Language, 1962) made whole-array operations a programming paradigm. Python's Numeric (1995) and numarray led to NumPy (Travis Oliphant, 2006), whose broadcasting rules became the de facto standard (Harris et al., 2020). Theano (2016 paper; in use from about 2008) and then TensorFlow (2015) put "tensor" at the centre of deep learning vocabulary; PyTorch (Paszke et al., 2019) and JAX adopted NumPy's semantics almost exactly, which is why this page's rules apply everywhere. Sasha Rush's Tensor Considered Harmful (2019) argued that positional axes are the root of most bugs and pushed for named dimensions.

First principles

Why align on the right? In row-major layout the last axis is the innermost, contiguous one, and by convention it holds features. The most common broadcast is "the same thing for every example", such as a bias of shape (D,) added to (B, T, D). Aligning on the right makes that work with no ceremony, and every extra leading axis (batch, heads, beams) can be added later without changing the shapes of parameters. Aligning on the left would force parameters to know how many batch axes the data has.

Why only size-1 axes stretch? Stretching must be unambiguous. An axis of size 1 has exactly one value to repeat. An axis of size 3 against size 6 could mean "repeat twice" or "interleave", so it is an error rather than a guess. And size 1 is exactly what stride 0 can implement for free.

Why do framework designers love strides? Separating the logical shape from the physical layout makes transposes, slices, broadcasts and many reshapes O(1) metadata changes instead of O(n) copies. The cost is that some operations then need contiguous memory and must copy: the .contiguous() calls you see in model code.

The gradient of broadcasting is a sum. If a value is used in many places, the chain rule adds up its effect from each place (chain rule and Jacobians). So when a bias (D,) is broadcast to (B, T, D), its gradient is the upstream gradient summed over the broadcast axes B and T. Every autodiff framework implements the backward pass of broadcasting as sum over the stretched axes (with keepdims for size-1 axes), and forgetting this is a classic bug when writing backprop by hand (Karpathy's "Backprop Ninja" drills exactly this).

The maths

Broadcast shape. Given shapes \((a_1,\dots,a_p)\) and \((b_1,\dots,b_q)\) with \(p\ge q\), left-pad \(b\) with ones to length \(p\). The result has shape \((c_1,\dots,c_p)\) with \(c_i = \max(a_i,b_i)\), valid iff for every \(i\), \(a_i = b_i\) or \(\min(a_i,b_i) = 1\). Element \(\mathbf{c}[i_1,\dots,i_p] = f(\mathbf{a}[i_1',\dots], \mathbf{b}[i_1'',\dots])\) where an index on a size-1 axis is replaced by 0.

einsum. For a specification \(\text{in}_1,\text{in}_2\to\text{out}\) with index sets \(I_1, I_2\) and \(O\subseteq I_1\cup I_2\):

\[ \text{out}[O] = \sum_{\text{indices in }(I_1\cup I_2)\setminus O}\ \text{in}_1[I_1]\;\text{in}_2[I_2]. \]

Matrix multiplication is \(C_{ij} = \sum_k A_{ik}B_{kj}\), i.e. "ik,kj->ij". The cost of a two-operand einsum is the product of the sizes of all distinct indices (one multiply–add per combination), so "bhqd,bhkd->bhqk" costs \(B\cdot H\cdot T\cdot T\cdot D_h\) multiply–adds. With more than two operands, the order of contraction matters enormously (matrices showed a 2,000× example); np.einsum(..., optimize=True) searches for a good order.

Derivation: the gradient of a broadcast is a sum over the broadcast axes

Let \(\mathbf{b}\in\mathbb{R}^D\) be broadcast to \(Y_{btd} = X_{btd} + b_d\) and let \(G_{btd} = \partial L/\partial Y_{btd}\). By the multivariable chain rule, \(b_d\) affects \(L\) through every \(Y_{btd}\) with that \(d\):

\[ \frac{\partial L}{\partial b_d} = \sum_{b,t}\frac{\partial L}{\partial Y_{btd}}\frac{\partial Y_{btd}}{\partial b_d} = \sum_{b,t} G_{btd}\cdot 1 . \]

So grad_b = G.sum(axis=(0, 1)), which has \(\mathbf{b}\)'s shape. In general: the gradient of a broadcast is the reduction (sum) over the axes that were stretched or added. Dually, the gradient of a sum is a broadcast. Reduction and broadcasting are adjoint operations, just as \(W\) and \(W^\top\) are.

Build it

NumPy: strides and views, the silent broadcasting bug, multi-head attention scores two ways, and the gradient of a broadcast checked by finite differences.

import numpy as np
rng = np.random.default_rng(0)

# 1. Shape, strides, views
x = np.arange(24, dtype=np.float32).reshape(2, 3, 4)
print("shape", x.shape, "strides", x.strides)
xt = x.transpose(0, 2, 1)                       # a view: no data copied
print("transposed shape", xt.shape, "strides", xt.strides, "contiguous?", xt.flags["C_CONTIGUOUS"])
b = np.broadcast_to(np.array([1.0, 2.0, 3.0]), (4, 3))
print("broadcast_to strides", b.strides, "(stride 0 = the row is reused, not copied)")

# 2. The (n,) vs (n,1) bug
y_true = np.array([1.0, 2.0, 3.0])              # shape (3,)
y_pred = np.array([[1.1], [1.9], [3.2]])        # shape (3, 1), e.g. a model's output column
wrong = ((y_pred - y_true) ** 2).mean()          # broadcasts to (3, 3)!
right = ((y_pred[:, 0] - y_true) ** 2).mean()
print("diff shape", (y_pred - y_true).shape, " wrong MSE", round(wrong, 4), " right MSE", round(right, 4))

# 3. Multi-head attention scores with reshape + einsum
B, T, D, H = 2, 5, 16, 4
Dh = D // H
X = rng.standard_normal((B, T, D))
Wq, Wk = rng.standard_normal((D, D)) / np.sqrt(D), rng.standard_normal((D, D)) / np.sqrt(D)
Q = (X @ Wq).reshape(B, T, H, Dh).transpose(0, 2, 1, 3)   # (B, H, T, Dh)
K = (X @ Wk).reshape(B, T, H, Dh).transpose(0, 2, 1, 3)
S1 = Q @ K.transpose(0, 1, 3, 2) / np.sqrt(Dh)            # batched matmul -> (B, H, T, T)
S2 = np.einsum("bhqd,bhkd->bhqk", Q, K) / np.sqrt(Dh)     # same thing, named indices
print("scores", S1.shape, "max |S1 - S2| =", np.abs(S1 - S2).max())

# 4. Backprop through broadcasting = sum over the broadcast axes
bias = np.zeros(D)
Y = X + bias                                    # bias (D,) broadcast over (B, T, D)
G = rng.standard_normal(Y.shape)                # upstream gradient dL/dY
grad_bias = G.sum(axis=(0, 1))                  # dL/dbias has bias's shape
eps = 1e-6; e0 = np.zeros(D); e0[0] = eps       # finite-difference check on bias[0]
fd = ((G * (X + bias + e0)).sum() - (G * (X + bias)).sum()) / eps
print("grad_bias[0] =", round(grad_bias[0], 6), " finite diff =", round(fd, 6))

Output:

shape (2, 3, 4) strides (48, 16, 4)
transposed shape (2, 4, 3) strides (48, 4, 16) contiguous? False
broadcast_to strides (0, 8) (stride 0 = the row is reused, not copied)
diff shape (3, 3)  wrong MSE 1.42  right MSE 0.02
scores (2, 4, 5, 5) max |S1 - S2| = 4.440892098500626e-16
grad_bias[0] = -0.126814  finite diff = -0.126814

The two attention computations agree to about \(4\times10^{-16}\), which is float64 rounding: einsum and batched matmul are the same contraction. The loss \(L = \sum G\odot Y\) is linear in the bias, so the finite difference matches the analytic gradient to every printed digit.

Things to try

  • Replace .reshape(B, T, H, Dh).transpose(0, 2, 1, 3) with the wrong .reshape(B, H, T, Dh). Does anything error? Compare the scores for head 0 with the correct version.
  • Merge the heads back: transpose (B, H, T, Dh) to (B, T, H, Dh) and reshape to (B, T, D). Check np.shares_memory before and after the reshape to see when NumPy copies.
  • Build a causal mask of shape (T, T) with np.tril and add -inf above the diagonal to S1 by broadcasting. Confirm the mask's shape broadcasts to (B, H, T, T).
  • Write np.einsum("ij,jk,kl->il", A, B, C) for shapes (1000, 2), (2, 1000), (1000, 1000) and time it with and without optimize=True.
  • Work through Sasha Rush's Tensor Puzzles: re-implement standard functions using only broadcasting and arange.

Common misconceptions

  • "A reshape rearranges the data." A reshape never changes the order of elements in row-major reading order; it only regroups them. To change the order you need a transpose (permute), and the two are not interchangeable.
  • "Broadcasting copies the smaller array." It uses stride 0. The stretched array is never materialised unless you force it.
  • "(n,) is a row vector." A 1-D array has no orientation. It behaves as a row when broadcast against 2-D arrays (because of right-alignment), but x.T on a 1-D array does nothing.
  • "If it runs, the shapes are right." Broadcasting turns many shape bugs into wrong numbers instead of errors.

Check yourself

What are the strides (in bytes) of a contiguous float16 array of shape (4, 8, 16)?

Bytes per element 2. Last axis 2; middle \(16\times2 = 32\); first \(8\times16\times2 = 256\). Strides (256, 32, 2).

What is the result shape of (8, 1, 6, 1) + (7, 1, 5)?

Right-align: (8, 1, 6, 1) and (1, 7, 1, 5). Each axis takes the larger size: (8, 7, 6, 5).

Write the einsum for a batched bilinear score s_b = x_bᵀ W y_b, with x, y of shape (B, D) and W of shape (D, D).

np.einsum("bi,ij,bj->b", x, W, y). The indices i and j are summed; b is kept.

A linear layer receives (B, T, D) = (16, 512, 1024) and has weight (1024, 4096). What is the output shape and how many FLOPs does the forward pass cost?

(16, 512, 4096). FLOPs \(= 2\times16\times512\times1024\times4096\approx 6.9\times10^{10}\).

Why does merging attention heads usually need a copy, but splitting them does not?

Splitting (B, T, D) → (B, T, H, Dh) regroups contiguous features: a view. The transpose to (B, H, T, Dh) is a stride change: a view. Merging requires the data to be in (B, T, H, Dh) order in memory before reshaping to (B, T, D), but after the transpose back it is not contiguous, so the reshape must copy.

A bias of shape (1, D, 1, 1) is added to activations of shape (N, D, H, W). What is the bias gradient?

Sum the upstream gradient over the broadcast axes 0, 2 and 3, keeping dims: G.sum(axis=(0, 2, 3), keepdims=True), shape (1, D, 1, 1). This is the per-channel bias of a convolution.

Hard: estimate the memory of the attention probabilities for batch 1, 64 heads and 128k tokens in bfloat16, and say what FlashAttention changes.

\(1\times64\times131072^2\times2\) bytes \(\approx 2.2\times10^{12}\) bytes, about 2 TiB, far beyond any single GPU. FlashAttention never materialises it: it streams tiles of K and V through on-chip memory, keeping running softmax statistics per query, so memory is linear in \(T\) while the FLOPs stay quadratic.

Go deeper

Papers

Videos and lectures

Articles and blog posts

Code

  • Tensor Puzzles — Sasha Rush. 21 puzzles that make broadcasting second nature.
  • einops — readable reshapes for NumPy, PyTorch, JAX and MLX.

Where this leads