Foundations to Frontier
Tests
A. Mathematical Foundations › A2 Linear Algebra › Advanced linear algebra

Tensors: Operations, Einstein Summation (einsum), CP and Tucker Decompositions

Data often has more than two axes, such as images × channels × time or users × items × context. Tensors are the arrays for it, einsum is the one notation every deep-learning operation can be written in, and CP and Tucker decompositions find structure and compress it.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Numbers, lists, tables… and stacks of tables

  • A single number (temperature now) is a scalar.
  • A list of numbers (temperature each hour) is a vector.
  • A table (temperature at each spot on a map) is a matrix.
  • A stack of tables (that map, hour after hour) is a tensor.

A colour photo is a tensor too: height × width × 3 colours. A video adds time.

Many tensor operations are “multiply matching numbers and add them up”. One neat notation, einsum, describes all of them by naming the axes.

einsum explorer: repeated indices are summed, output indices are kept
kept (free): ik · summed: j · 12 multiply-adds
input 1: ij · shape (2, 3)
33-3
-13-3
input 2: jk · shape (3, 2)
-32
2-3
-2-3
→
output: ik · shape (2, 2)
36
15-2
Rule: out[ik] = Σ over j of the product of the inputs. Sizes used: i=2, j=3 (a letter repeated inside one input, like ii, gets 3), k=2, b=2, h=2, q=2, d=3; other letters = 2. Edit the spec to try your own.
Why engineers care

A Mars rover’s cameras produce tensors (images × colour channels × time), and so do its arm’s force sensors (sensors × axes × time). Every neural network that processes this data is a chain of tensor operations, usually written in exactly this einsum language.

📝 Quick check (Level 0)
0/3 answered
  1. 1. How many numbers describe one pixel of a colour (RGB) image?
  2. 2. A greyscale video (frames × height × width) is a tensor with how many axes?
  3. 3. A matrix is a tensor with how many axes?

Level 1: Beginner

★★☆☆☆ Basic⏱ 15 minSecondary-school mathematics: arithmetic and elementary algebra.

Vocabulary

Term Meaning Example
order (number of modes) number of indices an RGB batch (B,C,H,W)(B, C, H, W) has order 4
shape size of each mode (32,3,224,224)(32, 3, 224, 224)
fiber fix all indices but one one pixel’s 3 colour values
slice fix all indices but two one colour channel of one image
element-wise ops ++, ⊙\odot, functions ReLU, broadcasting (A2.2-6)

A tensor with shape (n1,…,nd)(n_1,\dots,n_d) has n1n2⋯ndn_1n_2\cdots n_d entries. Computers store it as one long list in row-major order: the last index changes fastest. In shape (2,3,4)(2,3,4), the entry (1,2,3)(1,2,3) sits at position 1⋅12+2⋅4+3=231\cdot12 + 2\cdot4 + 3 = 23.

📝 Quick check (Level 1)
0/3 answered
  1. 1. How many entries in shape (2, 3, 4)?
  2. 2. What is the order of a batch of RGB images (B, C, H, W)?
  3. 3. In row-major storage, which index changes fastest?

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 45 minUndergraduate students and practising engineers.

Einstein summation

Write the indices of every input and the output. Every index not in the output is summed over.

einsum Formula Operation
ij,jk->ik Cik=∑jAijBjkC_{ik} = \sum_jA_{ij}B_{jk} matrix product
ii-> ∑iAii\sum_iA_{ii} trace
ij->ji Bji=AijB_{ji} = A_{ij} transpose
i,j->ij aibja_ib_j outer product
ij,ij-> ∑ijAijBij\sum_{ij}A_{ij}B_{ij} Frobenius inner product
bij,bjk->bik per-batch matmul batched layers
bhqd,bhkd->bhqk ∑dQbhqdKbhkd\sum_dQ_{bhqd}K_{bhkd} multi-head attention scores

Einstein introduced the convention in 1916 for general relativity. It is now np.einsum, torch.einsum and the einops library.

🐍 Exercise 1: one notation for everything
Implement matmul, trace, a 3-way outer product, batched matmul and scaled attention scores, each as a single einsum call, and check them against NumPy.

Unfolding and the mode-n product

The mode-n unfolding X(n)X_{(n)} lays out all mode-nn fibers as the columns of a matrix of size nn×∏m≠nnmn_n\times\prod_{m\ne n}n_m. The mode-n product X×nU\mathcal X\times_nU multiplies every mode-nn fiber by the matrix UU:

(X×nU)(n)=U X(n)(\mathcal X\times_nU)_{(n)} = U\,X_{(n)}

Each unfolding has a rank, and the tuple of these ranks is the multilinear rank. Unfolding turns tensor problems into matrix problems that we already know how to solve.

📝 Quick check (Level 2)
0/3 answered
  1. 1. einsum('ii->', [[1, 2], [3, 4]]) = ?
  2. 2. In 'bij,bjk->bik', which index is summed?
  3. 3. Mode-1 unfolding of a 3 × 4 × 5 tensor has shape…

Level 3: Advanced

★★★★☆ Advanced⏱ 45 minGraduate level, with full derivations and proofs.

CP decomposition: tensor rank

A rank-1 tensor is an outer product a∘b∘c\mathbf a\circ\mathbf b\circ\mathbf c, with entries aibjcka_ib_jc_k. The CP (CANDECOMP/PARAFAC) decomposition writes

X≈∑r=1Rar∘br∘cr\mathcal X\approx\sum_{r=1}^R\mathbf a_r\circ\mathbf b_r\circ\mathbf c_r

The smallest exact RR is the tensor rank. It behaves very differently from matrix rank:

  • Computing it is NP-hard (Håstad, 1990; Hillar and Lim, 2013).
  • It can differ over R\mathbb R and over C\mathbb C, and it can exceed every dimension.
  • A best rank-R approximation may not exist: sequences of rank-2 tensors can converge to a rank-3 tensor (de Silva and Lim, 2008).
  • But CP is often unique. Kruskal’s theorem: if kA+kB+kC≥2R+2k_A + k_B + k_C\ge2R + 2 (the kk’s are Kruskal ranks), then the factors are unique up to scaling and permutation. Matrix factorizations A=BCA = BC never are, since B→BMB\to BM and C→M−1CC\to M^{-1}C. This uniqueness is why CP is used to discover interpretable components, as in PARAFAC in chemometrics.

Tucker decomposition and HOSVD

X≈G×1U1×2U2×3U3\mathcal X\approx\mathcal G\times_1U_1\times_2U_2\times_3U_3

Here G\mathcal G is a small core tensor and UnU_n are factor matrices with orthonormal columns. The higher-order SVD (De Lathauwer et al., 2000) takes UnU_n as the leading left singular vectors of the unfolding X(n)X_{(n)}, and sets G=X×1U1⊤×2U2⊤×3U3⊤\mathcal G = \mathcal X\times_1U_1^\top\times_2U_2^\top\times_3U_3^\top. Truncated HOSVD is not optimal, but it is within a factor d\sqrt d of the best approximation:

∥X−X^∥2≤∑n∑i>rnσi(X(n))2\lVert\mathcal X - \hat{\mathcal X}\rVert^2\le\sum_n\sum_{i>r_n}\sigma_i(X_{(n)})^2
Exercise 3.1: Count the parameters of CP vs Tucker for a 10 × 20 × 30 tensor

The full tensor has 6,000 entries. CP with R=5R = 5 needs 5(10+20+30)=3005(10+20+30) = 300 numbers. Tucker with ranks (5,5,5)(5,5,5) needs 125+5(10+20+30)=425125 + 5(10+20+30) = 425. Tucker is more flexible, because its core mixes the components. CP is more compact and unique.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Computing the rank of a general 3-way tensor is…
  2. 2. Which decomposition is typically unique up to scaling and permutation?
  3. 3. HOSVD gets its factors from…

Level 4: Expert

★★★★★ Expert⏱ 40 minResearchers: original papers and open problems.

Fitting CP: alternating least squares

Fix two factor matrices, and the third solves a linear least-squares problem:

A←X(1)(C⊙B)((B⊤B)∗(C⊤C))†A\leftarrow X_{(1)}(C\odot B)\big((B^\top B)*(C^\top C)\big)^{\dagger}

Here ⊙\odot is the Khatri–Rao (column-wise Kronecker) product and ∗* is the Hadamard product. Cycle through the modes until the fit stops improving (Kolda and Bader, 2009).

🐍 Exercise 2 (research): CP-ALS recovers planted factors
Plant a rank-3 tensor plus 1% noise. Fit it with CP-ALS, and check the fit and that every true factor column is recovered (cosine above 0.99). Unlike a matrix factorization, the factors are unique.

Tensors in research

  • Compressing neural networks. A convolution kernel of shape out × in × k×kk\times k can be CP-decomposed into four thin convolutions, which gives large speed-ups with little accuracy loss (Lebedev et al., 2015). Tucker and tensor-train layers compress fully connected weights (Novikov et al., 2015).
  • Tensor networks and tensor trains (Oseledets, 2011) store a dd-way tensor with O(dnr2)O(dnr^2) numbers instead of ndn^d. They beat the curse of dimensionality in high-dimensional PDEs, quantum many-body physics and uncertainty quantification.
  • Multi-sensor and spatiotemporal data. Sensor × time × trial tensors come from robot force/torque logs, EEG, and spacecraft telemetry. CP finds shared components, and Tucker/HOSVD compresses smooth fields (Practice Code 5 gets 93× on a heating panel). Tensor completion fills missing sensor readings.
  • Knowledge graphs and recommenders. Entity × relation × entity tensors are factorized by RESCAL, ComplEx and TuckER to predict missing facts. User × item × context tensors are used for recommendations.
  • Deep learning frameworks compile einsum expressions and choose the contraction order. For long chains, finding the cheapest order is itself hard; opt_einsum searches for it.

References

  1. A. Einstein (1916). “Die Grundlage der allgemeinen Relativitätstheorie.” Annalen der Physik, 49.
  2. J. Kruskal (1977). “Three-way arrays: rank and uniqueness of trilinear decompositions.” Linear Algebra and its Applications, 18.
  3. L. De Lathauwer, B. De Moor, J. Vandewalle (2000). “A multilinear singular value decomposition.” SIAM J. Matrix Anal. Appl., 21(4).
  4. V. de Silva, L.-H. Lim (2008). “Tensor rank and the ill-posedness of the best low-rank approximation problem.” SIAM J. Matrix Anal. Appl., 30(3).
  5. T. Kolda, B. Bader (2009). “Tensor decompositions and applications.” SIAM Review, 51(3).
  6. I. Oseledets (2011). “Tensor-train decomposition.” SIAM J. Scientific Computing, 33(5).
  7. C. Hillar, L.-H. Lim (2013). “Most tensor problems are NP-hard.” Journal of the ACM, 60(6).
  8. V. Lebedev, Y. Ganin, M. Rakhuba, I. Oseledets, V. Lempitsky (2015). “Speeding-up convolutional neural networks using fine-tuned CP-decomposition.” ICLR.
  9. A. Novikov, D. Podoprikhin, A. Osokin, D. Vetrov (2015). “Tensorizing neural networks.” NeurIPS.