Linear Algebra

Dive into Deep Learning · §1.3

Linear Algebra: The Computational Engine of Deep Learning
tensors & symmetry · axis reductions · projections & matrix products · norms · spectral dynamics

Why Linear Algebra Powers Deep Learning

Motivation

  • Alternating linear and nonlinear maps: Every dense, convolutional, and attention layer alternates between linear transformations (\mathbf{O} = \mathbf{X}\mathbf{W} + \mathbf{b}) and nonlinear activations.
  • From single vectors to hardware batches: Stacking 256 flattened Fashion-MNIST images into \mathbf{X} \in \mathbb{R}^{256 \times 784} and 10 class templates into \mathbf{W} \in \mathbb{R}^{784 \times 10} runs 256 evaluations as one matrix product on GPU Tensor Cores.
  • Predictable shapes and cost: Output shape (256, 10) and work (2 \times 256 \times 784 \times 10 \approx 4.0 \times 10^6\text{ FLOPs}) are known before execution.

Scalars, Vectors, and Dimensionality vs. Tensor Order

Building Blocks

  • Scalars (x \in \mathbb{R}): 0^\textrm{th}-order tensors with empty shape () (e.g., loss \mathcal{L} or learning rate \eta).
  • Vectors (\mathbf{x} \in \mathbb{R}^d): 1^\textrm{st}-order tensors of shape (d,), treated mathematically as column vectors \mathbf{x} = [x_1, \ldots, x_d]^\top.
  • Terminology trap: A vector’s dimensionality d is its length along axis 0 (len(x)), whereas a tensor’s order (rank) is its number of axes (ndim). A 784-D vector is a 1^\textrm{st}-order tensor.
x = torch.tensor(3.0)
x, x.shape
(tensor(3.), torch.Size([]))
x = torch.arange(3, dtype=torch.float32)
x
tensor([0., 1., 2.])
len(x), x.shape
(3, torch.Size([3]))

Matrices, Transposition, and Symmetry

2D Representations

  • Design matrices (\mathbf{X} \in \mathbb{R}^{n \times d}): Store one example per row i and one feature per column j.
  • Transpose ([\mathbf{A}^\top]_{ij} = a_{ji}): Reflects entries across the main diagonal, turning (m, n) \to (n, m).
  • Symmetric (\mathbf{S} = \mathbf{S}^\top): Covariances \frac{1}{n}\mathbf{X}^\top\mathbf{X} and Hessians \nabla^2 \mathcal{L}.
A.T
tensor([[0., 3.],
        [1., 4.],
        [2., 5.]])

Higher-Order Tensors and Elementwise (Hadamard) Arithmetic

Tensors & Hadamard Product

  • Higher-order tensors: 3D token sequences (B, T, d) and 4D images (256, 1, 28, 28) unroll to 2D matrices via reshape(256, -1).
  • Hadamard product (\mathbf{A} \odot \mathbf{B}, A * B): Multiplies matching entries [\mathbf{A} \odot \mathbf{B}]_{ij} = a_{ij} b_{ij} for gating (LSTMs, SwiGLU), distinct from matrix product A @ B.
A * A
tensor([[ 0.,  1.,  4.],
        [ 9., 16., 25.]])

Axis Reductions: Collapsing Dimensions

Reductions

  • Reductions (.sum(), .mean()) aggregate entries along a chosen axis and remove that axis from the shape:
    • All axes (A.sum()): collapses (2, 3) -> (), a scalar.
    • Down rows (axis=0): c_j = \sum_{i=1}^m a_{ij} leaves column totals of shape (3,).
    • Across columns (axis=1): r_i = \sum_{j=1}^n a_{ij} leaves row totals of shape (2,).
A.sum(), A.sum(axis=0), A.sum(axis=1)
(tensor(15.), tensor([3., 5., 7.]), tensor([ 3., 12.]))

Non-Reduction Sums (keepdims=True) and Broadcasting Normalization

Reduction + Broadcasting

  • Why A / A.sum(axis=1) fails: Dividing (2, 3) by (2,) right-aligns as (2, 3) vs. (1, 2)—trailing dimensions 3 \neq 2 clash.
  • keepdims=True retains length 1 ((2, 1)): Now A / sum_A broadcasts across columns so each row sums to 1 (softmax, attention).
  • Centering \mathbf{X} \in \mathbb{R}^{256 \times 784}: Per-pixel means (axis=0, (784,)) broadcast directly; per-image means (axis=1, (256, 1)) need keepdims=True (LayerNorm).
sum_A = A.sum(axis=1, keepdims=True)
sum_A, sum_A.shape
(tensor([[ 3.],
         [12.]]),
 torch.Size([2, 1]))
A / sum_A
tensor([[0.0000, 0.3333, 0.6667],
        [0.2500, 0.3333, 0.4167]])

The Dot Product: Weighted Sums and Geometric Projection

Inner Products

  • Given \mathbf{x}, \mathbf{y} \in \mathbb{R}^d, their dot product (inner product) sums the products of corresponding coordinates: \mathbf{x}^\top \mathbf{y} = \langle \mathbf{x}, \mathbf{y} \rangle = \sum_{i=1}^{d} x_i y_i = \|\mathbf{x}\|_2 \|\mathbf{y}\|_2 \cos\theta
  • Deep learning role: A single neuron’s pre-activation \mathbf{w}^\top \mathbf{x} + b is an offset dot product; when w_i \geq 0 and \sum_i w_i = 1, \mathbf{w}^\top \mathbf{x} computes a convex weighted average.
y = torch.ones(3)
x, y, torch.dot(x, y)
(tensor([0., 1., 2.]), tensor([1., 1., 1.]), tensor(3.))
image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/
torch.sum(x * y)
tensor(3.)

Cosine Similarity and the Cauchy–Schwarz Inequality

Angles in High Dimensions

  • Dividing by Euclidean lengths defines cosine similarity in any dimension d: \cos\theta = \frac{\mathbf{x}^\top \mathbf{y}}{\|\mathbf{x}\|_2 \|\mathbf{y}\|_2} \in [-1, 1]
  • Scale invariance: Rescaling brightness or embedding magnitude (2 * x) leaves \cos\theta unchanged—making it the workhorse similarity score for token, image, and retrieval embeddings.
  • Cauchy–Schwarz (|\mathbf{x}^\top\mathbf{y}| \leq \|\mathbf{x}\|_2\|\mathbf{y}\|_2): Follows directly from 0 \leq \|\mathbf{u} \mp \mathbf{v}\|_2^2 = 2 \mp 2\mathbf{u}^\top\mathbf{v} on unit vectors \mathbf{u}, \mathbf{v}.

def cosine(x, y):
    return torch.dot(x, y) / (torch.linalg.vector_norm(x) *
                              torch.linalg.vector_norm(y))

x, y = torch.tensor([1.0, 1, 1, 1]), torch.tensor([1.0, 1, 1, -1])
cosine(x, y), cosine(2 * x, y), torch.acos(cosine(x, y))
(tensor(0.5000), tensor(0.5000), tensor(1.0472))

Matrix–Vector Products: Linear Maps on Feature Spaces

Matrix–Vector Products

  • A matrix \mathbf{A} \in \mathbb{R}^{m \times n} defines a linear map \mathbb{R}^n \to \mathbb{R}^m, with two complementary views:
    1. Row-wise (m parallel dot products): [\mathbf{A}\mathbf{x}]_i = \mathbf{a}_i^\top \mathbf{x} projects input \mathbf{x} onto each of the m row templates of \mathbf{A}.
    2. Column-wise (basis combination): \mathbf{A}\mathbf{x} = \sum_{j=1}^n x_j \mathbf{a}_{:,j} forms a linear combination of the columns of \mathbf{A} weighted by the coordinates of \mathbf{x}.
A.shape, x.shape, A @ x
(torch.Size([2, 3]), torch.Size([3]), tensor([ 5., 14.]))

Geometric View: How Matrices Transform Space

Linear Geometry

  • Because \mathbf{A}\mathbf{e}_j extracts the j^\textrm{th} column of \mathbf{A}, the columns show where the standard basis vectors \mathbf{e}_1, \mathbf{e}_2 land:
    • Rotations, axis rescalings, and shears deform the dashed unit square into the parallelogram spanned by \mathbf{A}\mathbf{e}_1 and \mathbf{A}\mathbf{e}_2.
    • Across layers of a neural network, each weight matrix \mathbf{W} rotates, stretches, and projects feature space so that tangled classes become linearly separable.

Matrix–Matrix Multiplication: Batching Linear Layers

Matrix–Matrix Products

  • For \mathbf{A} \in \mathbb{R}^{m \times k} and \mathbf{B} \in \mathbb{R}^{k \times n}, \mathbf{C} = \mathbf{A}\mathbf{B} \in \mathbb{R}^{m \times n} (A @ B) computes mn dot products of length k: c_{ij} = \mathbf{a}_i^\top \mathbf{b}_{:,j} = \sum_{l=1}^{k} a_{il}\, b_{lj}
  • Shape rule: (m, k) \times (k, n) \to (m, n)—inner dimensions k must match and contract away.
B = torch.ones(3, 4)
A @ B
tensor([[ 3.,  3.,  3.,  3.],
        [12., 12., 12., 12.]])
  • Batching a 10-class classifier (\mathbf{O} = \mathbf{X}\mathbf{W} + \mathbf{b}): (256, 784) @ (784, 10) + (10,) -> (256, 10) evaluates all 2{,}560 logits at once; argmax along axis 1 predicts each image’s class:
W = 0.01 * torch.randn(784, 10)  # Column j: category j
b = torch.zeros(10)              # Entry j: category j
O = X @ W + b                    # Row i: image i
O.shape, O.argmax(dim=1).shape
(torch.Size([256, 10]), torch.Size([256]))

Computational Complexity and Arithmetic Intensity of Matmul

Systems & FLOPs

  • FLOP count: Multiplying (m, k) \times (k, n) computes mn dot products of length k, costing \approx 2mkn\text{ FLOPs}.
  • O(n^2) bytes vs. O(n^3) FLOPs: Elementwise ops (0.33\text{ FLOP/el}) and single-vector matvecs (2\text{ FLOP/el}) starve on HBM bandwidth.
  • Why we batch: Grouping vectors into a matrix \mathbf{X}\mathbf{W} raises arithmetic intensity to O(n) (2{,}730\text{ FLOP/el} at n=4096), saturating GPU Tensor Cores.

Concept Check: Predicting Reduction, Broadcast, and Matmul Shapes

Check Your Understanding

Given flattened minibatch X of shape (256, 784) and weight matrix W_T stored row-wise with shape (10, 784):

  1. Why does X @ W_T fail, and what expression computes the (256, 10) logit matrix?
  2. What are the shapes of X.sum(axis=0) and X.sum(axis=1, keepdims=True)?
  3. Suppose a minibatch happens to contain n = 784 images so X is square (784, 784). What happens if you evaluate X - X.mean(axis=1) without keepdims=True?

Answers:

  1. Inner dimensions 784 \neq 10 mismatch; transposing via X @ W_T.T aligns (256, 784) @ (784, 10) -> (256, 10).
  2. X.sum(axis=0) has shape (784,) (per-pixel totals); X.sum(axis=1, keepdims=True) has shape (256, 1) (per-image totals).
  3. Silent broadcasting bug: X.mean(axis=1) has shape (784,), which right-aligns to (1, 784) and subtracts image j’s mean from pixel j of every image without raising an error.

Vector and Matrix Norms: Measuring Magnitude

Norms

  • Every norm \|\cdot\| satisfies \|\alpha\mathbf{x}\| = |\alpha|\|\mathbf{x}\|, \|\mathbf{x} + \mathbf{y}\| \leq \|\mathbf{x}\| + \|\mathbf{y}\|, and \|\mathbf{x}\| > 0 for \mathbf{x} \neq \mathbf{0}:
    • Euclidean (\ell_2): \|\mathbf{x}\|_2 = \sqrt{\sum_i x_i^2} (for (3, -4), \|\mathbf{x}\|_2 = 5).
    • Manhattan (\ell_1): \|\mathbf{x}\|_1 = \sum_i |x_i| (for (3, -4), \|\mathbf{x}\|_1 = 7).
    • \ell_p & Frobenius: \|\mathbf{x}\|_p = (\sum_i |x_i|^p)^{1/p}, \|\mathbf{A}\|_\textrm{F} = \sqrt{\sum_{i,j} a_{ij}^2}.
x = torch.tensor([3.0, -4.0])
torch.linalg.vector_norm(x), torch.abs(x).sum()
(tensor(5.), tensor(7.))
image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/
torch.linalg.matrix_norm(torch.ones(4, 9))
tensor(6.)

Why Choice of Norm Matters: Outliers, Weight Decay, and Sparsity

Norms in Machine Learning

  • Outliers (\ell_2^2 vs. \ell_1 loss): On \mathbf{r} = (1, -1, 1, -1, 10), the single outlier 10 dominates 96\% of \|\mathbf{r}\|_2^2 (slope 2r), versus 71\% of \|\mathbf{r}\|_1 (bounded slope \pm 1).
  • Weight decay (\frac{\lambda}{2}\|\mathbf{W}\|_\textrm{F}^2): Round \ell_2 ball shrinks weights smoothly toward zero.
  • Sparsity (\lambda\|\mathbf{w}\|_1): Sharp axis corners of the \ell_1 diamond drive irrelevant weights to exact zero.

Eigendecomposition: Invariant Directions and the Spectral Theorem

Eigendecomposition

  • A nonzero \mathbf{v} is an eigenvector of \mathbf{A} \in \mathbb{R}^{n \times n} with eigenvalue \lambda if \mathbf{A}\mathbf{v} = \lambda \mathbf{v} \Longrightarrow \mathbf{A}^k \mathbf{v} = \lambda^k \mathbf{v}.
  • Spectral theorem: Every real symmetric matrix \mathbf{S} = \mathbf{S}^\top has n real eigenvalues and an orthonormal eigenbasis (linalg.eigh).
S = torch.tensor([[2.0, 1.0], [1.0, 2.0]])
eigenvalues, eigenvectors = torch.linalg.eigh(S)
eigenvalues, eigenvectors
(tensor([1., 3.]),
 tensor([[-0.7071,  0.7071],
         [ 0.7071,  0.7071]]))

Power Iteration and the Spectral Norm

Repeated Matrix Multiplication

  • Expanding any input \mathbf{x} = \sum_{i=1}^n c_i \mathbf{v}_i in the orthonormal eigenbasis shows how repeated multiplication evolves: \mathbf{A}^k \mathbf{x} = \sum_{i=1}^n c_i \lambda_i^k \mathbf{v}_i
  • Power iteration: As k grows, the term with the largest |\lambda_i| dominates—aligning \mathbf{A}^k\mathbf{x} with the dominant eigenvector and stretching its norm by \max_i |\lambda_i| per step.
  • For symmetric \mathbf{A}, \max_i |\lambda_i| equals the spectral norm \|\mathbf{A}\|_2 = \max_{\mathbf{x}\neq\mathbf{0}} \|\mathbf{A}\mathbf{x}\|_2 / \|\mathbf{x}\|_2 (maximum stretch factor).
norm = torch.linalg.vector_norm
v = torch.tensor([1.0, 0.0])
for _ in range(10):
    v_prev, v = v, S @ v
growth = norm(v) / norm(v_prev)
growth, v / norm(v)
(tensor(3.0000), tensor([0.7071, 0.7071]))

Spectral Dynamics in Deep Networks: Exploding and Vanishing Signals

Why Initialization & Normalization Matter

  • Across L = 50 layers, even a 10\% eigenvalue deviation (\lambda_1 = 1.1, \lambda_2 = 0.9) explodes as 1.1^{50} \approx \mathbf{117.4\times} or vanishes as 0.9^{50} \approx \mathbf{0.0052\times}.
  • Keeping each layer’s stretch factors (its singular values) near 1 motivates Xavier/He initialization, residual connections, and LayerNorm.
M = torch.tensor([[1.0, 0.1], [0.1, 1.0]])
# The eigenvectors (1, 1) and (-1, 1) of M, as columns of length 1
V = torch.tensor([[1.0, -1.0], [1.0, 1.0]]) / 2 ** 0.5
for _ in range(50):  # 50 "layers"
    V = M @ V
torch.linalg.vector_norm(V, dim=0)
tensor([1.1739e+02, 5.1538e-03])

Summary: Linear Algebra Operations, Shapes, and Roles

Key Takeaways

Operation Form Shape Rule FLOPs Deep Learning Role
Hadamard Product \mathbf{A} \odot \mathbf{B} (A * B) (m, n) \to (m, n) mn Gating in LSTMs, SwiGLU, masks
Axis Reduction sum(axis=1, keepdims=True) (m, n) \to (m, 1) mn Softmax normalization, LayerNorm
Dot Product & Cosine \mathbf{x}^\top\mathbf{y} = \|\mathbf{x}\|_2\|\mathbf{y}\|_2\cos\theta (d,), (d,) \to () 2d Neuron logit, query–key similarity
Matrix–Vector \mathbf{A}\mathbf{x} (A @ x) (m, n) \times (n,) \to (m,) 2mn Single-example linear map
Matrix–Matrix \mathbf{C} = \mathbf{X}\mathbf{W} (X @ W) (n, k) \times (k, m) \to (n, m) 2nkm Batched dense & attention layers
Norms (\ell_2, \ell_1, \textrm{F}) \|\mathbf{x}\|_2, \|\mathbf{x}\|_1, \|\mathbf{W}\|_\textrm{F} Any tensor \to () 2N MSE/MAE loss, weight decay, clipping
Eigendecomposition \mathbf{A}\mathbf{v} = \lambda\mathbf{v} \Rightarrow \mathbf{A}^k\mathbf{v} = \lambda^k\mathbf{v} (n, n) \to (\lambda_i, \mathbf{v}_i) O(n^3) Exploding/vanishing signals, curvature