Tensors, Broadcasting & Einsum
(B, T, D), learn broadcasting and einsum once, and you'll read any paper or any PyTorch repo without squinting. Tensors are how GPUs talk; einsum is the dictionary.After this lesson, you will be able to:
- Read and write tensor shapes like (B, T, D) and (B, C, H, W) and explain what each axis means in real ML systems
- Apply broadcasting rules to combine tensors of different shapes without writing explicit loops, and spot the silent (N, 1) versus (N,) bug
- Translate any matrix or tensor operation into Einstein-summation (einsum) string syntax, and back again
Before you start
#Why Tensors
A tensor is just a list of lists of lists. That is genuinely all it is. The reason it gets a fancy name is that ML code constantly stacks more "list of" layers. A single image is a 2D list, a batch of images is a 3D list, a batch of color images is a 4D list, and a batch of color video frames is a 5D list. The math stays the same; only the bookkeeping gets harder.
(B, T, D) and returns (B, T, D)," "this loss reduces (B,) to a scalar," "this projection takes (B, T, D_in) to (B, T, D_out)." Many deep-learning bugs are shape mismatches. Get the shapes right and the math usually follows.#Common shapes you will see every day
(B, D)— a batch of B feature vectors of dimension D. Tabular data, classifier logits (a classifier's raw scores, one per class).(B, T, D). Transformer activations (the numbers a layer produces). B sequences, T tokens, D-dimensional embeddings. Vary T per batch and you get padding masks (flags that mark the filler positions).(B, C, H, W)— CNN inputs/activations in PyTorch (channels-first).B=32, C=3, H=224, W=224is the canonical ImageNet shape.(B, H, W, C)— same, channels-last (TensorFlow default, also faster on Apple Silicon).(B, H, T, D_h)— multi-head attention activations. Attention (covered in the Transformers track) runsHsmaller copies called heads side by side;D_h = D / His the per-head dimension.(L, B, D)— RNN/LSTM convention: time-major instead of batch-major.
(32, 3, 224, 224) could be a batch of color photos OR 32 separate 3-channel volumetric scans of size (224, 224). Convention and context decide.Try it! Open the Python REPL (bottom-right of the screen: click Quick Actions, then Python) and type these lines yourself.
A multi-head attention layer for a batch of B=8 sequences of length T=64 with hidden size D=512 and H=8 heads splits D into per-head dimension d_h = D/H = 64. What is the shape of the queries tensor Q inside the attention computation?
#Broadcasting: Math Without Loops
X = [[1, 2, 3], [4, 5, 6]] (shape (2, 3)) and b = [10, 20, 30] (shape (3,)). Writing X + b gives [[11, 22, 33], [14, 25, 36]]: the vector b was added to every row of X, with no loop in sight. That automatic stretching is broadcasting, and NumPy and PyTorch both do it.1 (or missing, which counts as 1). A "1" axis gets virtually expanded (no memory copy) to match the other tensor. In the example, (2, 3) against (3,) pairs 3 with 3, and the missing axis of b stretches to 2.Pick two shapes in the widget below and watch which axes stretch to match and which pairs get rejected.
Where does that rule come from? Open the derivation to see why the result takes the larger size on every axis, and why the silent bug below produces an (N, N) table.
#Worked example: per-position positional encoding
X of shape (B, T, D) and positional encodings P of shape (T, D), the same for every example in the batch. Adding them must "broadcast" P across the batch axis.#The (B, 1, D) and (1, T, D) trick
q of shape (B, D) and a memory M of shape (T, D) and you want pairwise distances ‖q - M_t‖ for every batch element and every memory slot. You need an output of shape (B, T, D) (per-coordinate differences) before reducing to (B, T).What does None actually do? It inserts a new axis of size 1 at that position. Try it on a = [1, 2, 3] with shape (3,) and b = [10, 20, 30, 40] with shape (4,). Then a[:, None] has shape (3, 1). Right-align it against b, which counts as (1, 4), and the 1s stretch: the result is a (3, 4) table. Its first row is 1 − 10, 1 − 20, 1 − 30, 1 − 40 = −9, −19, −29, −39. Its last row is −7, −17, −27, −37.
Here the stretching is what you asked for, one answer per pair. The silent bug below is the same mechanics happening by accident.
#The classic silent bug
pred of shape (32, 1) (one prediction per row, with a trailing axis of size 1) and target has shape (32,). Right-aligning pairs the 1 against the 32 and stretches both, so pred - target quietly becomes a (32, 32) table of every prediction minus every target. The cell below shows the bug on 5 numbers, then the fix.pred (5, 1) target (5,) pred - target (5, 5), then broken loss: 6.4 and fixed loss: 1.2. Check the fixed one by hand: the five squared errors are 0, 1, 0, 1, 4, which sum to 6 and average to 1.2. The broken version averaged 25 mismatched pairs and got a different number with no warning.You have logits L of shape (B, V) (batch B, vocabulary V: one raw score per word) and a temperature t of shape (B,), a different temperature per example. You write L / t. What happens if you do not reshape t first?
#From Index Notation to Einsum
Matrix multiplication in standard notation:
i and j appear on the left-hand side and survive. k appears twice on the right-hand side and not at all on the left. That is precisely the index we summed over. Einstein's idea: drop the Σ and let the bookkeeping of which indices appear where say what is summed.Σ symbols all day in general relativity equations was driving him crazy. In his original convention, an index repeated within a product is summed automatically.einsum use a slightly more explicit version: you write the letters for each input, an arrow, and the letters you want in the output. The string 'ik,kj->ij' is the same equation typed sideways. Read it left-to-right:'ik'— A has axes labeled i (rows) and k (cols).','— separator between operands.'kj'— B has axes labeled k (rows) and j (cols).'->'— separator before the output spec.'ij'— the output has axes i and j.
Three rules tell you what any einsum string does:
- The same letter in different inputs means those axes are lined up, so their sizes must be equal. Here
kties A's columns to B's rows. - A letter that appears after the arrow is kept: it becomes an axis of the output (a free or batch axis). Here
iandj. - A letter that appears in the inputs but NOT after the arrow is summed away (multiplied along that axis, then added up). Here
k.
'ik,kj->ij' means: line up A and B along k, multiply, sum over k, keep i and j. That is matrix multiplication. Notice that sharing a letter is not by itself a reason to sum: what decides is whether the letter appears after the arrow.One more rule appears in the trace example below. The same letter twice inside one input means walk the diagonal, and the arrow still decides whether that letter is summed.
The three rules are a recipe for a sum. Open the derivation to check that two familiar strings, matrix multiplication and its batched version, are exactly the explicit sums you know.
Toggle through the presets below to see einsum operations execute one cell at a time. Watch the summed index disappear, and the kept indices fall into their slots in the output tensor. Internalise the visual once and you will never have to reason about einsum from scratch again.
#Worked Examples: Einsum Cookbook
Once you internalize the three rules, dozens of operations collapse into one syntax.
#Matrix multiplication
#Batched matrix multiplication
(B, M, K) tensor times a (B, K, N) tensor gives (B, M, N). The batch axis b rides along untouched.#Attention scores (the famous one)
Q and keys K both have shape (B, H, T, d_h): batch, heads, sequence positions, per-head dimension. The attention-score matrix is shape (B, H, T, T): how much each query position attends to each key position, separately for each head and each batch.'bhid,bhjd->bhij' with the three rules. The letters after the arrow are b, h, i, j, so all four are kept. The letter d is in both inputs but not after the arrow, so it is the only one summed. Note that b and h also appear in both inputs, yet they are not summed, because they are in the output. That is the whole difference between a batch axis and a summed axis.Now compute one by hand. Use one batch element and one head, so b and h each have size 1, and take two positions with two numbers each. Let Q = [[1, 2], [3, 0]] and K = [[1, 0], [2, 1]]. Each cell S[i][j] is the dot product of query row i with key row j, summed over d (leaving out the 1/√d_h scaling).
S[0][0] = 1 × 1 + 2 × 0 = 1. S[0][1] = 1 × 2 + 2 × 1 = 4. S[1][0] = 3 × 1 + 0 × 0 = 3. S[1][1] = 3 × 2 + 0 × 1 = 6. So S = [[1, 4], [3, 6]], and with the b and h axes it has shape (1, 1, 2, 2). Notice S[0][1] is 4 but S[1][0] is 3. The first letter picks the query, the second picks the key, so i and j are not interchangeable.
V of shape (B, H, T, d_h), is 'bhij,bhjd->bhid': the attention matrix (T, T) weights (T, d_h) to produce (T, d_h) per head per example, summing over the sequence index j.d collapse while batch b, head h, query position i, and key position j survive into the output. Every "scaled dot-product attention" diagram you have ever seen is this one contraction with a 1/√d_h scaling and a softmax tacked on the end.A tensor A has shape (32, 16, 8, 64) and B has shape (32, 16, 64, 8). What is the output shape of einsum('bhij,bhjk->bhik', A, B)?
#Trace (sum of diagonal)
'ii->' keeps cells (0, 0) and (1, 1), which hold 1 and 4, and adds them: 5. The string 'ii->i' keeps the same two cells but leaves them unsummed: [1, 4]. So the rule for a repeated letter inside one input is that it walks the diagonal, and the arrow then decides whether to sum.'ij,ji->' multiplies A[i, j] by B[j, i] and adds everything. By hand: 1 × 0 + 2 × 2 + 3 × 1 + 4 × 5 = 27. That equals the trace of A @ B, whose diagonal is 4 and 23.#Outer product
The opposite of summing: take two vectors and produce a matrix.
Two more strings, ii-> and i,j->ij, follow from the same recipe. The derivation below checks that they give the trace and the outer product.
#Sum along axis (one input only)
#Elementwise product (nothing is summed)
Does the order of indices on the right-hand side of an einsum string matter? Compare einsum('ik,kj->ij', A, B) vs einsum('ik,kj->ji', A, B).
A whole einsum cookbook in one runnable cell. Each pattern below shows you the einsum string, what it computes, and a shape sanity-check. After running, edit the strings: swap letters, drop indices, see what breaks.
#Try It Yourself
Two short exercises: einsum by hand and a shape bug.
#Einsum by hand
Tests: Verify trace(A) = 5, outer(a,b)[1,1] = 40, batched matmul produces shape (4, 2, 5), attention scores shape is (2, 4, 6, 6), the Frobenius inner product equals 70, the row sums are [3 7], and the transposed product is [[19 43] [22 50]].
A @ B = [[19 22] [43 50]], trace(A) = 5, the outer product [[10 20] [20 40] [30 60]], then the shapes (4, 2, 5) and (2, 4, 6, 6). The solution adds <A, B> = 70, row sums of A = [3 7] and (A @ B)^T = [[19 43] [22 50]].#Debug a shape
The broken loss from the broadcasting section, now as a tiny debugging task. Run it, find the bug, and fix it with an assert.
Tests: Verify the shapes are (5, 1), (5,) and (5, 5), the broken loss is 6.4, the fixed loss is 1.2, and the by-hand check is 1.2.
shapes: (5, 1) (5,) (5, 5), broken loss: 6.4, fixed loss: 1.2 and by hand: 1.2. Reshaping target to (5, 1) instead (with target[:, None]) also fixes it and gives the same 1.2.Tensor Comprehensions: Framework-Agnostic High-Performance Machine Learning Abstractions
Nicolas Vasilache, Oleksandr Zinenko, Theodoros Theodoridis, Priya Goyal, Zachary DeVito, William S. Moses, Sven Verdoolaege, Andrew Adams, Albert Cohen (2018)
Pioneering paper introducing index-notation as a programming abstraction for ML.
#Key Takeaways
- Tensor = list of lists of lists. Rank counts how many axes it has; shape is the size at each axis. Many ML bugs are shape mismatches, so train your eye to read shapes.
- Broadcasting eliminates loops. Right-aligned shape compatibility lets you add a (D,) bias to a (B, D) batch, or compare a (B, 1, D) query to a (1, T, D) memory, without copying tensors. But a (N, 1) minus (N,) silently gives (N, N), so assert shapes before losses.
- Einsum, in two decisions. Letters after the arrow are kept; input letters missing from the output are summed. Matmul, batch matmul, trace, outer product and attention scores all follow.
- Attention scores. The string
'bhid,bhjd->bhij'keeps b, h, i, j and sums d: a dot product over the per-head dimension for every query-key pair.
#Quick Check
An einsum string is `'bhid,bhjd->bhij'`. Which axis is summed away?