Repository navigation
Module 01
⬅️ Home · 🗺️ Curriculum · 🏠 Home · Module 02 ➡️
Level: Foundational · Prerequisites: school algebra and coordinate geometry · Time: about 6–8 hours
On this page: Overview and learning goals · Beginner: the big picture · Core concepts and derivations · Worked example · Implementation · Advanced topics · Pitfalls and best practices · Conceptual questions and answers · Sources and further reading
Almost every computation in deep learning is linear algebra on batches of numbers. A dense layer is a matrix product, a convolution is a structured (sparse, weight-shared) matrix product, attention is two matrix products and a softmax, and a graph layer multiplies by a normalised adjacency matrix. This module builds the vocabulary — vectors, matrices, tensors, norms, rank, eigenvalues, SVD — and the geometric intuition that lets you read an architecture as a sequence of linear maps and nonlinearities.
After this module you should be able to:
- name every axis of a tensor and predict the output shape of
matmul, broadcasting andeinsum; - compute dot products, norms, cosine similarity and projections by hand;
- explain rank, column space and null space, and decide whether a linear system is solvable;
- compute and interpret eigendecompositions and the SVD, and state the Eckart–Young theorem;
- recognise positive (semi)definite matrices and explain why they matter for optimisation.
Scalars, vectors, matrices, tensors. A scalar is one number. A vector
| Object | Typical shape | Meaning |
|---|---|---|
| Tabular batch |
|
|
| Image batch | channels first (PyTorch) | |
| Token batch |
|
|
| Attention scores | per head, query × key |
Habit to build: always label axes (batch, channel, time, feature). A shape such as
(32, 64)does not tell you whether the 64 is features or time.
A matrix is a machine. Feed in a vector, get a vector out. Geometrically a matrix stretches, rotates and reflects space. The figure below shows a

Figure 1.1 — A matrix figures/make_figs_1.py).
flowchart LR
X["Input batch X: B x d_in"] --> M["Matrix product XW"]
W["Weights W: d_in x d_out"] --> M
M --> A["Add bias b (broadcast over batch)"]
B["Bias b: d_out"] --> A
A --> Y["Output Y: B x d_out"]
Index an element of a matrix as
Broadcasting (NumPy/PyTorch) aligns shapes from the right; two axes are compatible if they are equal or one of them is 1, and the size-1 axis is virtually repeated. So Y = X @ W + b with
The dot product
For
Cauchy–Schwarz
Vectors are orthogonal when
The same idea, applied to a subspace spanned by the columns of
Vectors are linearly independent if
-
column space
$\mathcal{C}(A)=\{A\mathbf{x}\}\subseteq\mathbb{R}^m$ ; rank$r=\dim\mathcal{C}(A)$ (= number of independent columns = number of independent rows); -
null space
$\mathcal{N}(A)=\{\mathbf{x}:A\mathbf{x}=\mathbf{0}\}\subseteq\mathbb{R}^n$ .
Rank–nullity:
Every linear map
An eigenpair satisfies
Spectral theorem. A real symmetric matrix has real eigenvalues and an orthonormal eigenbasis:
Every real
with orthonormal
Eckart–Young–Mirsky theorem. The best rank-

Figure 1.2 — A rank-5 signal plus noise shows five dominant singular values; the relative error of the best rank-figures/make_figs_1.py).
The condition number
A symmetric
A contraction sums over a shared axis; matrix multiplication, dot products and traces are special cases. einsum writes them explicitly. Attention scores for
Layout conventions differ: PyTorch images are nn.Linear(in, out) stores
Let
- Dot product:
$2\cdot1+(-1)\cdot2+3\cdot(-1)=-3$ . Not orthogonal. - Norms:
$\lVert\mathbf{x}\rVert=\sqrt{14}$ ,$\lVert\mathbf{w}\rVert=\sqrt6$ ;$\cos\theta=-3/\sqrt{84}\approx-0.327$ . - Projection of
$\mathbf{x}$ on$\mathbf{w}$ :$t=-3/6=-\frac12$ , so$\mathrm{proj}=(-0.5,-1,0.5)$ . Residual$(2.5,0,2.5)$ ; check$(2.5,0,2.5)\cdot(1,2,-1)=0$ ✓. -
Eigen/SVD.
$S=\begin{pmatrix}2&1\\1&2\end{pmatrix}$ has$\det(S-\lambda I)=(2-\lambda)^2-1=0\Rightarrow\lambda\in\{3,1\}$ with eigenvectors$(1,1)/\sqrt2$ and$(1,-1)/\sqrt2$ . For the rank-one$A=\begin{pmatrix}1&2\\2&4\end{pmatrix}$ :$A^\top A=\begin{pmatrix}5&10\\10&20\end{pmatrix}$ has eigenvalues$25,0$ , so$\sigma_1=5$ ,$\mathbf{v}_1=\mathbf{u}_1=(1,2)/\sqrt5$ and$A=5\,\mathbf{u}_1\mathbf{v}_1^\top$ ✓. - Shapes: a
$32\times128$ batch times a$128\times64$ matrix gives$32\times64$ .
import numpy as np
A = np.array([[2., 1.], [0.5, 1.2]])
U, S, Vt = np.linalg.svd(A)
assert np.allclose(U @ np.diag(S) @ Vt, A) # reconstruction
assert np.isclose(S[0] / S[-1], np.linalg.cond(A)) # kappa = sigma_max / sigma_min
# Best rank-1 approximation and its Frobenius error (Eckart-Young)
A1 = S[0] * np.outer(U[:, 0], Vt[0])
assert np.isclose(np.linalg.norm(A - A1), S[1]) # 2x2: error = sigma_2
# Attention-style contraction
Q, K = np.random.randn(2, 4, 8, 16), np.random.randn(2, 4, 8, 16) # b,h,t,d
S_ein = np.einsum('bhqd,bhkd->bhqk', Q, K)
assert np.allclose(S_ein, Q @ K.transpose(0, 1, 3, 2))In PyTorch, check the layout convention: torch.nn.Linear(in_f, out_f).weight.shape == (out_f, in_f).
-
Low-rank structure in practice. Fine-tuning updates
$\Delta W$ often have low intrinsic rank, motivating LoRA,$W+\Delta W=W+BA$ with$B\in\mathbb{R}^{d\times r}$ ,$A\in\mathbb{R}^{r\times k}$ (Module 22). Embedding tables and attention maps are also compressed this way. -
Numerical precision. Finite-precision error scales with
$\kappa(A)\epsilon_{\text{machine}}$ ; mixed-precision training (Module 24) exploits well-conditioned layers and loss scaling. - Orthogonal parametrisations keep singular values at 1, controlling signal growth in deep or recurrent networks (Modules 09, 12).
- Tensor decompositions (CP, Tucker) generalise SVD to higher orders and compress convolution kernels.
- Sparse and structured matrices (block-diagonal, Kronecker, circulant) give fast products; convolutions are circulant-like (Module 11).
- Random matrix theory explains why random initial weights have predictable singular value spectra (Module 09).
- Confusing tensor order (number of axes) with matrix rank (dimension of column space).
- Confusing matrix product
@with elementwise*. - Forgetting that
$(AB)^\top=B^\top A^\top$ and that inverses should rarely be formed explicitly — solve linear systems instead. - Relying on eigenvectors of non-symmetric matrices: they may be complex or non-orthogonal; prefer the SVD.
- Silent broadcasting bugs: assert shapes after every non-trivial operation.
- Using
$\ell_2$ distance on unnormalised embeddings when you meant cosine similarity.
Q1. Why does adding a bias vector
Show answer
Broadcasting aligns trailing axes, so
Q2. Dot product versus cosine similarity — when do you use which?
Show answer
The dot product mixes direction and magnitude; cosine similarity
Q3. What is the difference between the order of a tensor and the rank of a matrix?
Show answer
Order is the number of axes (a matrix has order 2 regardless of its contents). Rank is the dimension of the column space — a property of the values. A
Q4. Why does PyTorch store nn.Linear weights as (out, in)?
Show answer
It computes
Q5. How are singular values related to eigenvalues?
Show answer
The singular values of
Q6. Why can every matrix have an SVD but not every matrix an eigendecomposition?
Show answer
An eigendecomposition needs a full set of independent eigenvectors of a square matrix (a rotation by 90° has no real eigenvectors; a Jordan block is defective). The SVD only needs
Q7. Why is low-rank adaptation (LoRA) plausible?
Show answer
Empirically, the weight change needed to adapt a pretrained model to a task has small intrinsic rank: most of its energy lies in a few singular directions (compare Figure 1.2). Parametrising
Q8. What does a positive semidefinite Hessian tell you about a critical point?
Show answer
All eigenvalues
Q9. Why does a large condition number slow down gradient descent?
Show answer
For a quadratic loss with Hessian
Q10. Is
Show answer
Generally no, and dimensions may not even permit it. Layer order therefore matters:
- Strang, G. (2016). Introduction to Linear Algebra (5th ed.). Wellesley-Cambridge Press.
- Trefethen, L. N., & Bau, D. (1997). Numerical Linear Algebra. SIAM. (SVD, conditioning.)
- Goodfellow, I., Bengio, Y., & Courville, A. (2016). Deep Learning, Ch. 2. MIT Press.
- Eckart, C., & Young, G. (1936). The approximation of one matrix by another of lower rank. Psychometrika, 1, 211–218.
- Hu, E. J., et al. (2022). LoRA: Low-rank adaptation of large language models. ICLR. arXiv:2106.09685.
⬅️ Home · 🗺️ Curriculum · 🏠 Home · Module 02 ➡️
🏠 Home · 🗺️ Curriculum · 🧭 Learning paths · ❓ Question bank · 📖 Glossary · 📚 References · ✏️ Contributing
🏠 Home · 🗺️ Curriculum · 🧭 Learning paths
❓ Question bank · 📖 Glossary · 📚 References
Jump to module:
01 02 03 04 05 06 07 08 09 10 11 12
13 14 15 16 17 18 19 20 21 22 23 24