Lesson 4 of 5 · Tensor Calculus

Tensor contraction and Einstein notation

Contraction sums over an axis shared by two tensors, or within one tensor, and removes it; it is the generalization that covers the dot product, matrix multiplication and the trace, and it is written concisely in einsum notation.

Mathematics for deep learning Difficulty: Advanced Study time: 40 min
Lesson contents
  1. Introduction
  2. Why study this topic?
  3. Theoretical explanation
  4. Mathematical definitions
  5. The equations
  6. Worked example
  7. Application in AI
  8. Interactive lab
  9. Practice exercises
  10. Summary
  11. Short quiz
  12. Related lessons

1 Introduction

Contraction is an operation that sums products over a shared index, so that index disappears from the result. The dot product is a contraction of two vectors, matrix multiplication is a contraction over the inner dimension, and the trace is a contraction of the two axes of a single matrix.

Learning objectives

  • Define contraction over a shared axis
  • Write the dot product, matrix multiplication and trace in Einstein notation
  • Predict the shape of an einsum result
  • Compute the cost of a contraction

2 Why study this topic?

The einsum function in NumPy, PyTorch and JAX writes any contraction in one clear line, and it is widely used to write attention layers, bilinear layers and tensor network models. Understanding contraction helps you read research papers that write computations with indices.

3 Theoretical explanation

Einstein notation

An index repeated in two terms implies summation over it. Matrix multiplication is written:

\[C_{ik} = A_{ij}B_{jk}\quad(\text{i.e.}\; \textstyle\sum_j A_{ij}B_{jk})\]

Examples in einsum form

OperationIndiceseinsum string
Dot product\(a_i b_i\)i,i->
Multiplying a matrix by a vector\(A_{ij}x_j\)ij,j->i
Matrix multiplication\(A_{ij}B_{jk}\)ij,jk->ik
Trace\(A_{ii}\)ii->
Outer product\(u_iv_j\)i,j->ij
Batched multiplication\(A_{bij}B_{bjk}\)bij,bjk->bik

General rule

Indices that appear in the inputs but not in the output are summed over, and indices that appear in the output are kept. The output shape consists of the lengths of the remaining indices in the written order.

Cost

The cost of a contraction is the product of the lengths of all participating indices (kept and summed). When contracting several tensors, the contraction order affects the cost greatly, just as the order of multiplying a chain of matrices does.

4 Mathematical definitions

Tensor contraction
Summing products over a shared index, which is then removed from the result.
\[C_{ik} = \sum_j A_{ij}B_{jk}\]
Einstein notation
A convention that drops the summation sign and treats a repeated index as summed over.
\[A_{ij}B_{jk} \equiv \textstyle\sum_j A_{ij}B_{jk}\]
Tensor contraction
An operation that sums products over a shared index, removing it from the result; it generalizes the dot product, matrix multiplication and the trace.
\[C_{ik}=A_{ij}B_{jk}\]
einsum notation
A text notation for writing contractions and products with indices, where indices that do not appear in the output are summed.
\[C_{ik}=A_{ij}B_{jk}\]

5 The equations

\[C_{ik} = A_{ij}B_{jk}\]
Matrix multiplication in Einstein notation
\[\operatorname{tr}A = A_{ii}\]
Trace
\[Y_{bhtd} = \sum_{s} P_{bhts}V_{bhsd}\]
Applying attention weights to the values

6 Step-by-step worked example

Shape of an einsum result

Problem: A tensor T has shape \((2, 3, 4)\) and a matrix W has shape \((4, 5)\). What is the shape of the einsum result with the string ijk,kl->ijl, and how many multiplications does it require?

  1. The index k (length 4) is shared and absent from the output, so it is summed over.
  2. The remaining indices i, j, l have lengths 2, 3, 5.
  3. The cost is \(2\cdot3\cdot4\cdot5 = 120\) multiplications.

Result: Shape \((2, 3, 5)\) and cost 120

Trace by contraction

Problem: Compute \(A_{ii}\) for the matrix \(\begin{bmatrix}1 & 2 \\ 3 & 4\end{bmatrix}\).

  1. We sum the elements whose two indices are equal: \(A_{11} + A_{22}\).

Result: \(5\)

7 Practical application in AI

  • Attention: Computing scores and outputs with strings such as bhtd,bhsd->bhts.
  • Bilinear layers: \(y_k = x_i W_{ijk} z_j\) is written as a single einsum line.
  • Tensor networks: Representing huge tensors as a chain of small contracted tensors to compress models.

8 Interactive lab linked to the lesson

A small network (two inputs, a hidden layer of two neurons, one output) computed entirely in the browser: inputs, weights and biases, the weighted sum, activation functions, the forward pass, the loss, backpropagation, gradient computation with numerical checking, and the…

Open the Neural Network Mathematics Lab

9 Practice exercises

Review questions for reflection

  • Write the einsum string to compute \(\mathbf{x}^\top A\mathbf{y}\).
  • Why does the order of multiplying three rectangular matrices matter?

Common mistakes

  • Unintentionally repeating an index in the output and in both inputs, so the summation turns into element-wise multiplication.
  • Forgetting that indices absent from the output are summed over.
  • Ignoring the contraction order in long chains.

Practice 5 questions from the question bank for this lesson

10 Lesson summary

  • Contraction sums over a shared index and removes it.
  • The dot product, matrix multiplication and trace are special cases.
  • einsum writes any contraction concisely.

11 Short quiz

5 questions · 10 minutes · pass mark 60% — passing it completes the lesson.