Module 1: Tensors, Diagrams, Contractions and Factorizations
Goal
After this module you can read and draw tensor diagrams, contract tensors by permuting, reshaping and multiplying, count the cost of a contraction order before running it, and factorize a tensor across any cut with the SVD, QR or LQ, including truncation and gauge changes.
In Module 0 we reshaped a quantum state into a matrix, took one SVD, and found that ground states have few important Schmidt values. To exploit this at every cut at once, we need to work with objects that have more than two indices, and we need to do so without ever writing down the full table.
This module collects the few operations that every tensor network algorithm is built from. There are only four: reshape (regroup indices), permute (reorder them), contract (sum over shared indices) and factorize (split a tensor into pieces across a cut). We introduce a diagram notation that makes long index expressions readable, learn to count what a contraction costs, and study the factorizations (SVD, QR, LQ) together with the freedom they leave, the gauge.
The notebooks implement each operation twice: once with plain arrays (so nothing is hidden) and once with a tensor library, TensorKit.jl in Julia and quimb in Python. At the end we use them to build the transverse-field Ising Hamiltonian as a dense operator, the exact reference that every later algorithm has to reproduce.
Tensors and diagrams
Definition 1.1 (Tensor).
A tensor of order is an array of complex numbers, where each index runs over . Equivalently it is an element of , or a multilinear map
Order 0 is a scalar, order 1 a vector, order 2 a matrix.
“Multilinear” means linear in each argument separately with the others held fixed. A matrix is the familiar case: it eats two vectors and returns , or, if we only feed it one vector, it returns a vector . That second reading generalizes: a tensor can be fed vectors on any subset of its legs, and what comes out is a tensor on the remaining legs. Libraries like TensorKit make this explicit by storing a tensor as a linear map from a domain (the legs we feed) to a codomain (the legs that come out), but the numbers are the same array.
Writing out indices quickly becomes unreadable. The diagram notation(1) replaces the formulas of Definition 1.1 with pictures, summarized in Figure 1.1.
A tensor is a shape; each index is a line (a leg) attached to it. The number of legs is the order.
Connecting two legs means summing over that shared index (a contraction). Connected legs must have the same dimension.
Open legs are the indices of the result. A diagram with no open legs is a number.
For quantum states we draw the ket on top and its complex conjugate (the bra) below it, so that in a norm or an overlap their physical legs meet in the middle (Figure 1.4). We draw the physical legs of a ket pointing down even when it stands alone, so that the same picture can be dropped onto a bra; only the connections carry meaning.
Figure 1.1. Diagram notation. A tensor is a shape and each of its indices is a leg; the order of the tensor is the number of legs.
Contraction, trace and outer product
All operations of linear algebra become ways of connecting legs. With an matrix and vectors:
The matrix-vector product connects one leg of to the leg of and leaves one leg open. The inner product connects the only legs and leaves a number. The trace connects two legs of the same tensor. The outer (tensor) product connects nothing: two tensors drawn side by side are multiplied entry by entry into a bigger tensor, whose order is the sum of the orders. Figure 1.2 draws all four.
Figure 1.2. The basic contractions as diagrams. Connected legs are summed; the number of open legs is the order of the result.
The diagram does not fix the order of the legs on the page, only which legs are connected. This is a real advantage: identities like become obvious, because both sides are the same ring of three tensors. It also hides a bookkeeping problem that code must solve, which is the subject of the next section.
Reshape and permute
A computer stores an array as one long list of numbers. A tensor of shape is mapped to that list by a fixed rule for the combined position. In row-major order (C, numpy) the last index runs fastest; in column-major order (Fortran, Julia) the first index does. For two indices with , ,
Two operations change how we read the list:
reshape fuses neighbouring indices into one, or splits one into several, without moving any data. It costs nothing.
permute (transpose) reorders the indices. It moves data in memory, so it costs one pass over the tensor.
Combining them gives a matricization: choose which legs go to the rows and which to the columns, permute so that the row legs come first, and reshape. We write for the matrix whose rows are labelled by and columns by . This is exactly what we did to a state in Module 0, and it is how every factorization below is applied to a tensor (Figure 1.3).
Figure 1.3. Matricization of a four-leg tensor across the cut (i j | k l). Fusing legs is a reshape; bringing the chosen legs next to each other first is a permute.
A contraction of two tensors is now a matrix product in disguise. To compute , matricize as , permute to and matricize it as , then multiply. Libraries do exactly this, because matrix multiplication is the most optimized routine in numerical computing. The only trap is that the fused index must be built in the same order on both sides. Notebook Hands-on 1.2 makes you do this by hand; on its deterministic test data both tracks print (they differ only in the last printed digit).
Remark 1.1 (Spaces and duals in TensorKit).
TensorKit attaches a vector space to every leg and distinguishes a space from its dual . A contraction must pair a leg with space against one with ; pairing two copies of raises a SpaceMismatch. Moving a leg from the domain to the codomain (permute, repartition) turns it into its dual. For plain complex spaces this is pure bookkeeping, but it catches many index errors, and with symmetries (Module 5) it becomes essential.
Contraction cost and why order matters
A network of many tensors is evaluated by contracting two tensors at a time. Because sums commute, the final result does not depend on the order of the pairwise steps. The cost does, often enormously.
Proposition 1.1 (Cost of a pairwise contraction).
Contracting a tensor with index set against a tensor with index set over their shared indices by direct summation takes
multiply-adds, and the result has entries (the open indices).
Proof
Each entry of the result is labelled by one value of every open index, and it is a sum with one term for every value of the shared indices. Each term is one product added to a running sum. The number of multiply-adds is (number of entries) (terms per entry), which is the product of the dimensions of the open and the shared indices, that is of all indices in . As a check, an times matrix product costs .
The simplest example is for an matrix . Computing costs ; computing costs , so at the counted ratio is about 500. The notebooks measure the second order to be tens of times faster (between about 30 and 100 in our runs), depending on the machine, the language and the run. The measured ratio is smaller than the counted one because a matrix-matrix product runs at a much higher rate of operations per second than a matrix-vector product, which is limited by reading from memory. Counting tells us which order wins; the exact factor depends on the hardware.
Worked example: one step of an MPS norm
The contraction that we will perform millions of times in later modules is one step of computing the norm of a matrix product state. An environment (a matrix) is absorbed into a site tensor (dimensions , ket on top) and its conjugate (bra at the bottom):
LAAbaraa'sbb'order 1: (L A) first, 2 d D3LAAbaraa'sbb'order 2: (A Abar) first, (d+1) D4Figure 1.4. The norm step of an MPS, with the ket tensor A on top and its conjugate below. The boxed region marks which pair is contracted first. Grouping L with A (left) keeps every intermediate at three legs; grouping A with its conjugate (right) creates a four-leg intermediate of size D⁴.
Order 1, . First involves : operations. Then involves : another . In total , and the largest intermediate has entries.
Order 2, . First involves : operations, and has entries. Then involves : . In total .
The ratio is
so the bad order is times slower at , times at and times at , the numbers Hands-on 1.3 prints. Worse, it needs memory: at the intermediate alone would take 1 TiB in double-precision complex numbers, while order 1 never needs more than MiB. quimb’s automatic order search finds order 1 and reports exactly operations at .
Figure 1.5. Left: number of multiply-adds for the two orders of the norm step, counted with the rule of the cost proposition, for D from 2 to 512 (log scales). The slopes are 3 and 4. Right: measured wall time with numpy tensordot; order 2 was only run up to D = 64 because of its D⁴ intermediate. At small D both are dominated by overhead, at large D the gap widens with D.
Figure 1.5 shows that the measured times follow the counted cost once is large enough for the arithmetic to dominate. At the timed ratio (several hundred to a few thousand, depending on the machine and the run) exceeds the counted ratio , because the intermediate no longer fits in cache. Measured ratios vary from run to run; the counted ones do not.
Intuition: keep intermediates small
A good contraction order keeps the number of open legs on every intermediate as small as possible. In the norm step, and share a leg, so contracting them removes one leg; and share only the physical leg, which is small, so contracting them first leaves four big legs open. A useful rule of thumb is to always contract along the largest shared legs first. For large networks finding the optimal order is a hard optimization problem in its own right, and libraries such as cotengra (used by quimb) search for good orders heuristically (2).
In code we specify a network with numbered legs. In the ncon convention (3), positive labels are contracted (in increasing order) and negative labels are the open legs of the result; TensorKit provides ncon and the @tensor macro (with the dual-space rule of Remark 1.1), and quimb names legs with strings. The order of the labels is a choice of contraction order, so it should be chosen with the counting rule in mind.
Factorizations across a bipartition
Every matrix factorization becomes a tensor factorization in three steps: matricize across a chosen cut, factorize the matrix, and reshape the factors back so that each carries its original legs plus one new leg, the bond. The bond dimension is at most the smaller side of the cut.
The three factorizations we need are, for an matricization with :
SVD, with () and () isometries and diagonal. It reveals how much each bond state matters and allows optimal truncation. Cost with a large constant.
QR, with () satisfying 𝟙 and upper triangular. Exact, no truncation, cheaper than the SVD.
LQ, with () satisfying 𝟙 and lower triangular. It is the QR of , transposed back.
For a Hermitian operator (a map from a space to itself) we can also diagonalize, . The two decompositions are linked by : the eigenvalues of are the squared singular values of . In Module 0 this was the statement that the Schmidt values squared are the eigenvalues of the reduced density matrix.
Definition 1.2 (Isometry).
A tensor is a left isometry with respect to a cut if its matricization satisfies 𝟙 on the bond (columns orthonormal), and a right isometry if 𝟙 on the bond (rows orthonormal). In diagrams, contracting a left isometry with its conjugate over all non-bond legs gives the identity on the bond (Figure 1.6).
QQbar=left isometryM=QRQR across a cutFigure 1.6. Left: a left isometry (blue) contracted with its conjugate over every leg except the bond gives the identity, drawn as a plain line. Right: QR splits any tensor into a left isometry and a remainder R.
An isometry is not unitary in general: is a projector onto the range of , not the identity, unless the bond is as large as the other side of the cut. What survives of Definition 1.2 is the property that matters, for vectors entering through the bond. Isometries are the reason canonical forms (Module 2) make local computations exact.
Truncation across a cut
Corollary 1.1 (Truncated SVD of a tensor).
Let be a tensor, fix a cut, and let be the singular values of its matricization. Keeping of them gives a pair of tensors and joined by a bond of dimension with
and no pair of tensors joined by a bond of dimension across this cut approximates better.
Proof
The Frobenius norm of a tensor is the square root of the sum of over all entries, so it is unchanged by permuting and reshaping. Two tensors joined by a bond of dimension contract to a tensor whose matricization across the cut is a product of an and a matrix, that is a matrix of rank at most ; conversely every such matrix can be written that way. The claim is therefore the Frobenius part of the Eckart-Young theorem from Module 0 applied to the matricization.
Notebook Hands-on 1.4 checks Corollary 1.1 on a tensor cut as , whose matricization is . The measured error , the formula , and the library’s own report (TensorKit’s svd_trunc, quimb’s tensor_split) agree to :
kept
1
2
4
8
12
error
3.0142
2.5751
1.8866
0.7764
0
Different cuts of the same tensor give different spectra. For a test tensor, Hands-on 1.1 finds that the cut is an matrix with eight singular values (), while the cut is with six (). Where we cut matters as much as how much we keep.
Gauge freedom
Factorizations are not unique. Take two tensors joined by a bond of dimension , , and any invertible matrix . Inserting 𝟙 on the bond, as drawn in Figure 1.7, does not change ,
AXXinvBX Xinv = 1 on the bond=A'B'A' = A XB' = Xinv BFigure 1.7. Gauge freedom. Inserting an invertible matrix and its inverse on a bond changes both tensors but not the network they form.
The converse is also true, so this is the only freedom.
Proposition 1.2 (Gauge freedom is the only freedom).
Let , where, as matrices across the cut, are with rank and are with rank . Then there is a unique invertible with and .
Proof
Since has full column rank, it has a left inverse with 𝟙. Since has full row rank, maps onto , so the range of is the range of ; likewise it is the range of . Hence every column of lies in the range of , and with . The matrix is and , so it is invertible. Now , and multiplying by from the left gives , that is . Uniqueness follows from .
Two consequences of Proposition 1.2 shape the rest of the course. First, the tensors of a network are never unique, so a numerical result can only be trusted if it is gauge invariant. The singular values of across the bond are gauge invariant, because itself does not change. Second, we can use the gauge to make tensors nicer. Take a QR decomposition across the cut and choose (or, when is singular, simply absorb it): then with a left isometry. Hands-on 1.5 does this for of size : the Frobenius norm changes from to under a random gauge and to after QR, while the singular values of () stay fixed throughout. Repeating this on every bond is how an MPS is brought into canonical form in Module 2.
Intuition: the bond is an internal coordinate system
The bond index labels a basis of a -dimensional space that lives “between” two tensors. Nothing outside the network can see which basis we use, just as a physical result cannot depend on the coordinates we choose. Changing the basis by rotates the bond legs of both neighbours in opposite ways. A canonical form is a choice of basis in which the tensors are isometries; the SVD basis is the special choice in which, in addition, the bond carries the Schmidt values of the state.
Worked example: the Ising chain as a dense operator
Time to put the primitives together. The notebooks build the transverse-field Ising Hamiltonian on an open chain of spins,
as one dense operator. Each term is an outer product of matrices, with the identity on every site that the term does not touch (Hands-on 1.6), and is their sum: a map from to itself with entries. This is the brute-force reference: it is exact, and its cost doubles with every site, which is precisely what Module 0 told us to avoid. Every later method has to reproduce its numbers.
For and (the critical point) the notebooks find
the ground-state energy , equal to the exact free-fermion result (4) to , so ;
a transverse magnetization that is largest at the edges () and smallest in the middle (), an effect of the open boundary;
across the middle cut, Schmidt values and entanglement entropy .
To get the Schmidt values the notebook repartitions the ground-state tensor so that sites form the codomain and the domain, and takes one SVD: Module 0’s reshape, now expressed as a tensor operation. Sweeping from to shows the two phases. Deep in the ordered phase the (symmetric) ground state is close to a GHZ state, with and average magnetization at . In the paramagnetic phase it approaches the product state , with and at . In between, near , the entropy crosses over.
Warning
Dense operators. A dense Hamiltonian with entries stops at on a laptop (the notebooks guard memory before building it). Module 4 writes as a matrix product operator instead.
Bad contraction orders. Correct code with a bad order can be slower by a factor that grows with , and its intermediates can exhaust memory. Count before you contract.
Index order. Reshape in row-major and column-major languages groups indices differently. Mixing conventions gives wrong numbers without an error; TensorKit’s spaces catch some of these mistakes, plain arrays catch none.
Gauge-dependent quantities. Individual tensor entries, and even their norms, change under gauge transformations. Compare singular values or contracted quantities, never raw tensors.
Degenerate singular values. When the truncated SVD is not unique, and truncating can break a symmetry of the state. Module 5 handles this by keeping symmetry blocks intact.
Why it matters
Every algorithm in this course is a sequence of the four operations of this module: permute, reshape, contract and factorize. The cost rule tells us in advance how expensive an algorithm is (for MPS methods per step, provided we contract in the right order). The truncated SVD gives optimal compression across a cut with a known error, and gauge freedom lets us choose isometric tensors so that local computations become exact. With these, Module 2 can build matrix product states.
Further reading
A gentle diagrammatic introduction with many worked examples: (1).
The broader review that connects these primitives to DMRG and MPS algorithms: (5).
Exact search for the optimal contraction order of small networks: (6).
Contraction order search for large networks and the cotengra library behind quimb: (2,7).
Tensor libraries used in practice: ITensor (8) and TeNPy (9).
An introductory course on tensor networks built around diagrams: (10).
Orús R. A practical introduction to tensor networks: Matrix product states and projected entangled pair states. Annals of Physics. 2014;349:117–58.
2.
Gray J, Kourtis S. Hyper-optimized tensor network contraction. Quantum. 2021;5:410.
3.
Pfeifer RNC, Evenbly G, Singh S, Vidal G. NCON: A tensor network contractor for MATLAB. 2014.
4.
Pfeuty P. The one-dimensional Ising model with a transverse field. Annals of Physics. 1970;57(1):79–90.
5.
Schollwöck U. The density-matrix renormalization group in the age of matrix product states. Annals of Physics. 2011;326(1):96–192.
6.
Pfeifer RNC, Haegeman J, Verstraete F. Faster identification of optimal contraction sequences for tensor networks. Physical Review E. 2014;90(3):033315.
7.
Gray J. quimb: a python package for quantum information and many-body calculations. Journal of Open Source Software. 2018;3(29):819.
8.
Fishman M, White SR, Stoudenmire EM. The ITensor Software Library for Tensor Network Calculations. SciPost Physics Codebases. 2022;4.
9.
Hauschild J, Pollmann F. Efficient numerical simulations with Tensor Networks: Tensor Network Python (TeNPy). SciPost Physics Lecture Notes. 2018;5.
10.
Bridgeman JC, Chubb CT. Hand-waving and interpretive dance: an introductory course on tensor networks. Journal of Physics A: Mathematical and Theoretical. 2017;50(22):223001.