Module contents
Lesson 20 of 25Advanced 100 min

Kronecker products and tensor decompositions

Kronecker products encode structure repeated along two axes and underpin preconditioners such as K-FAC and Shampoo; the vec trick works with them without materialization. Then explore tensor rank and CP and Tucker decompositions, including a memorable example: the minimum multiplications needed for matrix multiplication is a tensor's rank, the problem AlphaTensor tackled with an AlphaZero-style agent.

After this lesson you can

  • Calculate Kronecker products and apply their algebraic and spectral properties.
  • Use the vec trick to solve matrix equations and multiply by A ⊗ B without forming it.
  • Explain how tensor rank differs from matrix rank and why it is hard to compute.
  • Verify Strassen's decomposition as a rank-7 decomposition of the 2×2 product tensor.
  • Fit CP decompositions by alternating least squares and Tucker decompositions using HOSVD.

Before you start

Motivation: structure repeated along two axes

Many huge matrices in practice are not arbitrary: they consist of a small matrix repeated across another. Three examples you will encounter:

  • Second-order preconditioners. For linear layer W∈Rdout×din\mat{W} \in \R^{d_{\text{out}}\times d_{\text{in}}}, the Fisher information matrix with respect to vec⁡(W)\vecop(\mat{W}) has (dindout)2(d_{\text{in}}d_{\text{out}})^2 entries: with din=dout=4096d_{\text{in}} = d_{\text{out}} = 4096 roughly 2.8⋅10142.8\cdot 10^{14} numbers, impossible to store, much less invert. K-FAC approximates it by A⊗S\mat{A}\otimes\mat{S} with A\mat{A} of size din×dind_{\text{in}}\times d_{\text{in}} and S\mat{S} of size dout×doutd_{\text{out}}\times d_{\text{out}}; Shampoo uses a similarly structured preconditioner. Both are feasible because A⊗S\mat{A}\otimes\mat{S} can be inverted and applied using only factors.
  • Separable filters. Blurring image X\mat{X} with a 2D Gaussian filter equals filtering columns then rows: Y=GXG⊤\mat{Y} = \mat{G}\mat{X}\mat{G}\T, where G\mat{G} is the 1D filter matrix. As a linear map on stacked pixels, it is G⊗G\mat{G}\otimes\mat{G}, but nobody forms it.
  • Separable covariances. If field Y∈Rns×nt\mat{Y} \in \R^{n_s\times n_t} (locations by times) has noninteracting spatial covariance Σs\mat{\Sigma}_s and temporal covariance Σt\mat{\Sigma}_t, covariance of vec⁡(Y)\vecop(\mat{Y}) is Σt⊗Σs\mat{\Sigma}_t\otimes\mat{\Sigma}_s. Likewise a Gaussian process on a grid with product kernel has a covariance matrix given by a Kronecker product of small matrices.

Kronecker product ⊗\otimes is the language of that structure, and the vec trick works with it without ever materializing it.

The second half makes a natural leap. Matrices have two axes; real data often have more: users by products by weeks, EEG channels by time by trials, or convolutional kernels (output channels by input channels by height by width). You already handle such tensors using einsum. Now decompose them as SVD decomposes matrices, and discover that nearly everything known about matrix rank ceases to hold. The standout example: minimum multiplications for a bilinear matrix multiplication algorithm equal the rank of a specific tensor. Strassen found a rank-7 decomposition for 2×22\times 2 in 1969; in 2022 AlphaTensor searched for new decompositions with an AlphaZero-style agent.

Intuition: a mosaic of copies

Take two small matrices,

A=[210−1],B=[1001300−10.5].\mat{A} = \begin{bmatrix} 2 & 1 \\ 0 & -1 \end{bmatrix}, \qquad \mat{B} = \begin{bmatrix} 1 & 0 & 0 \\ 1 & 3 & 0 \\ 0 & -1 & 0.5 \end{bmatrix}.

Their Kronecker product is the 6×66\times 6 matrix obtained by replacing each entry aija_{ij} of A\mat{A} with block aijBa_{ij}\mat{B}:

A⊗B=[2B1B0B−1B].\mat{A}\otimes\mat{B} = \begin{bmatrix} 2\mat{B} & 1\mat{B} \\ 0\mat{B} & -1\mat{B} \end{bmatrix}.

It is a mosaic: B\mat{B}‘s shape repeats in each block and A\mat{A} decides each copy’s brightness and sign. Edit both matrices in the interactive to see which entry scales each block.

InteractiveThe Kronecker mosaic
Hover over the mosaic or A\mat{A}: each block copies B\mat{B} scaled by highlighted entry aija_{ij}, and each cell is a product aijbkla_{ij}b_{kl}. Below, on the complex plane, rings are products λiμj\lambda_i\mu_j of factor eigenvalues and points are eigenvalues of A⊗B\mat{A}\otimes\mat{B} calculated directly: they always agree. Try A: 90° rotation (eigenvalues ±i\pm i), singular A (ranks multiply), and order B ⊗ A.

Three interactive observations the rest of this section proves:

  1. Eigenvalues of A⊗B\mat{A}\otimes\mat{B} are the six products λiμj\lambda_i\mu_j. For the matrices above, λ∈{2,−1}\lambda \in \{2, -1\} and μ∈{1,3,0.5}\mu \in \{1, 3, 0.5\}, giving spectrum {2,6,1,−1,−3,−0.5}\{2, 6, 1, -1, -3, -0.5\}.
  2. Traces multiply and determinants almost do: det⁡(A⊗B)=(det⁡A)3(det⁡B)2\det(\mat{A}\otimes\mat{B}) = (\det\mat{A})^3(\det\mat{B})^2, with crossed exponents.
  3. B⊗A\mat{B}\otimes\mat{A} has the same 36 entries in another order. It is not the same matrix, but is the same linear map read with permuted coordinates.

Kronecker product and its properties

For vectors x⊗y\vb{x}\otimes\vb{y} stacks x1y,x2y,…x_1\vb{y}, x_2\vb{y}, \dots: all products xiykx_iy_k, like tensor product xy⊤\vb{x}\vb{y}\T, flattened into a vector. The underlying idea: ⊗\otimes is tensor product in coordinates, with a specific ordering of index pairs (A\mat{A}‘s index varies slowly and B\mat{B}‘s quickly).

Property 3 does the work. Its blockwise proof is worth doing once.

ProofThe mixed-product property
Prove: If AC\mat{A}\mat{C} and BD\mat{B}\mat{D} are defined, (A⊗B)(C⊗D)=(AC)⊗(BD)(\mat{A}\otimes\mat{B})(\mat{C}\otimes\mat{D}) = (\mat{A}\mat{C})\otimes(\mat{B}\mat{D}). Hence if A\mat{A} and B\mat{B} are invertible, (A⊗B)−1=A−1⊗B−1(\mat{A}\otimes\mat{B})\inv = \mat{A}\inv\otimes\mat{B}\inv.
0
Let A∈Rm×n\mat{A} \in \R^{m\times n}, C∈Rn×r\mat{C} \in \R^{n\times r}, B∈Rp×q\mat{B} \in \R^{p\times q} and D∈Rq×s\mat{D} \in \R^{q\times s}.

Step 1 of 4. How do you organize the left-hand product?

Spectrum, singular values and everything that multiplies

Mixed product immediately yields all the “spectral algebra” of ⊗\otimes.

Proof

For eigenvectors, (A⊗B)(x⊗y)=(Ax)⊗(By)=(λx)⊗(μy)=λμ (x⊗y)(\mat{A}\otimes\mat{B})(\vb{x}\otimes\vb{y}) = (\mat{A}\vb{x})\otimes(\mat{B}\vb{y}) = (\lambda\vb{x})\otimes(\mu\vb{y}) = \lambda\mu\,(\vb{x}\otimes\vb{y}) by mixed product for column vectors. This does not prove the full spectrum (with multiplicities and for nondiagonalizable A\mat{A}), so use Schur forms A=QATAQA∗\mat{A} = \mat{Q}_A\mat{T}_A\mat{Q}_A^* and B=QBTBQB∗\mat{B} = \mat{Q}_B\mat{T}_B\mat{Q}_B^*, with unitary Q\mat{Q} and upper-triangular T\mat{T} having eigenvalues on the diagonal. Mixed product gives

A⊗B=(QA⊗QB)(TA⊗TB)(QA⊗QB)∗,\mat{A}\otimes\mat{B} = (\mat{Q}_A\otimes\mat{Q}_B)(\mat{T}_A\otimes\mat{T}_B)(\mat{Q}_A\otimes\mat{Q}_B)^*,

with unitary QA⊗QB\mat{Q}_A\otimes\mat{Q}_B. TA⊗TB\mat{T}_A\otimes\mat{T}_B is upper triangular (each block tijTBt_{ij}\mat{T}_B with i>ji > j is zero and diagonal blocks triangular), with diagonal λiμj\lambda_i\mu_j. Similarity preserves eigenvalues, proving 1. Trace is the sum of λiμj\lambda_i\mu_j, factoring as (∑iλi)(∑jμj)(\sum_i\lambda_i)(\sum_j\mu_j), and determinant is their product: each λi\lambda_i appears nn times and each μj\mu_j, mm times. For 3, mixed product gives the factorization; UA⊗UB\mat{U}_A\otimes\mat{U}_B and VA⊗VB\mat{V}_A\otimes\mat{V}_B have orthonormal columns (again mixed product, (UA⊗UB)⊤(UA⊗UB)=I⊗I(\mat{U}_A\otimes\mat{U}_B)\T(\mat{U}_A\otimes\mat{U}_B) = \mat{I}\otimes\mat{I}); and ΣA⊗ΣB\mat{\Sigma}_A\otimes\mat{\Sigma}_B is diagonal with entries σiτj≥0\sigma_i\tau_j \ge 0. Rank counts nonzero products, rank⁡A⋅rank⁡B\rank\mat{A}\cdot\rank\mat{B}.

∎

An equally useful additive relative is the Kronecker sum of A∈Rm×m\mat{A} \in \R^{m\times m} and B∈Rn×n\mat{B} \in \R^{n\times n}: A⊕B=A⊗In+Im⊗B\mat{A}\oplus\mat{B} = \mat{A}\otimes\mat{I}_n + \mat{I}_m\otimes\mat{B}. Since terms commute and share eigenvectors xi⊗yj\vb{x}_i\otimes\vb{y}_j (when A\mat{A} and B\mat{B} are diagonalizable), eigenvalues are sums λi+μj\lambda_i + \mu_j. This always holds: using Schur forms above, A⊕B\mat{A}\oplus\mat{B} is similar to upper-triangular TA⊗I+I⊗TB\mat{T}_A\otimes\mat{I} + \mat{I}\otimes\mat{T}_B with diagonal λi+μj\lambda_i + \mu_j. The classic example is a discrete Laplacian on an n×nn\times n grid: T⊕T\mat{T}\oplus\mat{T} with T\mat{T} the 1D Laplacian tridiagonal (−1,2,−1)(-1, 2, -1); its spectrum sums known closed-form 1D eigenvalues pairwise.

The vec operator and vec trick

Connecting matrices and vectors requires a way to flatten.

This is column-major flattening, used by Fortran, MATLAB and Julia. NumPy defaults to row-major: X.ravel() is vec⁡(X⊤)\vecop(\mat{X}\T), and vec⁡(X)\vecop(\mat{X}) is X.reshape(-1, order="F"). The difference seems cosmetic and causes this lesson’s most common error.

The vec operator and vec trick are central to the first half: they translate any linear equation in an unknown matrix, however complicated, to ordinary linear system Mvec⁡(X)=c\mat{M}\vecop(\mat{X}) = \vb{c}, and conversely allow applying a giant Kronecker matrix with two small matrix products.

ProofProving the vec trick
Prove: For A∈Rm×n\mat{A} \in \R^{m\times n}, X∈Rn×p\mat{X} \in \R^{n\times p} and B∈Rp×q\mat{B} \in \R^{p\times q}, with vec⁡\vecop stacking columns, vec⁡(AXB)=(B⊤⊗A)vec⁡(X)\vecop(\mat{A}\mat{X}\mat{B}) = (\mat{B}\T\otimes\mat{A})\vecop(\mat{X}).
0
Write xj\vb{x}_j for column jj of X\mat{X}, bk\vb{b}_k for column kk of B\mat{B} and bjkb_{jk} for its entries, so vec⁡(X)=(x1;… ;xp)\vecop(\mat{X}) = (\vb{x}_1; \dots; \vb{x}_p).

Step 1 of 3. Where do you start?

Never materialize A⊗B\mat{A}\otimes\mat{B}

Read right to left, the vec trick is an algorithm. For A,B∈Rn×n\mat{A}, \mat{B} \in \R^{n\times n}, A⊗B\mat{A}\otimes\mat{B} has n4n^4 entries and multiplying it by a vector costs n4n^4 multiplications. Instead,

(A⊗B)x=vec⁡(BXA⊤),x=vec⁡(X),(\mat{A}\otimes\mat{B})\vb{x} = \vecop(\mat{B}\mat{X}\mat{A}\T), \qquad \vb{x} = \vecop(\mat{X}),

costs two n×nn\times n products, about 2n32n^3 multiplications, and no more memory than X\mat{X}. With n=1000n = 1000, the dense matrix occupies 8 TB in double precision; the trick uses 8 MB.

The same holds for solving. If A\mat{A} and B\mat{B} are invertible,

(A⊗B)x=c  ⟺  BXA⊤=C  ⟺  X=B−1CA−T,(\mat{A}\otimes\mat{B})\vb{x} = \vb{c} \iff \mat{B}\mat{X}\mat{A}\T = \mat{C} \iff \mat{X} = \mat{B}\inv\mat{C}\mat{A}^{-\mathsf{T}},

so factor A\mat{A} and B\mat{B} separately (LU, Cholesky or appropriate method): cost O(n3)\bigO(n^3) instead of O(n6)\bigO(n^6) for elimination on an n2×n2n^2\times n^2 matrix. And since A⊗B=(LA⊗LB)(LA⊗LB)⊤\mat{A}\otimes\mat{B} = (\mat{L}_A\otimes\mat{L}_B)(\mat{L}_A\otimes\mat{L}_B)\T when A=LALA⊤\mat{A} = \mat{L}_A\mat{L}_A\T and B=LBLB⊤\mat{B} = \mat{L}_B\mat{L}_B\T, the Kronecker product’s Cholesky factor is the product of factors.

Matrix equations: Sylvester

The vec trick turns an equation with unknown matrix into a linear system. The Sylvester equation AX+XB=C\mat{A}\mat{X} + \mat{X}\mat{B} = \mat{C}, with A∈Rm×m\mat{A} \in \R^{m\times m}, B∈Rn×n\mat{B} \in \R^{n\times n} and X,C∈Rm×n\mat{X}, \mat{C} \in \R^{m\times n}, appears in control theory, linear-system stability (the Lyapunov equation is the B=A⊤\mat{B} = \mat{A}\T case) and some matrix-gradient derivations. Applying vec,

(In⊗A+B⊤⊗Im)vec⁡(X)=vec⁡(C).\big(\mat{I}_n\otimes\mat{A} + \mat{B}\T\otimes\mat{I}_m\big)\vecop(\mat{X}) = \vecop(\mat{C}).

The system matrix is Kronecker sum B⊤⊕A\mat{B}\T\oplus\mat{A} (factors in that order), with eigenvalues λi(A)+μj(B)\lambda_i(\mat{A}) + \mu_j(\mat{B}). Hence a unique solution exists if and only if A\mat{A} and −B-\mat{B} share no eigenvalue. For small sizes solve the mn×mnmn\times mn system directly; for medium sizes use Bartels–Stewart (each factor’s Schur form and substitution), behind scipy.linalg.solve_sylvester, costing O(m3+n3)\bigO(m^3 + n^3) rather than O(m3n3)\bigO(m^3n^3).

K-FAC and Shampoo in one line

Now read K-FAC’s approximation. For linear layer s=Wa\vb{s} = \mat{W}\vb{a}, one example’s loss gradient with respect to W\mat{W} is G=δa⊤\mat{G} = \boldsymbol{\delta}\vb{a}\T, with δ=∂ℓ/∂s\boldsymbol{\delta} = \partial\ell/\partial\vb{s}. Since vec⁡(δa⊤)=a⊗δ\vecop(\boldsymbol{\delta}\vb{a}\T) = \vb{a}\otimes\boldsymbol{\delta} (vec trick with X=δ\mat{X} = \boldsymbol{\delta}, A=I\mat{A} = \mat{I} and B=a⊤\mat{B} = \vb{a}\T), layer Fisher is

F=E[vec⁡(G)vec⁡(G)⊤]=E[(aa⊤)⊗(δδ⊤)]≈E[aa⊤]⊗E[δδ⊤]=A⊗S.\mat{F} = \E\big[\vecop(\mat{G})\vecop(\mat{G})\T\big] = \E\big[(\vb{a}\vb{a}\T)\otimes(\boldsymbol{\delta}\boldsymbol{\delta}\T)\big] \approx \E[\vb{a}\vb{a}\T]\otimes\E[\boldsymbol{\delta}\boldsymbol{\delta}\T] = \mat{A}\otimes\mat{S}.

Approximation exchanges expectation and product as if activations and backpropagated signals were independent (Martens and Grosse, 2015). Then natural-gradient direction F−1vec⁡(∇WL)\mat{F}\inv\vecop(\nabla_{\mat{W}}\Loss) uses vec: (A−1⊗S−1)vec⁡(∇WL)=vec⁡(S−1 ∇WL A−1)(\mat{A}\inv\otimes\mat{S}\inv)\vecop(\nabla_{\mat{W}}\Loss) = \vecop(\mat{S}\inv\,\nabla_{\mat{W}}\Loss\,\mat{A}\inv), inverting one din×dind_{\text{in}}\times d_{\text{in}} and one dout×doutd_{\text{out}}\times d_{\text{out}} matrix. Shampoo (Gupta, Koren and Singer, 2018) accumulates L=∑tGtGt⊤\mat{L} = \sum_t\mat{G}_t\mat{G}_t\T and R=∑tGt⊤Gt\mat{R} = \sum_t\mat{G}_t\T\mat{G}_t, updating with L−1/4GR−1/4\mat{L}^{-1/4}\mat{G}\mat{R}^{-1/4}, which vec shows applies preconditioner R−1/4⊗L−1/4\mat{R}^{-1/4}\otimes\mat{L}^{-1/4} to vec⁡(G)\vecop(\mat{G}).

Lab 1: Kronecker without Kronecker

Start with the Kronecker product as a mosaic and check the preceding properties.

[ ]Kronecker from scratch and its propertiesBrowser
import numpy as np

def kron(A, B):
    """A ⊗ B por bloques: el bloque (i, j) es a_ij * B."""
    m, n = A.shape
    p, q = B.shape
    K = np.zeros((m * p, n * q))
    for i in range(m):
        for j in range(n):
            K[i*p:(i+1)*p, j*q:(j+1)*q] = A[i, j] * B
    return K

rng = np.random.default_rng(0)
A, C = rng.normal(size=(3, 4)), rng.normal(size=(4, 2))
B, D = rng.normal(size=(2, 5)), rng.normal(size=(5, 3))
print("coincide con np.kron:      ", np.allclose(kron(A, B), np.kron(A, B)))
print("producto mixto:            ", np.allclose(kron(A, B) @ kron(C, D), kron(A @ C, B @ D)))

S, T = rng.normal(size=(3, 3)), rng.normal(size=(4, 4))
print("inversa de Kronecker:      ", np.allclose(np.linalg.inv(kron(S, T)), kron(np.linalg.inv(S), np.linalg.inv(T))))
lam = np.linalg.eigvals(S)
mu = np.linalg.eigvals(T)
prods = np.outer(lam, mu).ravel()
ev = np.linalg.eigvals(kron(S, T))
print("espectro = productos:      ", np.abs(ev[:, None] - prods[None, :]).min(axis=1).max() < 1e-9)
sA = np.linalg.svd(A, compute_uv=False)
sB = np.linalg.svd(B, compute_uv=False)
print("valores singulares:        ", np.allclose(np.linalg.svd(kron(A, B), compute_uv=False)[:6], np.sort(np.outer(sA, sB).ravel())[::-1]))
R1 = rng.normal(size=(5, 2)) @ rng.normal(size=(2, 6))
print("rango(R1 ⊗ T) =", np.linalg.matrix_rank(kron(R1, T)), "= 2 · 4")

Now the vec trick under both conventions and cost comparison. The dense matrix is formed only to check; notice its size already at n=48n = 48.

[ ]The vec trick: multiply without forming A ⊗ BBrowser
import time

def vec(X):
    return X.reshape(-1, order="F")        # apila columnas (convención matemática)

A, X, B = rng.normal(size=(4, 3)), rng.normal(size=(3, 5)), rng.normal(size=(5, 2))
print("vec(AXB) = (Bᵀ ⊗ A) vec(X):", np.allclose(vec(A @ X @ B), np.kron(B.T, A) @ vec(X)))
x = X.ravel()                               # aplanado por filas de NumPy
P, Q = rng.normal(size=(6, 3)), rng.normal(size=(7, 5))
print("(P ⊗ Q) x = (P X Qᵀ).ravel(): ", np.allclose(np.kron(P, Q) @ x, (P @ X @ Q.T).ravel()))

n = 48
A, B = rng.normal(size=(n, n)), rng.normal(size=(n, n))
x = rng.normal(size=n * n)
t0 = time.perf_counter(); K = np.kron(A, B); y1 = K @ x; t_dense = time.perf_counter() - t0
t0 = time.perf_counter(); y2 = (A @ x.reshape(n, n) @ B.T).ravel(); t_trick = time.perf_counter() - t0
print(f"n = {n}: A ⊗ B tiene {K.size:,} entradas ({K.nbytes / 1e6:.0f} MB)")
print(f"densa: {t_dense * 1e3:.1f} ms   truco vec: {t_trick * 1e3:.2f} ms   iguales: {np.allclose(y1, y2)}")
for n in [100, 1000, 10000]:
    print(f"n = {n:>5}: densa {8 * n**4 / 1e9:>12,.1f} GB y {n**4:.1e} flops;  truco {8 * n**2 / 1e6:>8,.2f} MB y {2 * n**3:.1e} flops")

Solve (A⊗B)x=b(\mat{A}\otimes\mat{B})\vb{x} = \vb{b} with LU factorizations of the factors versus elimination on the 576×576576\times 576 matrix:

[ ]Solving with the factorsBrowser
import scipy.linalg as sla
n = 24
A = rng.normal(size=(n, n)) + n**0.5 * np.eye(n)
B = rng.normal(size=(n, n)) + n**0.5 * np.eye(n)
b = rng.normal(size=n * n)

np.linalg.solve(np.eye(2), np.ones(2)); sla.lu_solve(sla.lu_factor(np.eye(2)), np.ones(2))   # calentamiento: la primera llamada carga código

t0 = time.perf_counter()
x_dense = np.linalg.solve(np.kron(A, B), b)          # O((n²)³) = O(n⁶)
t_dense = time.perf_counter() - t0

t0 = time.perf_counter()
luA, luB = sla.lu_factor(A), sla.lu_factor(B)         # O(n³) cada una
Bm = b.reshape(n, n)                                  # (A ⊗ B) x = b  <=>  A X Bᵀ = Bm (por filas)
Y = sla.lu_solve(luA, Bm)                             # Y = A⁻¹ Bm
X = sla.lu_solve(luB, Y.T).T                          # X = Y B⁻ᵀ
x_fact = X.ravel()
t_fact = time.perf_counter() - t0
print(f"densa: {t_dense * 1e3:.1f} ms   con factores: {t_fact * 1e3:.2f} ms   misma solución: {np.allclose(x_dense, x_fact)}")

The Sylvester equation via vec and SciPy, and a check that Kronecker-sum eigenvalues are eigenvalue sums:

[ ]Sylvester as a linear systemBrowser
m, n = 4, 3
A = rng.normal(size=(m, m)) + 3 * np.eye(m)
B = rng.normal(size=(n, n)) + 3 * np.eye(n)
C = rng.normal(size=(m, n))
L = np.kron(np.eye(n), A) + np.kron(B.T, np.eye(m))   # vec(AX + XB) = L vec(X)
X = np.linalg.solve(L, vec(C)).reshape(m, n, order="F")
print("residuo AX + XB - C:", np.abs(A @ X + X @ B - C).max())
print("igual que scipy.linalg.solve_sylvester:", np.allclose(X, sla.solve_sylvester(A, B, C)))
sums = np.add.outer(np.linalg.eigvals(A), np.linalg.eigvals(B)).ravel()
ev = np.linalg.eigvals(L)
print("autovalores de L = λᵢ(A) + μⱼ(B):", np.abs(ev[:, None] - sums[None, :]).min(axis=1).max() < 1e-9)

And K-FAC in miniature: with independent activations and backpropagation, layer Fisher is nearly exactly A⊗S\mat{A}\otimes\mat{S}, and natural-gradient direction needs only 5×55\times 5 and 3×33\times 3 inverses.

[ ]K-FAC: layer Fisher as a Kronecker productBrowser
d_in, d_out, N = 5, 3, 200_000
a = rng.normal(size=(N, d_in)) * np.array([1, 2, 0.5, 1, 3])
delta = rng.normal(size=(N, d_out)) @ np.array([[1, 0.5, 0], [0, 1, 0.3], [0, 0, 2]])
g = np.einsum("ni,nj->nij", delta, a)                       # gradiente por ejemplo: δ aᵀ
gv = g.transpose(0, 2, 1).reshape(N, -1)                    # vec por columnas: a ⊗ δ
F = gv.T @ gv / N                                           # Fisher empírica, (15 × 15)
A_ = a.T @ a / N
S_ = delta.T @ delta / N
print("‖F − A ⊗ S‖ / ‖F‖ =", np.linalg.norm(F - np.kron(A_, S_)) / np.linalg.norm(F))
G = g.mean(0)
nat_dense = np.linalg.solve(np.kron(A_, S_), vec(G))
nat_kfac = np.linalg.solve(S_, G) @ np.linalg.inv(A_)       # S⁻¹ G A⁻¹
print("misma dirección sin formar la Fisher:", np.allclose(nat_dense, vec(nat_kfac)))

In a real network activations and backpropagation are not independent, so A⊗S\mat{A}\otimes\mat{S} is only an approximation; K-FAC buys invertibility of the approximation.

Rank-one tensors and tensor rank

Change questions. A rank-rr matrix M\mat{M} is a sum of rr outer products uv⊤\vb{u}\vb{v}\T and no fewer. Ask the same for an order-3 tensor.

For matrices (K=1K = 1), this is ordinary rank. For tensors, the definition is the same but behavior differs.

Uniqueness, the big advantage. A low-rank matrix factorization M=UV⊤\mat{M} = \mat{U}\mat{V}\T is never unique: UQ\mat{U}\mat{Q} and VQ−T\mat{V}\mat{Q}^{-\mathsf{T}} also work for any invertible Q\mat{Q}. Matrix factors cannot therefore be interpreted without additional conditions (orthogonality in SVD). CP differs: under mild conditions it is essentially unique, apart from reordering terms and redistributing scales within each. The classical condition uses Kruskal rank kAk_{\mat{A}}, the greatest kk such that any kk columns of A\mat{A} are linearly independent.

For example, generic 10×310\times 3, 8×38\times 3 and 6×36\times 3 factors each have Kruskal rank 3 and 9≥2⋅3+29 \ge 2\cdot 3 + 2: the rank-3 decomposition is unique. This is why CP (as PARAFAC) has been used since the 1970s in psychometrics and chemometrics for interpretable factors, and underlies the fitting interactive below. The proof is long; see Kruskal (1977).

What stops being true

Almost all convenient properties of matrix rank fail.

  1. Rank can exceed every dimension. The 2×2×22\times 2\times 2 tensor W=e1∘e1∘e2+e1∘e2∘e1+e2∘e1∘e1\mat{\mathcal{W}} = \vb{e}_1\circ\vb{e}_1\circ\vb{e}_2 + \vb{e}_1\circ\vb{e}_2\circ\vb{e}_1 + \vb{e}_2\circ\vb{e}_1\circ\vb{e}_1 has rank 3, greater than any side.
  2. It depends on the field. The 2×2×22\times 2\times 2 tensor with frontal slices I\mat{I} and rotation J=[0−110]\mat{J} = \begin{bmatrix} 0 & -1 \\ 1 & 0 \end{bmatrix} has rank 3 over R\R and rank 2 over C\C: over C\C, J\mat{J} diagonalizes with eigenvalues ±i\pm i in the same basis as I\mat{I}, giving two terms. Matrix rank is the same over R\R and C\C.
  3. There is no unique generic rank over R\R. A 2×2×22\times 2\times 2 tensor with Gaussian entries has rank 2 with probability π/4≈0.785\pi/4 \approx 0.785 and rank 3 with probability 1−π/41 - \pi/4; neither is almost sure, unlike a random matrix’s full rank. The lab checks this by simulation.
  4. Calculating it is hard. Deciding whether an order-3 tensor has rank at most rr is NP-complete over finite fields and NP-hard over Q\Q (Håstad, 1990); Hillar and Lim (2013) extend hardness to R\R and C\C and nearly all natural tensor problems. Matrices need only Gaussian elimination.
  5. A best rank-kk approximation may not exist. This has the greatest practical consequences and deserves its own section.

Approximations without a minimum: border rank

For matrices, the Eckart–Young theorem guarantees a best rank-kk approximation exists by truncating the SVD. Not for tensors. Take independent a,b\vb{a}, \vb{b} and rank-3 tensor

W=a∘a∘b+a∘b∘a+b∘a∘a.\mat{\mathcal{W}} = \vb{a}\circ\vb{a}\circ\vb{b} + \vb{a}\circ\vb{b}\circ\vb{a} + \vb{b}\circ\vb{a}\circ\vb{a}.

For every ε>0\eps > 0, tensor

Wε=1ε[(a+εb)∘(a+εb)∘(a+εb)−a∘a∘a]\mat{\mathcal{W}}_\eps = \frac{1}{\eps}\Big[(\vb{a} + \eps\vb{b})\circ(\vb{a} + \eps\vb{b})\circ(\vb{a} + \eps\vb{b}) - \vb{a}\circ\vb{a}\circ\vb{a}\Big]

has rank at most 2 (difference of two rank-one tensors). Expand the cube: Wε=W+ε(a∘b∘b+b∘a∘b+b∘b∘a)+ε2 b∘b∘b\mat{\mathcal{W}}_\eps = \mat{\mathcal{W}} + \eps(\vb{a}\circ\vb{b}\circ\vb{b} + \vb{b}\circ\vb{a}\circ\vb{b} + \vb{b}\circ\vb{b}\circ\vb{a}) + \eps^2\,\vb{b}\circ\vb{b}\circ\vb{b}, so ∥W−Wε∥=O(ε)\norm{\mat{\mathcal{W}} - \mat{\mathcal{W}}_\eps} = \bigO(\eps). Rank-2 approximation error for W\mat{\mathcal{W}} can be arbitrarily small but never zero: the infimum is unattained and no best rank-2 approximation exists. The cost: both terms have coefficients ±1/ε\pm 1/\eps, exploding while nearly cancelling. W\mat{\mathcal{W}} has border rank 2. De Silva and Lim (2008) showed this is no rarity: for real tensors, the set without a best rank-2 approximation has positive measure in some formats.

The matrix multiplication tensor

This example makes tensor rank unforgettable. Multiplying 2×22\times 2 matrices,

[c11c12c21c22]=[a11a12a21a22][b11b12b21b22],\begin{bmatrix} c_{11} & c_{12} \\ c_{21} & c_{22} \end{bmatrix} = \begin{bmatrix} a_{11} & a_{12} \\ a_{21} & a_{22} \end{bmatrix}\begin{bmatrix} b_{11} & b_{12} \\ b_{21} & b_{22} \end{bmatrix},

is a bilinear map: each cik=∑jaijbjkc_{ik} = \sum_j a_{ij}b_{jk} sums products of one A\mat{A} entry and one B\mat{B} entry. Any bilinear map R4×R4→R4\R^4\times\R^4 \to \R^4 is described by tensor T∈R4×4×4\mat{\mathcal{T}} \in \R^{4\times 4\times 4}: tpqst_{pqs} is the coefficient of apbqa_pb_q in csc_s, with p,q,sp, q, s indexing the four entries of A\mat{A}, B\mat{B} and C\mat{C}. For matrix multiplication, T\mat{\mathcal{T}} has 64 cells, exactly 8 ones (one per aijbjka_{ij}b_{jk}) and zeros elsewhere.

Proof

Substitute mrm_r in csc_s: cs=∑p,q(∑ruprvqrwsr)apbqc_s = \sum_{p, q}\big(\sum_r u_{pr}v_{qr}w_{sr}\big)a_pb_q. The algorithm works for all matrices if and only if each coefficient matches matrix product coefficient tpqst_{pqs}, i.e. tpqs=∑ruprvqrwsrt_{pqs} = \sum_r u_{pr}v_{qr}w_{sr} for all p,q,sp, q, s, the stated tensor equality. Additions and multiplication by constants u,v,wu, v, w do not count as multiplications between data.

∎

The school algorithm uses 8 obvious terms, one one each: rank ≤8\le 8. Strassen (1969) found seven:

m1=(a11+a22)(b11+b22),m5=(a11+a12) b22,m2=(a21+a22) b11,m6=(a21−a11)(b11+b12),m3=a11(b12−b22),m7=(a12−a22)(b21+b22),m4=a22(b21−b11),\begin{aligned} m_1 &= (a_{11} + a_{22})(b_{11} + b_{22}), & m_5 &= (a_{11} + a_{12})\,b_{22}, \\ m_2 &= (a_{21} + a_{22})\,b_{11}, & m_6 &= (a_{21} - a_{11})(b_{11} + b_{12}), \\ m_3 &= a_{11}(b_{12} - b_{22}), & m_7 &= (a_{12} - a_{22})(b_{21} + b_{22}), \\ m_4 &= a_{22}(b_{21} - b_{11}), & & \end{aligned}

with c11=m1+m4−m5+m7c_{11} = m_1 + m_4 - m_5 + m_7, c12=m3+m5c_{12} = m_3 + m_5, c21=m2+m4c_{21} = m_2 + m_4 and c22=m1−m2+m3+m6c_{22} = m_1 - m_2 + m_3 + m_6. Each mrm_r is rank-one tensor ur∘vr∘wr\vb{u}_r\circ\vb{v}_r\circ\vb{w}_r with entries in {−1,0,1}\{-1, 0, 1\}; their sum is T\mat{\mathcal{T}}.

InteractiveStrassen as a rank-7 tensor
Tensor T\mat{\mathcal{T}} is drawn as four slices, one per entry of C\mat{C}; in each, rows are entries of A\mat{A} and columns entries of B\mat{B}, with boxes marking the 8 ones. Play the rank-one sum using the school algorithm then Strassen. Strassen terms fill unwanted cells (±1\pm 1 outside boxes), which eventually cancel. Hover a cell for contributing products; below, C\mat{C} formulas fill in.

Why save one multiplication out of eight? The algorithm does not use commutativity of entries: aija_{ij} and bjkb_{jk} may be blocks. Split a 2k×2k2^k\times 2^k matrix into 2×22\times 2 blocks of 2k−1×2k−12^{k-1}\times 2^{k-1}, apply Strassen’s seven block products, recurse. Scalar multiplication count is 7k=nlog⁡27≈n2.8077^k = n^{\log_2 7} \approx n^{2.807} versus 8k=n38^k = n^3. Generally, if the n0×n0n_0\times n_0 product tensor has rank RR, recursion gives O(nlog⁡n0R)\bigO(n^{\log_{n_0}R}); the matrix multiplication exponent is a tensor-rank problem, and the algorithmic Strassen version is in the algorithms module.

AlphaTensor: decomposition as a game

Finding low-rank decompositions with small coefficients is a huge combinatorial search. Fawzi et al. (2022) turned it into a single-player game, TensorGame:

  • The state is residual tensor St\mat{\mathcal{S}}_t, starting at S0=T\mat{\mathcal{S}}_0 = \mat{\mathcal{T}}.
  • A move chooses a term u∘v∘w\vb{u}\circ\vb{v}\circ\vb{w} with coefficients from a small finite set, such as {−2,−1,0,1,2}\{-2, -1, 0, 1, 2\}, and goes to St+1=St−u∘v∘w\mat{\mathcal{S}}_{t+1} = \mat{\mathcal{S}}_t - \vb{u}\circ\vb{v}\circ\vb{w}.
  • Each move costs −1-1 reward and the game ends at zero tensor (with a penalty if the move limit is exhausted).

Winning in few moves finds a low-rank decomposition, hence an algorithm with few multiplications. The agent uses AlphaZero: a network proposing moves and estimating state value guides Monte Carlo tree search. The action space is gigantic (each term chooses three vectors), far larger than Go’s. Among other results, it found a 4×44\times 4 matrix algorithm using 47 multiplications in modulo-2 arithmetic, fewer than Strassen twice at 49. It is the same framework you build in the reinforcement module, applied to linear algebra.

Fitting CP: alternating least squares

Rank calculation is NP-hard, but fitting a fixed-rank RR CP to data is an ordinary optimization problem:

min⁡A,B,C ∥X−[ ⁣[A,B,C] ⁣]∥F2.\min_{\mat{A}, \mat{B}, \mat{C}}\ \norm{\mat{\mathcal{X}} - [\![\mat{A}, \mat{B}, \mat{C}]\!]}_F^2.

Nonconvex, but beautifully structured: fix two factors and the third is a linear least-squares problem. Two ingredients:

Matricization. Mode-nn matricization X(n)\mat{X}_{(n)} places mode-nn fibers as columns: vectors obtained by fixing all but index nn. For X∈RI×J×K\mat{\mathcal{X}} \in \R^{I\times J\times K}, X(1)∈RI×JK\mat{X}_{(1)} \in \R^{I\times JK} has fiber x:jkx_{:jk} in column j+(k−1)Jj + (k-1)J, similarly X(2)∈RJ×IK\mat{X}_{(2)} \in \R^{J\times IK} and X(3)∈RK×IJ\mat{X}_{(3)} \in \R^{K\times IJ} (Kolda–Bader convention: first remaining index varies fastest). It is a specific tensor reorganization, animated in the final interactive.

Khatri–Rao product. For B∈RJ×R\mat{B} \in \R^{J\times R} and C∈RK×R\mat{C} \in \R^{K\times R}, C⊙B=[c1⊗b1 ⋯ cR⊗bR]∈RJK×R\mat{C}\odot\mat{B} = [\vb{c}_1\otimes\vb{b}_1 \ \cdots\ \vb{c}_R\otimes\vb{b}_R] \in \R^{JK\times R}: column-wise Kronecker product.

Using these, CP is a matrix factorization in each mode:

X(1)=A(C⊙B)⊤,X(2)=B(C⊙A)⊤,X(3)=C(B⊙A)⊤.\mat{X}_{(1)} = \mat{A}(\mat{C}\odot\mat{B})\T, \qquad \mat{X}_{(2)} = \mat{B}(\mat{C}\odot\mat{A})\T, \qquad \mat{X}_{(3)} = \mat{C}(\mat{B}\odot\mat{A})\T.

(Column j+(k−1)Jj + (k-1)J of A(C⊙B)⊤\mat{A}(\mat{C}\odot\mat{B})\T is ∑rar ckrbjr\sum_r\vb{a}_r\,c_{kr}b_{jr}, CP fiber x:jkx_{:jk}.) Thus with fixed B\mat{B} and C\mat{C}, minimizing over A\mat{A} is least squares with matrix C⊙B\mat{C}\odot\mat{B}; normal equations give

A←X(1)(C⊙B)[(C⊤C)∗(B⊤B)]†,\mat{A} \leftarrow \mat{X}_{(1)}(\mat{C}\odot\mat{B})\big[(\mat{C}\T\mat{C}) * (\mat{B}\T\mat{B})\big]^{\dagger},

where ∗* is Hadamard (entrywise) product and †\dagger pseudoinverse. Identity (C⊙B)⊤(C⊙B)=(C⊤C)∗(B⊤B)(\mat{C}\odot\mat{B})\T(\mat{C}\odot\mat{B}) = (\mat{C}\T\mat{C})*(\mat{B}\T\mat{B}), directly from mixed product, avoids forming the large Gram matrix: invert only an R×RR\times R matrix. Product X(1)(C⊙B)\mat{X}_{(1)}(\mat{C}\odot\mat{B}) (MTTKRP) is expensive, O(IJKR)\bigO(IJKR), and can be one einsum on X\mat{\mathcal{X}}, B\mat{B} and C\mat{C} without unfolding.

CP-ALS (alternating least squares) repeats: update A\mat{A}, then B\mat{B} analogously, then C\mat{C}. It is block coordinate descent with exact minimization per block, so error never increases. It does not guarantee a global minimum, speed, or even existence of a minimum.

InteractiveCP fitting and degeneracy
A synthetic users-by-products-by-weeks tensor generated with three patterns (steady purchase, rising trend, four-week cycle) and 5% noise. With R=3R = 3, ALS recovers all three (gray dots and dashes are truth) and error falls to the noise line. With R=1R = 1 or 22 it stalls; with R=4R = 4 or 55 it fits noise. Select border tensor (rank 3, border rank 2) with R=2R = 2: error falls without bottoming out, largest weight λr\lambda_r grows without limit and two components become opposites (congruence near −1-1). Try random starts.

Three reasonable responses to degeneracy: lower rank; add regularization (penalizing ∑r∥ar∥2+∥br∥2+∥cr∥2\sum_r\norm{\vb{a}_r}^2 + \norm{\vb{b}_r}^2 + \norm{\vb{c}_r}^2 prevents exploding weights and makes a minimum exist); or impose meaningful constraints such as nonnegativity, forbidding cancellation and ensuring an approximation solution. More iterations do not help: there is nowhere to converge.

Tucker, HOSVD and tensor train

CP is compact and interpretable, but hard to compute. Tucker sacrifices some compactness for something SVD can compute.

InteractiveUnfolding a tensor
A 3×4×23\times 4\times 2 tensor with entries numbered in vec order. Choose mode nn and unfold: each cube flies to its cell of X(n)\mat{X}_{(n)}, whose columns are mode-nn fibers (selected fiber highlighted in block and matrix). With default numbering, X(1)\mat{X}_{(1)} reads 1,2,3,…1, 2, 3, \dots column by column. Change tensor to see all three unfolding ranks change: Tucker (2, 2, 1) has ranks (2,2,1)(2, 2, 1) although its unfoldings have 8, 6 and 12 columns. Drag to rotate the block.

The three unfolding ranks (r1,r2,r3)=(rank⁡X(1),rank⁡X(2),rank⁡X(3))(r_1, r_2, r_3) = (\rank\mat{X}_{(1)}, \rank\mat{X}_{(2)}, \rank\mat{X}_{(3)}) form X\mat{\mathcal{X}}‘s multilinear rank. Unlike CP rank, it is computed by three matrix SVDs, and each rnr_n is at most CP rank (each rank-one term contributes at most one direction to each unfolding).

To write the decomposition, multiply a tensor by a matrix “in one mode”. The mode-nn product Y=X×nU\mat{\mathcal{Y}} = \mat{\mathcal{X}}\times_n\mat{U} applies U\mat{U} to each mode-nn fiber; in unfoldings, Y(n)=UX(n)\mat{Y}_{(n)} = \mat{U}\mat{X}_{(n)}. In einsum, X×1U\mat{\mathcal{X}}\times_1\mat{U} is einsum("ijk,ai->ajk", X, U), a contraction on the first index.

CP is the special case of diagonal core; Tucker lets each column of U1\mat{U}_1 interact with each column of U2\mat{U}_2 and U3\mat{U}_3 at weight gabcg_{abc}. Kronecker returns in matrix form: X(1)=U1G(1)(U3⊗U2)⊤\mat{X}_{(1)} = \mat{U}_1\mat{G}_{(1)}(\mat{U}_3\otimes\mat{U}_2)\T.

HOSVD does not give the best rank-(r1,r2,r3)(r_1, r_2, r_3) approximation, but is close. De Lathauwer, De Moor and Vandewalle (2000) proved that if σi(n)\sigma_i^{(n)} are singular values of X(n)\mat{X}_{(n)},

∥X−X^HOSVD∥F2≤∑n=13 ∑i>rn(σi(n))2≤3 ∥X−X^oˊptima∥F2.\norm{\mat{\mathcal{X}} - \hat{\mat{\mathcal{X}}}_{\text{HOSVD}}}_F^2 \le \sum_{n=1}^{3}\ \sum_{i > r_n}\big(\sigma_i^{(n)}\big)^2 \le 3\,\norm{\mat{\mathcal{X}} - \hat{\mat{\mathcal{X}}}_{\text{óptima}}}_F^2.

The first inequality is a computable error bound; the second says HOSVD is quasi-optimal, at most factor 3\sqrt{3} (generally N\sqrt{N} for order NN) worse than best. For more, HOOI alternates modes like ALS. Here a minimum exists: tensors with bounded multilinear rank form a closed set, so best Tucker approximation always exists.

Compression. Tucker stores r1r2r3+Ir1+Jr2+Kr3r_1r_2r_3 + Ir_1 + Jr_2 + Kr_3 numbers instead of IJKIJK. For order dd with all ranks rr, the core has rdr^d entries: exponential in order, making Tucker unsuitable for large dd.

Tensor train. Tensor train (TT) avoids that explosion (Oseledets, 2011). Write each entry as a product of small matrices,

xi1i2⋯id=G1[i1] G2[i2]⋯Gd[id],Gk[ik]∈Rrk−1×rk, r0=rd=1,x_{i_1i_2\cdots i_d} = \mat{G}_1[i_1]\,\mat{G}_2[i_2]\cdots\mat{G}_d[i_d], \qquad \mat{G}_k[i_k] \in \R^{r_{k-1}\times r_k},\ r_0 = r_d = 1,

using roughly dnr2dnr^2 parameters instead of ndn^d. TT-SVD obtains them with d−1d - 1 successive SVDs: unfold, truncate, pass the remainder to the next reorganization. Total error is bounded by the square root of the sum of squared truncation errors. Physics calls this a matrix product state.

Lab 2: CP, Strassen and HOSVD from scratch

First, the matrix multiplication tensor and Strassen verification using einsum. The last line checks the factors really form an algorithm: seven multiplications and linear combinations.

[ ]The 2×2 product tensor and Strassen factorsBrowser
def matmul_tensor(n):
    T = np.zeros((n * n, n * n, n * n))
    for i in range(n):
        for j in range(n):
            for k in range(n):
                T[i * n + j, j * n + k, i * n + k] = 1   # a_ij · b_jk contribuye a c_ik
    return T

T = matmul_tensor(2)
# columnas: m1..m7. Filas: (a11, a12, a21, a22), (b11, ...), (c11, ...)
U = np.array([[1, 0, 1, 0, 1, -1, 0], [0, 0, 0, 0, 1, 0, 1], [0, 1, 0, 0, 0, 1, 0], [1, 1, 0, 1, 0, 0, -1]])
V = np.array([[1, 1, 0, -1, 0, 1, 0], [0, 0, 1, 0, 0, 1, 0], [0, 0, 0, 1, 0, 0, 1], [1, 0, -1, 0, 1, 0, 1]])
W = np.array([[1, 0, 0, 1, -1, 0, 1], [0, 0, 1, 0, 1, 0, 0], [0, 1, 0, 1, 0, 0, 0], [1, -1, 1, 0, 0, 1, 0]])
print("Strassen reproduce T:", np.array_equal(np.einsum("pr,qr,sr->pqs", U, V, W), T))

def bilinear_matmul(Am, Bm, U, V, W):
    m = (U.T @ Am.ravel()) * (V.T @ Bm.ravel())     # R multiplicaciones escalares
    return (W @ m).reshape(2, 2)

Am, Bm = rng.normal(size=(2, 2)), rng.normal(size=(2, 2))
print("y multiplica matrices:", np.allclose(bilinear_matmul(Am, Bm, U, V, W), Am @ Bm))
print("tamaño del tensor 3×3:", matmul_tensor(3).shape, "con", int(matmul_tensor(3).sum()), "unos")

Full CP-ALS: matricization, Khatri–Rao and least-squares update. For an exact rank-3 tensor with generic factors, Kruskal uniqueness promises recovered factors equal truth up to ordering and scale.

[ ]CP by alternating least squaresBrowser
def unfold(X, n):
    """Matricización de modo n (convención de Kolda y Bader: columnas = fibras de modo n)."""
    return np.moveaxis(X, n, 0).reshape(X.shape[n], -1, order="F")

def khatri_rao(B, C):
    """C ⊙ B: Kronecker columna a columna, ordenado para encajar con unfold."""
    R = B.shape[1]
    return np.einsum("kr,jr->kjr", C, B).reshape(-1, R)

def cp_full(A, B, C):
    return np.einsum("ir,jr,kr->ijk", A, B, C)

def cp_als(X, R, iters=200, seed=0):
    g = np.random.default_rng(seed)
    F = [g.normal(size=(s, R)) for s in X.shape]
    nX = np.linalg.norm(X)
    hist = []
    for _ in range(iters):
        for n in range(3):
            P, Q = [F[m] for m in range(3) if m != n]
            KR = khatri_rao(P, Q)                    # C ⊙ B para n = 0, C ⊙ A para n = 1...
            V = (P.T @ P) * (Q.T @ Q)                 # Gram de Khatri-Rao = producto de Hadamard
            F[n] = np.linalg.lstsq(V, (unfold(X, n) @ KR).T, rcond=None)[0].T
        hist.append(np.linalg.norm(X - cp_full(*F)) / nX)
    return F, np.array(hist)

X0 = rng.normal(size=(6, 5, 4))
print("columnas de X₍₂₎ = fibras de modo 2:", np.allclose(unfold(X0, 1)[:, 0], X0[0, :, 0]))
A0, B0, C0 = rng.normal(size=(10, 3)), rng.normal(size=(8, 3)), rng.normal(size=(6, 3))
X = cp_full(A0, B0, C0)
print("X₍₁₎ = A (C ⊙ B)ᵀ:", np.allclose(unfold(X, 0), A0 @ khatri_rao(B0, C0).T))
(A, B, C), h = cp_als(X, 3, iters=100)
print("error relativo final con R = 3:", f"{h[-1]:.2e}")
cong = np.abs((A / np.linalg.norm(A, axis=0)).T @ (A0 / np.linalg.norm(A0, axis=0)))
print("mejor |cos| de cada factor recuperado con uno verdadero:", np.round(cong.max(axis=1), 6))

A modest AlphaTensor experiment: does ALS find a rank-7 decomposition of Strassen’s tensor from random starts? And rank 6?

[ ]Searching rank-7 and rank-6 decompositions with ALSBrowser
t0 = time.perf_counter()
for R in [6, 7]:
    errs = [cp_als(T, R, iters=300, seed=s)[1][-1] for s in range(6)]
    print(f"R = {R}: errores finales", np.round(errs, 4))
print(f"({time.perf_counter() - t0:.1f} s)")

With R=7R = 7, several starts reach zero error (real decimals, not Strassen’s ±1\pm 1: decomposition is unique up to a continuous symmetry group and ALS lands elsewhere in that family). Others get stuck in plateaus, ALS “swamps”. With R=6R = 6 all stall at 1/8≈0.3541/\sqrt{8} \approx 0.354, consistent with both rank and border rank being 7. AlphaTensor seeks small integer coefficients, not real factors, yielding exact cheap algorithms: a discrete problem where ALS fails and search succeeds.

Degeneracy in preceding tensor W\mat{\mathcal{W}}, and rank-2 probability π/4\pi/4 for 2×2×22\times 2\times 2. The rank criterion uses Cayley’s hyperdeterminant: a generic real 2×2×22\times 2\times 2 tensor has rank 2 if positive, rank 3 if negative.

[ ]No best rank-2 approximation and typical ranksBrowser
a, b = np.array([1.0, 0.0]), np.array([0.0, 1.0])
o3 = lambda x, y, z: np.einsum("i,j,k->ijk", x, y, z)
Wt = o3(a, a, b) + o3(a, b, a) + o3(b, a, a)               # rango 3
for eps in [1e-1, 1e-2, 1e-3]:
    approx = (o3(a + eps * b, a + eps * b, a + eps * b) - o3(a, a, a)) / eps   # rango ≤ 2
    print(f"ε = {eps:g}: error {np.linalg.norm(Wt - approx):.1e}, coeficientes de tamaño {1 / eps:g}")
(A, B, C), h = cp_als(Wt, 2, iters=2000, seed=1)
lam = np.linalg.norm(A, axis=0) * np.linalg.norm(B, axis=0) * np.linalg.norm(C, axis=0)
print("ALS con R = 2, error tras 10, 100 y 2000 iteraciones:", np.round(h[[9, 99, -1]], 4))
print("pesos de los dos componentes (‖W‖ = 1.73):", np.round(lam, 1))

def hyperdet(t):
    a000, a001, a010, a011, a100, a101, a110, a111 = [t[:, i, j, k] for i in (0, 1) for j in (0, 1) for k in (0, 1)]
    return (a000**2 * a111**2 + a001**2 * a110**2 + a010**2 * a101**2 + a100**2 * a011**2
            - 2 * (a000*a001*a110*a111 + a000*a010*a101*a111 + a000*a100*a011*a111
                   + a001*a010*a101*a110 + a001*a100*a011*a110 + a010*a100*a011*a101)
            + 4 * (a000*a011*a101*a110 + a001*a010*a100*a111))

Z = rng.normal(size=(200_000, 2, 2, 2))
print(f"fracción de rango 2: {(hyperdet(Z) > 0).mean():.4f}   π/4 = {np.pi / 4:.4f}")

HOSVD and its error bound on a noisy tensor with multilinear ranks (3,4,2)(3, 4, 2):

[ ]HOSVD y TuckerBrowser
def hosvd(X, ranks):
    Us = [np.linalg.svd(unfold(X, n), full_matrices=False)[0][:, :r] for n, r in enumerate(ranks)]
    G = np.einsum("ijk,ia,jb,kc->abc", X, *Us)               # G = X ×₁ U₁ᵀ ×₂ U₂ᵀ ×₃ U₃ᵀ
    return G, Us

def tucker_full(G, Us):
    return np.einsum("abc,ia,jb,kc->ijk", G, *Us)

Q = [np.linalg.qr(rng.normal(size=(s, r)))[0] for s, r in [(20, 3), (15, 4), (10, 2)]]
Xt = tucker_full(rng.normal(size=(3, 4, 2)), Q)
Xn = Xt + 0.05 * rng.normal(size=Xt.shape)
print("rangos de los desplegados (sin ruido):", [int(np.linalg.matrix_rank(unfold(Xt, n))) for n in range(3)])
G, Us = hosvd(Xn, (3, 4, 2))
err = np.linalg.norm(Xn - tucker_full(G, Us))
bound = np.sqrt(sum((np.linalg.svd(unfold(Xn, n), compute_uv=False)[r:] ** 2).sum() for n, r in enumerate((3, 4, 2))))
print(f"error HOSVD {err:.4f} ≤ cota {bound:.4f}")
print("números: tensor", Xn.size, "  Tucker", G.size + sum(U.size for U in Us))

TT-SVD on a long “tensorized” vector: 65536=4865536 = 4^8 samples of a smooth function viewed as an order-8 tensor.

[ ]Tensor train by successive SVDsBrowser
def tt_svd(X, rmax):
    dims, cores, r = X.shape, [], 1
    M = X.reshape(r * dims[0], -1)
    for k in range(len(dims) - 1):
        U, s, Vt = np.linalg.svd(M, full_matrices=False)
        rk = min(rmax, len(s))
        cores.append(U[:, :rk].reshape(r, dims[k], rk))
        M = (s[:rk, None] * Vt[:rk]).reshape(rk * dims[k + 1], -1)
        r = rk
    cores.append(M.reshape(r, dims[-1], 1))
    return cores

def tt_full(cores):
    out = cores[0]
    for G in cores[1:]:
        out = np.einsum("...a,abc->...bc", out, G)
    return out.reshape([G.shape[1] for G in cores])

x = np.linspace(0, 1, 4 ** 8)
f = np.sin(7 * x) + 0.3 * np.cos(31 * x) * x
F8 = f.reshape([4] * 8)
for rmax in [2, 4, 6]:
    cores = tt_svd(F8, rmax)
    rel = np.linalg.norm(tt_full(cores) - F8) / np.linalg.norm(F8)
    print(f"rango TT ≤ {rmax}: {sum(G.size for G in cores):>4} números para {F8.size} valores, error relativo {rel:.1e}")

Rank 6 reconstructs exactly, not by accident: sin⁡(7x)\sin(7x) has TT rank 2 (by the sine addition formula, each index “digit” contributes a rotation-matrix factor), xx has rank 2 and cos⁡(31x)\cos(31x) too, so xcos⁡(31x)x\cos(31x) has rank at most 4 and the sum at most 6.

The professional version

What you wrote by hand has direct library equivalents:

From scratchLibrary
kron(A, B)np.kron, scipy.linalg.kron, torch.kron
(A @ X @ B.T).ravel()same: vec trick has no dedicated function, it is the right way to use np.kron
Sylvester by vecscipy.linalg.solve_sylvester (Bartels–Stewart)
khatri_rao, MTTKRPscipy.linalg.khatri_rao(C, B) (arguments in C⊙B\mat{C}\odot\mat{B} order), np.einsum(..., optimize=True)
cp_als, hosvd, tt_svdtensorly.decomposition.parafac, tucker, tensor_train
[ ]Library versions and their correspondenceBrowser
B_, C_ = rng.normal(size=(5, 3)), rng.normal(size=(4, 3))
print("scipy.linalg.khatri_rao(C, B) = nuestro khatri_rao(B, C):", np.allclose(sla.khatri_rao(C_, B_), khatri_rao(B_, C_)))
Xb = rng.normal(size=(30, 40, 50))
Ab, Bb, Cb = rng.normal(size=(30, 6)), rng.normal(size=(40, 6)), rng.normal(size=(50, 6))
m1 = unfold(Xb, 0) @ khatri_rao(Bb, Cb)                       # MTTKRP de modo 1
m2 = np.einsum("ijk,jr,kr->ir", Xb, Bb, Cb, optimize=True)     # un solo einsum: NumPy elige el orden
print("MTTKRP por einsum:", np.allclose(m1, m2))
print(np.einsum_path("ijk,jr,kr->ir", Xb, Bb, Cb, optimize="optimal")[0])

einsum_path shows chosen contraction order as pairs of positions in the operand list (renumbered after each step). Here (1, 2) first joins B\mat{B} and C\mat{C}, forming Khatri–Rao as a 40×50×640\times 50\times 6 tensor (only 1200012000 numbers), then contracts it with X\mat{\mathcal{X}}. The last contraction dominates, O(IJKR)\bigO(IJKR), as when contracting X\mat{\mathcal{X}} with C\mat{C} first: small RR makes forming C⊙B\mat{C}\odot\mat{B} cheap. Avoid unfolding copies of the large tensor; huge or sparse implementations also avoid forming Khatri–Rao.

TensorLy is absent from browser and local lab, but is Python’s reference library and its interface matches your implementation. If you install it (pip install tensorly):

import tensorly as tl
from tensorly.decomposition import parafac, tucker, tensor_train

cp = parafac(tl.tensor(X), rank=3, init="random", n_iter_max=500, tol=1e-10)
weights, factors = cp              # pesos λ_r y la lista [A, B, C]
core, tucker_factors = tucker(tl.tensor(Xn), rank=[3, 4, 2])
tt = tensor_train(tl.tensor(F8), rank=[1, 6, 6, 6, 6, 6, 6, 6, 1])

One detail: tl.unfold orders matricization columns with the last index varying fastest (NumPy row-major), opposite Kolda–Bader, and orders Khatri–Rao accordingly. ALS formulas are identical with factors reversed; mixing conventions is a common mistake combining your code with the library.

Deep learning applications

CP convolution compression. Convolution kernel K∈RT×S×d×d\mat{\mathcal{K}} \in \R^{T\times S\times d\times d} (TT output channels, SS input channels, d×dd\times d filter) is order 4 with TSd2TSd^2 parameters. Approximate it with rank-RR CP, ktsyx≈∑rutr(t)usr(s)uyr(y)uxr(x)k_{tsyx} \approx \sum_r u^{(t)}_{tr}u^{(s)}_{sr}u^{(y)}_{yr}u^{(x)}_{xr}, and convolution becomes four cheap layers: a 1×11\times 1 convolution from SS to RR channels, d×1d\times 1 then 1×d1\times d each acting separately on RR channels, and 1×11\times 1 from RR to TT. This is an extreme depthwise separable convolution. With T=S=256T = S = 256, d=3d = 3 and R=64R = 64, parameters fall from 589824589824 to 64⋅(256+256+3+3)=3315264\cdot(256 + 256 + 3 + 3) = 33152, about 18 times fewer, with operations falling proportionately. Lebedev et al. (2015) fit CP to a trained network and retrain a few epochs to regain lost accuracy.

[ ]Four small convolutions equal one large oneBrowser
from numpy.lib.stride_tricks import sliding_window_view
Tc, Sc, d, R = 8, 6, 3, 4
Ut, Us_, Uy, Ux = rng.normal(size=(Tc, R)), rng.normal(size=(Sc, R)), rng.normal(size=(d, R)), rng.normal(size=(d, R))
Kc = np.einsum("tr,sr,yr,xr->tsyx", Ut, Us_, Uy, Ux)        # núcleo de rango CP R
img = rng.normal(size=(Sc, 12, 12))
patches = sliding_window_view(img, (d, d), axis=(1, 2))      # (S, 10, 10, d, d)
full = np.einsum("tsyx,shwyx->thw", Kc, patches)             # convolución (correlación) completa
z = np.einsum("sr,shw->rhw", Us_, img)                       # 1×1: de S a R canales
z = np.einsum("rhwy,yr->rhw", sliding_window_view(z, d, axis=1), Uy)   # d×1 en cada canal
z = np.einsum("rhwx,xr->rhw", sliding_window_view(z, d, axis=2), Ux)   # 1×d en cada canal
out = np.einsum("tr,rhw->thw", Ut, z)                        # 1×1: de R a T canales
print("cuatro convoluciones pequeñas = una grande:", np.allclose(full, out))
T_, S_, d_, R_ = 256, 256, 3, 64
print(f"parámetros: {T_ * S_ * d_ * d_:,} -> {R_ * (T_ + S_ + 2 * d_):,}")

Degeneracy is no longer a curiosity: a degenerate CP fit yields enormous cancelling factors, numerically fragile and useless for retraining. Monitor weights and congruences or regularize.

Tensor-train dense layers. A 1024×10241024\times 1024 weight matrix can be viewed as order 10 (row and column indices split into five base-4 “digits”) and stored as a TT-matrix with cores rk−1×4×4×rkr_{k-1}\times 4\times 4\times r_k. With ranks 8 this is 16⋅8+3⋅(8⋅16⋅8)+8⋅16=332816\cdot 8 + 3\cdot(8\cdot 16\cdot 8) + 8\cdot 16 = 3328 numbers instead of 10485761048576, about 315 times fewer. Novikov et al. (2015) train such layers directly, backpropagating through cores.

Low rank everywhere. LoRA parameterizes an update as low-rank BA\mat{B}\mat{A}: the matrix version of the same idea. Tensor formats extend it to objects with more than two axes (filters, heads, stacked layers), and Kronecker preconditioners apply it to curvature rather than weights.

Common mistakes

Exercises

NumericKronecker product rank
A\mat{A} has rank 3 and B\mat{B} rank 4. What is the rank of A⊗B\mat{A}\otimes\mat{B}?
NumericKronecker product determinant
A∈R2×2\mat{A} \in \R^{2\times 2} has det⁡A=3\det\mat{A} = 3 and B∈R3×3\mat{B} \in \R^{3\times 3} has det⁡B=2\det\mat{B} = 2. What is det⁡(A⊗B)\det(\mat{A}\otimes\mat{B})?
NumericGrid Laplacian
Let T∈R3×3\mat{T} \in \R^{3\times 3} be tridiagonal with 2 on the diagonal and −1-1 on both subdiagonals, and L=I3⊗T+T⊗I3\mat{L} = \mat{I}_3\otimes\mat{T} + \mat{T}\otimes\mat{I}_3 the discrete Laplacian of a 3×33\times 3 grid. What is L\mat{L}'s smallest eigenvalue?
QuizKronecker and NumPy order
X has shape (n, q) and x = X.ravel() (row-major, NumPy's default). A has shape (m, n) and B has shape (p, q). Which expressions equal np.kron(A, B) @ x?

More than one answer may be correct.

CodeMultiply by A ⊗ B without forming it
Implement kron_matvec(A, B, x) returning np.kron(A, B) @ x without forming the Kronecker product. A has shape (m, n), B shape (p, q) and x is length n * q in np.kron order. Result has length m * p. One test uses sizes where A⊗B\mat{A}\otimes\mat{B} would occupy 48 GB.
import numpy as np

def kron_matvec(A, B, x):
  # tu código: reorganiza x como matriz y usa dos productos pequeños
  return np.zeros(A.shape[0] * B.shape[0])
Shift+Enter to run
QuizWhat fails for tensors
Which matrix-rank properties cease to hold for order-3 tensors?

More than one answer may be correct.

NumericStrassen twice
How many scalar multiplications multiply two 4×44\times 4 matrices by recursive Strassen (on 2×22\times 2 blocks, then within each block product)?
NumericTucker storage
A 100×100×100100\times 100\times 100 tensor is approximated by Tucker ranks (10,10,10)(10, 10, 10). How many numbers are stored (core plus factors)?
QuizDiagnosing a CP fit
You fit CP-ALS with R=5R = 5 to a data tensor of norm 20. After 2000 iterations error still falls very slowly, two components have weights λr\lambda_r 400 and 390, and congruence −0.98-0.98. Which conclusions or actions are reasonable?

More than one answer may be correct.

CodeMatricize with the correct convention
Implement unfold(X, n) returning mode-n matricization (n zero-based) of an order-3 tensor X, in Kolda–Bader convention: the row is mode n's index and the column traverses the other two indices with the first varying fastest. For example, with n = 0 and X of shape (I, J, K), entry X[i, j, k] goes to row i and column j + J * k; with n = 2, to row k and column i + I * j.
import numpy as np

def unfold(X, n):
  # mueve el modo n al principio... ¿en qué orden se aplanan los otros dos?
  return np.moveaxis(X, n, 0).reshape(X.shape[n], -1)
Shift+Enter to run

Summary

  • A⊗B=[aijB]\mat{A}\otimes\mat{B} = [a_{ij}\mat{B}] is a mosaic of B\mat{B} copies. Mixed product (A⊗B)(C⊗D)=AC⊗BD(\mat{A}\otimes\mat{B})(\mat{C}\otimes\mat{D}) = \mat{A}\mat{C}\otimes\mat{B}\mat{D} factors everything: inverse, Cholesky and SVD are Kronecker products of factor versions; eigenvalues and singular values are products; ranks and condition numbers multiply.
  • Vec trick vec⁡(AXB)=(B⊤⊗A)vec⁡(X)\vecop(\mat{A}\mat{X}\mat{B}) = (\mat{B}\T\otimes\mat{A})\vecop(\mat{X}) turns matrix equations (Sylvester, Lyapunov) into linear systems and conversely applies or solves with A⊗B\mat{A}\otimes\mat{B} in O(n3)\bigO(n^3) without forming it. K-FAC and Shampoo work this way. NumPy uses rows: kron(A, B) @ X.ravel() == (A @ X @ B.T).ravel().
  • Tensor rank is defined like matrix rank but behaves differently: it can exceed dimensions, depends on field, is NP-hard to compute, and a best rank-kk approximation may not exist (border rank). In return CP is essentially unique under mild conditions (Kruskal), making factors interpretable.
  • Minimum multiplications in a bilinear matrix-product algorithm equal the product tensor’s rank: Strassen is a rank-7 decomposition of the 4×4×44\times 4\times 4 tensor, and AlphaTensor searches decompositions by repeatedly subtracting rank-one terms.
  • CP-ALS alternates exact least squares using X(1)=A(C⊙B)⊤\mat{X}_{(1)} = \mat{A}(\mat{C}\odot\mat{B})\T; monitor weights and congruences for degeneracy. Tucker/HOSVD uses SVD of each unfolding and is quasi-optimal; tensor train avoids core explosion at high orders. Both compress network layers.
Key idea
A huge Kronecker-structured matrix and a low-rank tensor teach the same lesson: do not materialize the large object; work with small factors. For matrices, mixed product and vec make this exact and cheap; for tensors, factorization is more powerful (unique, interpretable, counts multiplications) and more treacherous (no SVD to calculate it, no guarantee the optimum exists).