LINEAR ALGEBRA / 3. MATRIX MULTIPLICATION
Matrix Multiplication
Composition of transformations — not just row × column
EXPLANATION
Matrix multiplication is the composition of two linear transformations. A @ B means "first apply B, then apply A." Three ways to think about matrix multiplication: 1. Row × column: C[i,j] = Σₖ A[i,k] × B[k,j] ← mechanical 2. Transformation composition: first B, then A ← geometric (3B1B) 3. Column combinations: each column of AB is a linear combination of columns of A ← algebraic Rules: • (m×k) @ (k×n) = (m×n) — inner dimensions must match • AB ≠ BA — order matters! Transformations don't commute • (AB)C = A(BC) — associative • A(B+C) = AB + AC — distributive In deep learning, the entire forward pass is just chained matrix multiplications: Layer 1: Z₁ = X @ W₁ + b₁ Layer 2: Z₂ = A₁ @ W₂ + b₂ ... Output: ŷ = Aₙ₋₁ @ Wₙ + bₙ The gradient of a matrix multiplication: If Z = X @ W, then: • dL/dW = Xᵀ @ dL/dZ • dL/dX = dL/dZ @ Wᵀ
DIAGRAM
Matrix multiplication: A(m×k) @ B(k×n) = C(m×n)
A = [[1,2], B = [[5,6,7],
[3,4]] [8,9,10]]
C[0,0] = row0(A) · col0(B) = 1*5 + 2*8 = 21
C[0,1] = row0(A) · col1(B) = 1*6 + 2*9 = 24
C[1,0] = row1(A) · col0(B) = 3*5 + 4*8 = 47
Dimensions: (2×2) @ (2×3) = (2×3) ✓
Batch matrix multiply (3D tensors):
(batch, seq, d_model) @ (d_model, d_k) = (batch, seq, d_k)
This is exactly the Q, K, V projections in attention!CODE