Foundations to Frontier
Tests
A. Mathematical Foundations › A2 Linear Algebra › Matrices

Hadamard and Kronecker Products, and Broadcasting

Element-wise products, "every block times every block" products, and the NumPy rule that lets arrays of different shapes work together. Masks, gates, normalisation, Kronecker-factored optimisers and batched tensor code all rest on these.

Level 0: Foundation

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

Multiplying box by box

Two price lists for the same shop: the old prices and a “discount factor” for each item. To get the new prices, you multiply each item’s price by its own factor, box by box. That’s the Hadamard product, nothing more.

One number for everyone

“Add ₹10 to every price.” You don’t need a whole table of 10s. You just say “+10” and it’s applied everywhere. Computers do the same thing, and it’s called broadcasting.

Tiling a pattern

Take a small 2 × 2 tile pattern and stamp it in every square of a 3 × 3 grid, scaling it by the number in that square. You get a 6 × 6 picture. Making a big pattern out of “every square times the tile” is the Kronecker product.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Prices [2, 3] and factors [4, 5], box by box. The first new price?
  2. 2. 'Add 10 to every price' without writing a table of 10s is…
  3. 3. A 2 × 2 tile stamped into every square of a 3 × 3 grid makes how many cells?

Level 1: Beginner

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

Hadamard (element-wise) product

A⊙B=(1234)⊙(5678)=(5122132)A\odot B = \begin{pmatrix}1&2\\3&4\end{pmatrix}\odot\begin{pmatrix}5&6\\7&8\end{pmatrix} = \begin{pmatrix}5&12\\21&32\end{pmatrix}

It needs the same shape. In NumPy and PyTorch it’s A * B. Matrix multiplication is A @ B, which is a completely different operation. Mixing them up is a classic bug.

Broadcasting, informally

np.array([1, 2, 3]) + 10 gives [11, 12, 13]. A column of shape (3,1)(3,1) plus a row of shape (1,4)(1,4) gives a full 3×43\times4 table, where entry (i,j)(i,j) is “row value + column value”, like an addition table.

Broadcasting checker
dim (from right)21
A31
B14
result34
✅ Compatible. Result shape: (3, 4), with 12 elements.
Rule: line the shapes up from the right. Each pair of sizes must be equal, or one of them must be 1 (or missing).
📝 Quick check (Level 1)
0/3 answered
  1. 1. In NumPy, A * B for two matrices computes…
  2. 2. Shape of (3, 1) + (1, 4)?
  3. 3. Shape of (5, 3) + (3,)?

Level 2: Intermediate

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

The broadcasting rule, precisely

Line the shapes up from the right. For each position, the sizes must be equal, or one of them must be 1 (or missing). The result takes the larger size. Sizes of 1 are “stretched” without copying memory.

Shapes Result
(3,4) + (4,) (3,4): add a vector to every row
(3,4) + (3,) ❌ error: aligned from the right, 4 ≠ 3. Use (3,1) instead
(4,1,3) + (2,1) (4,2,3)
(B,H,T,T) + (1,1,T,T) (B,H,T,T): one attention mask for every batch item and head
🐍 Exercise 1: implement the broadcasting rule
Return the broadcast result shape, or raise ValueError. The tests compare with np.broadcast_shapes.

The Kronecker product

A⊗B=(a11B⋯a1nB⋮⋮am1B⋯amnB)∈Rmp×nqA\otimes B = \begin{pmatrix}a_{11}B & \cdots & a_{1n}B\\ \vdots & & \vdots\\ a_{m1}B & \cdots & a_{mn}B\end{pmatrix} \in \mathbb{R}^{mp\times nq}

For A=(1234)A = \begin{pmatrix}1&2\\3&4\end{pmatrix} and B=(0110)B = \begin{pmatrix}0&1\\1&0\end{pmatrix}, it’s a 4×44\times4 matrix built from the blocks 1B,2B,3B,4B1B, 2B, 3B, 4B.

Where they’re used

Operation Use
Hadamard ⊙\odot masks (dropout, attention masks, padding), gates in LSTMs, GRUs and GLU/SwiGLU, element-wise activations and their gradients, per-feature scaling
Broadcasting adding biases, standardizing columns (X−μ)/σ(X - \boldsymbol\mu)/\boldsymbol\sigma, pairwise distances, batched operations everywhere
Kronecker ⊗\otimes separable 2-D filters, multi-dimensional grids, covariance of matrix-valued data, the K-FAC optimizer, quantum computing
Common mistake

Broadcasting is powerful but silent. y.shape == (n,) minus pred.shape == (n,1) gives an n×nn\times n matrix instead of an error, a famous source of wrong losses. Always check shapes (A1-7).

📝 Quick check (Level 2)
0/3 answered
  1. 1. Shape of A ⊗ B for 2 × 2 and 3 × 3?
  2. 2. (4, 1, 3) + (2, 1) → ?
  3. 3. An LSTM gate multiplies a signal by values in (0, 1) using…

Level 3: Advanced

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

Kronecker identities

(A⊗B)(C⊗D)=(AC)⊗(BD),(A⊗B)−1=A−1⊗B−1,(A⊗B)⊤=A⊤⊗B⊤(A\otimes B)(C\otimes D) = (AC)\otimes(BD), \qquad (A\otimes B)^{-1} = A^{-1}\otimes B^{-1}, \qquad (A\otimes B)^\top = A^\top\otimes B^\top
tr⁡(A⊗B)=tr⁡Atr⁡B,rank⁡(A⊗B)=rank⁡Arank⁡B,det⁡(A⊗B)=(det⁡A)q(det⁡B)m\operatorname{tr}(A\otimes B) = \operatorname{tr}A\operatorname{tr}B, \qquad \operatorname{rank}(A\otimes B) = \operatorname{rank}A\operatorname{rank}B, \qquad \det(A\otimes B) = (\det A)^q(\det B)^m

(for A∈Rm×mA\in\mathbb{R}^{m\times m} and B∈Rq×qB\in\mathbb{R}^{q\times q}). The eigenvalues of A⊗BA\otimes B are all the products λiμj\lambda_i\mu_j.

The vec trick

Stacking the columns of XX into a vector vec⁡(X)\operatorname{vec}(X) turns a matrix equation into an ordinary linear system:

vec⁡(AXB)=(B⊤⊗A)vec⁡(X)\operatorname{vec}(AXB) = (B^\top\otimes A)\operatorname{vec}(X)

That’s how Sylvester and Lyapunov equations from control theory (S2), AX+XB=CAX + XB = C, become (I⊗A+B⊤⊗I)vec⁡X=vec⁡C(I\otimes A + B^\top\otimes I)\operatorname{vec}X = \operatorname{vec}C. The other way round, it lets you multiply by a giant Kronecker matrix without forming it.

The Schur product theorem

Theorem (Schur, 1911)

If AA and BB are symmetric positive semidefinite, so is A⊙BA\odot B.

Proof sketch. A⊗BA\otimes B is PSD (its eigenvalues are products of non-negative numbers), and A⊙BA\odot B is a principal submatrix of A⊗BA\otimes B: pick the rows and columns indexed by pairs (i,i)(i,i). Principal submatrices of PSD matrices are PSD. ∎ In ML, this means the product of two valid kernels is a valid kernel, a basic rule for building Gaussian-process and SVM kernels (B3, I2).

Exercise 3.1: A is 2 × 3, X is 3 × 4, B is 4 × 5. What size is the Kronecker matrix in vec(AXB) = (Bᵀ ⊗ A) vec(X)?

B⊤B^\top is 5×45\times4 and AA is 2×32\times3, so B⊤⊗AB^\top\otimes A is (5⋅2)×(4⋅3)=10×12(5\cdot2)\times(4\cdot3) = 10\times12. It maps vec⁡X∈R12\operatorname{vec}X\in\mathbb{R}^{12} to vec⁡(AXB)∈R10\operatorname{vec}(AXB)\in\mathbb{R}^{10}.

📝 Quick check (Level 3)
0/3 answered
  1. 1. rank A = 2 and rank B = 3. rank(A ⊗ B)?
  2. 2. tr A = 3 and tr B = 4. tr(A ⊗ B)?
  3. 3. The product of two valid kernel matrices, element-wise, is…

Level 4: Expert

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

Kronecker-factored curvature: K-FAC

Natural-gradient and second-order optimizers need the curvature (Fisher) matrix of the weights. For a 1000×10001000\times1000 layer that’s a 106×10610^6\times10^6 matrix: impossible. K-FAC (Martens and Grosse, 2015) approximates each layer’s block as a Kronecker product A⊗GA\otimes G of two small matrices (input-activation and output-gradient covariances). Thanks to (A⊗G)−1=A−1⊗G−1(A\otimes G)^{-1} = A^{-1}\otimes G^{-1} and the vec trick, inverting it only needs the two small inverses. Shampoo (Gupta et al., 2018), which has performed strongly in recent optimizer benchmarks, uses a similar Kronecker structure (A6).

🐍 Exercise 2 (research): multiply by a Kronecker matrix without building it
Implement (A ⊗ B) vec(X) both ways, by forming np.kron and with vec(B X Aᵀ). Compare the results and the memory.

Element-wise structure in modern architectures

  • Gating. GLU-style feed-forward layers (Shazeer, 2020), as used in many modern LLMs, compute (xW)⊙σ(xV)(\mathbf xW)\odot\sigma(\mathbf xV): one path decides how much of the other to let through.
  • Masks. Causal attention adds a broadcast mask of −∞-\infty before the softmax, and dropout multiplies by a random 0/1 mask.
  • Robotics and controls. Multi-dimensional grids for value functions and occupancy maps are built with Kronecker or broadcast structure. The covariance of a stack of independent identical sensors is I⊗ΣI\otimes\Sigma, which keeps multi-sensor fusion cheap.

References

  1. L. Kronecker (c. 1866). Lectures; the product was studied earlier by J. G. Zehfuss (1858), “Über eine gewisse Determinante.” Zeitschrift für Mathematik und Physik, 3.
  2. I. Schur (1911). “Bemerkungen zur Theorie der beschränkten Bilinearformen mit unendlich vielen Veränderlichen.” Journal für die reine und angewandte Mathematik, 140.
  3. C. Van Loan (2000). “The ubiquitous Kronecker product.” Journal of Computational and Applied Mathematics, 123.
  4. J. Martens and R. Grosse (2015). “Optimizing neural networks with Kronecker-factored approximate curvature.” ICML.
  5. V. Gupta, T. Koren, Y. Singer (2018). “Shampoo: Preconditioned stochastic tensor optimization.” ICML.
  6. N. Shazeer (2020). “GLU variants improve Transformer.” arXiv:2002.05202.
  7. NumPy documentation, “Broadcasting.” numpy.org.