Search

Search papers and lessons

Tensor Contraction

Level 2 · 12 min read

Tensor contraction sums a tensor over a pair of matching indices, which removes those two indices; it is how matrix products, dot products and traces are all written as one operation.

On this page

  • Colour = topic mix
  • Linear algebra
  • Discrete math
  • ReadReady to readNot yet

TL;DR

A tensor is a grid of numbers with one or more index slots: a vector has one slot, a matrix has two. Tensor contraction takes two slots of the same size, sets their indices equal, and adds up the results over all their values. The number of indices drops by two. This single rule covers matrix products, dot products and traces.

Builds on: Tensor Product, Matrix Multiplication · Leads to: Tensor Network

Where it's used

  • Quantum computing. A gate acting on one Qubit of a joint state is a contraction over the qubit's index. Tensor-network simulators store a large quantum state as a chain of small arrays and answer questions by contracting them, and the cost of each contraction decides which circuits can be simulated.
  • Deep learning. The score that a Transformer attention layer assigns to a pair of tokens is a sum of products of their query and key vectors over the feature index. Computing those scores for every pair of tokens and every attention head is the same kind of contraction, written once for a whole batch.
  • Physics papers. General relativity and continuum mechanics write their laws with tensors. A common check is that every term in an equation has the same free indices, which is a contraction bookkeeping rule applied to the whole equation.

How it works

Take two matrices, each with two index slots. Matrix A has rows (1, 2) and (3, 4). Matrix B has rows (5, 6) and (7, 8).

  1. Name the indices. Write each entry with its position: A has entries AijA_{ij}, where i is the row and j is the column. B has entries BjkB_{jk}. The letter j appears in both, so it is the shared index. Check: A and B each have two slots.
  2. Sum over the shared index. Set the shared j equal on both sides and add over its values j = 1 and j = 2: Cik=Ai1B1k+Ai2B2kC_{ik} = A_{i1}B_{1k} + A_{i2}B_{2k}. The indices i and k appear once, so they stay free and label the result. Check: two free indices means the result is a matrix.
  3. Compute the entry C11C_{11}. Row 1 of A is (1, 2) and column 1 of B is (5, 7). So C11=1⋅5+2⋅7=5+14=19C_{11} = 1 \cdot 5 + 2 \cdot 7 = 5 + 14 = 19. Check: this is the dot product of row 1 with column 1.
  4. Compute the other three entries. C12=1⋅6+2⋅8=22C_{12} = 1 \cdot 6 + 2 \cdot 8 = 22, C21=3⋅5+4⋅7=43C_{21} = 3 \cdot 5 + 4 \cdot 7 = 43, and C22=3⋅6+4⋅8=50C_{22} = 3 \cdot 6 + 4 \cdot 8 = 50. Check: each entry uses one row of A and one column of B.
  5. Read the result. C has rows (19, 22) and (43, 50). This is exactly the usual matrix product, so contracting over the shared index is matrix multiplication. Check: the entries are the dot products of rows of A with columns of B.
  6. Contract a matrix with itself. Set both slots of A equal and sum: A11+A22=1+4=5A_{11} + A_{22} = 1 + 4 = 5. This is the trace. Both indices were removed and nothing is left, so the result is one number. Check: the number of indices went from 2 to 0.
  7. Contract two vectors. For u = (1, 2) and v = (3, 4), set the single index equal on both and sum: u1v1+u2v2=3+8=11u_1 v_1 + u_2 v_2 = 3 + 8 = 11. This is the dot product of two vectors. Check: each vector had one index, and both were removed.
flowchart LR
  T[Tensor with index slots] --> P[Pick two slots of equal size]
  P --> S[Set their indices equal and sum over all values]
  S --> R[Result has two fewer indices]

The math

Definition: Tensor contraction

Let TT be an array with index slots of sizes n1,…,nrn_1, \dots, n_r, and let slots pp and qq have the same size nn. The contraction of TT over slots pp and qq is the array whose entries are

∑k=1nTi1…ip−1 k ip+1…iq−1 k iq+1…ir,\sum_{k=1}^{n} T_{i_1 \dots i_{p-1}\, k\, i_{p+1} \dots i_{q-1}\, k\, i_{q+1} \dots i_r},

with the index kk appearing in both slots and summed, and every other index left free. The result has r−2r - 2 indices.

A contraction is linear in the tensor: contracting a sum of tensors gives the sum of their contractions, and contracting a scaled tensor scales the result. Each index is named by a letter, and a letter that appears in exactly two slots of a term is summed. This convention is the Einstein notation described in the History section.

Steps 1 and 2 in symbols: the matrix product

In Cik=∑jAijBjkC_{ik} = \sum_{j} A_{ij} B_{jk} the index j is summed (the summation notation at work), and i and k are free. Written out for two-by-two matrices, Cik=Ai1B1k+Ai2B2kC_{ik} = A_{i1} B_{1k} + A_{i2} B_{2k}. This is the matrix product, so matrix multiplication is one example of contraction.

Steps 3 and 4 in symbols: the numbers

C11=A11B11+A12B21=1⋅5+2⋅7=19.C_{11} = A_{11} B_{11} + A_{12} B_{21} = 1 \cdot 5 + 2 \cdot 7 = 19.

The other entries follow the same pattern with the index pair changed: C12=22C_{12} = 22, C21=43C_{21} = 43, C22=50C_{22} = 50.

Step 6 in symbols: the trace

tr⁡(A)=∑iAii=A11+A22=5.\operatorname{tr}(A) = \sum_{i} A_{ii} = A_{11} + A_{22} = 5.

Here the same letter i fills both slots of one matrix, so the contraction is over that matrix's own two slots.

Step 7 in symbols: the dot product and the tensor product

The dot product of two vectors is u⋅v=∑iuiviu \cdot v = \sum_i u_i v_i. The tensor product Mij=uivjM_{ij} = u_i v_j from Tensor Product has two slots. Contracting those slots gives ∑iuivi\sum_i u_i v_i, which is the trace of M. For u = (1, 2) and v = (3, 4), the entries of M are M11=3M_{11} = 3, M12=4M_{12} = 4, M21=6M_{21} = 6 and M22=8M_{22} = 8. Its trace is 3+8=113 + 8 = 11, the same as the dot product.

Worked examples

Example
1. A dot product as a contraction

Let u = (1, 2) and v = (3, 4), two vectors. Find ∑iuivi\sum_i u_i v_i, then check the answer with the tensor product.

  1. Write the sum with the index i in both slots: u1v1+u2v2u_1 v_1 + u_2 v_2. Since i is in both, it is summed.
  2. Put in the numbers: 1⋅3+2⋅41 \cdot 3 + 2 \cdot 4.
  3. Multiply each pair: 3+83 + 8.
  4. Add: the answer is 11. It is a single number, because both indices were removed.
  5. Check with the tensor product. Form Mij=uivjM_{ij} = u_i v_j, which gives M11=3M_{11} = 3, M12=4M_{12} = 4, M21=6M_{21} = 6, M22=8M_{22} = 8. Its trace M11+M22=3+8=11M_{11} + M_{22} = 3 + 8 = 11 matches. The dot product of two vectors is the trace of their tensor product.
Example
2. A matrix product as one contraction

A has rows (1, 2) and (3, 4). B has rows (5, 6) and (7, 8). Compute Cik=∑jAijBjkC_{ik} = \sum_j A_{ij} B_{jk}, then compute BABA to see whether the order matters.

  1. Entry C11C_{11}: sum over j of A1jBj1A_{1j} B_{j1}, which is 1⋅5+2⋅7=191 \cdot 5 + 2 \cdot 7 = 19.
  2. Entry C12C_{12}: 1⋅6+2⋅8=221 \cdot 6 + 2 \cdot 8 = 22.
  3. Entry C21C_{21}: 3⋅5+4⋅7=433 \cdot 5 + 4 \cdot 7 = 43.
  4. Entry C22C_{22}: 3⋅6+4⋅8=503 \cdot 6 + 4 \cdot 8 = 50. So C has rows (19, 22) and (43, 50).
  5. Swap the roles: (BA)ik=∑jBijAjk(BA)_{ik} = \sum_j B_{ij} A_{jk}. Entry (BA)11(BA)_{11} is 5⋅1+6⋅3=235 \cdot 1 + 6 \cdot 3 = 23.
  6. Entry (BA)12(BA)_{12} is 5⋅2+6⋅4=345 \cdot 2 + 6 \cdot 4 = 34. Entry (BA)21(BA)_{21} is 7⋅1+8⋅3=317 \cdot 1 + 8 \cdot 3 = 31. Entry (BA)22(BA)_{22} is 7⋅2+8⋅4=467 \cdot 2 + 8 \cdot 4 = 46.
  7. Compare the two results. BA has rows (23, 34) and (31, 46), which is not C. The summed index is the same kind in both products, but the free indices sit in different slots, so the answer changes.
Example
3. Applying a gate to one qubit

A two-qubit state is ψ=12(∣00⟩+∣11⟩)\psi = \frac{1}{\sqrt{2}}(|00\rangle + |11\rangle). Store its amplitudes as a two-by-two array ψab\psi_{ab}, where a is the first qubit and b is the second. The bit-flip gate X on the first qubit is the array XacX_{ac} with X00=0X_{00} = 0, X01=1X_{01} = 1, X10=1X_{10} = 1 and X11=0X_{11} = 0. Write s=1/2s = 1/\sqrt{2}, about 0.707.

  1. Store the state: ψ00=s\psi_{00} = s, ψ01=0\psi_{01} = 0, ψ10=0\psi_{10} = 0, ψ11=s\psi_{11} = s.
  2. Write the gate as a contraction: ψab′=∑cXacψcb\psi'_{ab} = \sum_c X_{ac} \psi_{cb}. The index c is the second slot of X and the first slot of ψ\psi, so it is summed. The indices a and b stay free. Check: the result has the same two free indices as ψ\psi.
  3. Compute ψ00′=X00ψ00+X01ψ10=0⋅s+1⋅0=0\psi'_{00} = X_{00} \psi_{00} + X_{01} \psi_{10} = 0 \cdot s + 1 \cdot 0 = 0.
  4. Compute ψ01′=X00ψ01+X01ψ11=0⋅0+1⋅s=s\psi'_{01} = X_{00} \psi_{01} + X_{01} \psi_{11} = 0 \cdot 0 + 1 \cdot s = s.
  5. Compute ψ10′=X10ψ00+X11ψ10=1⋅s+0⋅0=s\psi'_{10} = X_{10} \psi_{00} + X_{11} \psi_{10} = 1 \cdot s + 0 \cdot 0 = s.
  6. Compute ψ11′=X10ψ01+X11ψ11=1⋅0+0⋅s=0\psi'_{11} = X_{10} \psi_{01} + X_{11} \psi_{11} = 1 \cdot 0 + 0 \cdot s = 0.
  7. Read the new state: ψ′=s(∣01⟩+∣10⟩)\psi' = s(|01\rangle + |10\rangle). Check: the squared amplitudes add to s2+s2=1s^2 + s^2 = 1, so it is still a valid state.

Try it: apply X to the second qubit instead, so ψab′′=∑cψacXcb\psi''_{ab} = \sum_c \psi_{ac} X_{cb}. Find ψ01′′\psi''_{01}.

Answer: ψ01′′=ψ00X01+ψ01X11=s⋅1+0⋅0=s\psi''_{01} = \psi_{00} X_{01} + \psi_{01} X_{11} = s \cdot 1 + 0 \cdot 0 = s, which is 1/21/\sqrt{2}, about 0.707.

Common mistakes and tradeoffs

  • It is tempting to think a tensor product and a contraction are opposite kinds of "combining". In fact a tensor product keeps every index and adds the counts (two vectors with one index each give a tensor with two), while a contraction removes two indices (a matrix becomes a single number). Because the index count changes in opposite directions, check it at every step.
  • It is tempting to think you can sum over an index that appears only once. In fact a summed index must appear in exactly two slots. An index that appears once is free and stays in the answer. An index that appears three times has no clear meaning without an extra rule, so avoid it.
  • It is tempting to think the order of matrices in a contraction does not matter. In fact matrix products are not commutative, as Example 2 shows, because the free indices land in different slots. Keep track of which matrix carries i and which carries k.
  • The contracted slots must have the same length. Contracting the column slot of a 2 by 3 matrix (length 3) with a slot of a 2 by 2 matrix (length 2) is undefined, because the two lengths differ.

When to use it: when several arrays share indices and you want the index pattern to say what is being computed, such as batched products, attention scores, and multi-index physics formulas. Many numerical libraries accept the pattern as text, which is convenient for these cases.

When not to use it: for a single matrix product or dot product, ordinary matrix notation is clearer. For long formulas, the index bookkeeping invites mistakes.

Cost: contracting many large arrays in a poor order can take far more work than the answer needs. Tensor-network methods spend effort choosing a cheap order. Alternatives are plain matrix notation, explicit loops (slow but easy to read), and an einsum-style function that can search for a cheaper order.

History

The tensor calculus that gave this operation its notation was built to describe curved spaces. Gregorio Ricci-Curbastro and Tullio Levi-Civita published their account of the absolute differential calculus around 1900, where manipulating indices was already the core technique. In 1916 Albert Einstein used a summation convention in his paper on general relativity: a letter repeated in a term means a sum over it. This is why the convention is called Einstein notation, and why many physics papers write equations without the summation signs. Later, numerical computing turned the same index patterns into function calls, which is how most programmers now meet contraction.

Recap

  • A tensor has index slots: a vector has one, a matrix has two.
  • A contraction picks two slots of equal size, sets their indices equal, and sums over all their values.
  • The result has two fewer indices. Matrix products, traces and dot products are all contractions.
  • Contracting the tensor product of two vectors gives their dot product, which ties contraction back to Tensor Product.
  • Read next: Tensor Network, which stores quantum states as networks of small arrays and contracts them, and Trace of a Matrix for the trace in more depth.

Check yourself

QuestionWhen you contract a tensor over two slots, how does its number of indices change? And how does the tensor product change it?Show answer
Contraction removes two indices, so the number of indices drops by two. The tensor product of two tensors keeps every index, so the counts add.
QuestionLet A have rows (2, 0) and (1, 3), and let B have rows (1, 4) and (2, 1). Compute the trace of the matrix product AB.Show answer
The diagonal entries of AB are (AB)11=2⋅1+0⋅2=2(AB)_{11} = 2 \cdot 1 + 0 \cdot 2 = 2 and (AB)22=1⋅4+3⋅1=7(AB)_{22} = 1 \cdot 4 + 3 \cdot 1 = 7. The trace is 2+7=92 + 7 = 9. The off-diagonal entries are not needed for the trace.
QuestionUsing the same matrices, BA has (BA)11=1⋅2+4⋅1=6(BA)_{11} = 1 \cdot 2 + 4 \cdot 1 = 6. Why does this show that the order of a contraction matters?Show answer
The product AB has (AB)11=2(AB)_{11} = 2, not 6. The summed index is the same in both, but the free indices sit in different slots, so the two contractions give different results.
QuestionA library call computes einsum with the pattern 'ii' on a 3 by 3 matrix M. What does it return, and why?Show answer
It returns the trace M11+M22+M33M_{11} + M_{22} + M_{33}. The letter i fills both slots of M, so both slots are contracted and the result is a single number.
QuestionAn attention score between two tokens is the sum of products of their query and key vectors over the feature index. Which operation is this, and what does it become when computed for a whole batch?Show answer
It is a dot product, which is the contraction of two vectors over their shared feature index. For a whole batch, the same index pattern becomes one larger contraction over all token pairs.

Sources