einsum and index notation for tensors
Einstein notation describes tensor products, traces, transpositions, and contractions with one index string. Learn to read and write einsum fluently, estimate its cost and choose contraction order, and rearrange axes readably with einops. This is the language used for attention, many modern layers, and much of the mathematics in papers.
After this lesson you can
- Translate indexed formulas (trace, batched matrix product, outer product, bilinear form) to einsum and back.
- Calculate multiplication cost and intermediate memory of a contraction and choose order with einsum_path or opt_einsum.
- Rearrange axes with einops rearrange, reduce, and repeat instead of opaque reshape and transpose chains.
- Implement toy multi-head attention using only einsum and einops and verify it against a loop-based version.
Before you start
Motivation: the paper’s formula and code nobody understands
Open any article on transformers and you will find multi-head attention scores written like this:
where is the batch example, the head, the querying position, the responding position, and the coordinate within the head. Five indices, one sum, and the formula says everything: which axes survive, which is summed, and that batch and head never mix. Now open the implementation. Typically it looks like this:
q = (x @ Wq).reshape(B, T, H, dk).transpose(0, 2, 1, 3)
k = (x @ Wk).reshape(B, T, H, dk).transpose(0, 2, 1, 3)
s = q @ k.transpose(0, 1, 3, 2) / np.sqrt(dk)
Two reshape, three transpose, and three @ operations, and to know whether it is correct you must mentally reconstruct the shape after each step. Worse, if someone “simplifies” the first line to (x @ Wq).reshape(B, H, T, dk), the code still runs, shapes still fit, and the result is garbage. No error, no warning.
import numpy as np
rng = np.random.default_rng(0)
B, T, d, H = 2, 5, 12, 3 # lote, posiciones, dimensión del modelo, cabezas
dk = d // H # 4 dimensiones por cabeza
x = rng.standard_normal((B, T, d))
Wq, Wk = rng.standard_normal((2, d, d)) / np.sqrt(d)
# 1) la versión habitual: dos reshape, tres transpose y tres @
q = (x @ Wq).reshape(B, T, H, dk).transpose(0, 2, 1, 3)
k = (x @ Wk).reshape(B, T, H, dk).transpose(0, 2, 1, 3)
s1 = q @ k.transpose(0, 1, 3, 2) / np.sqrt(dk)
# 2) la fórmula, letra a letra: S[b,h,t,s] = sum_c Q[b,h,t,c] K[b,h,s,c] / sqrt(dk)
s2 = np.einsum("bhtc,bhsc->bhts", q, k) / np.sqrt(dk)
# 3) el error clásico: separar las cabezas con un reshape sin transpose
q_mal = (x @ Wq).reshape(B, H, T, dk)
k_mal = (x @ Wk).reshape(B, H, T, dk)
s3 = np.einsum("bhtc,bhsc->bhts", q_mal, k_mal) / np.sqrt(dk)
print("formas:", s1.shape, s2.shape, s3.shape)
print("einsum == versión habitual:", np.allclose(s1, s2))
print("reshape sin transpose :", np.allclose(s1, s3), " error máximo:", np.abs(s1 - s3).max().round(2))The second line is the paper’s formula copied letter by letter: "bhtc,bhsc->bhts". That string is a complete language for describing tensor products, sums, traces, transpositions, and contractions, and the language in which attention, many modern layers, and much of the mathematics you will read are written. This lesson teaches it at three levels:
- Read and write
einsumfluently, knowing exactly which loops it executes and which shape it returns. - Estimate its cost and choose the order of contracting several operands, which can change computation time by orders of magnitude.
- Rearrange named axes with einops instead of
reshapeandtransposechains nobody can review.
The linear algebra module studies the same object from the other side, as tensor contraction in the multilinear sense; here the viewpoint is that of someone writing and debugging code. One convention: since everything that follows executes, concrete indices start at 0 in the text too.
Einstein summation convention
In 1916, in his paper on the foundations of general relativity, Einstein introduced a rule to avoid writing summation signs: if an index is repeated in a term, sum over it. Thus means , the product of a matrix and a vector, and is matrix multiplication. Indices appearing once are called free and range over result components; repeated indices, dummy or summed, disappear.
einsum turns that rule into a small language. The string "ij,jk->ik" says: the first operand has axes named i and j; the second, j and k; the output has axes i and k, in that order. Everything else follows.
The formula reads like a program. Each letter is a for loop; free-letter loops go outside and traverse output cells, while summed-letter loops go inside and accumulate:
R = np.zeros((nb, ni, nk))
for b in range(nb):
for i in range(ni):
for k in range(nk):
for j in range(nj): # j no está en la salida: se suma
R[b, i, k] += A[b, i, j] * B[b, j, k]
That literal translation is einsum semantics, with an immediate cost consequence: the loop performs one iteration for each combination of values of all letters, with multiplications in each. Evaluated this way, an einsum costs
whether or not each letter appears in the output. Here “letras” means letters and “multiplicaciones” means multiplications. Explore it.
j to leave it free and see how the shape of changes without changing iteration count. Reverse output order. Then try trace, diagonal, and both implicit-mode examples, and write your own strings.What you should have seen:
- Output shape is the list of free letters, in order, and nothing else. In
bij,bjk->bikit is . Ifjis freed, output becomesbikj, shape : nothing is summed and each cell stores one product. Ifbis summed, you get the sum of batch products,(A @ B).sum(axis=0). - Iteration count does not depend on which letters are free. They are the same loops; only which cell accumulates each product changes. Naive evaluation cost depends on all letters, not output.
- Reversing output changes no number’s place inside the sum: it only transposes the result.
ij,jk->kiis . If dimensions match, nothing warns you that you wanted the other one. - Trace traverses one loop. In
ii->a single variableiindexes both positions of the term, so only diagonal cells are read.ii->ileavesifree and returns the diagonal. - Implicit mode sorts alphabetically.
ij,jkis a matrix product becauseiprecedesk;bais a transpose, because implicit output isab. Always write the arrow.
Reading a string in three questions
With the definition, decode any string by answering in order: which letters survive and in what order (shape); which are summed (what is contracted); are letters repeated within a term (diagonals)? The table lists the strings you will see most; all are instances of the same formula.
| Operation | Formula | einsum | Equivalent |
|---|---|---|---|
| Trace | ii-> | np.trace(A) | |
| Diagonal | ii->i | np.diag(A) | |
| Transpose | ij->ji | A.T | |
| Column sum | ij->j | A.sum(axis=0) | |
| Dot product | i,i-> | x @ y | |
| Outer product | i,j->ij | np.outer(x, y) | |
| Matrix product | ij,jk->ik | A @ B | |
| Trace of a product | ij,ji-> | np.trace(A @ B) | |
| Frobenius | ij,ij-> | (A * B).sum() | |
| Bilinear form | i,ij,j-> | x @ A @ y | |
| Batched product | bij,bjk->bik | A @ B | |
| Batched bilinear form | bi,ij,bj->b | ((X @ A) * Y).sum(1) | |
| Row Gram matrix | bi,ci->bc | X @ X.T | |
| Double contraction | ijk,jkl->il | np.tensordot(T, U, axes=2) |
Three rows deserve comment. The trace of a product, ij,ji->, never forms : it sums products instead of doing multiplications and keeping the diagonal. The outer product, i,j->ij, is the rank-one matrix , and appears when differentiating a linear layer. The diagonal ii->i copies nothing: it is a view with one stride equal to the sum of the two axis strides, exactly as studied with strides. The cell checks the whole table and that detail.
import numpy as np
rng = np.random.default_rng(1)
A, B = rng.standard_normal((2, 4, 4))
x, y = rng.standard_normal((2, 4))
Ab, Bb = rng.standard_normal((5, 4, 3)), rng.standard_normal((5, 3, 2)) # lotes de 5 matrices
X, Y = rng.standard_normal((2, 5, 4)) # lotes de 5 vectores de R^4
T3, U3 = rng.standard_normal((4, 3, 2)), rng.standard_normal((3, 2, 6))
catalogo = {
"ii-> traza": (np.einsum("ii->", A), np.trace(A)),
"ii->i diagonal": (np.einsum("ii->i", A), np.diag(A)),
"ij->ji traspuesta": (np.einsum("ij->ji", A), A.T),
"ij-> suma total": (np.einsum("ij->", A), A.sum()),
"ij->j suma por columnas": (np.einsum("ij->j", A), A.sum(axis=0)),
"i,i-> producto escalar": (np.einsum("i,i->", x, y), x @ y),
"i,j->ij producto exterior": (np.einsum("i,j->ij", x, y), np.outer(x, y)),
"ij,j->i matriz por vector": (np.einsum("ij,j->i", A, x), A @ x),
"ij,jk->ik producto": (np.einsum("ij,jk->ik", A, B), A @ B),
"ij,ji-> tr(AB)": (np.einsum("ij,ji->", A, B), np.trace(A @ B)),
"ij,ij-> Frobenius": (np.einsum("ij,ij->", A, B), (A * B).sum()),
"i,ij,j-> forma bilineal": (np.einsum("i,ij,j->", x, A, y), x @ A @ y),
"bij,bjk->bik producto por lotes": (np.einsum("bij,bjk->bik", Ab, Bb), Ab @ Bb),
"bi,ij,bj->b bilineal por lotes": (np.einsum("bi,ij,bj->b", X, A, Y), ((X @ A) * Y).sum(axis=1)),
"bi,ci->bc Gram de las filas": (np.einsum("bi,ci->bc", X, X), X @ X.T),
"ijk,jkl->il contracción doble": (np.einsum("ijk,jkl->il", T3, U3), np.tensordot(T3, U3, axes=2)),
}
for nombre, (a, b) in catalogo.items():
print(f"{nombre:38s} {np.allclose(a, b)}")
d = np.einsum("ii->i", A)
print("\n¿la diagonal es una vista?", np.shares_memory(d, A), " strides:", A.strides, "->", d.strides)Two operands are a matrix product
The table suggests something stronger: almost every row with two operands is a disguised @. This is no coincidence, and understanding it explains when einsum runs at BLAS speed and when it does not.
Proof
By rule 4 of the definition, , where each Greek letter denotes the list of indices in its group and axes are already written permuted (permuting axes changes no values, only where they live). The assumption that each letter occurs in two places ensures there are no other cases: a letter only in and outside would be summed within A before multiplication. Grouping in row-major order a list of indices of sizes into index is a bijection between tuples and . Replacing each group by its grouped index transforms the multiple sum over into a single sum over with the same terms, the stated formula.
∎The proof is also the algorithm libraries use: torch.einsum contracts in pairs and executes each pair as a bmm after permuting and grouping. np.einsum, when asked to optimize, does the same with tensordot (and therefore BLAS) for pairs without batch letters; it leaves pairs with batch letters to its C loop. The cell does this manually for a contraction with deliberately disordered letters.
import numpy as np
rng = np.random.default_rng(2)
# R[b,i,k,l] = sum_{j,m} A[b,j,i,m] C[m,b,l,j,k] (letras desordenadas a propósito)
A = rng.standard_normal((3, 4, 5, 6)) # ejes b j i m
C = rng.standard_normal((6, 3, 2, 4, 7)) # ejes m b l j k
R = np.einsum("bjim,mbljk->bikl", A, C)
# lote: b · contraídas: j, m · solo de A: i · solo de C: l, k
A2 = A.transpose(0, 2, 1, 3).reshape(3, 5, 4 * 6) # (b, i, (j m))
C2 = C.transpose(1, 3, 0, 2, 4).reshape(3, 4 * 6, 2 * 7) # (b, (j m), (l k))
R2 = (A2 @ C2).reshape(3, 5, 2, 7).transpose(0, 1, 3, 2) # (b, i, l, k) -> (b, i, k, l)
print("einsum == un único producto por lotes:", np.allclose(R, R2))
print("A2 comparte memoria con A:", np.shares_memory(A, A2), "· C2 con C:", np.shares_memory(C, C2))
print("forma del producto de matrices:", A2.shape, "@", C2.shape, "->", (A2 @ C2).shape)Notice the second output line. transpose is a view, but the following reshape cannot group axes that are no longer contiguous in memory and makes a copy (seen in views and copies). Thus einsum performance also depends on operand layout: if contracted axes are already last and contiguous, contraction is a direct @; otherwise a copy is paid first. On a GPU the copy is usually cheap compared with the product, but not free.
The gradient of an einsum is another einsum
There is another reason to write models with einsum: its derivative is written in the same language directly.
Proof
is a sum of products in which appears exactly once as a factor, so it is linear in and is the product of the other factors, summed over letters in neither nor (if fixes those letters, the rest remain free). By the chain rule, , that is, the sum over all letters not in of . This is literally the stated einsum. The hypothesis on ‘s letters guarantees all have known sizes in the new operands; if a letter appeared only in , the derivative would be constant along that axis and need broadcasting, and if had a repeated letter, the derivative would live only on the diagonal.
∎For ij,jk->ik the rule gives ik,jk->ij with respect to A, that is, , and ik,ij->jk with respect to B, : linear-layer backpropagation formulas appear without drawing any matrices. This calculates a vector-Jacobian product as implemented inside autograd.
import numpy as np
rng = np.random.default_rng(4)
X, Y = rng.standard_normal((2, 6, 3)) # lotes de 6 vectores
A = rng.standard_normal((3, 3))
G = rng.standard_normal(6) # G = dL/dR, lo que llega desde arriba
R = lambda X, A, Y: np.einsum("bi,ij,bj->b", X, A, Y)
L = lambda X, A, Y: G @ R(X, A, Y) # una pérdida lineal en R: dL/dR = G
# regla: el gradiente respecto de un operando es el einsum de G con los demás, con la salida en su término
dA = np.einsum("b,bi,bj->ij", G, X, Y)
dX = np.einsum("b,ij,bj->bi", G, A, Y)
def numerico(f, Z, h=1e-6):
g = np.zeros_like(Z)
for idx in np.ndindex(Z.shape):
E = np.zeros_like(Z); E[idx] = h
g[idx] = (f(Z + E) - f(Z - E)) / (2 * h)
return g
print("dL/dA:", np.allclose(dA, numerico(lambda Z: L(X, Z, Y), A)))
print("dL/dX:", np.allclose(dX, numerico(lambda Z: L(Z, A, Y), X)))A toy einsum from scratch
The best way to remove doubt about the semantics is to implement them. Three ideas you already know suffice: take diagonals to remove repeated letters, align all operands in a global letter order with new size-1 axes, and let broadcasting construct the product over the whole index space before summing contracted axes.
import numpy as np
from collections import Counter
def parse(spec):
spec = spec.replace(" ", "")
if "->" in spec:
lhs, out = spec.split("->")
else: # modo implícito
lhs = spec
n = Counter(lhs.replace(",", ""))
out = "".join(sorted(c for c in n if n[c] == 1))
return lhs.split(","), out
def quitar_repetidas(x, term):
"""Toma diagonales hasta que cada letra aparece una vez: ('ii', A) -> ('i', diag A)."""
while len(set(term)) < len(term):
c = next(c for c in term if term.count(c) > 1)
i = term.index(c)
j = term.index(c, i + 1)
x = np.diagonal(x, axis1=i, axis2=j) # una vista; la diagonal pasa al final
term = term[:i] + term[i + 1:j] + term[j + 1:] + c
return x, term
def my_einsum(spec, *ops):
terms, out = parse(spec)
assert len(terms) == len(ops), "hace falta un término por operando"
pares = [quitar_repetidas(np.asarray(x), t) for x, t in zip(ops, terms)]
todas = {c for _, t in pares for c in t}
letras = list(out) + sorted(todas - set(out)) # libres primero, sumadas al final
alineados = []
for x, t in pares:
presentes = [c for c in letras if c in t]
x = x.transpose([t.index(c) for c in presentes]) # ejes en el orden global
x = x.reshape([x.shape[presentes.index(c)] if c in t else 1 for c in letras]) # ejes nuevos de tamaño 1
alineados.append(x)
producto = alineados[0]
for x in alineados[1:]:
producto = producto * x # broadcasting: el espacio de índices entero
return producto.sum(axis=tuple(range(len(out), len(letras))))
rng = np.random.default_rng(3)
r = lambda *s: rng.standard_normal(s)
A = r(3, 3)
casos = [
("ij,jk->ik", (r(2, 3), r(3, 4))), ("ii->", (A,)), ("ii->i", (A,)), ("ij->ji", (A,)),
("ij", (A,)), ("ba", (r(3, 2),)), ("i,j->ij", (r(3), r(4))), ("i,ij,j->", (r(3), A, r(3))),
("bij,bjk->bik", (r(5, 2, 3), r(5, 3, 4))), ("iij->ji", (r(3, 3, 2),)), ("ij,jk", (r(2, 3), r(3, 4))),
("ij,j->i", (r(2, 1), r(5))), ("bhtc,bhsc->bhts", (r(2, 3, 4, 5), r(2, 3, 6, 5))),
]
for spec, ops in casos:
print(f"{spec:18s} {np.allclose(my_einsum(spec, *ops), np.einsum(spec, *ops))}")Thirteen cases, including the diagonal of an order-3 tensor (iij->ji), both implicit modes, and a size-1 axis that broadcasts (ij,j->i with shapes and , which NumPy accepts). Comparison against a reference implementation is the technique formalized in testing against a reference.
my_einsum is correct, but materializes the product over all letters before summing: for an matrix product, an array of elements. The next cell measures it.
import time
n = 120
A, B = rng.standard_normal((2, n, n))
t0 = time.perf_counter(); C1 = my_einsum("ij,jk->ik", A, B)
t1 = time.perf_counter(); C2 = np.einsum("ij,jk->ik", A, B)
t2 = time.perf_counter(); C3 = A @ B
t3 = time.perf_counter()
print(f"intermedio de my_einsum: {n**3:,} elementos ({n**3 * 8 / 1e6:.1f} MB); la salida tiene {n * n:,}".replace(",", " "))
print(f"my_einsum {1e3 * (t1 - t0):6.1f} ms np.einsum {1e3 * (t2 - t1):6.1f} ms A @ B {1e3 * (t3 - t2):6.1f} ms")
print("iguales:", np.allclose(C1, C2) and np.allclose(C2, C3))The intermediate is 120 times larger than the output, and with a small transformer’s shapes it would be impossible: scores bhtc,bhsc->bhts with , , , and would need tens of gigabytes (you will calculate this in the exercises). np.einsum avoids that problem because it runs loops in C and accumulates on the fly without storing products. But it has another problem that appears with more than two operands.
Cost and contraction order
An einsum with three or more operands can be calculated many ways. The literal way, a single nest of loops over all letters, costs the product of all sizes. The alternative is to contract in pairs: choose two operands, contract them into an intermediate tensor, and repeat until one remains. The result is the same in exact arithmetic because sum and product are associative and commutative and multiplication distributes over addition (floating-point rounding differs); the cost is not.
The simplest example shows everything. A batch of 2 vectors of dimension 10 passes through three linear layers without activation: , , , , and we want ij,jk,kl,lm->im. Left to right, costs
multiplications, and never forms anything larger than . Right to left, begins by multiplying the two large matrices: multiplications in the first step alone, 45 times more than the entire previous order. The single loop performs iterations with three products each.
Proof
Parenthesizations: the final multiplication splits the chain into a prefix of matrices and a suffix of , each parenthesized independently, so with , the Catalan recurrence with . Trees: each tree with leaves comes from exactly one with leaves by inserting the new leaf on one of its edges or above the root, possibilities; with this gives .
∎For a chain, the optimal order is found in with dynamic programming for matrix-chain multiplication: what np.linalg.multi_dot does. For a general tensor network, finding the optimal order is NP-hard (Lam, Sadayappan, and Wenger, 1997), and libraries combine exhaustive search for few operands with heuristics. NumPy’s einsum_path(..., optimize="greedy"), also used by optimize=True, is:
- Consider operand pairs sharing a letter (outer products only if nothing else remains).
- Discard those creating an intermediate larger than the memory limit, by default the size of the largest operand or output.
- Among the rest, contract the pair that eliminates most elements, the size of the two operands minus result size, breaking ties by cost.
- Repeat with the new tensor.
This is reasonable and fast, but does not look ahead. In the chain above, contracting eliminates elements, far more than any other pair, so greedy starts with the most expensive contraction.
einsum_path memory limit). The initial state is the text's chain: greedy chooses , 46 times more expensive than optimal. Move to 1000 and see the winner change. Then switch to , the core of linear attention (without softmax), and increase length : one order grows as and the other as .What you should have seen:
- The five chain orders span almost two orders of magnitude in cost, determined by intermediate sizes: the optimum never forms anything larger than .
- Greedy fails in the most natural case, a small batch passing through large layers, because it rewards eliminating much memory at once without considering cost.
optimize="optimal"succeeds here. When the optimal intermediate exceeds the default limit (largest operand or output), evenoptimalcannot find it: raise the limit withoptimize=("optimal", limite). - In , order is the difference between a quadratic and linear model. forms the score matrix, at cost ; forms a matrix, at cost . Without softmax they agree: the idea of linear attention. With softmax in between, reordering is no longer valid, so standard attention is quadratic.
What libraries do
- NumPy does not optimize by default.
np.einsumhasoptimize=False: with three or more operands it runs the single loop.optimize=Trueequals"greedy"; it also accepts"optimal"and a precalculated path, whichnp.einsum_pathreturns with a report. In that report, “FLOP” counts multiplications plus additions: a contraction with summed indices counts twice our multiplications. - opt_einsum (Smith and Gray, 2018) is the specialized library:
oe.contractwith strategies"auto","greedy","dp","branch-2", or"optimal", explicit memory limits, andoe.contract_expressionto fix a path once and reuse it at each training step. - PyTorch uses opt_einsum to order contractions of three or more operands if installed (
torch.backends.opt_einsum.is_available()); otherwise it contracts left to right. JAX depends on opt_einsum andjnp.einsumoptimizes order by default.
import numpy as np, time
rng = np.random.default_rng(5)
A = rng.standard_normal((2, 10)) # un lote de 2 vectores...
B = rng.standard_normal((10, 100)) # ...que atraviesa tres capas lineales
C = rng.standard_normal((100, 1000))
D = rng.standard_normal((1000, 1000))
spec = "ij,jk,kl,lm->im"
camino, informe = np.einsum_path(spec, A, B, C, D, optimize="greedy")
print(informe)
print("camino óptimo:", np.einsum_path(spec, A, B, C, D, optimize="optimal")[0])
def ms(f, rep=3):
f(); t0 = time.perf_counter()
for _ in range(rep): f()
return 1e3 * (time.perf_counter() - t0) / rep
print(f"\noptimize='greedy' {ms(lambda: np.einsum(spec, A, B, C, D, optimize='greedy')):7.1f} ms")
print(f"optimize='optimal' {ms(lambda: np.einsum(spec, A, B, C, D, optimize='optimal')):7.1f} ms")
print(f"A @ B @ C @ D {ms(lambda: A @ B @ C @ D):7.1f} ms (Python asocia por la izquierda)")
print(f"multi_dot {ms(lambda: np.linalg.multi_dot([A, B, C, D])):7.1f} ms (programación dinámica)")The report lists greedy’s steps: first lm,kl->km (that is, ), then with and finally with . Paths are pairs of positions in the remaining operand list at each step, with the result appended: (0, 1), (0, 2), (0, 1) means , then with and then . Measurement confirms the theory: greedy is tens of times slower. The naive case remains, which with these shapes would not finish in time:
Cs, Ds = C[:, :100], D[:100, :50] # recortadas: con las formas originales serían 2·10⁹ iteraciones
t_ing = ms(lambda: np.einsum(spec, A, B, Cs, Ds), rep=1)
t_opt = ms(lambda: np.einsum(spec, A, B, Cs, Ds, optimize=True))
print(f"formas recortadas: {2 * 10 * 100 * 100 * 50:,} iteraciones con optimize=False".replace(",", " "))
print(f"optimize=False {t_ing:8.1f} ms optimize=True {t_opt:6.2f} ms iguales:",
np.allclose(np.einsum(spec, A, B, Cs, Ds), np.einsum(spec, A, B, Cs, Ds, optimize=True)))einops: named axes
einsum handles contractions, but much tensor code contracts nothing: it rearranges axes. Split heads, join them, cut an image into patches, move channels to the end, flatten. In NumPy and PyTorch this uses reshape, transpose, permute, and view, producing the unreadable lines at the start. einops (Rogozhnikov, 2022) is an alternative with the same philosophy as einsum: describe the operation using axis names.
Proof
reshape in C order numbers elements row-major, with the last axis varying fastest (in a contiguous array, this reinterprets the same memory with new strides): element of an axis of length moves to position with and . Euclidean division of by uniquely gives and . With (h p), the elements sharing value are , consecutive; with (p h) they are for , separated by .
The proposition is key to tokenizing a Vision Transformer. A image is cut into patches and each flattened into a token of numbers: rearrange(img, "b c (h p1) (w p2) -> b (h w) (p1 p2 c)", p1=p, p2=p). Group (h p1) says the pixel row splits into patch row (slow) and row within the patch (fast); (h w) numbers patches row-wise; (p1 p2 c) fixes the order of numbers in each token.
(h p1) (w p2) to (p1 h) (p2 w): shape is identical and each token mixes all four quadrants. Read each pattern's equivalent reshape and transpose chain and trigger the three errors.What you should have seen:
- Shape is insufficient to tell whether a pattern is correct. Correctly and incorrectly split patches both give ; only the data reveal the error. This is the same trap as
reshapewithouttransposeat the start, and why a test comparing a specific token with its patch helps. - Every rearrange follows the same three-step recipe: decompose with
reshape, reorder withtranspose, compose withreshape. The pattern is shorter and, above all, reviewable: names express intent. - Order within a token is a convention with consequences.
(p1 p2 c)and(c p1 p2)are two valid tokenizations, but patch-projection weights work for only one. - einops errors explain what is missing: an axis that cannot be divided, a name on only one side (rearrange does not sum; use
reduce), two unknowns in a group.
Patch projection is an einsum, and a convolution
The cell writes tokenization and its inverse with reshape and transpose, and checks the last observation: a ViT’s patch projection, a product of tokens by a matrix , is exactly convolution with a kernel and stride , provided weights are reordered to (d, c, p1, p2) as used by a convolutional layer.
import numpy as np
rng = np.random.default_rng(6)
B, C, H, W, p = 8, 3, 32, 32, 8 # 8 imágenes RGB de 32×32, parches de 8×8
h, w = H // p, W // p # rejilla de 4×4 parches
img = rng.standard_normal((B, C, H, W))
# 'b c (h p1) (w p2) -> b (h w) (p1 p2 c)'
tok = img.reshape(B, C, h, p, w, p).transpose(0, 2, 4, 3, 5, 1).reshape(B, h * w, p * p * C)
print("tokens:", tok.shape)
# comprobación directa: el token 6 de la imagen 0 es el parche de la fila 1 y la columna 2
parche = img[0, :, 1 * p:2 * p, 2 * p:3 * p] # (c, p1, p2)
print("token 6 == parche (1, 2):", np.array_equal(tok[0, 1 * w + 2], parche.transpose(1, 2, 0).ravel()))
# y la vuelta: 'b (h w) (p1 p2 c) -> b c (h p1) (w p2)'
vuelta = tok.reshape(B, h, w, p, p, C).transpose(0, 5, 1, 3, 2, 4).reshape(B, C, H, W)
print("ida y vuelta exacta:", np.array_equal(vuelta, img))
# la proyección de parches: un einsum sobre los tokens...
dm = 64
Wp = rng.standard_normal((p * p * C, dm)) / np.sqrt(p * p * C)
emb = np.einsum("bnf,fd->bnd", tok, Wp)
# ...o una convolución con núcleo y paso p, cuyos pesos viven en el orden (d, c, p1, p2)
Wconv = Wp.reshape(p, p, C, dm).transpose(3, 2, 0, 1)
emb_conv = np.einsum("bcxpyq,dcpq->bxyd", img.reshape(B, C, h, p, w, p), Wconv)
print("proyección == convolución:", np.allclose(emb, emb_conv.reshape(B, h * w, dm)))The last contraction, bcxpyq,dcpq->bxyd, is convolution written as einsum: with stride equal to kernel size, windows do not overlap and a reshape suffices to extract them. Overlapping windows need a sliding-window view, and the contraction is the same.
Lab: multi-head attention using only einsum
You now have all pieces to write causal multi-head attention without a single loop. The reference version traverses batches and heads with Python loops and works with matrices; the einsum version is the paper’s formula. The mechanisms (why scale by , what the causal mask does, why multiple heads) are studied in multi-head attention; here we focus only on its index algebra.
import numpy as np, time
rng = np.random.default_rng(7)
B, T, d, H = 2, 16, 32, 4
dk = d // H
X = rng.standard_normal((B, T, d))
Wq, Wk, Wv, Wo = rng.standard_normal((4, d, d)) / np.sqrt(d)
causal = np.triu(np.ones((T, T), dtype=bool), k=1) # True donde s > t: prohibido
def softmax(z):
z = z - z.max(axis=-1, keepdims=True)
e = np.exp(z)
return e / e.sum(axis=-1, keepdims=True)
def atencion_bucles(X):
Y = np.zeros((B, T, d))
for b in range(B):
cabezas = []
for h in range(H):
cols = slice(h * dk, (h + 1) * dk) # las columnas de la cabeza h
q, k, v = X[b] @ Wq[:, cols], X[b] @ Wk[:, cols], X[b] @ Wv[:, cols]
s = q @ k.T / np.sqrt(dk)
s[causal] = -np.inf
cabezas.append(softmax(s) @ v)
Y[b] = np.concatenate(cabezas, axis=1) @ Wo
return Y
def atencion_einsum(X):
# proyectar y separar cabezas: reshape (B, T, H, dk) y después transpose
Q, K, V = (np.einsum("btd,de->bte", X, W).reshape(B, T, H, dk).transpose(0, 2, 1, 3) for W in (Wq, Wk, Wv))
S = np.einsum("bhtc,bhsc->bhts", Q, K) / np.sqrt(dk)
P = softmax(np.where(causal, -np.inf, S))
O = np.einsum("bhts,bhsc->bhtc", P, V)
return O.transpose(0, 2, 1, 3).reshape(B, T, d) @ Wo # juntar cabezas y proyectar
def atencion_einsum_sin_reshape(X):
# los pesos vistos como tensores (d, H, dk) y (H, dk, d): ni un reshape de activaciones
Wq3, Wk3, Wv3 = (W.reshape(d, H, dk) for W in (Wq, Wk, Wv))
Q, K, V = (np.einsum("btd,dhc->bhtc", X, W3) for W3 in (Wq3, Wk3, Wv3))
P = softmax(np.where(causal, -np.inf, np.einsum("bhtc,bhsc->bhts", Q, K) / np.sqrt(dk)))
O = np.einsum("bhts,bhsc->bhtc", P, V)
return np.einsum("bhtc,hcd->btd", O, Wo.reshape(H, dk, d)) # suma sobre cabezas
ref = atencion_bucles(X)
print("einsum == bucles:", np.allclose(atencion_einsum(X), ref))
print("sin reshape == bucles:", np.allclose(atencion_einsum_sin_reshape(X), ref))The third version deserves attention. If you view as a tensor (a reshape of the weights, which is a view), projection and splitting into heads are a single contraction, btd,dhc->bhtc, already returning order . Output projection, bhtc,hcd->btd, joins heads and projects in one step, making visible what reshape hides: attention output is a sum over heads of each one’s contribution (output projection as a sum over heads), central to interpretability.
The optimize parameter remains. Scores can be written directly from in a single four-operand string. Without optimization, NumPy traverses all seven letters at once.
Wq3, Wk3 = Wq.reshape(d, H, dk), Wk.reshape(d, H, dk)
spec = "btd,dhc,bse,ehc->bhts"
def ms(f, rep=3):
f(); t0 = time.perf_counter()
for _ in range(rep): f()
return 1e3 * (time.perf_counter() - t0) / rep
S_ingenuo = np.einsum(spec, X, Wq3, X, Wk3)
S_opt = np.einsum(spec, X, Wq3, X, Wk3, optimize=True)
print("iguales:", np.allclose(S_ingenuo, S_opt))
print(f"optimize=False {ms(lambda: np.einsum(spec, X, Wq3, X, Wk3), rep=1):7.1f} ms")
print(f"optimize=True {ms(lambda: np.einsum(spec, X, Wq3, X, Wk3, optimize=True)):7.2f} ms")
print(np.einsum_path(spec, X, Wq3, X, Wk3, optimize=True)[1].split("\n")[3:7])The report predicts a roughly 400-fold speedup: the single loop traverses combinations, while the optimized path calculates and separately and then contracts them. The actual measurement is in the same order of magnitude: with multiple operands, optimize=True matters.
The PyTorch version, with einops
In PyTorch translation is literal: torch.einsum accepts the same strings, and einops works the same on NumPy, PyTorch, or JAX tensors. The cell rewrites attention using einops to split and join heads, compares it with F.scaled_dot_product_attention using torch.testing.assert_close, and shows einops errors; it needs PyTorch and einops, so runs locally.
import time
import numpy as np
import torch
import torch.nn.functional as F
from einops import rearrange, reduce, repeat, EinopsError
img = np.arange(96.0).reshape(2, 3, 4, 4)
print(rearrange(img, "b c (h p1) (w p2) -> b (h w) (p1 p2 c)", p1=2, p2=2).shape)
print(reduce(img, "b c (h 2) (w 2) -> b c h w", "max").shape, " (max-pooling 2×2)")
print(reduce(img, "b c h w -> b c", "mean").shape, " (media global)")
print(repeat(img, "b c h w -> b c (h 2) (w 2)").shape, " (sobremuestreo por vecino más cercano)")
for patron, tam in [("b c (h p1) (w p2) -> b (h w) (p1 p2 c)", dict(p1=3, p2=3)), ("b c h w -> b (h w)", {})]:
try:
rearrange(img, patron, **tam)
except EinopsError as e:
print("\nEinopsError:", str(e).strip().splitlines()[-1][:160])
dev = "cuda" if torch.cuda.is_available() else "cpu"
torch.manual_seed(0)
B, T, d, H = 8, 512, 512, 8
dk = d // H
X = torch.randn(B, T, d, device=dev)
Wq, Wk, Wv, Wo = (torch.randn(d, d, device=dev) / d**0.5 for _ in range(4))
causal = torch.triu(torch.ones(T, T, dtype=torch.bool, device=dev), diagonal=1)
def atencion_einops(X):
q, k, v = (rearrange(X @ W, "b t (h c) -> b h t c", h=H) for W in (Wq, Wk, Wv))
S = torch.einsum("bhtc,bhsc->bhts", q, k) / dk**0.5
O = torch.einsum("bhts,bhsc->bhtc", S.masked_fill(causal, float("-inf")).softmax(-1), v)
return rearrange(O, "b h t c -> b t (h c)") @ Wo
def atencion_sdpa(X):
q, k, v = ((X @ W).view(B, T, H, dk).transpose(1, 2) for W in (Wq, Wk, Wv))
O = F.scaled_dot_product_attention(q, k, v, is_causal=True)
return O.transpose(1, 2).reshape(B, T, d) @ Wo
torch.testing.assert_close(atencion_einops(X), atencion_sdpa(X), rtol=1e-4, atol=1e-4)
print("\neinops + torch.einsum == scaled_dot_product_attention (en", dev + ")")
def ms(f, rep=20):
f()
if dev == "cuda": torch.cuda.synchronize()
t0 = time.perf_counter()
for _ in range(rep): f()
if dev == "cuda": torch.cuda.synchronize()
return 1e3 * (time.perf_counter() - t0) / rep
print(f"einops + einsum {ms(lambda: atencion_einops(X)):6.2f} ms")
print(f"scaled_dot_product_attention {ms(lambda: atencion_sdpa(X)):6.2f} ms")npm run lab and open the connection link.Both versions calculate the same result, and the einsum version is readable and easy to verify. scaled_dot_product_attention is faster because, depending on dtype and GPU, it dispatches to a fused kernel that does not materialize the matrix in global memory: the idea of FlashAttention, which traverses and in blocks with online softmax. No einsum achieves this: each einsum is a separate contraction, and softmax between them requires materializing the full score matrix (and prevents reordering as in linear attention). Practical lesson: write with einsum and einops to understand and verify, then replace critical pieces with specialized kernels when profiling justifies it. @ and two-operand einsums end up in the same cuBLAS calls; einops adds only views or at most a copy.
The second cell checks torch.einsum behavior with three operands. It prints whether opt_einsum is available; otherwise PyTorch contracts left to right, and in ij,jk,k->i that means forming , with multiplications, instead of two matrix-vector products.
import time, torch
dev = "cuda" if torch.cuda.is_available() else "cpu"
print("opt_einsum disponible para torch.einsum:", torch.backends.opt_einsum.is_available())
n = 4096
A, Bm = torch.randn(2, n, n, device=dev)
x = torch.randn(n, device=dev)
def ms(f, rep=10):
f()
if dev == "cuda": torch.cuda.synchronize()
t0 = time.perf_counter()
for _ in range(rep): f()
if dev == "cuda": torch.cuda.synchronize()
return 1e3 * (time.perf_counter() - t0) / rep
print(f"einsum('ij,jk,k->i') {ms(lambda: torch.einsum('ij,jk,k->i', A, Bm, x)):8.3f} ms")
print(f"(A @ B) @ x {ms(lambda: (A @ Bm) @ x):8.3f} ms")
print(f"A @ (B @ x) {ms(lambda: A @ (Bm @ x)):8.3f} ms")npm run lab and open the connection link.Without opt_einsum, einsum takes as long as , tens of times longer than . With uv add opt-einsum, PyTorch will automatically choose the right order; meanwhile, with three or more operands, specify the order yourself or check the environment.
Toward named tensors
einsum and einops name axes, but only within a string: the tensor remains an array with positional axes, and axis 1 being “time” is a private convention between writer and reader. In “Tensor Considered Harmful” (2019), Alexander Rush argued this is the root of this lesson’s errors (silent transposes, reshape mixing axes, accidental broadcasting) and proposed named tensors: each axis carries a name with the data, operations refer to axes by name, and broadcasting is by name rather than position.
The idea has successors of different scope. xarray has used named dimensions in scientific computing for years. PyTorch included named tensors as an experimental feature that did not become widespread. The JAX ecosystem has libraries built entirely on named axes, such as Haliax. einops is the pragmatic middle ground that has prevailed: it does not change tensor types, but requires naming axes in each shape operation and checks shapes at runtime. Along with shape annotations in function signatures, it covers most benefits with minimal adoption cost.
Common mistakes
Exercises
More than one answer may be correct.
td,sd,se->te (that is, without softmax) with , (letter d) and (letter e), how many times more multiplications does require than ?my_einsum materializes the product over all letters before summing. For scores bhtc,bhsc->bhts with , , and in float32, how many GB would that intermediate occupy? (1 GB bytes)einsum('bij,bjk->bik', A, B) and . What is ?np.einsum: bilineal_por_lotes(X, A, Y), which for X of shape , A of shape and Y of shape returns a vector of shape with at each position; and gram_por_lotes(X), which for X of shape returns each batch's Gram matrix of shape , with . Tests use random shapes and rectangular matrices and check that each Gram matrix is symmetric.import numpy as np
def bilineal_por_lotes(X, A, Y):
# una sola llamada a np.einsum
pass
def gram_por_lotes(X):
# una sola llamada a np.einsum
passx be an array of shape whose features are grouped by head: feature is coordinate of head . Which expressions return the correct array?More than one answer may be correct.
x be an array of shape . Which statements are correct?More than one answer may be correct.
rearrange(x, patron, **tamanos) with einops semantics for patterns without ...: each side is a list of axes, and an axis is a name or a parenthesized group of names. Use only reshape and transpose: decompose with the first reshape using given or inferred sizes (at most one unknown size per left-side group), reorder with transpose, and compose with the second reshape. Raise ValueError with a clear message if both sides lack the same names, the number of left axes does not match x.ndim, an axis is not divisible, or a group has two unknown sizes. The pattern parser is already written.import numpy as np
def _ejes(lado):
"""'b c (h p1) w' -> [['b'], ['c'], ['h', 'p1'], ['w']]"""
ejes, grupo = [], None
for tok in lado.replace("(", " ( ").replace(")", " ) ").split():
if tok == "(":
if grupo is not None:
raise ValueError("los paréntesis no se pueden anidar")
grupo = []
elif tok == ")":
if grupo is None:
raise ValueError("')' sin su '('")
ejes.append(grupo)
grupo = None
elif grupo is not None:
grupo.append(tok)
else:
ejes.append([tok])
if grupo is not None:
raise ValueError("falta cerrar un paréntesis")
return ejes
def rearrange(x, patron, **tamanos):
x = np.asarray(x)
izq, der = (_ejes(s) for s in patron.split("->"))
# 1) comprobar nombres y número de ejes
# 2) deducir el tamaño de cada nombre de la izquierda
# 3) reshape, transpose, reshape
passStep 1 of 4. How is written with indices?
Summary
- An einsum string is a program: one loop variable per letter, free letters form output in written order, the rest are summed, and a repeated letter in a term traverses a diagonal. Without an arrow, output is alphabetical.
- Every two-operand contraction is a batched matrix product after permuting and grouping axes; this is how libraries execute it. An einsum gradient with respect to an operand is another einsum, with in place of that operand and its term as output.
- With three or more operands, contraction order determines cost and intermediate memory, sometimes by orders of magnitude. NumPy does not optimize by default, its greedy method can fail, and PyTorch only optimizes if opt_einsum is installed.
- einops describes axis rearrangements with names:
rearrangeis reshape, transpose, reshape;reduceandrepeatreduce and create axes. In a group, the first name is the slow axis, and correct shape does not guarantee correct data.