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
- 02Tensor as a multidimensional arrayTensor product and multilinear mapsTensor contractionEinstein notation and einsumTensor reshaping and axis permutationSingular value decompositionLow-rank approximationRankLeast squaresEigenvalues and eigenvectorsMatrix multiplication
- 06Coordinate descentBlock coordinate descent and alternating minimization
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 , the Fisher information matrix with respect to has entries: with roughly numbers, impossible to store, much less invert. K-FAC approximates it by with of size and of size ; Shampoo uses a similarly structured preconditioner. Both are feasible because can be inverted and applied using only factors.
- Separable filters. Blurring image with a 2D Gaussian filter equals filtering columns then rows: , where is the 1D filter matrix. As a linear map on stacked pixels, it is , but nobody forms it.
- Separable covariances. If field (locations by times) has noninteracting spatial covariance and temporal covariance , covariance of is . Likewise a Gaussian process on a grid with product kernel has a covariance matrix given by a Kronecker product of small matrices.
Kronecker product 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 in 1969; in 2022 AlphaTensor searched for new decompositions with an AlphaZero-style agent.
Intuition: a mosaic of copies
Take two small matrices,
Their Kronecker product is the matrix obtained by replacing each entry of with block :
It is a mosaic: ‘s shape repeats in each block and decides each copy’s brightness and sign. Edit both matrices in the interactive to see which entry scales each block.
Three interactive observations the rest of this section proves:
- Eigenvalues of are the six products . For the matrices above, and , giving spectrum .
- Traces multiply and determinants almost do: , with crossed exponents.
- 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 stacks : all products , like tensor product , flattened into a vector. The underlying idea: is tensor product in coordinates, with a specific ordering of index pairs (‘s index varies slowly and ‘s quickly).
Property 3 does the work. Its blockwise proof is worth doing once.
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 .
Proof
For eigenvectors, by mixed product for column vectors. This does not prove the full spectrum (with multiplicities and for nondiagonalizable ), so use Schur forms and , with unitary and upper-triangular having eigenvalues on the diagonal. Mixed product gives
with unitary . is upper triangular (each block with is zero and diagonal blocks triangular), with diagonal . Similarity preserves eigenvalues, proving 1. Trace is the sum of , factoring as , and determinant is their product: each appears times and each , times. For 3, mixed product gives the factorization; and have orthonormal columns (again mixed product, ); and is diagonal with entries . Rank counts nonzero products, .
∎An equally useful additive relative is the Kronecker sum of and : . Since terms commute and share eigenvectors (when and are diagonalizable), eigenvalues are sums . This always holds: using Schur forms above, is similar to upper-triangular with diagonal . The classic example is a discrete Laplacian on an grid: with the 1D Laplacian tridiagonal ; 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 , and 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 , and conversely allow applying a giant Kronecker matrix with two small matrix products.
Step 1 of 3. Where do you start?
Never materialize
Read right to left, the vec trick is an algorithm. For , has entries and multiplying it by a vector costs multiplications. Instead,
costs two products, about multiplications, and no more memory than . With , the dense matrix occupies 8 TB in double precision; the trick uses 8 MB.
The same holds for solving. If and are invertible,
so factor and separately (LU, Cholesky or appropriate method): cost instead of for elimination on an matrix. And since when and , 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 , with , and , appears in control theory, linear-system stability (the Lyapunov equation is the case) and some matrix-gradient derivations. Applying vec,
The system matrix is Kronecker sum (factors in that order), with eigenvalues . Hence a unique solution exists if and only if and share no eigenvalue. For small sizes solve the system directly; for medium sizes use Bartels–Stewart (each factor’s Schur form and substitution), behind scipy.linalg.solve_sylvester, costing rather than .
K-FAC and Shampoo in one line
Now read K-FAC’s approximation. For linear layer , one example’s loss gradient with respect to is , with . Since (vec trick with , and ), layer Fisher is
Approximation exchanges expectation and product as if activations and backpropagated signals were independent (Martens and Grosse, 2015). Then natural-gradient direction uses vec: , inverting one and one matrix. Shampoo (Gupta, Koren and Singer, 2018) accumulates and , updating with , which vec shows applies preconditioner to .
Lab 1: Kronecker without Kronecker
Start with the Kronecker product as a mosaic and check the preceding properties.
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 .
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 with LU factorizations of the factors versus elimination on the matrix:
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:
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 , and natural-gradient direction needs only and inverses.
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 is only an approximation; K-FAC buys invertibility of the approximation.
Rank-one tensors and tensor rank
Change questions. A rank- matrix is a sum of outer products and no fewer. Ask the same for an order-3 tensor.
For matrices (), this is ordinary rank. For tensors, the definition is the same but behavior differs.
Uniqueness, the big advantage. A low-rank matrix factorization is never unique: and also work for any invertible . 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 , the greatest such that any columns of are linearly independent.
For example, generic , and factors each have Kruskal rank 3 and : 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.
- Rank can exceed every dimension. The tensor has rank 3, greater than any side.
- It depends on the field. The tensor with frontal slices and rotation has rank 3 over and rank 2 over : over , diagonalizes with eigenvalues in the same basis as , giving two terms. Matrix rank is the same over and .
- There is no unique generic rank over . A tensor with Gaussian entries has rank 2 with probability and rank 3 with probability ; neither is almost sure, unlike a random matrix’s full rank. The lab checks this by simulation.
- Calculating it is hard. Deciding whether an order-3 tensor has rank at most is NP-complete over finite fields and NP-hard over (Håstad, 1990); Hillar and Lim (2013) extend hardness to and and nearly all natural tensor problems. Matrices need only Gaussian elimination.
- A best rank- 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- approximation exists by truncating the SVD. Not for tensors. Take independent and rank-3 tensor
For every , tensor
has rank at most 2 (difference of two rank-one tensors). Expand the cube: , so . Rank-2 approximation error for can be arbitrarily small but never zero: the infimum is unattained and no best rank-2 approximation exists. The cost: both terms have coefficients , exploding while nearly cancelling. 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 matrices,
is a bilinear map: each sums products of one entry and one entry. Any bilinear map is described by tensor : is the coefficient of in , with indexing the four entries of , and . For matrix multiplication, has 64 cells, exactly 8 ones (one per ) and zeros elsewhere.
Proof
Substitute in : . The algorithm works for all matrices if and only if each coefficient matches matrix product coefficient , i.e. for all , the stated tensor equality. Additions and multiplication by constants do not count as multiplications between data.
∎The school algorithm uses 8 obvious terms, one one each: rank . Strassen (1969) found seven:
with , , and . Each is rank-one tensor with entries in ; their sum is .
Why save one multiplication out of eight? The algorithm does not use commutativity of entries: and may be blocks. Split a matrix into blocks of , apply Strassen’s seven block products, recurse. Scalar multiplication count is versus . Generally, if the product tensor has rank , recursion gives ; 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 , starting at .
- A move chooses a term with coefficients from a small finite set, such as , and goes to .
- Each move costs 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 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 CP to data is an ordinary optimization problem:
Nonconvex, but beautifully structured: fix two factors and the third is a linear least-squares problem. Two ingredients:
Matricization. Mode- matricization places mode- fibers as columns: vectors obtained by fixing all but index . For , has fiber in column , similarly and (Kolda–Bader convention: first remaining index varies fastest). It is a specific tensor reorganization, animated in the final interactive.
Khatri–Rao product. For and , : column-wise Kronecker product.
Using these, CP is a matrix factorization in each mode:
(Column of is , CP fiber .) Thus with fixed and , minimizing over is least squares with matrix ; normal equations give
where is Hadamard (entrywise) product and pseudoinverse. Identity , directly from mixed product, avoids forming the large Gram matrix: invert only an matrix. Product (MTTKRP) is expensive, , and can be one einsum on , and without unfolding.
CP-ALS (alternating least squares) repeats: update , then analogously, then . 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.
Three reasonable responses to degeneracy: lower rank; add regularization (penalizing 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.
The three unfolding ranks form ‘s multilinear rank. Unlike CP rank, it is computed by three matrix SVDs, and each 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- product applies to each mode- fiber; in unfoldings, . In einsum, 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 interact with each column of and at weight . Kronecker returns in matrix form: .
HOSVD does not give the best rank- approximation, but is close. De Lathauwer, De Moor and Vandewalle (2000) proved that if are singular values of ,
The first inequality is a computable error bound; the second says HOSVD is quasi-optimal, at most factor (generally for order ) 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 numbers instead of . For order with all ranks , the core has entries: exponential in order, making Tucker unsuitable for large .
Tensor train. Tensor train (TT) avoids that explosion (Oseledets, 2011). Write each entry as a product of small matrices,
using roughly parameters instead of . TT-SVD obtains them with 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.
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.
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?
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 , several starts reach zero error (real decimals, not Strassen’s : decomposition is unique up to a continuous symmetry group and ALS lands elsewhere in that family). Others get stuck in plateaus, ALS “swamps”. With all stall at , 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 , and rank-2 probability for . The rank criterion uses Cayley’s hyperdeterminant: a generic real tensor has rank 2 if positive, rank 3 if negative.
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 :
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: samples of a smooth function viewed as an order-8 tensor.
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: has TT rank 2 (by the sine addition formula, each index “digit” contributes a rotation-matrix factor), has rank 2 and too, so has rank at most 4 and the sum at most 6.
The professional version
What you wrote by hand has direct library equivalents:
| From scratch | Library |
|---|---|
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 vec | scipy.linalg.solve_sylvester (Bartels–Stewart) |
khatri_rao, MTTKRP | scipy.linalg.khatri_rao(C, B) (arguments in order), np.einsum(..., optimize=True) |
cp_als, hosvd, tt_svd | tensorly.decomposition.parafac, tucker, tensor_train |
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 and , forming Khatri–Rao as a tensor (only numbers), then contracts it with . The last contraction dominates, , as when contracting with first: small makes forming 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 ( output channels, input channels, filter) is order 4 with parameters. Approximate it with rank- CP, , and convolution becomes four cheap layers: a convolution from to channels, then each acting separately on channels, and from to . This is an extreme depthwise separable convolution. With , and , parameters fall from to , 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.
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 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 . With ranks 8 this is numbers instead of , 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 : 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
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.
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 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])More than one answer may be correct.
More than one answer may be correct.
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)Summary
- is a mosaic of copies. Mixed product 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 turns matrix equations (Sylvester, Lyapunov) into linear systems and conversely applies or solves with in 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- 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 tensor, and AlphaTensor searches decompositions by repeatedly subtracting rank-one terms.
- CP-ALS alternates exact least squares using ; 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.