Module contents
Lesson 19 of 25Core 100 min

Tensors, broadcasting and einsum

In deep learning everything is a tensor: image batches (B, C, H, W), sequences (B, T, D) and per-head scores (B, H, T, T); shape errors are a major source of bugs. Connect the mathematical view (tensor products and multilinear maps) with computation (axes, reshape, broadcasting and contractions), and master einsum for expressing and reasoning about linear tensor operations.

After this lesson you can

  • Describe a tensor by its shape and axis semantics and relate it to multilinear maps.
  • Predict reshape, permute and broadcasting results and detect accidental axis mixing.
  • Use einsum for batched matrix products, traces, diagonals, bilinear forms and outer products.
  • Express per-head operations in an attention model as contractions without depending on the mechanism.
  • Choose a tensor contraction order to minimize cost and memory.

Before you start

Motivation: everything in deep learning is a tensor

Open any modern network’s code and you will barely see isolated matrices. An image batch has shape (B,C,H,W)(B, C, H, W): examples, channels, height and width. A sequence of tokens converted to vectors is (B,T,d)(B, T, d). Inside transformer attention, pairwise token scores for each head and example form (B,H,T,T)(B, H, T, T). Multi-head attention weights can be written as (d,H,dk)(d, H, d_k). Everything is a tensor; nearly all the network does is combine tensors with linear operations and apply elementwise nonlinearities.

This ubiquity has a practical cost: shape errors are the leading source of bugs in model implementation. Benign ones throw an exception (mat1 and mat2 shapes cannot be multiplied). Dangerous ones do not. Subtracting a vector of shape (n,)(n,) from a column (n,1)(n, 1) silently produces a matrix (n,n)(n, n); splitting attention heads using reshape instead of reshape followed by permute produces a tensor with the correct shape and scrambled contents. In both cases the network trains, loss falls somewhat, and nobody knows why the model underperforms.

This lesson gives you tools to prevent that:

  • Two readings of tensor: an array with meaningful axes (programming) and a multilinear map (mathematics), linked by the tensor product.
  • Memory: tensor storage, what reshape and permute actually do, and when reshape preserves axis meaning.
  • Broadcasting: precise rules, uses and silent traps.
  • Tensor contraction, generalizing dot product, matrix multiplication and trace, and einsum, an index language expressing any contraction in one line.
  • Cost: why the order of contracting tensors can change time and memory by orders of magnitude.

With these tools you can read and write transformer code confidently and reason about its cost before running it.

Two readings of tensor

Tensor as an array: shape, order and axes

The computational reading is most direct. A vector is a list of numbers indexed once, a matrix a table indexed twice, and nothing prevents us from going further.

With entrywise addition and scalar multiplication, Rn1×⋯×nk\R^{n_1 \times \cdots \times n_k} is a vector space of dimension n1⋯nkn_1 \cdots n_k. As a vector space it is nothing special: RN\R^N with coordinates arranged on a grid. The grid itself makes it useful, because each axis has meaning. In X∈RB×T×d\mat{X} \in \R^{B \times T \times d}, entry XbtjX_{btj} is feature jj of token tt of example bb. Meaningful operations respect those meanings: summing (or averaging) over tt aggregates each example’s tokens; summing over bb mixes unrelated examples.

That is why this platform writes shapes with letters naming each axis (B×T×dB \times T \times d); your code should do the same in comments or shape annotations.

Tensor as a multilinear map

The mathematical reading starts with a question: what does a matrix represent? In lesson 3 the answer was a linear map. But A∈Rm×n\mat{A} \in \R^{m \times n} also represents a bilinear form,

β(x,y)=x⊤Ay=∑i=1m∑j=1nxiAijyj,\beta(\vb{x}, \vb{y}) = \vb{x}\T\mat{A}\vb{y} = \sum_{i=1}^{m}\sum_{j=1}^{n} x_i A_{ij} y_j,

a function of two vectors, linear in each with the other fixed. Recover the matrix by evaluating on the standard basis: Aij=β(ei,ej)A_{ij} = \beta(\vb{e}_i, \vb{e}_j). An order-3 array does the same with three arguments:

τ(u,v,w)=∑i,j,kTijk uivjwk,Tijk=τ(ei,ej,ek).\tau(\vb{u}, \vb{v}, \vb{w}) = \sum_{i,j,k} T_{ijk}\, u_i v_j w_k, \qquad T_{ijk} = \tau(\vb{e}_i, \vb{e}_j, \vb{e}_k).

Thus an order-kk array is a coefficient table for a multilinear map of kk arguments in specific bases, just as a matrix is a coefficient table for a linear map.

The distinction between table and object appears under a basis change. Take square A\mat{A}, n×nn \times n. If columns of P\mat{P} form a new basis of Rn\R^n, linear map A\mat{A} has matrix P−1AP\mat{P}\inv\mat{A}\mat{P} (change of basis), but bilinear form x⊤Ay\vb{x}\T\mat{A}\vb{y} has matrix P⊤AP\mat{P}\T\mat{A}\mat{P}. Same starting numbers, different transformation rules: physics and differential geometry call the object plus rule a tensor, distinguishing “vector” and “covector” indices by how they transform. Deep learning rarely changes basis explicitly and uses the array reading; the multilinear reading reappears when determining coordinate-independent operations, as with trace.

The tensor product

The simplest order-2 tensor that is not “just a table” is the outer product of two vectors: u∈Rm\vb{u} \in \R^m and v∈Rn\vb{v} \in \R^n yield matrix uv⊤\vb{u}\vb{v}\T with entries uivju_i v_j, a rank-one matrix. Three vectors give order-3 array (uivjwk)(u_i v_j w_k). These pieces build everything else.

Two observations explain the definition. First, not every element of V⊗WV \otimes W is elementary. A rank-rr matrix is a sum of rr outer products and no fewer; elementary elements are the exception. For order 3 or more, the minimum number of elementary terms is lesson 20’s tensor rank, generally NP-hard to calculate (Håstad, 1990), unlike matrix rank.

Second, the tensor product linearizes bilinear maps. Every bilinear map β:V×W→U\beta : V \times W \to U is uniquely written as β(v,w)=L(v⊗w)\beta(\vb{v}, \vb{w}) = L(\vb{v} \otimes \vb{w}) with linear L:V⊗W→UL : V \otimes W \to U; define L(ei⊗fj)=β(ei,fj)L(\vb{e}_i \otimes \vb{f}_j) = \beta(\vb{e}_i, \vb{f}_j) and extend linearly. This universal property says studying bilinear (or multilinear) maps is the same as studying linear maps on a larger space. Thus both tensor readings agree: array (Tijk)(T_{ijk}) contains coordinates of an element of Rm⊗Rn⊗Rp\R^m \otimes \R^n \otimes \R^p, and coefficients of a trilinear form.

The proof constructs an explicit basis from bases of VV and WW. Do it step by step:

ProofA basis for bilinear forms
Prove: If dim⁡V=m\dim V = m and dim⁡W=n\dim W = n, then dim⁡Bil⁡(V,W)=mn\dim \operatorname{Bil}(V, W) = mn.
0
Let e1,…,em\vb{e}_1, \dots, \vb{e}_m be a basis of VV and f1,…,fn\vb{f}_1, \dots, \vb{f}_n a basis of WW. Every v∈V\vb{v} \in V is v=∑iaiei\vb{v} = \sum_i a_i\vb{e}_i and every w∈W\vb{w} \in W is w=∑jbjfj\vb{w} = \sum_j b_j\vb{f}_j. Bil⁡(V,W)\operatorname{Bil}(V, W) is a vector space with pointwise addition and scalar multiplication.

Step 1 of 4. What completely determines a bilinear form β\beta?

In code this takes one or two lines. Outer product and trilinear-form evaluation use einsum, studied below; for now read it as “multiply entries with matching indices and sum indices absent after the arrow”.

[ ]Tensors as arrays and multilinear mapsBrowser
import numpy as np
rng = np.random.default_rng(0)

x = rng.standard_normal((2, 3, 4))      # (B, T, d): 2 secuencias de 3 tokens con 4 características
print("forma:", x.shape, " orden (ndim):", x.ndim, " elementos:", x.size)

u, v, w = rng.standard_normal(3), rng.standard_normal(4), rng.standard_normal(2)
uv = np.einsum('i,j->ij', u, v)          # u ⊗ v = u vᵀ
print("u⊗v es u vᵀ:", np.allclose(uv, np.outer(u, v)), " rango:", np.linalg.matrix_rank(uv))
uvw = np.einsum('i,j,k->ijk', u, v, w)   # u ⊗ v ⊗ w, de orden 3
print("forma de u⊗v⊗w:", uvw.shape)

# un arreglo de orden 3 es una forma trilineal: tau(a, b, c) = sum_ijk T_ijk a_i b_j c_k
T = rng.standard_normal((3, 4, 2))
tau = lambda a, b, c: np.einsum('ijk,i,j,k->', T, a, b, c)
a1, a2, b, c = rng.standard_normal(3), rng.standard_normal(3), rng.standard_normal(4), rng.standard_normal(2)
print("lineal en el primer argumento:", np.isclose(tau(2*a1 - 3*a2, b, c), 2*tau(a1, b, c) - 3*tau(a2, b, c)))
e, f, g = np.eye(3), np.eye(4), np.eye(2)
print("T[1, 2, 0] = tau(e_1, f_2, g_0):", np.isclose(tau(e[1], f[2], g[0]), T[1, 2, 0]))

Axes, shape and memory: reshape and permute

How a tensor is stored

Computer memory is a single row of locations. A tensor of shape (n1,…,nk)(n_1, \dots, n_k) is stored as a block of n1⋯nkn_1 \cdots n_k consecutive numbers plus a rule for locating entries: strides (s1,…,sk)(s_1, \dots, s_k), the memory positions advanced when each index increases by one. Entry (i1,…,ik)(i_1, \dots, i_k), zero-indexed as in code, lives at offset

off⁡(i1,…,ik)=∑r=1kir sr.\operatorname{off}(i_1, \dots, i_k) = \sum_{r=1}^{k} i_r\, s_r .

NumPy and PyTorch create tensors in row-major order (C order): the last index varies fastest. Strides are sk=1s_k = 1 and sr=nr+1nr+2⋯nks_r = n_{r+1} n_{r+2} \cdots n_k. For (2,3,4)(2, 3, 4) they are (12,4,1)(12, 4, 1); entry [1,2,3][1, 2, 3] is at 1⋅12+2⋅4+3⋅1=231\cdot 12 + 2\cdot 4 + 3\cdot 1 = 23, the last location. The flat index is a mixed-radix number with digits i1,…,iki_1, \dots, i_k and “bases” n1,…,nkn_1, \dots, n_k. The array memory model and strides are in the tools module; here their consequences for meaning matter.

Reshape and permute

Two operations reorganize a tensor without changing its numbers, but are fundamentally different.

A permute never moves data: permute shape and strides. The transpose of a contiguous 3×43 \times 4 matrix with strides (4,1)(4, 1) is a view of shape (4,3)(4, 3) and strides (1,4)(1, 4) on the same memory. That view is no longer row-major (contiguous). Reshape instead is defined by logical order. For a contiguous tensor this is memory order and reshape is a free view; otherwise no stride choice may describe the result, requiring a copy. torch.Tensor.view refuses to copy and errors; reshape copies when needed; contiguous() copies to row-major order. Views versus copies affect performance and aliasing. Here the question is when reshape preserves axis meaning.

Proof

Row-major order maps each index tuple to flat index ∑rirsr\sum_r i_r s_r, a mixed-radix number. Merging consecutive digits iri_r (base nrn_r) and ir+1i_{r+1} (base nr+1n_{r+1}) into digit irnr+1+ir+1i_r n_{r+1} + i_{r+1} (base nrnr+1n_r n_{r+1}) does not change the represented number: irsr+ir+1sr+1=(irnr+1+ir+1)sr+1i_r s_r + i_{r+1}s_{r+1} = (i_r n_{r+1} + i_{r+1})s_{r+1}, since sr=nr+1sr+1s_r = n_{r+1}s_{r+1}. Reshape preserves flat index, so the entry moves exactly to the tuple with merged digits; other digits remain intact. Splitting an axis reverses this. If instead a new axis grouped nonconsecutive digits or changed their order, the same number would need a different mixed radix and new digits would no longer depend on single groups of old digits. Example (2,3)→(3,2)(2, 3) \to (3, 2) shows this: original entry [0,2][0, 2] (flat index 2) moves to [1,0][1, 0], so the new first index depends on both old ones.

∎

Attention heads are the important case. Input is X∈RB×T×d\mat{X} \in \R^{B \times T \times d} and model dimension splits into HH heads of size dk=d/Hd_k = d/H, with head hh owning features hdk,…,(h+1)dk−1h d_k, \dots, (h+1)d_k - 1. We want (B,H,T,dk)(B, H, T, d_k) where each [b,h][b, h] block is head hh‘s T×dkT \times d_k matrix.

  • X.reshape(B, T, H, dk) splits the last axis into (H,dk)(H, d_k) with j=hdk+cj = h d_k + c: a split preserving meaning. Then .permute(0, 2, 1, 3) moves the head axis before the token axis without moving data. Correct.
  • X.reshape(B, H, T, dk) has the desired shape, but splits no axis: it rereads each example’s TdT d numbers as if ordered by head then token. Wrong, silently.
InteractiveReshape is not permute
A (2,3,4)(2, 3, 4) tensor interpreted as (batch, token, feature), with d=4d = 4 split into 2 heads of dk=2d_k = 2. Color denotes token, intensity head; each cell's number is its original memory location. Above is memory, below the logical view. In split with reshape only, the block intended for head 0 mixes tokens and heads, detected by panel checks. Compare split with reshape and permute: memory is unchanged, only strides change. In merge without undoing permute, the last reshape must copy and still scrambles tokens. Hover a cell for its stride-calculated address.

Named-axis notation libraries such as einops (Rogozhnikov, 2022) make this error impossible by construction: rearrange(X, 'b t (h k) -> b h t k', h=H) explicitly says which axis splits, in what order and where each piece goes. Underneath it is precisely reshape followed by permute.

[ ]Strides, views and reshape mixing headsBrowser
import numpy as np
x = np.arange(24).reshape(2, 3, 4)       # cada elemento vale su posición en memoria
print("strides en elementos:", tuple(s // x.itemsize for s in x.strides))
print("x[1, 2, 3] =", x[1, 2, 3], "= 1*12 + 2*4 + 3*1")

B, T, d, H = 2, 3, 4, 2
dk = d // H
bien = x.reshape(B, T, H, dk).transpose(0, 2, 1, 3)   # (B, H, T, dk)
mal = x.reshape(B, H, T, dk)                           # misma forma, otro contenido
print("formas:", bien.shape, mal.shape)
print("bloque [0, 0] (cabeza 0), bien:\n", bien[0, 0])
print("bloque [0, 0] (cabeza 0), mal:\n", mal[0, 0])
cabeza = lambda ids: (ids % d) // dk       # cabeza a la que pertenece cada elemento original
print("cabezas presentes en el bloque [0, 0], bien:", np.unique(cabeza(bien[0, 0])))
print("cabezas presentes en el bloque [0, 0], mal: ", np.unique(cabeza(mal[0, 0])))

p = x.transpose(0, 2, 1)                   # permute: solo cambian forma y strides
print("strides tras transpose(0, 2, 1):", tuple(s // x.itemsize for s in p.strides), " contiguo:", p.flags['C_CONTIGUOUS'])
print("comparte memoria con x:", np.shares_memory(p, x))
r = p.reshape(2, 12)                       # no puede ser una vista: NumPy copia
print("el reshape posterior comparte memoria:", np.shares_memory(r, x))
print("y respeta el orden lógico:", np.array_equal(r, np.ascontiguousarray(p).reshape(2, 12)))

Broadcasting

The exact rules

Adding bias vector b∈Rd\vb{b} \in \R^d to each token in X∈RB×T×d\mat{X} \in \R^{B \times T \times d} is a common network operation. Loops would be absurd, and a copy of b\vb{b} with shape (B,T,d)(B, T, d) would waste memory. Broadcasting allows X + b and lets the system understand “the same b\vb{b} for each bb and tt”.

In words: a size-1 axis is stretched to the other’s size by repeating its sole value; a missing axis counts as size 1. Stretching copies nothing: it uses stride 0 on that axis, so advancing its index does not advance in memory. Thus np.broadcast_to(b, (3, 4)) with b of shape (4,) and type float64 is a view with byte strides (0, 8). NumPy and PyTorch rules are identical.

InteractiveAlign right and stretch ones
Shapes align on the right, the shorter is padded with ones (dashed), and each size-1 axis stretches (orange) to the other's size; differing non-1 sizes error. Start with the trap: AA of shape (3,)(3,) minus BB of shape (3,1)(3, 1) yields a 3×33 \times 3 matrix with only the intended values on the diagonal. Note the warning: both operands stretch. Try the fix, bias and per-channel normalization examples, pairwise distances (where stretching both is intended), and the error. Readouts show broadcast operand strides: zeros are copies that do not exist.

Uses

Three patterns cover most network uses.

  • Bias and feature scaling. X + b with X (B,T,d)(B, T, d) and b (d,)(d,), or X * gamma in layer normalization. The vector aligns with the last, feature axis.
  • Per-axis statistics with keepdims. Batch normalization of images (N,C,H,W)(N, C, H, W) subtracts each channel’s mean: mu = X.mean(axis=(0, 2, 3), keepdims=True) has shape (1,C,1,1)(1, C, 1, 1) and X - mu broadcasts unambiguously. Without keepdims, mu would have shape (C,)(C,) and align with WW: error if W≠CW \ne C, silently wrong if equal.
  • Pairwise operations. Insert size-1 axes at different positions (X[:, None, :] and Y[None, :, :], shapes (n,1,d)(n, 1, d) and (1,m,d)(1, m, d)) to combine each row of X\mat{X} with each row of Y\mat{Y}. Subtraction and squaring yield all pairwise differences, shape (n,m,d)(n, m, d); summing the last axis gives squared distances.

Pairwise distances without loops

Matrix Dij=∥xi−yj∥2D_{ij} = \norm{\vb{x}_i - \vb{y}_j}^2 appears in kk-nearest neighbors, Gaussian kernels, clustering and many contrastive-model losses. Broadcasting is correct but creates an intermediate of nmdn m d numbers: with n=m=104n = m = 10^4 and d=128d = 128 in float32 that is 51 GB. Expanding the square avoids it:

∥xi−yj∥2=∥xi∥2+∥yj∥2−2 xi⊤yj,D=a 1⊤+1 c⊤−2 XY⊤,\norm{\vb{x}_i - \vb{y}_j}^2 = \norm{\vb{x}_i}^2 + \norm{\vb{y}_j}^2 - 2\,\vb{x}_i\T\vb{y}_j, \qquad \mat{D} = \vb{a}\,\vb{1}\T + \vb{1}\,\vb{c}\T - 2\,\mat{X}\mat{Y}\T,

with ai=∥xi∥2a_i = \norm{\vb{x}_i}^2 and cj=∥yj∥2c_j = \norm{\vb{y}_j}^2. The first two terms broadcast column (n,1)(n, 1) and row (1,m)(1, m), and the third is one matrix product, the most optimized operation available. The largest intermediate is D\mat{D} itself.

The price is numerical. If points are far from the origin and close together, ∥xi∥2\norm{\vb{x}_i}^2 and 2xi⊤yj2\vb{x}_i\T\vb{y}_j are enormous nearly equal numbers, and subtraction loses nearly all significant digits (catastrophic cancellation). The result can be negative and its square root NaN. Combine two remedies: subtract the same center from all points (distances unchanged, norms smaller), and clip to zero using np.maximum(D, 0).

[ ]Broadcasting from scratch, pitfalls and pairwise distancesBrowser
import numpy as np

def broadcast_shape(*shapes):
    """Forma resultante de difundir varias formas, o ValueError si son incompatibles."""
    n = max(len(s) for s in shapes)
    padded = [(1,) * (n - len(s)) + tuple(s) for s in shapes]   # rellenar con 1 por la izquierda
    out = []
    for k, sizes in enumerate(zip(*padded)):
        distintos = {t for t in sizes if t != 1}
        if len(distintos) > 1:
            raise ValueError(f"eje {k - n}: tamaños {sizes} incompatibles")
        out.append(distintos.pop() if distintos else 1)
    return tuple(out)

casos = [((2, 3, 4), (4,)), ((5, 1), (1, 6)), ((3,), (3, 1)), ((), (2, 2)), ((4, 1, 3), (5, 1), (1, 1, 1))]
for c in casos:
    assert broadcast_shape(*c) == np.broadcast_shapes(*c), c
    print(c, "->", broadcast_shape(*c))
try:
    broadcast_shape((3, 4), (3,))
except ValueError as e:
    print("(3, 4) y (3,):", e)
print("strides de (4,) difundido a (3, 4):", np.broadcast_to(np.arange(4.0), (3, 4)).strides, "bytes")

# trampa 1: (n, 1) - (n,)
y = np.array([1.0, 2.0, 3.0])
pred = np.array([[1.1], [1.9], [3.2]])     # salida típica de un modelo: (n, 1)
print("forma de pred - y:", (pred - y).shape)
print("MSE equivocado:", np.mean((pred - y) ** 2).round(4), "  MSE correcto:", np.mean((pred[:, 0] - y) ** 2).round(4))

# trampa 2: olvidar keepdims con una matriz cuadrada
X = np.arange(9.0).reshape(3, 3)
print("suma de cada fila tras 'centrar' sin keepdims:", (X - X.mean(axis=1)).sum(axis=1))
print("suma de cada fila con keepdims:              ", (X - X.mean(axis=1, keepdims=True)).sum(axis=1))

# distancias por pares: dos formas de calcularlas
rng = np.random.default_rng(1)
X, Y = rng.standard_normal((500, 64)), rng.standard_normal((400, 64))
D_bc = ((X[:, None, :] - Y[None, :, :]) ** 2).sum(-1)                        # intermedio (n, m, d)
D_mm = (X**2).sum(1)[:, None] + (Y**2).sum(1)[None, :] - 2 * X @ Y.T          # intermedio (n, m)
print("misma matriz:", np.allclose(D_bc, D_mm), D_bc.shape)
print(f"intermedio: {500 * 400 * 64 * 8 / 2**20:.0f} MiB frente a {500 * 400 * 8 / 2**20:.1f} MiB")

# cancelación: puntos lejos del origen y muy cerca entre sí
Z = 1e5 + rng.standard_normal((6, 3)) * 1e-3
W = Z + rng.standard_normal((6, 3)) * 1e-3
exacta = ((Z[:, None] - W[None]) ** 2).sum(-1)
truco = (Z**2).sum(1)[:, None] + (W**2).sum(1)[None, :] - 2 * Z @ W.T
print("entradas negativas con el truco:", (truco < 0).sum(), "de", truco.size, "  mínimo:", truco.min())
c0 = Z.mean(0)                                                               # trasladar no cambia distancias
Zc, Wc = Z - c0, W - c0
arreglada = np.maximum((Zc**2).sum(1)[:, None] + (Wc**2).sum(1)[None, :] - 2 * Zc @ Wc.T, 0)
print(f"error relativo máximo: sin centrar {np.abs(truco - exacta).max() / exacta.max():.1e}, centrando {np.abs(arreglada - exacta).max() / exacta.max():.1e}")

Tensor contraction

Dot product, matrix multiplication, matrix–vector multiplication and trace seem different. They are the same: multiply entries whose indices are paired and sum those indices.

The familiar catalog follows:

  • Dot product: u⊤v=∑iuivi\vb{u}\T\vb{v} = \sum_i u_i v_i contracts both axes of u⊗v\vb{u} \otimes \vb{v}.
  • Matrix product: (AB)ik=∑jAijBjk(\mat{A}\mat{B})_{ik} = \sum_j A_{ij}B_{jk} contracts A\mat{A}‘s second axis with B\mat{B}‘s first in order-4 A⊗B\mat{A} \otimes \mat{B}. Result order is 2+2−2=22 + 2 - 2 = 2.
  • Matrix–vector product: (Ax)i=∑jAijxj(\mat{A}\vb{x})_i = \sum_j A_{ij}x_j, order 2+1−2=12 + 1 - 2 = 1.
  • Trace: tr⁡A=∑iAii\tr \mat{A} = \sum_i A_{ii} contracts two axes of one matrix. It alone needs no second tensor.
  • Bilinear form: x⊤Ay=∑i,jxiAijyj\vb{x}\T\mat{A}\vb{y} = \sum_{i,j} x_i A_{ij} y_j, two contractions on x⊗A⊗y\vb{x} \otimes \mat{A} \otimes \vb{y}.

Generally, contracting cc axis pairs between order-pp and order-qq tensors leaves order p+q−2cp + q - 2c. Loop cost is easy to read: one iteration per combination of values of all involved indices, free and summed, and one multiplication per iteration. Multiplying m×nm \times n by n×pn \times p costs mnpmnp multiplications because three indices have sizes mm, nn and pp.

The multilinear reading adds a useful nuance. Basis-independent contraction pairs a “vector” index with a “covector” index: evaluation V∗⊗V→RV^* \otimes V \to \R, φ⊗v↦φ(v)\varphi \otimes \vb{v} \mapsto \varphi(\vb{v}). Thus the trace of a linear map is invariant, tr⁡(P−1AP)=tr⁡A\tr(\mat{P}\inv\mat{A}\mat{P}) = \tr\mat{A}, whereas the “trace” of a bilinear-form matrix is not: tr⁡(P⊤AP)≠tr⁡A\tr(\mat{P}\T\mat{A}\mat{P}) \ne \tr\mat{A} generally. With orthonormal bases and orthogonal changes (P−1=P⊤\mat{P}\inv = \mat{P}\T), the difference disappears, the setting of nearly all deep learning. Libraries contract any equal-size axes without asking their meaning; deciding whether contraction makes sense is your job.

Einstein notation and einsum

Einstein summation convention

Writing summation symbols in every formula quickly gets tedious. The Einstein summation convention omits them: an index repeated in a term is summed. Thus yi=Aijxjy_i = A_{ij}x_j means yi=∑jAijxjy_i = \sum_j A_{ij}x_j, and Cik=AijBjkC_{ik} = A_{ij}B_{jk} is matrix multiplication. Indices appearing once are free and index the output. Physics also distinguishes upper and lower indices for the preceding transformation rule; computing uses the version without index height.

einsum turns this convention into a language. String 'ij,jk->ik' says: first operand has axes i,ji, j; second j,kj, k; output i,ki, k. Everything else follows.

The formula nests loops: one per letter, free letters outside and summed letters inside. That is literally what the visualizer does.

InteractiveEinsum visualizer
Enter an einsum string and operand shapes, or select an example. Each letter is a loop: blue if retained in output, orange if summed. Play: each iteration highlights multiplied cells and output cell RR accumulating the product; faint orange operand cells all contribute to that output cell. Start with attention scores bhqd,bhkd->bhqk: batch and head survive, dd is summed and heads never mix. Click an RR cell to jump there. Try trace, diagonal, outer product and implicit mode, and trigger shape errors to read their explanation.

A dictionary

These rules fit nearly all elementary linear algebra into a table. Read each row asking “which letters survive and which are summed?”

OperationeinsumCommon equivalent
Dot product u⊤v\vb{u}\T\vb{v}i,i->u @ v
Outer product uv⊤\vb{u}\vb{v}\Ti,j->ijnp.outer(u, v)
Matrix–vectorij,j->iA @ x
Matrix productij,jk->ikA @ B
AB⊤\mat{A}\mat{B}\Tik,jk->ijA @ B.T
Transposeij->jiA.T
Traceii->np.trace(A)
Diagonalii->inp.diag(A)
Total sum, by columnsij->, ij->jA.sum(), A.sum(0)
Hadamard productij,ij->ijA * B
Frobenius inner productij,ij->(A * B).sum()
Bilinear form x⊤Ay\vb{x}\T\mat{A}\vb{y}i,ij,j->x @ A @ y
Batched productbij,bjk->bikA @ B (batched)
Batched bilinear formbi,ij,bj->b((X @ A) * Y).sum(1)
Batched tracebii->bnp.trace(A, axis1=1, axis2=2)

Two practical details. Ellipsis ... represents any number of batch axes: '...ij,...jk->...ik' works for both (n,n)(n, n) and (B,H,n,n)(B, H, n, n). Implicit mode is a trap: np.einsum('ij,jk', A, B) is matrix multiplication, but np.einsum('ba', A) transposes because implicit output sorts letters alphabetically. Always write the arrow.

Einsum in deep learning

Einsum’s value in real models is that its string documents shapes and removes intermediate reshape, permute and transpose, where bugs hide. Examples return in the transformer module (mechanisms there; index algebra here).

Per-head projections. Store query weights as tensor WQ∈Rd×H×dk\mat{W}^Q \in \R^{d \times H \times d_k} instead of matrix d×dd \times d, and all heads’ queries follow by contraction over dd:

Qbhtk=∑jXbtj WjhkQ’btd,dhk->bhtk’.Q_{bhtk} = \sum_{j} X_{btj}\, W^Q_{jhk} \qquad \texttt{'btd,dhk->bhtk'} .

Output is already ordered (B,H,T,dk)(B, H, T, d_k): no reshape or permute to get wrong. Matrix version (X @ Wq.reshape(d, H*dk)).reshape(B, T, H, dk).permute(0, 2, 1, 3) calculates exactly the same because Wq.reshape(d, H*dk) merges consecutive axes (H,dk)(H, d_k) and output reshape splits them again. Both end in the same GPU matrix product.

Scores by batch and head. Sbhqs=∑kQbhqkKbhskS_{bhqs} = \sum_k Q_{bhqk}K_{bhsk}, i.e. 'bhqk,bhsk->bhqs' (factor 1/dk1/\sqrt{d_k} and softmax are elementwise and row-wise). Batch and head appear throughout: they survive and never mix. This is QK⊤\mat{Q}\mat{K}\T per (b,h)(b, h) without writing a transpose.

Join heads and project. After attention, per-head output O∈RB×H×T×dk\mat{O} \in \R^{B \times H \times T \times d_k} is joined and multiplied by WO\mat{W}^O. With WO\mat{W}^O stored as (H,dk,d)(H, d_k, d), both are one contraction over hh and kk:

Ybtj=∑h∑kObhtk WhkjO’bhtk,hkj->btj’.Y_{btj} = \sum_{h}\sum_{k} O_{bhtk}\, W^O_{hkj} \qquad \texttt{'bhtk,hkj->btj'} .

The formula reveals what reshape code hides: output projection is a sum over heads of each contribution (output as a head sum), key to interpretability.

Bilinear layers. A layer yo=x⊤Woz+boy_o = \vb{x}\T\mat{W}_o\vb{z} + b_o, with weight tensor W∈RO×I×J\mat{W} \in \R^{O \times I \times J}, is 'bi,oij,bj->bo'. This is torch.nn.Bilinear, combining two representations with multiplicative interactions.

Mixture of experts as weighted contraction. With EE linear experts We\mat{W}_e and per-token gate weights gteg_{te}, output yt=∑egteWext\vb{y}_t = \sum_e g_{te}\mat{W}_e\vb{x}_t, weights stored as (E,dout,din)(E, d_{\text{out}}, d_{\text{in}}), is 'te,efd,td->tf'. This dense version sends every token through every expert; a real mixture-of-experts layer selects only a few per token to save compute, but algebra is the same with most gteg_{te} zero.

Graph message passing. With adjacency A\mat{A} of size N×NN \times N and batched features (B,N,d)(B, N, d), aggregating neighbors is 'ij,bjd->bid' (message passing).

Cost and contraction order

Same result, very different costs

With three or more operands, an einsum string admits many evaluation orders. Most directly use one loop nest over all letters, with p−1p - 1 multiplications per iteration: cost is the product of all letter sizes. Alternatively contract in pairs: choose two operands, contract into an intermediate, repeat. A pair contraction costs the product of participating letter sizes and retains only letters still needed (appearing in another operand or output).

An example with three matrices and one vector, all size nn: 'ij,jk,kl,l->i', namely ABCx\mat{A}\mat{B}\mat{C}\vb{x}.

  • One loop: four letters, n4n^4 iterations with three products each.
  • Left to right, ((AB)C)x((\mat{A}\mat{B})\mat{C})\vb{x}: two matrix products and one matrix–vector, 2n3+n22n^3 + n^2.
  • Right to left, A(B(Cx))\mat{A}(\mat{B}(\mat{C}\vb{x})): three matrix–vector products, 3n23n^2.

With n=256n = 256 these are 1.3⋅10101.3 \cdot 10^{10}, 3.4⋅1073.4 \cdot 10^{7} and 196 608196\,608 multiplications: the best order is about 170 times cheaper than starting left and 65 53665\,536 times cheaper than the single loop. You saw matrices in lesson 1; tensors can differ much more because a bad pair can create an intermediate with many axes.

Proof

By induction. With p=2p = 2 there is one tree. A tree with pp leaves has 2p−12p - 1 nodes and 2p−22p - 2 edges; every tree with p+1p + 1 leaves comes from exactly one pp-leaf tree by inserting the new leaf on an edge or above the root (subdividing the edge and attaching the leaf to the new node): 2p−12p - 1 choices. Thus N(p+1)=(2p−1)N(p)N(p + 1) = (2p - 1)N(p), giving N(p)=(2p−3)!!N(p) = (2p - 3)!!. For p=10p = 10, 17!!=34 459 42517!! = 34\,459\,425.

∎

Finding a general tensor network’s optimal order is NP-hard, so many operands call for heuristics. opt_einsum offers several: 'optimal' tries all orders (feasible for few operands), 'dp' uses dynamic programming, 'greedy' contracts the cheapest pair each step, and 'auto' chooses by problem size. Also watch intermediate memory: an order can be cheap in multiplications yet produce a tensor too large for GPU memory.

InteractiveContraction order
Four tensors form a network: each node is a tensor (size grows with element count), each edge a shared index; dashed legs are output indices. Drag a node onto another or click one then another to contract. Each step shows cost (product of all involved index sizes) and intermediate size. Bars rank 15 possible orders logarithmically: decisions gray out discarded ones, green is optimum, as opt_einsum would choose. In batched bilinear form, first contract XX with YY: only the batch is shared, so intermediate (b,i,k)(b, i, k) has 64 times as many elements as the optimal largest one, and contracting it with UU exceeds 50 times optimal cost. In linear attention order decides whether the T×TT \times T matrix appears. Change sizes: the optimum changes.

What libraries do

  • np.einsum does not optimize by default (optimize=False): with many operands it runs one loop nest costing the product of all sizes. With optimize=True (or 'greedy', 'optimal', or a precomputed path) it contracts pairs and uses BLAS matrix products where possible. np.einsum_path returns path and cost report.
  • torch.einsum uses opt_einsum to choose order with three or more operands if installed (torch.backends.opt_einsum.is_available()); otherwise contracts left to right, per its documentation. Each pair contraction becomes batched matrix multiplication, so on GPU a well-ordered chain runs as fast as hand-written code.

Compare counts carefully: NumPy’s report counts “FLOP” as multiplications plus additions, so a contraction over summed indices counts twice the multiplications used here. The tools module covers contraction order from an engineering perspective.

Implementation from scratch

A toy einsum

Implementing einsum using explicit loops shows there is no magic: semantics fit in twenty lines. The interpreter validates the string using the definition’s rules, decides which letters survive and which are summed, and traverses all value combinations with itertools.product.

[ ]A toy einsum validated against np.einsumBrowser
import numpy as np
from itertools import product

def toy_einsum(spec, *ops):
    """einsum con bucles explícitos: un bucle por letra; se suman las letras que no están en la salida."""
    spec = spec.replace(' ', '')
    if '->' in spec:
        lhs, out = spec.split('->')
    else:                                  # modo implícito: letras que aparecen una vez, en orden alfabético
        lhs = spec
        letras = lhs.replace(',', '')
        out = ''.join(sorted(c for c in set(letras) if letras.count(c) == 1))
    terms = lhs.split(',')
    assert len(terms) == len(ops), "hace falta un término por operando"
    sizes = {}
    for t, op in zip(terms, ops):
        assert len(t) == op.ndim, f"'{t}' tiene {len(t)} letras y el operando {op.ndim} ejes"
        for c, n in zip(t, op.shape):
            assert sizes.setdefault(c, n) == n, f"la letra {c} mide {sizes[c]} y {n}"
    assert len(set(out)) == len(out) and set(out) <= set(sizes), "salida no válida"
    loop = list(out) + [c for c in sizes if c not in out]      # libres por fuera, sumadas por dentro
    R = np.zeros(tuple(sizes[c] for c in out))
    for vals in product(*(range(sizes[c]) for c in loop)):
        a = dict(zip(loop, vals))
        term = 1.0
        for t, op in zip(terms, ops):
            term *= op[tuple(a[c] for c in t)]
        R[tuple(a[c] for c in out)] += term
    return R

rng = np.random.default_rng(0)
r = lambda *s: rng.standard_normal(s)
A, B, M = r(3, 4), r(4, 2), r(3, 3)
u, v, x3, y4 = r(3), r(4), r(3), r(4)
Ab, Bb = r(2, 3, 4), r(2, 4, 2)
Q, K = r(2, 2, 3, 4), r(2, 2, 5, 4)
casos = [
    ('i,i->', u, x3), ('i,j->ij', u, v), ('ij,j->i', A, v), ('ij,jk->ik', A, B), ('ij->ji', A),
    ('ii->', M), ('ii->i', M), ('ij->', A), ('ij->j', A), ('ij,ij->ij', A, A),
    ('ij,ij->', A, A), ('i,ij,j->', x3, A, y4), ('bij,bjk->bik', Ab, Bb), ('bij->bji', Ab), ('bij->b', Ab),
    ('bhqd,bhkd->bhqk', Q, K), ('ij,jk', A, B), ('ba', A), ('i,j,k->ijk', u, v, x3), ('ik,jk->ij', A, A),
]
for spec, *ops in casos:
    assert np.allclose(toy_einsum(spec, *ops), np.einsum(spec, *ops)), spec
print(f"{len(casos)} expresiones: el intérprete de juguete coincide con np.einsum")
print("modo implícito, 'ba' es la traspuesta:", np.allclose(toy_einsum('ba', A), A.T))

The interpreter is correct and extremely slow: Python runs every single-loop iteration, exactly the cost the previous section taught you to avoid. Libraries also contract pairs in a good order and translate each pair to matrix multiplication (grouping each operand’s free letters into one axis and summed letters into another with reshape and permute) for BLAS or cuBLAS.

Contraction order in NumPy

[ ]np.einsum_path and the cost of bad orderingBrowser
import numpy as np, time
rng = np.random.default_rng(0)
n = 400
A, B, C = rng.standard_normal((3, n, n))
x = rng.standard_normal(n)

path, info = np.einsum_path('ij,jk,kl,l->i', A, B, C, x, optimize='optimal')
print(path)
print(info)

def tiempo(f, rep=3):
    t = time.perf_counter()
    for _ in range(rep):
        f()
    return (time.perf_counter() - t) / rep

t_izq = tiempo(lambda: ((A @ B) @ C) @ x, rep=1)
t_der = tiempo(lambda: A @ (B @ (C @ x)))
t_opt = tiempo(lambda: np.einsum('ij,jk,kl,l->i', A, B, C, x, optimize=path))
print(f"((AB)C)x: {1e3 * t_izq:.1f} ms   A(B(Cx)): {1e3 * t_der:.2f} ms   einsum con el camino óptimo: {1e3 * t_opt:.2f} ms")
print("mismo resultado:", np.allclose(((A @ B) @ C) @ x, A @ (B @ (C @ x))))

The report confirms the previous calculation: the optimal path contracts vector with C\mat{C} first and the largest intermediate has nn elements. np.einsum without optimize would use a single loop costing order n4n^4 operations; do not try with n=400n = 400.

The professional version: PyTorch on GPU

In PyTorch torch.einsum has the same syntax and runs on GPU. The next cell requires the local lab. It computes multi-head attention scores two ways, using einsum and reshape, permute and matmul, verifies equality and times them. It then plants the memory section’s bug (splitting heads with direct reshape) and shows a property test catching it: changing only head 0’s weights may change only head 0’s scores.

[ ]Multi-head projections with torch.einsum on GPULocal GPU
import torch, time

torch.manual_seed(0)
dev = "cuda" if torch.cuda.is_available() else "cpu"
B, T, d, H = 16, 512, 768, 12
dk = d // H
X = torch.randn(B, T, d, device=dev)
Wq = torch.randn(d, H, dk, device=dev) / d**0.5   # pesos por cabeza: (d, H, dk)
Wk = torch.randn(d, H, dk, device=dev) / d**0.5

def scores_einsum(X, Wq, Wk):
    Q = torch.einsum("btd,dhk->bhtk", X, Wq)       # ya en (B, H, T, dk)
    K = torch.einsum("btd,dhk->bhtk", X, Wk)
    return torch.einsum("bhqk,bhsk->bhqs", Q, K) / dk**0.5

def scores_matmul(X, Wq, Wk):
    Q = (X @ Wq.reshape(d, H * dk)).reshape(B, T, H, dk).permute(0, 2, 1, 3)
    K = (X @ Wk.reshape(d, H * dk)).reshape(B, T, H, dk).permute(0, 2, 1, 3)
    return Q @ K.transpose(-1, -2) / dk**0.5

def scores_bug(X, Wq, Wk):                          # el error plantado: reshape directo a (B, H, T, dk)
    Q = (X @ Wq.reshape(d, H * dk)).reshape(B, H, T, dk)
    K = (X @ Wk.reshape(d, H * dk)).reshape(B, H, T, dk)
    return Q @ K.transpose(-1, -2) / dk**0.5

S1, S2, S3 = scores_einsum(X, Wq, Wk), scores_matmul(X, Wq, Wk), scores_bug(X, Wq, Wk)
print("forma:", tuple(S1.shape), "  einsum frente a matmul, error máx.:", (S1 - S2).abs().max().item())
print("con el reshape mal hecho, error máx.:", round((S3 - S2).abs().max().item(), 3), "  y la forma es la misma:", tuple(S3.shape))

def cronometra(f, rep=20):
    for _ in range(3):
        f()                                        # calentamiento
    if dev == "cuda":
        torch.cuda.synchronize()
    t = time.perf_counter()
    for _ in range(rep):
        f()
    if dev == "cuda":
        torch.cuda.synchronize()                   # la GPU es asíncrona: sin esto solo mides el lanzamiento
    return 1e3 * (time.perf_counter() - t) / rep

print(f"{dev}: einsum {cronometra(lambda: scores_einsum(X, Wq, Wk)):.2f} ms   reshape+permute+matmul {cronometra(lambda: scores_matmul(X, Wq, Wk)):.2f} ms")

# prueba de propiedad: tocar los pesos de la cabeza 0 solo debe cambiar las puntuaciones de la cabeza 0
def cabezas_afectadas(f):
    Wq2 = Wq.clone()
    Wq2[:, 0, :] += 1.0
    cambio = (f(X, Wq2, Wk) - f(X, Wq, Wk)).abs().amax(dim=(0, 2, 3))
    return [h for h in range(H) if cambio[h] > 1e-4]

print("cabezas que cambian (correcto):  ", cabezas_afectadas(scores_matmul))
print("cabezas que cambian (con el error):", cabezas_afectadas(scores_bug))

# sin opt_einsum, torch.einsum contrae de izquierda a derecha
print("opt_einsum disponible para torch.einsum:", torch.backends.opt_einsum.is_available())
n = 4096
A, Bm, C = torch.randn(3, n, n, device=dev) / n**0.5
x = torch.randn(n, device=dev)
t_ein = cronometra(lambda: torch.einsum("ij,jk,kl,l->i", A, Bm, C, x), rep=5)
t_man = cronometra(lambda: A @ (Bm @ (C @ x)), rep=5)
print(f"einsum('ij,jk,kl,l->i'): {t_ein:.2f} ms   A @ (B @ (C @ x)): {t_man:.3f} ms")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Expected result: the correct versions agree up to rounding, often exactly because both end in the same batched-product kernel, and take the same time; the buggy version has the same shape and entirely different values; the property test shows one head’s change contaminating all heads. Such a test, checking a structural invariant instead of one value, best catches silent shape errors. Finally, if opt_einsum is absent, the four-operand string is evaluated left to right with two n×nn \times n matrix products and is tens of times slower than right to left. Installing opt_einsum or writing the order manually fixes it.

Common mistakes

Exercises

QuizBroadcast result shape
What is the shape of the sum of tensors shaped (8,1,6,1)(8, 1, 6, 1) and (7,1,5)(7, 1, 5)?
QuizSplitting heads
X has shape (B,T,d)(B, T, d) with d=Hdkd = H d_k, and head hh owns features hdk,…,(h+1)dk−1h d_k, \dots, (h + 1)d_k - 1. Which PyTorch expressions yield the correct (B,H,T,dk)(B, H, T, d_k) tensor, with head hh's matrix in block [b, h]? Multiple answers may apply.

More than one answer may be correct.

QuizReading einsum
P has shape (B,n,d)(B, n, d) and Q shape (B,m,d)(B, m, d). Which calls calculate, for each bb, PbQb⊤\mat{P}_b\mat{Q}_b\T of shape (B,n,m)(B, n, m)? Multiple answers may apply.

More than one answer may be correct.

QuizCentering without keepdims
X has shape (n,d)(n, d), with n,d≥2n, d \ge 2, and you want to subtract each row's mean. You write X - X.mean(axis=1). What happens?
QuizOrder and rank
A library says tensor t has ‘rank 2’ and shape (64,10)(64, 10). What can you assert about its algebraic matrix rank?
NumericBest order
How many scalar multiplications does np.einsum('ij,jk,k->i', A, B, z) need in the best pairwise contraction order, with i=j=k=1000i = j = k = 1000?
NumericAttention-score memory
A model computes attention scores (B,H,T,T)(B, H, T, T) with B=8B = 8, H=12H = 12, T=1024T = 1024 in float32. How many MiB does the tensor use? (11 MiB =220= 2^{20} bytes.)
NumericAddress after permute
x is contiguous with shape (2,3,4)(2, 3, 4) and y = x.permute(0, 2, 1), shape (2,4,3)(2, 4, 3), is a view. At what memory offset (elements, zero-based) is y[0, 1, 2]?
CodePairwise distances without loops
Implement pairwise_sq_dists(X, Y) that, for X shaped (n, d) and Y shaped (m, d), returns (n, m) matrix of squared Euclidean distances Dij=∥xi−yj∥2D_{ij} = \norm{\vb{x}_i - \vb{y}_j}^2. No Python loops or (n, m, d) intermediate: use expansion ∥x∥2+∥y∥2−2x⊤y\norm{\vb{x}}^2 + \norm{\vb{y}}^2 - 2\vb{x}\T\vb{y} with broadcasting. Output cannot have negative entries and must be accurate (relative error on the order of rounding), even for nearby points far from the origin.
import numpy as np

def pairwise_sq_dists(X, Y):
  # tu código
  return None
Shift+Enter to run
CodeFive operations, five einsums
Implement each function with one np.einsum call. batch_trace(A): A shaped (B, n, n), return B traces. batch_bilinear(x, A, y): x (B, n), A (B, n, m), y (B, m), return B values xb⊤Abyb\vb{x}_b\T\mat{A}_b\vb{y}_b. batch_outer(u, v): u (B, n), v (B, m), return outer products (B, n, m). diag_sum(A): A (B, n, n), return a scalar summing diagonals of all matrices. heads_matmul(P, V): P (B, H, T, S), V (B, H, S, d), return matrix product for each batch and head, (B, H, T, d).
import numpy as np

def batch_trace(A):
  return None

def batch_bilinear(x, A, y):
  return None

def batch_outer(u, v):
  return None

def diag_sum(A):
  return None

def heads_matmul(P, V):
  return None
Shift+Enter to run

Summary

Key idea
A tensor is an array whose axes have meaning, and almost everything a network does with it is contraction: multiply entries with paired indices and sum those that do not survive. Einsum expresses any contraction as a string specifying what is summed and what survives.
  • Two readings, one object. An order-kk array gives coordinates of a tensor-product element and coefficients of a multilinear map. Outer product u⊗v=uv⊤\vb{u} \otimes \vb{v} = \vb{u}\vb{v}\T is elementary, and bilinear forms on V×WV \times W form a space of dimension dim⁡V⋅dim⁡W\dim V \cdot \dim W.
  • Reshape rereads, permute reorders. Reshape preserves axis meaning only when splitting or merging consecutive axes; permute changes strides without moving data. Split heads using reshape(B, T, H, dk) then permute(0, 2, 1, 3), and undo permute before joining.
  • Broadcasting: align right, pad with ones, stretch ones with stride 0. When both operands stretch, the result is an outer product: correct for pairwise distances, a silent bug in pred - y.
  • Contraction and einsum. Dot product, matrix product, trace and bilinear forms are contractions. Each einsum letter is a loop: output letters survive, the rest are summed, and a repeated letter in one operand traverses its diagonal.
  • Order matters. Pair contraction costs the product of involved letter sizes; with pp operands there are (2p−3)!!(2p - 3)!! possible orders with costs and memory differing by orders of magnitude. np.einsum does not optimize by default and torch.einsum does only with opt_einsum installed.