AI and ML FoundationsVol. 14A · Part XIV
0 / 0

Shelves / AI and ML Foundations

AI·145

Linear Algebra

The language models are written in: vectors as data and as directions, vector spaces, dot products and what they measure, norms (L1, L2, L∞) and distances, matrices as linear transformations and as data tables, matrix multiplication four ways and its cost, transpose, inverse and solving linear systems, rank and linear independence, orthogonality and projections (least squares), eigenvectors and eigenvalues, the singular value decomposition, low-rank approximation, PCA derived step by step, and tensors with batched operations, each computed in NumPy and connected to embeddings, attention, LoRA and recommendation systems.

33 topics · ~24 min read · 31-question quiz
Updated Suggest a correction

Start here: data as vectors, models as matrices

Linear algebra is the language ML is written in. A vector is a list of numbers: a dish described by its features, a word as an embedding, an image as pixels. A matrix is a grid of numbers, and multiplying a vector by a matrix transforms it: rotates, stretches, projects, mixes its features. A neural network layer is, at heart, "multiply by a matrix, then bend the result a little"; an LLM does this billions of times per answer.

Similarity: how close are two vectors?

Each dish as a vector of five features (spicy, sweet, protein, rice-based, price). The cosine similarity (the dot product of the two vectors after scaling each to length 1) measures how much they point the same way:

Text
similar to 'veg biryani':  chicken biryani 0.94   dal tadka 0.87   paneer butter masala 0.62
                           rasmalai 0.15          gulab jamun 0.07

Two biryanis point almost the same way; sweets point elsewhere. Recommendation systems, semantic search and retrieval-augmented generation (Volume 14b) all rank by exactly this number, computed on learned vectors (embeddings) with hundreds of dimensions.

A matrix moves vectors

Text
rotation by 90° applied to (1, 0)       → (0, 1)
diag(2, 0.5) applied to (1, 1)          → (2, 0.5)     stretch x, squash y
determinants: rotation 1.0, scaling 1.0  (both preserve area)

Every matrix is some combination of rotations, stretches and projections. The singular value decomposition (SVD) makes that literal: any matrix = rotate × stretch × rotate, and the stretch factors (singular values) say how much each direction matters.

Hidden structure: low rank

A 500-customer × 300-dish ratings matrix was generated from just 5 hidden tastes plus noise. Its singular values:

Text
432.7  397.0  374.8  359.1  352.7  |  11.6  11.5  11.5 …

Five large values, then a cliff: the SVD found the five tastes without being told. Keeping only the top k directions:

Text
rank  1: relative error 0.867    801 numbers stored (of 150,000)
rank  5: relative error 0.132  4,005 numbers stored
rank 50: relative error 0.106 40,050 numbers stored     (the rest is noise)

Rank 5 captured nearly all the structure with 2.7% of the numbers. This is why compression, recommendation (matrix factorisation) and parameter-efficient fine-tuning (LoRA, chapter 158) work: real data and real weight updates are often close to low rank.

Matrix multiplication is the workhorse

Text
 256×256  float32 matmul:   1.52 ms    22 GFLOP/s
1024×1024 float32 matmul:  21.36 ms   100 GFLOP/s
2048×2048 float32 matmul: 143.26 ms   120 GFLOP/s   (2 CPU cores; a modern GPU does tens to hundreds of TFLOP/s)

Multiplying two n×n matrices takes about 2n³ arithmetic operations. Bigger matrices ran more efficiently because the library could keep data in cache; this is why ML frameworks batch work into large matrix multiplications.

How deep to go in linear algebra

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain vectors, dot products, matrices and matrix multiplication
L2 Use them in NumPy/PyTorch with correct shapes for similarity, projections and layers
L3 Explain eigenvectors, SVD, rank, norms and their roles in PCA, embeddings and LoRA
L4 Diagnose shape bugs, ill-conditioning and numerical issues; use low-rank structure deliberately
L5 Choose decompositions and approximations for systems (search, compression, fine-tuning)
L6 Apply numerical linear algebra at scale (distributed and accelerated computation)

Why linear algebra

Almost every AI computation is linear algebra:

  • Data are vectors and matrices: a customer is a feature vector; a dataset is a matrix (rows = samples, columns = features); an image is a 3-D tensor (height × width × channels); a batch of token embeddings is a tensor (batch × sequence × dimension).
  • Models are matrices: a neural network layer computes y = Wx + b; an LLM is mostly large matrix multiplications.
  • Similarity is geometry: embeddings place meaning in vector spaces; nearest neighbours by dot product or cosine similarity drive semantic search and RAG.
  • Compression and structure: SVD/PCA find low-dimensional structure; LoRA fine-tuning (14B) exploits low-rank updates; recommender systems factorise user-item matrices.
  • GPUs exist to multiply matrices: performance engineering for AI is largely about feeding matrix-multiply units.

Vectors

Vectors as lists and as arrows

A vector in ℝⁿ is an ordered list of n real numbers: v = (v₁, v₂, …, vₙ). Two complementary views:

  • Data view: a point in a feature space (a house = (area, bedrooms, age, distance to metro)).
  • Geometric view: an arrow with a direction and a length (magnitude), starting at the origin.

Operations:

  • Addition: (u + v)ᵢ = uᵢ + vᵢ (tip-to-tail).
  • Scalar multiplication: (c·v)ᵢ = c·vᵢ (stretch/shrink/flip).
  • Linear combination: c₁v₁ + c₂v₂ + … + cₖvₖ. Everything in linear algebra is built on linear combinations.
Python
import numpy as np
u = np.array([2.0, 1.0]); v = np.array([1.0, 3.0])
u + v, 3 * u, 2 * u - v           # array([3., 4.]), array([6., 3.]), array([3., -1.])

Vector spaces, span, basis, dimension

  • The span of a set of vectors is all their linear combinations.
  • Vectors are linearly independent if none is a linear combination of the others.
  • A basis is an independent set that spans the space; every vector has unique coordinates in a basis. The dimension is the number of basis vectors.
  • Changing basis changes coordinates, not the vector: PCA (below) is a change to a basis aligned with the data's variance.

Embedding spaces in LLMs have hundreds to thousands of dimensions (e.g. 768, 1024, 4096); intuition from 2-D/3-D geometry largely carries over, with caveats (in high dimensions, random vectors are nearly orthogonal, and most volume lies near the surface of a ball).

Dot product

Definition and geometry

The dot product (inner product) of u, v ∈ ℝⁿ:

u · v = Σᵢ uᵢvᵢ = ‖u‖ ‖v‖ cos θ

where θ is the angle between them. It measures alignment:

  • u · v > 0: pointing in similar directions (θ < 90°).
  • u · v = 0: orthogonal (perpendicular, θ = 90°): "unrelated".
  • u · v < 0: opposite directions.

Cosine similarity normalises away lengths: cos θ = (u · v) / (‖u‖‖v‖) ∈ [−1, 1], the standard similarity for text embeddings (chapter 159). If vectors are normalised to unit length, dot product = cosine similarity.

u v proj of v on u = (v·û) û θ u·v = ‖u‖‖v‖cos θ aligned: > 0 orthogonalu·v = 0 oppositeu·v < 0
The dot product as alignment and projection. Vectors u and v at angle theta: their dot product equals the length of u times the length of v times cos theta. The projection of v onto the direction of u has length v dot u-hat. Aligned vectors give a large positive dot product, perpendicular vectors give zero, and opposite vectors give a negative value.

Where dot products appear

  • Linear models: prediction ŷ = w · x + b; the weight vector "votes" along each feature.
  • Attention (chapter 154): scores = query · key for every pair of tokens.
  • Retrieval: rank documents by query-embedding · document-embedding.
  • Neurons: each output of a dense layer is a dot product of weights and inputs, followed by a non-linearity.
Python
def cosine(u, v):
    return float(u @ v / (np.linalg.norm(u) * np.linalg.norm(v)))

king, queen, man, woman = (np.random.default_rng(i).normal(size=300) for i in range(4))  # stand-ins
cosine(np.array([1, 0]), np.array([0, 1]))        # 0.0 (orthogonal)
cosine(np.array([1, 2]), np.array([2, 4]))        # 1.0 (same direction)

Norms and distances

A norm ‖v‖ measures a vector's size. The Lp norms:

Norm Formula Geometry / use
L2 (Euclidean) √(Σ vᵢ²) Ordinary length; Euclidean distance ‖u − v‖₂; L2 regularisation (weight decay)
L1 (Manhattan) Σ |vᵢ| Grid distance; L1 regularisation (Lasso) encourages sparse weights
L∞ (max) maxᵢ |vᵢ| Largest component; adversarial robustness bounds
L0 ("norm") count of non-zeros Sparsity (not a true norm)

Unit balls (all vectors with norm ≤ 1) are a circle (L2), a diamond (L1), a square (L∞) in 2-D; the corners of the L1 diamond explain why L1 regularisation pushes weights exactly to zero.

Matrix norms: Frobenius norm ‖A‖_F = √(Σ aᵢⱼ²) (L2 of all entries); spectral norm ‖A‖₂ = largest singular value (how much A can stretch a vector).

Python
v = np.array([3.0, -4.0])
np.linalg.norm(v), np.linalg.norm(v, 1), np.linalg.norm(v, np.inf)   # 5.0, 7.0, 4.0
# Normalise rows of an embedding matrix to unit length (then dot product = cosine similarity)
E = np.random.default_rng(0).normal(size=(10_000, 384)).astype(np.float32)
E /= np.linalg.norm(E, axis=1, keepdims=True)

Matrices

Matrices as data and as transformations

An m × n matrix A has m rows and n columns. Two views again:

  • Data: a table of m samples × n features (a design matrix X).
  • Linear transformation: a function from ℝⁿ to ℝᵐ, x ↦ Ax, that preserves addition and scaling: A(u + v) = Au + Av, A(cv) = cAv. Rotations, scalings, shears, projections and reflections are linear maps; every linear map between finite-dimensional spaces is a matrix.

The columns of A are where the basis vectors land: A's first column is A·e₁. This is the key to visualising matrices: draw where the unit square goes.

e₁ e₂ area 1 A = [[2,1],[0,1]] Ae₁ = (2,0) Ae₂ = (1,1) area = det A = 2
A 2-by-2 matrix as a transformation of the plane. The unit square spanned by e1 and e2 is mapped to a parallelogram spanned by the matrix's columns. Here A = [[2, 1], [0, 1]] stretches the x direction by 2 and shears; its determinant, 2, is the factor by which areas grow.

Matrix multiplication

For A (m × n) and B (n × p), C = AB is m × p with

Cᵢⱼ = Σₖ Aᵢₖ Bₖⱼ (row i of A · column j of B)

Inner dimensions must match: (m × n)(n × p) → (m × p). Four equivalent views, each useful:

  1. Dot products: each entry is a row-column dot product.
  2. Column view: each column of C is A times the corresponding column of B (a linear combination of A's columns).
  3. Row view: each row of C is a linear combination of B's rows.
  4. Sum of outer products: C = Σₖ (column k of A)(row k of B): a sum of rank-1 matrices (the view behind low-rank approximation and LoRA).

Properties: associative ((AB)C = A(BC)), distributive, but not commutative (AB ≠ BA in general). Composition: applying B then A is the single transformation AB.

Cost: multiplying m×n by n×p takes m·n·p multiply-adds (2mnp FLOPs). For square n×n matrices, O(n³). This is why model size and sequence length dominate AI compute: a Transformer layer's matmuls cost roughly 2 × parameters FLOPs per token in the forward pass.

Python
A = np.array([[1, 2], [3, 4]]); B = np.array([[0, 1], [1, 0]])
A @ B            # [[2, 1], [4, 3]]  (swaps A's columns)
B @ A            # [[3, 4], [1, 2]]  (swaps A's rows) — not equal: not commutative

# Outer-product view equals ordinary product
C = sum(np.outer(A[:, k], B[k, :]) for k in range(2))
np.array_equal(C, A @ B)                                      # True

# Order matters for cost: (x row vector) · A · B with huge B: compute left to right

A neural network layer on a batch: Y = XWᵀ + b with X (batch × in_features), W (out × in), b broadcast over rows. A whole MLP is a chain of matmuls with non-linearities in between (chapter 151).

Transpose, identity, inverse

  • Transpose Aᵀ swaps rows and columns; (AB)ᵀ = BᵀAᵀ; u · v = uᵀv.
  • Identity I: AI = IA = A.
  • Inverse A⁻¹ (square A only, if it exists): AA⁻¹ = I. Exists iff A is non-singular: det A ≠ 0, full rank, columns independent. Undoes the transformation.
  • Determinant det A: the factor by which A scales areas/volumes (sign = orientation flip); zero means A squashes space into a lower dimension.

Solving linear systems

Ax = b: find x such that the transformation maps x to b. Never compute A⁻¹ explicitly to solve systems (slower and numerically worse); use solvers based on LU/QR/Cholesky decompositions:

Python
A = np.array([[3.0, 1.0], [1.0, 2.0]]); b = np.array([9.0, 8.0])
x = np.linalg.solve(A, b)          # [2., 3.]
np.allclose(A @ x, b)              # True
np.linalg.cond(A)                  # condition number: large → small changes in b cause large changes in x

Numerical stability matters in ML: ill-conditioned matrices (nearly dependent features, e.g. highly correlated columns) amplify errors; regularisation (adding λI) improves conditioning (ridge regression).

Rank

The rank of A is the number of linearly independent columns (= independent rows) = the dimension of its output space (column space). An m × n matrix has rank ≤ min(m, n).

  • Full rank: no redundancy.
  • Low rank: A can be written as a product of thinner matrices: A (m×n) = U (m×r) V (r×n) with r ≪ min(m, n), storing r(m + n) numbers instead of mn.

Low rank everywhere in AI: user-item rating matrices are approximately low rank (a few latent tastes explain preferences); weight updates during fine-tuning are approximately low rank, so LoRA trains W + BA with B (d × r), A (r × k), r = 8–64 instead of updating all of W (14B, chapter 163).

Python
U = np.random.default_rng(0).normal(size=(1000, 8)); V = np.random.default_rng(1).normal(size=(8, 500))
M = U @ V                          # 1000 × 500 matrix of rank 8
np.linalg.matrix_rank(M)           # 8 — stored as 12,000 numbers instead of 500,000

Orthogonality and projections

Orthogonal vectors and matrices

Vectors are orthogonal if their dot product is zero; orthonormal if also unit length. A square matrix Q with orthonormal columns is orthogonal: QᵀQ = I, so Q⁻¹ = Qᵀ. Orthogonal matrices are rotations/reflections: they preserve lengths and angles (‖Qx‖ = ‖x‖), which makes them numerically ideal.

Projections

The projection of v onto a unit vector û is (v · û)û: the component of v along û (shadow). Onto a subspace spanned by the columns of A, the projection of b is

p = A(AᵀA)⁻¹Aᵀb

and the residual b − p is orthogonal to the subspace. This is exactly least squares: when Ax = b has no exact solution (more equations than unknowns, noisy data), the best x minimises ‖Ax − b‖², giving the normal equations AᵀA x = Aᵀb. Linear regression (chapter 148) is a projection of the target vector onto the space spanned by the features.

Python
rng = np.random.default_rng(0)
X = np.c_[np.ones(100), rng.uniform(0, 10, 100)]                # intercept + one feature
y = 2 + 3 * X[:, 1] + rng.normal(0, 1, 100)
w_normal = np.linalg.solve(X.T @ X, X.T @ y)                     # normal equations
w_lstsq, *_ = np.linalg.lstsq(X, y, rcond=None)                  # QR/SVD-based: more stable
residual = y - X @ w_lstsq
np.allclose(X.T @ residual, 0, atol=1e-8)                        # residual ⟂ column space: True

Gram-Schmidt and QR decomposition (A = QR, Q orthonormal, R upper triangular) build orthonormal bases and give stable least-squares solutions.

Eigenvectors and eigenvalues

Definition and meaning

For a square matrix A, a non-zero vector v is an eigenvector with eigenvalue λ if

Av = λv

A only scales v (by λ) without changing its direction. Eigenvectors are the transformation's "natural axes".

  • λ > 1 stretches, 0 < λ < 1 shrinks, λ < 0 flips, λ = 0 collapses (A is singular).
  • Found by solving det(A − λI) = 0 (characteristic polynomial) for small matrices; numerically by iterative algorithms (QR algorithm, power iteration).
  • If A has n independent eigenvectors: A = VΛV⁻¹ (eigendecomposition), so Aᵏ = VΛᵏV⁻¹: repeated application is dominated by the largest |λ|.

Symmetric matrices (A = Aᵀ, like covariance matrices) have real eigenvalues and orthogonal eigenvectors: A = QΛQᵀ (spectral theorem). This is what makes PCA work.

v₁ v₂ x A Av₁ = 3v₁ Av₂ = v₂ Axrotated eigenvectors keep their direction; eigenvalues are the stretch factors
Eigenvectors are directions a matrix only stretches. A symmetric matrix maps the unit circle to an ellipse; the ellipse's axes are the eigenvectors, and their lengths are the eigenvalues. Any other vector is both stretched and rotated.
Python
A = np.array([[2.0, 1.0], [1.0, 2.0]])           # symmetric
vals, vecs = np.linalg.eigh(A)                    # eigh for symmetric/Hermitian (sorted ascending)
vals                                              # [1., 3.]
vecs                                              # columns ≈ [0.707, -0.707], [0.707, 0.707]
np.allclose(A @ vecs, vecs * vals)                # A v = λ v for each column: True

# Power iteration: repeated multiplication converges to the dominant eigenvector (idea behind PageRank)
v = np.random.default_rng(0).normal(size=2)
for _ in range(50):
    v = A @ v; v /= np.linalg.norm(v)
v, v @ A @ v                                      # ≈ [0.707, 0.707], λ ≈ 3

Where eigen-things appear: PCA (eigenvectors of the covariance matrix), PageRank (dominant eigenvector of the link matrix), stability of recurrent networks and dynamical systems (|λ| > 1 explodes, < 1 vanishes: the exploding/vanishing gradient problem), spectral clustering (eigenvectors of graph Laplacians), Hessian eigenvalues describing loss curvature (chapter 146).

Singular value decomposition

The decomposition

Every matrix A (m × n, any shape, any rank) has a singular value decomposition:

A = U Σ Vᵀ

  • U (m × m): orthonormal columns (left singular vectors).
  • Σ (m × n): diagonal with non-negative singular values σ₁ ≥ σ₂ ≥ … ≥ 0.
  • V (n × n): orthonormal columns (right singular vectors).

Geometric meaning: every linear map is a rotation (Vᵀ), then a scaling along axes (Σ), then another rotation (U). Singular values are the semi-axis lengths of the ellipse (ellipsoid) that the unit sphere maps to. Relation to eigen: the columns of V are eigenvectors of AᵀA, U of AAᵀ, and σᵢ² are their eigenvalues.

unit circle Vᵀ rotate Σ σ₁σ₂scale axes U rotate → A
The singular value decomposition as three steps. Starting from the unit circle, V-transpose rotates it, Sigma stretches it along the coordinate axes by the singular values, and U rotates the resulting ellipse into place. Every matrix, of any shape, factors this way.

Low-rank approximation

Keeping the top k singular values gives the best rank-k approximation of A in Frobenius and spectral norm (Eckart–Young theorem):

A_k = Σᵢ₌₁ᵏ σᵢ uᵢ vᵢᵀ

Applications: compression (images, embeddings), denoising, latent semantic analysis (topics from document-term matrices), recommender systems (latent factors), analysing how much of a weight matrix's "energy" lies in a few directions, and initialising/understanding LoRA.

Python
rng = np.random.default_rng(0)
true = rng.normal(size=(200, 5)) @ rng.normal(size=(5, 100))     # rank-5 signal
A = true + 0.1 * rng.normal(size=(200, 100))                      # plus noise
U, s, Vt = np.linalg.svd(A, full_matrices=False)
s[:8].round(1)                     # five large values, then a sharp drop to noise level
k = 5
A5 = (U[:, :k] * s[:k]) @ Vt[:k]
np.linalg.norm(A5 - true) / np.linalg.norm(true)                  # small: denoised
(s[:k]**2).sum() / (s**2).sum()                                   # fraction of energy kept (~0.99)

PCA: principal component analysis

Goal

Given n samples with d features, find a small number k of orthogonal directions (principal components) that capture as much variance as possible, then represent each sample by its k coordinates along those directions. Uses: visualisation (k = 2), compression, noise reduction, decorrelating features, speeding up downstream models, analysing embeddings.

Derivation

  1. Centre the data: X̃ = X − mean (each column has mean 0).
  2. The covariance matrix is C = X̃ᵀX̃ / (n − 1) (d × d, symmetric, positive semi-definite).
  3. The variance of the data projected onto a unit vector w is wᵀCw. Maximise wᵀCw subject to ‖w‖ = 1: by Lagrange multipliers (chapter 146), Cw = λw, so w must be an eigenvector of C, and the variance captured equals its eigenvalue λ.
  4. The first principal component is the eigenvector with the largest eigenvalue; the second is the next (orthogonal to the first), and so on.
  5. Project: Z = X̃ W_k (n × k).

Equivalently, via SVD of the centred data: X̃ = UΣVᵀ; principal directions are the columns of V; component variances are σᵢ²/(n − 1). SVD is the numerically preferred way.

PC1 (92%) PC2 (8%) 1. centre the data2. covariance C = X̃ᵀX̃/(n−1)3. eigenvectors of C (or SVD of X̃)4. keep top-k components5. Z = X̃ W_k
PCA on two correlated features. The data cloud is elongated along one diagonal direction; the first principal component points along it and captures most of the variance; the second is perpendicular and captures the rest. Projecting onto the first component reduces two dimensions to one while keeping most information.
Python
rng = np.random.default_rng(0)
X = rng.multivariate_normal(mean=[0, 0, 0], cov=[[3, 2.5, 0], [2.5, 3, 0], [0, 0, 0.2]], size=1000)

# PCA from scratch via SVD
Xc = X - X.mean(axis=0)
U, s, Vt = np.linalg.svd(Xc, full_matrices=False)
explained = s**2 / (s**2).sum()
explained.round(3)                     # ≈ [0.88, 0.08, 0.03]: one dominant direction
Z = Xc @ Vt[:2].T                      # project to 2-D

# Same with scikit-learn
from sklearn.decomposition import PCA
pca = PCA(n_components=2).fit(X)
pca.explained_variance_ratio_          # matches explained[:2]
np.allclose(np.abs(pca.components_), np.abs(Vt[:2]))   # same directions (up to sign)

Practical notes: standardise features first when they have different units (otherwise high-variance units dominate); PCA is linear (non-linear structure needs t-SNE/UMAP for visualisation, or autoencoders); choose k by explained variance (e.g. 95%) or downstream performance; components are hard to interpret when many features load on them.

Tensors and batched operations

A tensor in ML means an n-dimensional array (generalising scalars (0-D), vectors (1-D), matrices (2-D)). Common shapes:

Data Shape convention
Tabular batch (batch, features)
Grayscale images (batch, height, width)
Colour images (PyTorch) (batch, channels, height, width) — NCHW
Token IDs (batch, sequence)
Token embeddings / hidden states (batch, sequence, d_model)
Attention scores (batch, heads, seq_q, seq_k)
Video (batch, time, channels, height, width)

Batched operations treat leading dimensions as batch: A @ B with A (b, m, n) and B (b, n, p) gives (b, m, p); broadcasting handles mismatched leading dims. einsum expresses any contraction explicitly:

Python
rng = np.random.default_rng(0)
B, T, D, H = 2, 5, 16, 4                         # batch, tokens, model dim, heads
X = rng.normal(size=(B, T, D))
Wq = rng.normal(size=(D, D)); Wk = rng.normal(size=(D, D))
Q = X @ Wq; K = X @ Wk                           # (B, T, D)
# split into heads: (B, T, H, D/H) → (B, H, T, D/H)
Qh = Q.reshape(B, T, H, D // H).transpose(0, 2, 1, 3)
Kh = K.reshape(B, T, H, D // H).transpose(0, 2, 1, 3)
scores = np.einsum("bhqd,bhkd->bhqk", Qh, Kh) / np.sqrt(D // H)    # (B, H, T, T): attention scores
scores.shape

This is exactly the first half of multi-head attention (chapter 154). Keeping track of shapes is the most common practical skill in ML code: write them in comments, assert them, or use shape-annotated types.

Linear algebra across languages and hardware

  • BLAS (Basic Linear Algebra Subprograms) levels 1–3 (vector, matrix-vector, matrix-matrix) and LAPACK (decompositions) underlie NumPy, R, Julia, MATLAB, Eigen and more. Implementations: OpenBLAS, Intel MKL/oneMKL, Apple Accelerate, BLIS; on GPUs, cuBLAS, cuSOLVER, rocBLAS.
  • GEMM (general matrix-matrix multiply) is the most optimised routine in computing: tiling for caches, SIMD, and on GPUs tensor cores performing small matrix multiply-accumulates in low precision per clock.
  • Libraries: NumPy/SciPy (Python), Eigen/Armadillo/xtensor (C++), ndarray/nalgebra/faer (Rust), gonum (Go), ND4J/EJML/Vector API (Java), LinearAlgebra stdlib (Julia), JAX and PyTorch for accelerators with autodiff.
julia
# Julia: linear algebra is part of the standard library with natural syntax
using LinearAlgebra
A = [2.0 1.0; 1.0 2.0]
eigen(A).values          # [1.0, 3.0]
F = svd(randn(100, 20)); F.S[1:3]
x = A \ [9.0, 8.0]       # solve Ax = b (backslash operator)

Lab: similarity, low rank and matmul throughput

NumPy 2.5.3 with scipy-openblas on the lab machine (2 vCPUs). Data: six hand-described dishes, and a synthetic 500 × 300 matrix built as (500×5 Gaussian) @ (5×300 Gaussian) + 0.3 × Gaussian noise.

Experiment 1: cosine similarity

Python
U = V / np.linalg.norm(V, axis=1, keepdims=True)    # normalise rows
S = U @ U.T                                          # all pairwise cosine similarities at once
Compared with veg biryani Cosine
chicken biryani 0.94
dal tadka 0.87
paneer butter masala 0.62
rasmalai 0.15
gulab jamun 0.07

One matrix product computed every pairwise similarity, which is how vector search computes scores in bulk. Hand-picked features weight dimensions arbitrarily (price in hundreds of rupees vs spiciness 0–3); learned embeddings avoid that by learning the space, but the same scale issue reappears whenever you mix features, which is why standardisation (chapter 144) comes first.

Experiment 2: SVD finds hidden factors

Text
singular values: 432.7 397.0 374.8 359.1 352.7 | 11.6 11.5 11.5 …
Rank k Relative error ‖A − Aₖ‖/‖A‖ Numbers stored
1 0.867 801
3 0.595 2,403
5 0.132 4,005
10 0.129 8,010
50 0.106 40,050
full 0 150,000

The Eckart–Young theorem says the truncated SVD is the best possible rank-k approximation in this error measure. Beyond rank 5 each extra component removes only a sliver of noise, so error falls slowly; the remaining ~0.1 is the noise's share of the matrix. Principal component analysis (PCA) is this SVD applied to centred data; the singular values' squares are the variances along each principal direction.

Experiment 3: matrix-multiplication throughput

Size Time GFLOP/s
256 × 256 1.52 ms 22.1
1024 × 1024 21.36 ms 100.5
2048 × 2048 143.26 ms 119.9

Two cores at roughly 3 GHz with 256-bit FMA units peak at around 2 × 3 × 32 ≈ 190 GFLOP/s for float32, so the large case reached about 60% of peak; small matrices spend proportionally more time on overhead and memory traffic. Arithmetic intensity (operations per byte moved) is the concept to remember: matmul does O(n³) work on O(n²) data, so it can run near peak; element-wise operations do O(n) work on O(n) data and are limited by memory bandwidth. Chapter 158 uses this to explain why LLM generation is memory-bound.

Try it yourself

  1. Run PCA on scikit-learn's bundled load_digits (8×8 images) and plot the cumulative explained variance. How many components hold 90%?
  2. Compare np.linalg.svd with scipy.sparse.linalg.svds(A, k=5) on a 5,000 × 3,000 version of the matrix.
  3. Measure element-wise X * Y for 2048 × 2048 and compute its GFLOP/s and GB/s. Which limit does it hit?
  4. Build a rank-8 "update" ΔW = B @ A for a 512 × 512 weight and count the parameters versus a full update.

Revision sheet: linear algebra

Key ideas

  • Vectors as data points and directions; dot product = |a||b|cos θ; cosine similarity; norms L1, L2, L∞.
  • Matrices as linear maps; matrix multiplication composes maps; shapes (m×n)(n×p) → (m×p).
  • Identity, inverse, transpose, determinant (volume scaling; zero means information lost).
  • Rank: number of independent directions; low rank = hidden low-dimensional structure.
  • Eigenvectors/eigenvalues: directions a matrix only scales; SVD for any matrix: UΣVᵀ.
  • PCA = SVD of centred data; Eckart–Young: truncated SVD is the best low-rank approximation.
  • In ML: layers are matrix multiplies; attention is dot products; embeddings live in vector spaces; LoRA is a low-rank update.
  • Compute: matmul ≈ 2n³ FLOPs; high arithmetic intensity; batching to use hardware well.

Numbers to remember

  • Lab: five hidden factors → five large singular values (≈350–430) then ≈11.5.
  • Lab: rank 5 kept error at 0.13 with 2.7% of the numbers.
  • Lab: 2048×2048 float32 matmul ≈ 120 GFLOP/s on 2 CPU cores.

Pitfalls

  • Shape mistakes hidden by broadcasting.
  • Cosine similarity on unnormalised, unscaled features.
  • Inverting matrices explicitly instead of solving linear systems (np.linalg.solve).
  • Ignoring conditioning (nearly singular matrices amplify errors).
  • Assuming element-wise operations are cheap at scale (memory-bound).

Glossary

  • Span / basis: all combinations of vectors / a minimal set spanning a space.
  • Orthogonal: perpendicular (dot product zero).
  • Singular value: stretch factor along a principal direction.
  • Condition number: ratio of largest to smallest singular value.
  • Arithmetic intensity: FLOPs per byte moved.