Skip to content

Module 01

Anurag Prasad edited this page Nov 8, 2026 · 10 revisions

Module 01 — Linear Algebra, Vector Spaces and Tensor Mathematics

⬅️ 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


Overview and learning goals

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 and einsum;
  • 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.

Beginner: the big picture

Scalars, vectors, matrices, tensors. A scalar is one number. A vector $\mathbf{x}\in\mathbb{R}^d$ is an ordered list of $d$ numbers — one data point with $d$ features, or one word embedding. A matrix $W\in\mathbb{R}^{m\times n}$ is a grid of numbers — a linear function from $\mathbb{R}^n$ to $\mathbb{R}^m$. A tensor generalises this to any number of axes. The number of axes is the order (not the rank — see below).

Object Typical shape Meaning
Tabular batch $B\times d$ $B$ examples, $d$ features
Image batch $B\times C\times H\times W$ channels first (PyTorch)
Token batch $B\times T\times d$ $T$ positions, $d$-dim embeddings
Attention scores $B\times h\times T\times T$ 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 $2\times2$ matrix turning the unit circle into an ellipse; the ellipse's axes are the matrix's singular directions, which we derive later.

Unit circle mapped to an ellipse by a 2x2 matrix, with singular vectors

Figure 1.1 — A matrix $A$ maps the unit circle to an ellipse. The semi-axes are $\sigma_i\mathbf{u}_i$. Original figure computed for this wiki (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"]
Loading

Core concepts and derivations

Shapes, indexing and broadcasting

Index an element of a matrix as $A_{ij}$ (row $i$, column $j$). Matrix multiplication requires matching inner dimensions: $(m\times n)(n\times p)\to(m\times p)$ with

$$ (AB)_{ij}=\sum_{k=1}^{n}A_{ik}B_{kj}. $$

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 $X\in\mathbb{R}^{B\times d_{in}}$, $b\in\mathbb{R}^{d_{out}}$ adds $b$ to every row. Broadcasting can silently produce a valid but unintended shape: adding a $(B,)$ vector to a $(B,B)$ matrix works but is almost never what you meant.

Dot products and matrix multiplication

The dot product $\mathbf{x}^\top\mathbf{y}=\sum_i x_iy_i=\lVert\mathbf{x}\rVert_2\lVert\mathbf{y}\rVert_2\cos\theta$ measures alignment. Matrix multiplication composes linear maps: $(AB)\mathbf{x}=A(B\mathbf{x})$. It is associative and distributive but not commutative ($AB\ne BA$ in general, and $BA$ may not even be defined). The elementwise (Hadamard) product $A\odot B$ is a different operation, used in gating (LSTM, GLU).

Norms, distances, orthogonality and projections

For $p\ge1$, $\lVert\mathbf{x}\rVert_p=\left(\sum_i\lvert x_i\rvert^p\right)^{1/p}$. The $\ell_2$ norm is Euclidean length; $\ell_1$ promotes sparsity; $\ell_\infty=\max_i\lvert x_i\rvert$. For matrices, the Frobenius norm is $\lVert A\rVert_F=\sqrt{\sum_{ij}A_{ij}^2}=\sqrt{\operatorname{tr}(A^\top A)}$.

Cauchy–Schwarz $\lvert\mathbf{x}^\top\mathbf{y}\rvert\le\lVert\mathbf{x}\rVert\lVert\mathbf{y}\rVert$ follows by noting $\lVert\mathbf{x}-t\mathbf{y}\rVert^2\ge0$ for all $t$ is a quadratic in $t$ with non-positive discriminant. It guarantees $\cos\theta\in[-1,1]$.

Vectors are orthogonal when $\mathbf{x}^\top\mathbf{y}=0$. The projection of $\mathbf{x}$ onto the line spanned by $\mathbf{w}$ is found by requiring the residual to be orthogonal to $\mathbf{w}$:

$$ \mathbf{x}-t\mathbf{w}\perp\mathbf{w};\Longrightarrow;(\mathbf{x}-t\mathbf{w})^\top\mathbf{w}=0;\Longrightarrow;t=\frac{\mathbf{x}^\top\mathbf{w}}{\mathbf{w}^\top\mathbf{w}},\qquad \operatorname{proj}_{\mathbf{w}}\mathbf{x}=\frac{\mathbf{x}^\top\mathbf{w}}{\mathbf{w}^\top\mathbf{w}},\mathbf{w}. $$

The same idea, applied to a subspace spanned by the columns of $A$, gives the least-squares solution $\hat{\boldsymbol{\beta}}=(A^\top A)^{-1}A^\top\mathbf{y}$ — the normal equations (Module 06).

Linear independence, span, basis, rank, null space

Vectors are linearly independent if $\sum_ic_i\mathbf{v}_i=\mathbf{0}$ forces all $c_i=0$. Their span is the set of all linear combinations; a basis is an independent spanning set. For $A\in\mathbb{R}^{m\times n}$:

  • 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: $\operatorname{rank}(A)+\dim\mathcal{N}(A)=n$. Consequently $A\mathbf{x}=\mathbf{b}$ is solvable iff $\mathbf{b}\in\mathcal{C}(A)$, and the solution is unique iff $\mathcal{N}(A)={\mathbf{0}}$. A layer with $d_{out}<d_{in}$ necessarily discards information along its null space.

Linear transformations, composition and change of basis

Every linear map $T:\mathbb{R}^n\to\mathbb{R}^m$ is $T(\mathbf{x})=A\mathbf{x}$ with columns $A_{:,j}=T(\mathbf{e}_j)$. Composition is multiplication. If the columns of an invertible $P$ are a new basis, the coordinates of $\mathbf{x}$ in that basis are $P^{-1}\mathbf{x}$, and a map $A$ is represented there by $P^{-1}AP$. Choosing a basis in which $A$ is simple (diagonal) is the whole point of the next two sections.

Eigenvalues and eigenvectors

An eigenpair satisfies $A\mathbf{v}=\lambda\mathbf{v}$, $\mathbf{v}\ne\mathbf{0}$: a direction that $A$ only rescales. Eigenvalues are roots of $\det(A-\lambda I)=0$. If $A$ has $n$ independent eigenvectors, $A=V\Lambda V^{-1}$ (diagonalisable), and $A^k=V\Lambda^kV^{-1}$ — which is why eigenvalues govern whether repeated application (an RNN, a power iteration, graph propagation) explodes or decays.

Spectral theorem. A real symmetric matrix has real eigenvalues and an orthonormal eigenbasis: $A=Q\Lambda Q^\top$, $Q^\top Q=I$. The largest eigenvalue is the maximum of the Rayleigh quotient $\mathbf{x}^\top A\mathbf{x}/\mathbf{x}^\top\mathbf{x}$.

Singular value decomposition and low-rank approximation

Every real $A\in\mathbb{R}^{m\times n}$ factors as

$$ A=U\Sigma V^\top=\sum_{i=1}^{r}\sigma_i,\mathbf{u}_i\mathbf{v}_i^\top,\qquad \sigma_1\ge\dots\ge\sigma_r>0, $$

with orthonormal $U,V$. Derivation sketch: $A^\top A$ is symmetric positive semidefinite, so $A^\top A=V\Lambda V^\top$ with $\lambda_i\ge0$; set $\sigma_i=\sqrt{\lambda_i}$ and $\mathbf{u}_i=A\mathbf{v}_i/\sigma_i$. Then $\mathbf{u}_i^\top\mathbf{u}_j=\mathbf{v}_i^\top A^\top A\mathbf{v}j/(\sigma_i\sigma_j)=\delta{ij}$.

Eckart–Young–Mirsky theorem. The best rank-$k$ approximation of $A$ in both the Frobenius and spectral norms is the truncated sum $A_k=\sum_{i\le k}\sigma_i\mathbf{u}_i\mathbf{v}_i^\top$, with errors

$$ \lVert A-A_k\rVert_2=\sigma_{k+1},\qquad \lVert A-A_k\rVert_F=\sqrt{\textstyle\sum_{i>k}\sigma_i^2}. $$

Singular value spectrum and rank-k reconstruction error

Figure 1.2 — A rank-5 signal plus noise shows five dominant singular values; the relative error of the best rank-$k$ approximation drops sharply at $k=5$. Original figure (figures/make_figs_1.py).

The condition number $\kappa(A)=\sigma_{\max}/\sigma_{\min}$ measures how much $A$ amplifies relative errors; ill-conditioned problems are slow to optimise (Module 08).

Positive (semi)definite matrices

A symmetric $A$ is PSD if $\mathbf{x}^\top A\mathbf{x}\ge0$ for all $\mathbf{x}$, and PD if strictly positive for $\mathbf{x}\ne\mathbf{0}$. Equivalent conditions: all eigenvalues $\ge0$ ($>0$); $A=B^\top B$ for some $B$ (a Gram matrix). Covariance matrices and kernel matrices are PSD. The Hessian of a twice-differentiable function being PSD at a critical point means locally convex (a minimum candidate); an indefinite Hessian signals a saddle (Module 08).

Tensor contractions and layouts

A contraction sums over a shared axis; matrix multiplication, dot products and traces are special cases. einsum writes them explicitly. Attention scores for $B$ examples, $h$ heads, $T$ positions, head width $d_k$:

$$ S_{bhqk}=\sum_{d}Q_{bhqd}K_{bhkd}\quad\Longleftrightarrow\quad\texttt{einsum('bhqd,bhkd->bhqk', Q, K)}. $$

Layout conventions differ: PyTorch images are $N\times C\times H\times W$; many TensorFlow models use $N\times H\times W\times C$. PyTorch's nn.Linear(in, out) stores $W$ as $(\text{out},\text{in})$ and computes $X W^\top+b$ — the transpose of the "row-batch" maths $XW$.

Worked example

Let $\mathbf{x}=(2,-1,3)$, $\mathbf{w}=(1,2,-1)$.

  1. Dot product: $2\cdot1+(-1)\cdot2+3\cdot(-1)=-3$. Not orthogonal.
  2. Norms: $\lVert\mathbf{x}\rVert=\sqrt{14}$, $\lVert\mathbf{w}\rVert=\sqrt6$; $\cos\theta=-3/\sqrt{84}\approx-0.327$.
  3. Projection of $\mathbf{x}$ on $\mathbf{w}$: $t=-3/6=-\tfrac12$, so $\operatorname{proj}=(-0.5,-1,0.5)$. Residual $(2.5,0,2.5)$; check $(2.5,0,2.5)\cdot(1,2,-1)=0$ ✓.
  4. 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$ ✓.
  5. Shapes: a $32\times128$ batch times a $128\times64$ matrix gives $32\times64$.

Implementation

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).

Advanced topics

  • 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).

Pitfalls and best practices

  • 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.

Conceptual questions and answers

Q1. Why does adding a bias vector $b\in\mathbb{R}^{d_{out}}$ to a $B\times d_{out}$ matrix work, and what would go wrong if it were shaped $(B,)$?

Broadcasting aligns trailing axes, so $b$ of shape $(d_{out},)$ is virtually repeated for every one of the $B$ rows — each example gets the same bias. A $(B,)$ vector would only broadcast if $B=d_{out}$ (adding a different value per column, not per example) or after an explicit reshape to $(B,1)$; otherwise it raises an error or silently does the wrong thing.

Q2. Dot product versus cosine similarity — when do you use which?

The dot product mixes direction and magnitude; cosine similarity $\mathbf{x}^\top\mathbf{y}/(\lVert\mathbf{x}\rVert\lVert\mathbf{y}\rVert)$ is scale-invariant. Use cosine when only direction matters (retrieval, contrastive learning with normalised embeddings); use the raw dot product when magnitude carries information (attention logits, where scaling by $1/\sqrt{d_k}$ controls their size).

Q3. What is the difference between the order of a tensor and the rank of a matrix?

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 $1000\times1000$ matrix of all ones has order 2 and rank 1.

Q4. Why does PyTorch store nn.Linear weights as (out, in)?

It computes $\mathbf{y}=W\mathbf{x}+\mathbf{b}$ for a single column vector $\mathbf{x}$, so rows of $W$ correspond to output units. For a batch of row vectors this becomes $XW^\top+\mathbf{b}$. The row-batch form $XW$ used in many textbooks is the transpose convention; mixing them is a classic shape bug when porting equations to code.

Q5. How are singular values related to eigenvalues?

The singular values of $A$ are the square roots of the eigenvalues of $A^\top A$ (equivalently $AA^\top$). For a symmetric PSD matrix they coincide with the eigenvalues; for a general symmetric matrix they are the absolute values of the eigenvalues.

Q6. Why can every matrix have an SVD but not every matrix an eigendecomposition?

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 $A^\top A$, which is always symmetric PSD and hence orthogonally diagonalisable, and it works for rectangular matrices.

Q7. Why is low-rank adaptation (LoRA) plausible?

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 $\Delta W=BA$ with small $r$ captures that subspace with $r(d+k)$ instead of $dk$ parameters.

Q8. What does a positive semidefinite Hessian tell you about a critical point?

All eigenvalues $\ge0$ means the function curves upward (or is flat) in every direction, so the point is a local minimum candidate — and if the Hessian is PSD everywhere, the function is convex and any local minimum is global. If some eigenvalues are negative, there is a descent direction: a saddle.

Q9. Why does a large condition number slow down gradient descent?

For a quadratic loss with Hessian $H$, the stable step size is limited by $\lambda_{\max}$ while progress along the flattest direction is governed by $\lambda_{\min}$; the number of iterations scales with $\kappa=\lambda_{\max}/\lambda_{\min}$ (see Module 08).

Q10. Is $AB=BA$? Why does it matter for network design?

Generally no, and dimensions may not even permit it. Layer order therefore matters: $W_2W_1\mathbf{x}$ applies $W_1$ first. Without a nonlinearity between them, $W_2W_1$ collapses into a single matrix, so depth adds no expressive power — nonlinearities are essential (Module 05).

Sources and further reading

  • 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 ➡️

🎓 Deep Learning Hub

🏠 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

Part 1 · Mathematical foundations
Part 2 · Neural network fundamentals
Part 3 · Training deep networks
Part 4 · Core architectures
Part 5 · Representation and generative learning
Part 6 · Specialised, modern and responsible deep learning
Reference and meta

Clone this wiki locally