Module contents
Lesson 7 of 24Advanced 75 min

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:

Sbhts=1dk∑c=1dkQbhtc Kbhsc,S_{bhts} = \frac{1}{\sqrt{d_k}} \sum_{c=1}^{d_k} Q_{bhtc}\, K_{bhsc},

where bb is the batch example, hh the head, tt the querying position, ss the responding position, and cc 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.

[ ]Three versions of the same scoresBrowser
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:

  1. Read and write einsum fluently, knowing exactly which loops it executes and which shape it returns.
  2. Estimate its cost and choose the order of contracting several operands, which can change computation time by orders of magnitude.
  3. Rearrange named axes with einops instead of reshape and transpose chains 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 yi=Aijxjy_i = A_{ij} x_j means yi=∑jAijxjy_i = \sum_j A_{ij} x_j, the product of a matrix and a vector, and Cik=AijBjkC_{ik} = A_{ij} B_{jk} 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 p−1p - 1 multiplications in each. Evaluated this way, an einsum costs

(p−1)∏ℓ ∈ letrasnℓmultiplicaciones,(p - 1) \prod_{\ell \,\in\, \text{letras}} n_\ell \quad \text{multiplicaciones},

whether or not each letter appears in the output. Here “letras” means letters and “multiplicaciones” means multiplications. Explore it.

Interactiveeinsum as nested loops
2
2
3
2
R = np.zeros((2, 2, 2))
for b in range(2):b = 0
for i in range(2):i = 0
for k in range(2):k = 0
for j in range(3):j = 0
R[b, i, k] += A[b, i, j] * B[b, j, k]
A [b, i, j] (2, 2, 3)
b=0b=1−2−1−2−2−2−2−12−2223
rows i · columns j
B [b, j, k] (2, 3, 2)
b=0b=1−11−113−1331−112
rows j · columns k
R [b, i, k] (2, 2, 2)
b=0b=12
rows i · columns k
R[0, 0, 0] += A[0, 0, 0] · B[0, 0, 0] = (−2) · (−1) = 2 → R[0, 0, 0] = 2
iteration 1 of 24
Examples
Output
Explicit stringbij,bjk->bik
Shape of R(2, 2, 2)
Free (output)b, i, k
Summedj
Iterations2·2·3·2 = 24
Multiplications24
Equivalent to producto de matrices por lotes: A @ B.
The string translates to loops: one variable per letter, free letters (blue) outside in output order, summed letters (orange) inside. Press play: at each iteration the multiplied elements light up yellow and the cell of RR accumulating the product magenta; faint yellow marks all elements contributing to that cell. Click letter j to leave it free and see how the shape of RR 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->bik it is (2,2,2)(2, 2, 2). If j is freed, output becomes bikj, shape (2,2,2,3)(2, 2, 2, 3): nothing is summed and each cell stores one product. If b is 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->ki is (AB)⊤(\mat{A}\mat{B})\T. If dimensions match, nothing warns you that you wanted the other one.
  • Trace traverses one loop. In ii-> a single variable i indexes both positions of the term, so only diagonal cells are read. ii->i leaves i free and returns the diagonal.
  • Implicit mode sorts alphabetically. ij,jk is a matrix product because i precedes k; ba is a transpose, because implicit output is ab. 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.

OperationFormulaeinsumEquivalent
Trace∑iAii\sum_i A_{ii}ii->np.trace(A)
DiagonalAiiA_{ii}ii->inp.diag(A)
TransposeAjiA_{ji}ij->jiA.T
Column sum∑iAij\sum_i A_{ij}ij->jA.sum(axis=0)
Dot product∑ixiyi\sum_i x_i y_ii,i->x @ y
Outer productxiyjx_i y_ji,j->ijnp.outer(x, y)
Matrix product∑jAijBjk\sum_j A_{ij} B_{jk}ij,jk->ikA @ B
Trace of a product∑ijAijBji\sum_{ij} A_{ij} B_{ji}ij,ji->np.trace(A @ B)
Frobenius∑ijAijBij\sum_{ij} A_{ij} B_{ij}ij,ij->(A * B).sum()
Bilinear form∑ijxiAijyj\sum_{ij} x_i A_{ij} y_ji,ij,j->x @ A @ y
Batched product∑jAbijBbjk\sum_j A_{bij} B_{bjk}bij,bjk->bikA @ B
Batched bilinear form∑ijXbiAijYbj\sum_{ij} X_{bi} A_{ij} Y_{bj}bi,ij,bj->b((X @ A) * Y).sum(1)
Row Gram matrix∑iXbiXci\sum_i X_{bi} X_{ci}bi,ci->bcX @ X.T
Double contraction∑jkTijkUjkl\sum_{jk} T_{ijk} U_{jkl}ijk,jkl->ilnp.tensordot(T, U, axes=2)

Three rows deserve comment. The trace of a product, ij,ji->, never forms AB\mat{A}\mat{B}: it sums n2n^2 products instead of doing n3n^3 multiplications and keeping the diagonal. The outer product, i,j->ij, is the rank-one matrix xy⊤\vb{x}\vb{y}\T, 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.

[ ]The catalog, checkedBrowser
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, R[β,α,γ]=∑κA[β,α,κ] B[β,κ,γ]R[\beta, \alpha, \gamma] = \sum_{\kappa} A[\beta, \alpha, \kappa]\, B[\beta, \kappa, \gamma], 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 tAt_A and outside oo would be summed within A before multiplication. Grouping in row-major order a list of indices (i1,…,ir)(i_1, \dots, i_r) of sizes (n1,…,nr)(n_1, \dots, n_r) into index ∑mim∏m′>mnm′\sum_m i_m \prod_{m' > m} n_{m'} is a bijection between tuples and {0,…,∏nm−1}\{0, \dots, \prod n_m - 1\}. Replacing each group by its grouped index transforms the multiple sum over κ\kappa into a single sum over kk 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.

[ ]An arbitrary contraction converted to one matmulBrowser
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

R[o]R[o] is a sum of products in which A(q)A^{(q)} appears exactly once as a factor, so it is linear in A(q)A^{(q)} and ∂R[o]/∂A(q)[tq]\partial R[o] / \partial A^{(q)}[t_q] is the product of the other factors, summed over letters in neither oo nor tqt_q (if tqt_q fixes those letters, the rest remain free). By the chain rule, ∂L/∂A(q)[tq]=∑oG[o] ∂R[o]/∂A(q)[tq]\partial L / \partial A^{(q)}[t_q] = \sum_{o} G[o]\, \partial R[o] / \partial A^{(q)}[t_q], that is, the sum over all letters not in tqt_q of G[o]∏r≠qA(r)[tr]G[o] \prod_{r \ne q} A^{(r)}[t_r]. This is literally the stated einsum. The hypothesis on tqt_q‘s letters guarantees all have known sizes in the new operands; if a letter appeared only in tqt_q, the derivative would be constant along that axis and need broadcasting, and if tqt_q 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, GB⊤\mat{G}\mat{B}\T, and ik,ij->jk with respect to B, A⊤G\mat{A}\T\mat{G}: linear-layer backpropagation formulas appear without drawing any matrices. This calculates a vector-Jacobian product as implemented inside autograd.

[ ]The gradient rule versus finite differencesBrowser
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.

[ ]my_einsum: parse, align, multiply, and sumBrowser
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 (2,1)(2, 1) and (5,)(5,), 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 n×nn \times n matrix product, an array of n3n^3 elements. The next cell measures it.

[ ]The cost of materializing the index spaceBrowser
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 B=8B = 8, H=12H = 12, T=1024T = 1024, and dk=64d_k = 64 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: A∈R2×10\mat{A} \in \R^{2 \times 10}, B∈R10×100\mat{B} \in \R^{10 \times 100}, C∈R100×1000\mat{C} \in \R^{100 \times 1000}, D∈R1000×1000\mat{D} \in \R^{1000 \times 1000}, and we want ij,jk,kl,lm->im. Left to right, ((AB)C)D((\mat{A}\mat{B})\mat{C})\mat{D} costs

2⋅10⋅100+2⋅100⋅1000+2⋅1000⋅1000=2 202 0002 \cdot 10 \cdot 100 + 2 \cdot 100 \cdot 1000 + 2 \cdot 1000 \cdot 1000 = 2\,202\,000

multiplications, and never forms anything larger than 2×10002 \times 1000. Right to left, A(B(CD))\mat{A}(\mat{B}(\mat{C}\mat{D})) begins by multiplying the two large matrices: 100⋅1000⋅1000=108100 \cdot 1000 \cdot 1000 = 10^8 multiplications in the first step alone, 45 times more than the entire previous order. The single loop performs 2⋅10⋅100⋅1000⋅1000=2⋅1092 \cdot 10 \cdot 100 \cdot 1000 \cdot 1000 = 2 \cdot 10^9 iterations with three products each.

Proof

Parenthesizations: the final multiplication splits the chain into a prefix of kk matrices and a suffix of p−kp - k, each parenthesized independently, so N(p)=∑k=1p−1N(k) N(p−k)N(p) = \sum_{k=1}^{p-1} N(k)\,N(p - k) with N(1)=1N(1) = 1, the Catalan recurrence with N(p)=Cp−1N(p) = C_{p-1}. Trees: each tree with p+1p + 1 leaves comes from exactly one with pp leaves by inserting the new leaf on one of its 2p−22p - 2 edges or above the root, 2p−12p - 1 possibilities; with N(2)=1N(2) = 1 this gives N(p)=(2p−3)!!N(p) = (2p - 3)!!.

∎

For a chain, the optimal order is found in O(p3)\bigO(p^3) 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:

  1. Consider operand pairs sharing a letter (outer products only if nothing else remains).
  2. Discard those creating an intermediate larger than the memory limit, by default the size of the largest operand or output.
  3. Among the rest, contract the pair that eliminates most elements, the size of the two operands minus result size, breaking ties by cost.
  4. Repeat with the new tensor.

This is reasonable and fast, but does not look ahead. In the chain above, contracting CD\mat{C}\mat{D} eliminates 105+106−105=10610^5 + 10^6 - 10^5 = 10^6 elements, far more than any other pair, so greedy starts with the most expensive contraction.

InteractiveOrder matters
np.einsum('ij,jk,kl,lm->im', A, B, C, D)
A: 2×10 · B: 10×100 · C: 100×1000 · D: 1000×1000
Tree of A(B(CD))
A 2×10B 10×100C 100×1000D 1000×1000100×10001·10⁸ mult. Σl10×10001·10⁶ mult. ΣkR 2×100020 000 mult. Σj
Multiplications per order (log scale)
((AB)C)D2.2·10⁶optimal(A(BC))D3.02·10⁶A((BC)D)1.1·10⁷(AB)(CD)1·10⁸A(B(CD))1.01·10⁸greedysingle loop6·10⁹
The other 10 of 15 possible orders are not shown: all include an outer product, such as contracting A with C.
Tensor network
Dimensions
2
10
100
1000
1000
Order A(B(CD))1.01·10⁸ mult.
Versus optimum46×
Largest intermediate1·10⁵ elem.
einsum_path limit1·10⁶ elem.
einsum_path greedyA(B(CD)), 46×
einsum_path optimal((AB)C)D, 1×
Greedy (used by optimize=True) chooses A(B(CD)): 46× more costly than ((AB)C)D. At each step it chooses the pair that removes the most elements, without looking ahead.
Each bar is a contraction order with multiplications on a logarithmic scale; click one to see its tree, with each node's shape, cost, and summed index (red marks intermediates exceeding the einsum_path memory limit). The initial state is the text's chain: greedy chooses A(B(CD))A(B(CD)), 46 times more expensive than optimal. Move d0d_0 to 1000 and see the winner change. Then switch to QKTVQK^{\mathsf T}V, the core of linear attention (without softmax), and increase length TT: one order grows as T2T^2 and the other as TT.

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 2×10002 \times 1000.
  • 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), even optimal cannot find it: raise the limit with optimize=("optimal", limite).
  • In QK⊤V\mat{Q}\mat{K}\T\mat{V}, order is the difference between a quadratic and linear model. (QK⊤)V(\mat{Q}\mat{K}\T)\mat{V} forms the T×ST \times S score matrix, at cost TS(dk+dv)T S (d_k + d_v); Q(K⊤V)\mat{Q}(\mat{K}\T\mat{V}) forms a dk×dvd_k \times d_v matrix, at cost (T+S) dkdv(T + S)\,d_k d_v. 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.einsum has optimize=False: with three or more operands it runs the single loop. optimize=True equals "greedy"; it also accepts "optimal" and a precalculated path, which np.einsum_path returns 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.contract with strategies "auto", "greedy", "dp", "branch-2", or "optimal", explicit memory limits, and oe.contract_expression to 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 and jnp.einsum optimizes order by default.
[ ]einsum_path on the interactive chainBrowser
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, CD\mat{C}\mat{D}), then with B\mat{B} and finally with A\mat{A}. Paths are pairs of positions in the remaining operand list at each step, with the result appended: (0, 1), (0, 2), (0, 1) means AB\mat{A}\mat{B}, then with C\mat{C} and then D\mat{D}. Measurement confirms the theory: greedy is tens of times slower. The naive case remains, which with these shapes would not finish in time:

[ ]optimize=False: the single loopBrowser
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 mm of an axis of length nanbn_a n_b moves to position (a,b)(a, b) with m=a nb+bm = a\,n_b + b and 0≤b<nb0 \le b < n_b. Euclidean division of mm by nbn_b uniquely gives aa and bb. With (h p), the npn_p elements sharing value hh are h np,h np+1,…,h np+np−1h\,n_p, h\,n_p + 1, \dots, h\,n_p + n_p - 1, consecutive; with (p h) they are p nh+hp\,n_h + h for p=0,…,np−1p = 0, \dots, n_p - 1, separated by nhn_h.

∎

The proposition is key to tokenizing a Vision Transformer. A C×H×WC \times H \times W image is cut into p×pp \times p patches and each flattened into a token of p2Cp^2 C 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.

Interactiverearrange with pictures
y = rearrange(x, 'b c (h p1) (w p2) -> b (h w) (p1 p2 c)', p1=2, p2=2)
1 · reshape (2, 3, 2, 2, 2, 2)axes b c h p1 w p2
2 · transpose (0, 2, 4, 3, 5, 1)axes b h w p1 p2 c
3 · reshape (2, 4, 12)axes b (h w) (p1 p2 c)
y = x.reshape(2, 3, 2, 2, 2, 2).transpose(0, 2, 4, 3, 5, 1).reshape(2, 4, 12)
x[0, 0] Rx[0, 1] Gx[0, 2] Bx[1, 0] Rx[1, 1] Gx[1, 2] BRRRRRRRRRRRRRRRRGGGGGGGGGGGGGGGGBBBBBBBBBBBBBBBBRRRRRRRRRRRRRRRRGGGGGGGGGGGGGGGGBBBBBBBBBBBBBBBBy (2, 4, 12)rows (h w) · columns (p1 p2 c)y[0]y[1]RGBRGBRGBRGBRGBRGBRGBRGBRGBRGBRGBRGBRGBRGBRGBRGBRGBRGBRGBRGBRGBRGBRGBRGBRGBRGBRGBRGBRGBRGBRGBRGB
Hover over (or tap) an input or output element.
Examples
Animation
Input shape(2, 3, 4, 4) = b c h w
Output shape(2, 4, 12)
Inferred sizesb=2, c=3, h=2, p1=2, w=2, p2=2
The input is two 4×44 \times 4 RGB images, shape (b,c,h,w)=(2,3,4,4)(b, c, h, w) = (2, 3, 4, 4). Each element's hue identifies its image and 2×22 \times 2 quadrant, intensity its position within the quadrant, and letter its channel. Press ‘See movement’: each element travels to its output position. With ViT patches, each output row is a token with one hue. Try ‘Incorrectly split patches’, changing only (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 (2,4,12)(2, 4, 12); only the data reveal the error. This is the same trap as reshape without transpose at 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 with transpose, compose with reshape. 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 W∈Rp2C×d\mat{W} \in \R^{p^2 C \times d}, is exactly convolution with a p×pp \times p kernel and stride pp, provided weights are reordered to (d, c, p1, p2) as used by a convolutional layer.

[ ]ViT tokenization with reshape and transposeBrowser
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 dk\sqrt{d_k}, what the causal mask does, why multiple heads) are studied in multi-head attention; here we focus only on its index algebra.

[ ]Attention: loops, einsum, and einsum without reshapeBrowser
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 WQ∈Rd×d\mat{W}^Q \in \R^{d \times d} as a d×H×dkd \times H \times d_k 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 (B,H,T,dk)(B, H, T, d_k). 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 X\mat{X} in a single four-operand string. Without optimization, NumPy traverses all seven letters at once.

[ ]Four operands: the effect of optimizeBrowser
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 B T d H dk S d=2⋅16⋅32⋅4⋅8⋅16⋅32≈1.7⋅107B\,T\,d\,H\,d_k\,S\,d = 2 \cdot 16 \cdot 32 \cdot 4 \cdot 8 \cdot 16 \cdot 32 \approx 1.7 \cdot 10^7 combinations, while the optimized path calculates Q\mat{Q} and K\mat{K} 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.

[ ]einops and torch.einsum on GPULocal GPU
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")
This cell needs the local lab (PyTorch with your GPU). Start it with 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 T×TT \times T matrix in global memory: the idea of FlashAttention, which traverses K\mat{K} and V\mat{V} 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 AB\mat{A}\mat{B}, with n3n^3 multiplications, instead of two matrix-vector products.

[ ]torch.einsum with three operandsLocal GPU
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")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Without opt_einsum, einsum takes as long as (AB)x(\mat{A}\mat{B})\vb{x}, tens of times longer than A(Bx)\mat{A}(\mat{B}\vb{x}). 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

QuizSix strings
Which statements are correct?

More than one answer may be correct.

NumericOrder of a chain of three
Let A∈R10×1000\mat{A} \in \R^{10 \times 1000}, B∈R1000×10\mat{B} \in \R^{1000 \times 10} and C∈R10×1000\mat{C} \in \R^{10 \times 1000}. How many times more scalar multiplications does A(BC)\mat{A}(\mat{B}\mat{C}) require than (AB)C(\mat{A}\mat{B})\mat{C}?
NumericAttention with and without the score matrix
In contraction td,sd,se->te (that is, QK⊤V\mat{Q}\mat{K}\T\mat{V} without softmax) with T=S=1000T = S = 1000, dk=128d_k = 128 (letter d) and dv=64d_v = 64 (letter e), how many times more multiplications does (QK⊤)V(\mat{Q}\mat{K}\T)\mat{V} require than Q(K⊤V)\mat{Q}(\mat{K}\T\mat{V})?
NumericThe cost of materializing
my_einsum materializes the product over all letters before summing. For scores bhtc,bhsc->bhts with B=8B = 8, H=12H = 12, T=S=1024T = S = 1024 and dk=64d_k = 64 in float32, how many GB would that intermediate occupy? (1 GB =109= 10^9 bytes)
QuizGradient of a batched product
Let R=R = einsum('bij,bjk->bik', A, B) and G=∂L/∂RG = \partial L/\partial R. What is ∂L/∂B\partial L / \partial B?
CodeBatched bilinear form and Gram matrix
Implement each with a single call to np.einsum: bilineal_por_lotes(X, A, Y), which for X of shape (B,m)(B, m), A of shape (m,n)(m, n) and Y of shape (B,n)(B, n) returns a vector of shape (B,)(B,) with xb⊤Ayb\vb{x}_b\T \mat{A} \vb{y}_b at each position; and gram_por_lotes(X), which for X of shape (B,n,d)(B, n, d) returns each batch's Gram matrix of shape (B,n,n)(B, n, n), with Gb=XbXb⊤G_b = \mat{X}_b \mat{X}_b\T. 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
  pass
Shift+Enter to run
QuizSplitting heads
Let x be an array of shape (B,T,H⋅dk)(B, T, H \cdot d_k) whose features are grouped by head: feature h dk+ch\,d_k + c is coordinate cc of head hh. Which expressions return the correct (B,H,T,dk)(B, H, T, d_k) array?

More than one answer may be correct.

Quizeinops patterns
Let x be an array of shape (8,3,32,32)(8, 3, 32, 32). Which statements are correct?

More than one answer may be correct.

CodeA minimal rearrange
Implement 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
  pass
Shift+Enter to run
ProofTrace is cyclic, using indices
Prove: Let A∈Rm×n\mat{A} \in \R^{m \times n}, B∈Rn×p\mat{B} \in \R^{n \times p} and C∈Rp×m\mat{C} \in \R^{p \times m}. Then tr⁡(ABC)=tr⁡(CAB)\tr(\mat{A}\mat{B}\mat{C}) = \tr(\mat{C}\mat{A}\mat{B}).
0
Use the definition of trace, tr⁡(M)=∑iMii\tr(\mat{M}) = \sum_i M_{ii}, and matrix multiplication.

Step 1 of 4. How is tr⁡(ABC)\tr(\mat{A}\mat{B}\mat{C}) 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 GG 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: rearrange is reshape, transpose, reshape; reduce and repeat reduce and create axes. In a group, the first name is the slow axis, and correct shape does not guarantee correct data.
Key idea
Write tensors as in the paper: with indices. An einsum string says which axes survive, which are summed, and which share a diagonal; an einops pattern says how they are grouped and ordered. Both can be read, verified, and differentiated, unlike a chain of reshape and transpose. With three or more operands, the result does not depend on contraction order, but cost does, by orders of magnitude.