Skip to content
English

Switch theme

Math & Machine Learning Foundations

Linear Algebra for AI: Vectors, Matrix Multiplication, Eigendecomposition and SVD

Intermediate 35 min For: Beginners / Researchers

Key takeaways

  • ▸A vector is an ordered list of numbers that can represent a word, an image or a layer's activations. The dot product equals the product of lengths times the cosine of the angle; cosine similarity divides out the lengths and compares direction only, which is why it is the standard measure for comparing embeddings.
  • ▸Matrix multiplication composes linear maps: applying R and then S is the same as multiplying by SR. A fully connected layer is y = Wx + b, and Transformer attention scores are QKᵀ.
  • ▸Rank is the number of linearly independent directions among a matrix's columns. A d×k matrix of rank r factors into a d×r and an r×k matrix, which is why LoRA can write a weight update as BA and cut trainable parameters from dk to r(d+k).
  • ▸SVD factors any matrix as UΣVᵀ. Eckart and Young (1936) proved that, in the Frobenius norm, truncating to the top k singular values gives the best rank-k approximation, with error equal to the square root of the sum of the squared discarded singular values.
  • ▸PCA is equivalent to the SVD of the centred data matrix: the right singular vectors are the principal directions and the squared singular values are proportional to the variance along each direction.

Overview: Linear algebra is the language in which embeddings, neural-network layers and attention are written. This lesson proceeds from vectors to matrix multiplication, rank, eigendecomposition, and finally SVD and low-rank approximation, tying each topic to a concrete use in large models: cosine similarity for vector search, matrix multiplication for dense layers and attention, and low-rank structure for PCA and LoRA.

This lesson belongs to the Linear Algebra unit; the prerequisite is Python and NumPy setup. Continue with Calculus and Optimization, Tokens and Embeddings, Transformers and Attention and Fine-tuning and LoRA. Related algorithm cards: PCA, Word2Vec, Transformer, LoRA.

Vectors, dot products and cosine similarity

An n-dimensional vector x ∈ ℝⁿ is an ordered list of n real numbers. In machine learning it may be a word embedding, the flattened pixels of an image, or the activations of a layer.

The dot product (inner product) of two vectors is a·b = Σᵢ aᵢbᵢ = aᵀb, which geometrically equals ‖a‖‖b‖cos θ, where ‖a‖ = √(aᵀa) is the L2 norm and θ the angle between them. Cosine similarity divides out the lengths:

cos θ = aᵀb / (‖a‖‖b‖)  ∈ [−1, 1]
Cosine Geometry Usual reading for embeddings
1 Same direction Very similar meaning
0 Orthogonal No linear relation in direction
−1 Opposite direction Opposite under this representation

Mikolov et al. (2013) introduced the CBOW and Skip-gram architectures of Word2Vec and examined semantic and syntactic relations with vector arithmetic; for example, vector("King") − vector("Man") + vector("Woman") is closest to vector("Queen") (Mikolov et al., 2013). Such "directions as relations" are measured with dot products and cosine similarity. Modern vector databases search L2-normalised embeddings with the inner product, which is equivalent to ranking by cosine similarity; see Vector Databases.

Matrix multiplication as a linear map

An m×n matrix A maps vectors in ℝⁿ to ℝᵐ: y = Ax. The map is linear: A(αx + βz) = αAx + βAz. The product SR is the composite map "first R, then S", so in general SR ≠ RS.

Shape rules are what you check most often when writing model code: (m×n)(n×p) = (m×p); the inner dimensions must match.

Where Operation Shape (single example)
Dense layer y = Wx + b W: dₒᵤₜ×dᵢₙ
Embedding lookup one-hot vector times embedding matrix E: V×d, pick row i
Attention scores QKᵀ (n×dₖ)(dₖ×n) = n×n
Attention output softmax(·)V (n×n)(n×dᵥ)

The Transformer's scaled dot-product attention is Attention(Q, K, V) = softmax(QKᵀ/√dₖ)V. Vaswani et al. explain the √dₖ: if the components of q and k are independent with mean 0 and variance 1, then q·k has variance dₖ, and for large dimensions the softmax is pushed into regions with extremely small gradients (Vaswani et al., 2017). The demo below checks this numerically.

Rank, linear independence and low-rank structure

A set of vectors is linearly independent if none of them can be written as a linear combination of the others. The rank of a matrix is the maximum number of linearly independent columns (equivalently, rows), i.e. the number of independent directions it spans.

A direct consequence: a d×k matrix of rank r can always be written as the product of a d×r and an r×k matrix, reducing storage from dk to r(d+k). When r ≪ min(d, k) the saving is large.

This structure appears repeatedly in large models:

  • LoRA: Hu et al. (2021) freeze the pretrained weight W₀ and write the update as ΔW = BA with B ∈ ℝ^(d×r), A ∈ ℝ^(r×k), r ≪ min(d, k). The abstract reports that, compared with fine-tuning GPT-3 175B with Adam, LoRA reduces trainable parameters by about 10,000 times and GPU memory by about 3 times (Hu et al., 2021).
  • Intrinsic dimension: Li et al. (2018) train networks in random subspaces and find that many problems need an "intrinsic dimension" far smaller than the parameter count (Li et al., 2018). Aghajanyan et al. (2020) report that optimising only 200 parameters, randomly projected back into the full space, lets RoBERTa reach 90% of full fine-tuning performance on MRPC (Aghajanyan et al., 2020). The LoRA paper cites such results to motivate its hypothesis that weight updates have a low intrinsic rank.

For a single 4096×4096 projection matrix (measured output of this lesson's demo):

LoRA rank r Full parameters dk LoRA parameters r(d+k) Reduction
4 16,777,216 32,768 512×
8 16,777,216 65,536 256×
16 16,777,216 131,072 128×
64 16,777,216 524,288 32×

Eigenvalues and eigenvectors

For a square matrix A, a non-zero vector v with Av = λv is an eigenvector and λ the corresponding eigenvalue: A only stretches v, without changing its direction.

Real symmetric matrices (covariance matrices, Hessians of quadratic functions) have an important property: they can be orthogonally diagonalised, A = QΛQᵀ, where the columns of Q are orthonormal eigenvectors and Λ is the diagonal matrix of real eigenvalues. This is used directly in two places:

  1. PCA: the eigenvectors of the covariance matrix give the principal directions; the eigenvalues are the variances along them.
  2. Optimisation: on a quadratic f(w) = ½wᵀAw, the convergence speed of gradient descent is governed by the ratio of the largest to the smallest eigenvalue (the condition number); see Calculus and Optimization.

Singular value decomposition and optimal low-rank approximation

Every real m×n matrix can be factored as

A = U Σ Vᵀ

where U (m×m) and V (n×n) are orthogonal and the diagonal of Σ holds the non-negative singular values σ₁ ≥ σ₂ ≥ … ≥ 0. The number of non-zero singular values equals the rank. The link to eigendecomposition: the columns of V are eigenvectors of AᵀA, and σᵢ² are its eigenvalues.

Keeping the top k singular values gives the truncated SVD Aₖ = Σᵢ₌₁ᵏ σᵢuᵢvᵢᵀ. Eckart and Young (1936) proved that, in the Frobenius norm, Aₖ is the closest matrix to A among all matrices of rank at most k, with error

‖A − A_k‖_F = √( Σ_{i>k} σᵢ² )

(Eckart & Young, 1936). This gives a single view of compression and denoising: large singular values carry the main structure, small ones are often noise.

PCA and SVD: Pearson (1901) framed PCA as finding the lines and planes of closest fit to a set of points (Pearson, 1901). For a centred data matrix X (one example per row), the right singular vectors are the principal directions and the variance along direction i is σᵢ²/(n−1). scikit-learn's PCA likewise centres each feature (without scaling) and then applies SVD (scikit-learn documentation).

Runnable example

The NumPy script below demonstrates, in turn: composition of maps, cosine similarity, eigendecomposition, low-rank SVD and the Eckart–Young error, LoRA parameter counts, and the variance of attention scores. It was run under Python 3.13 and NumPy 2.5 with a fixed seed and is reproducible.

import numpy as np
rng = np.random.default_rng(0)

# 1) A matrix is a linear map: rotate by 90°, then stretch x by 2
R = np.array([[0., -1.], [1., 0.]])
S = np.array([[2., 0.], [0., 1.]])
x = np.array([1., 0.])
print("S@(R@x) =", S @ (R @ x), " (S@R)@x =", (S @ R) @ x)

# 2) Dot product and cosine similarity
def cos(a, b):
    return a @ b / (np.linalg.norm(a) * np.linalg.norm(b))
a, b, c = np.array([1., 2., 0.]), np.array([2., 4., 0.]), np.array([-2., 1., 0.])
print("cos(a,b) =", round(cos(a, b), 4), " cos(a,c) =", round(cos(a, c), 4))

# 3) Eigendecomposition (symmetric matrix)
A = np.array([[2., 1.], [1., 2.]])
w, V = np.linalg.eigh(A)
print("eigenvalues =", w)

# 4) Low-rank SVD: a rank-2 signal plus noise
n = 64
u = np.linspace(-1, 1, n)
img = (np.outer(np.cos(3 * u), np.sin(2 * u)) + 0.5 * np.outer(u, u ** 2)
       + 0.05 * rng.standard_normal((n, n)))
U, s, Vt = np.linalg.svd(img, full_matrices=False)
for k in (1, 2, 4, 8, 16):
    Ak = (U[:, :k] * s[:k]) @ Vt[:k]
    err = np.linalg.norm(img - Ak)            # Frobenius norm
    tail = np.sqrt((s[k:] ** 2).sum())         # error predicted by Eckart–Young
    print(f"k={k:2d} rel_err={err / np.linalg.norm(img):.4f} "
          f"frob_err={err:.4f} tail_sigma={tail:.4f}")

# 5) LoRA parameter count: ΔW = B A, B: d×r, A: r×k
d = k = 4096
for r in (4, 8, 16, 64):
    print(f"r={r:3d} full={d * k:,} lora={r * (d + k):,}")

# 6) Attention-score variance grows with d_k; dividing by sqrt(d_k) restores ~1
for dk in (16, 64, 256):
    q = rng.standard_normal((20000, dk)); kk = rng.standard_normal((20000, dk))
    dots = (q * kk).sum(1)
    print(f"d_k={dk:3d} var={dots.var():7.2f} scaled_var={(dots / np.sqrt(dk)).var():.3f}")

Key points from the measured output:

  • Both orders of evaluation give [0. 1.]; cos(a,b)=1.0 (same direction) and cos(a,c)=0.0 (orthogonal); the symmetric matrix [[2,1],[1,2]] has eigenvalues 1 and 3.
  • The noisy image has full rank (64), but its signal has rank 2: the relative error is 0.2589 at k = 1, drops sharply to 0.0868 at k = 2, and then falls slowly (0.0558 at k = 16); what remains is mostly noise. On every row frob_err equals tail_sigma (e.g. 3.0893 at k = 2), as the Eckart–Young theorem predicts.
  • Attention scores: for dₖ = 16, 64, 256 the unscaled variances are about 15.97, 63.28 and 257.85; after dividing by √dₖ they are 0.998, 0.989 and 1.007.

Where these concepts appear in large models

Concept Where it appears Further reading
Dot product, cosine similarity Embedding search, attention scores Tokens and Embeddings
Matrix multiplication Dense layers, Q/K/V projections, output layer Transformers and Attention
Rank and low-rank factorisation LoRA, QLoRA and other parameter-efficient fine-tuning Fine-tuning and LoRA
Eigendecomposition Covariance, Hessians and conditioning Calculus and Optimization
SVD PCA, low-rank compression, analysing learned weights PCA card

Exercises

  1. Unit project: load a greyscale image (or use the synthetic one above), compute truncated SVDs for k = 1, 2, 4, …, plot rank k against relative reconstruction error, and use this lesson's LoRA parameter formula to explain why a few directions can describe a weight update.
  2. Complete the vectors, matrix multiplication and eigenvalue practice sets in Khan Academy Linear Algebra.
  3. Work through problem sets and past exams from MIT 18.06; for matrix methods in machine learning, continue with MIT 18.065.
  4. Use numpy.linalg or torch.linalg to compute svd, eigh and matrix_rank for the same matrix, and check that the eigenvalues of AᵀA equal the squared singular values (NumPy docs, PyTorch docs).

Suggested order of study

Start with 3Blue1Brown's Essence of Linear Algebra for geometric intuition, then use D2L section 2.3 to put the concepts into tensor code; for systematic study, take MIT 18.06 or chapters 2–4 of Mathematics for Machine Learning (linear algebra, analytic geometry, matrix decompositions). Then continue with Calculus and Optimization.

FAQ

How much linear algebra do I need for deep learning?

For reading papers and writing code you should be fluent with vector and matrix shapes, matrix multiplication and transposes, dot products and norms, rank, eigenvalues and eigenvectors, and SVD. Determinants and Jordan normal form are rarely used directly in LLM work. MIT 18.06 and chapters 2–4 of Mathematics for Machine Learning cover everything listed above.

What is the difference between cosine similarity and the dot product?

The dot product a·b = ‖a‖‖b‖cosθ depends on both length and direction; cosine similarity cosθ = a·b /(‖a‖‖b‖) depends on direction only and lies between −1 and 1. When vectors are L2-normalised the two are equal, which is why many vector databases search normalised embeddings with the inner product.

Why does attention divide by √d_k?

Vaswani et al. (2017) explain that if the components of q and k are independent with mean 0 and variance 1, then q·k has variance d_k. Large dimensions produce large dot products that push the softmax into regions with extremely small gradients; dividing by √d_k brings the variance back to about 1. In this lesson's demo, the unscaled variance at d_k = 256 is about 258 and the scaled variance about 1.0.

How are SVD and eigendecomposition related?

Eigendecomposition needs a square, diagonalisable matrix; real symmetric matrices can always be orthogonally diagonalised. SVD exists for any m×n matrix: the right singular vectors of A are eigenvectors of AᵀA and the singular values are the square roots of its eigenvalues. Numerical work on non-square or ill-conditioned matrices usually relies on SVD.

Is LoRA the same thing as low-rank SVD approximation?

No. Low-rank SVD compresses a known matrix. LoRA freezes the pretrained weight W₀, parameterises the unknown update ΔW directly as a low-rank product BA, and trains B and A by gradient descent. What they share is the fact that a rank-r matrix is described by only r(d+k) numbers. The LoRA paper also uses SVD to analyse the subspaces of the learned ΔW.

Sources & further reading

  1. MIT OpenCourseWare: 18.06 Linear Algebra (Gilbert Strang)
  2. MIT OpenCourseWare: 18.065 Matrix Methods in Data Analysis, Signal Processing, and Machine Learning
  3. Deisenroth, Faisal, Ong: Mathematics for Machine Learning (official free edition)
  4. Dive into Deep Learning: 2.3 Linear Algebra
  5. NumPy documentation: Linear algebra (numpy.linalg)
  6. PyTorch documentation: torch.linalg
  7. Eckart & Young (1936), The Approximation of One Matrix by Another of Lower Rank, Psychometrika
  8. Pearson (1901), On lines and planes of closest fit to systems of points in space
  9. scikit-learn documentation: Decomposing signals in components (PCA and more)
  10. Mikolov et al. (2013), Efficient Estimation of Word Representations in Vector Space
  11. Vaswani et al. (2017), Attention Is All You Need
  12. Hu et al. (2021), LoRA: Low-Rank Adaptation of Large Language Models
  13. Aghajanyan, Zettlemoyer, Gupta (2020), Intrinsic Dimensionality Explains the Effectiveness of Language Model Fine-Tuning
  14. Li et al. (2018), Measuring the Intrinsic Dimension of Objective Landscapes
  15. 3Blue1Brown: Essence of Linear Algebra
  16. Khan Academy: Linear algebra

Part of these paths

Data updated: Learn AI curriculum · Lesson news(UTC+8)