1.3 Linear Algebra

Dividing an image minibatch by 255255 rescales each pixel in isolation, whereas a predictive model must combine hundreds or thousands of input features into a decision. Linear algebra is the mathematical language of such weighted combinations, allowing us to express the forward pass of an entire layer across a minibatch in one compact equation and read off its output shape and floating-point cost ahead of time.

Consider a linear image classifier sorting 28×2828 \times 28 grayscale clothing images (Chapter 3) into 1010 categories. Flattening each photograph yields 28×28=78428 \times 28 = 784 pixels. Stacking a minibatch of 256256 flattened images as the rows of a data matrix X∈R256×784\mathbf{X} \in \mathbb{R}^{256 \times 784}, arranging the 784784 weights for each of the 1010 categories as the columns of W∈R784×10\mathbf{W} \in \mathbb{R}^{784 \times 10}, and collecting the 1010 category offsets into b∈R10\mathbf{b} \in \mathbb{R}^{10} (7,8507{,}850 parameters in all), all 256×10=2,560256 \times 10 = 2{,}560 category scores across the minibatch are given by

O=XW+b,(1.3.1)\mathbf{O} = \mathbf{X}\mathbf{W} + \mathbf{b}, \tag{1.3.1}

where b\mathbf{b} is added to every row via broadcasting (Figure 1.3.1).

Figure 1.3.1:

The scores of a linear classifier for a minibatch of 256 images and 10 categories. Row ii of X\mathbf{X} holds image ii, column jj of W\mathbf{W} holds the weights of category jj, and the two meet in the score oijo_{ij}.

In this section, we build up to O=XW+b\mathbf{O} = \mathbf{X}\mathbf{W} + \mathbf{b} starting from scalars, vectors, matrices, and tensors, through reductions, dot products, and matrix products, and conclude with norms and eigenvalues (notational conventions are summarized in Notation).

import torch

1.3.1 Scalars, Vectors, Matrices, and Tensors#

We already created and reshaped 0th0^\textrm{th}-, 1st1^\textrm{st}-, 2nd2^\textrm{nd}-, and 4th4^\textrm{th}-order arrays in Section 1.1; here we pair each order (ndim in code) with its standard mathematical name and notation.

1.3.1.1 Scalars#

Single numbers are called scalars, denoted by ordinary lowercase italic letters (x,y,zx, y, z). Writing x∈Rx \in \mathbb{R} states that xx is a real number. In code, a scalar is a 0th0^\textrm{th}-order tensor with empty shape ():

x = torch.tensor(3.0)
x, x.shape
(tensor(3.), torch.Size([]))

1.3.1.2 Vectors#

A vector is a fixed-length 1D array of scalars (its elements or components), denoted by bold lowercase letters (x,y,w\mathbf{x}, \mathbf{y}, \mathbf{w}). We write x∈Rn\mathbf{x} \in \mathbb{R}^n for an nn-dimensional real vector, treated by default as a column vector:

x=[x1⋮xn],(1.3.2)\mathbf{x} =\begin{bmatrix}x_{1} \\ \vdots \\ x_{n}\end{bmatrix}, \tag{1.3.2}

or written inline as x=(x1,…,xn)\mathbf{x} = (x_1, \ldots, x_n). In code, a vector is a 1st1^\textrm{st}-order tensor:

x = torch.arange(3, dtype=torch.float32)
x
tensor([0., 1., 2.])

Whereas mathematical notation uses 1-based indexing (x1,…,xnx_1, \ldots, x_n), Python uses 0-based indexing, so the third component x3x_3 is accessed via x[2]:

x[2]
tensor(2.)

A vector's dimensionality nn (its number of components) is returned by Python's built-in len(x) or as the sole entry in its 1-tuple shape x.shape:

len(x), x.shape
(3, torch.Size([3]))

To prevent confusion when "dimension" is used informally, we reserve order (ndim) for the number of axes of a tensor and dimensionality for the number of components of a vector.

1.3.1.3 Matrices#

Matrices are 2nd2^\textrm{nd}-order tensors, denoted by bold uppercase letters (A,X,W\mathbf{A}, \mathbf{X}, \mathbf{W}). Writing A∈Rm×n\mathbf{A} \in \mathbb{R}^{m \times n} indicates mm rows and nn columns (when m=nm = n, A\mathbf{A} is square), with entry aija_{ij} in row ii and column jj:

A=[a11a12⋯a1na21a22⋯a2n⋮⋮⋱⋮am1am2⋯amn].(1.3.3)\mathbf{A}=\begin{bmatrix} a_{11} & a_{12} & \cdots & a_{1n} \\ a_{21} & a_{22} & \cdots & a_{2n} \\ \vdots & \vdots & \ddots & \vdots \\ a_{m1} & a_{m2} & \cdots & a_{mn} \\ \end{bmatrix}. \tag{1.3.3}

Tabular and flattened minibatch matrices X∈Rn×d\mathbf{X} \in \mathbb{R}^{n \times d} store one example per row and one feature per column. Below, we construct a 2×32 \times 3 matrix A:

A = torch.arange(6, dtype=torch.float32).reshape(2, 3)
A
tensor([[0., 1., 2.],
        [3., 4., 5.]])

Exchanging a matrix's rows and columns yields its transpose A⊤∈Rn×m\mathbf{A}^\top \in \mathbb{R}^{n \times m}, with [A⊤]ij=aji[\mathbf{A}^\top]_{ij} = a_{ji}, accessed in code via .T:

A.T
tensor([[0., 3.],
        [1., 4.],
        [2., 5.]])

A square matrix is symmetric if S=S⊤\mathbf{S} = \mathbf{S}^\top (sij=sjis_{ij} = s_{ji} for all i,ji, j):

S = torch.tensor([[2.0, 1.0], [1.0, 2.0]])
(S == S.T).all()
tensor(True)

1.3.1.4 Higher-Order Tensors#

Tensors with three or more axes are denoted by sans-serif uppercase letters (X,Y,Z\mathsf{X}, \mathsf{Y}, \mathsf{Z}). Below, we generate a synthetic 4D image minibatch images of shape (256,1,28,28)(256, 1, 28, 28) with entries in [0,1][0, 1] and flatten each image to form the 2D matrix X∈R256×784\mathbf{X} \in \mathbb{R}^{256 \times 784}:

images = torch.rand(256, 1, 28, 28)
X = images.reshape(256, -1)  # One row of 784 pixels per image
images.shape, X.shape
(torch.Size([256, 1, 28, 28]), torch.Size([256, 784]))

1.3.2 Elementwise Operations and Reductions#

1.3.2.1 Elementwise Operations and the Hadamard Product#

The elementwise product of two identically shaped matrices A,B∈Rm×n\mathbf{A}, \mathbf{B} \in \mathbb{R}^{m \times n} is their Hadamard product A⊙B\mathbf{A} \odot \mathbf{B}, with entries [A⊙B]ij=aijbij[\mathbf{A} \odot \mathbf{B}]_{ij} = a_{ij} b_{ij}, computed in code with *:

A * A
tensor([[ 0.,  1.,  4.],
        [ 9., 16., 25.]])

1.3.2.2 Reductions Along Axes#

Passing axis=0 to .sum() sums over rows to produce a vector of column sums (∑i=1maij\sum_{i=1}^m a_{ij}), whereas axis=1 sums over columns to produce a vector of row sums (∑j=1naij\sum_{j=1}^n a_{ij}); omitting axis sums all entries (Figure 1.3.2):

Figure 1.3.2:

Reductions of a 2×32 \times 3 matrix. Summing over axis 0 leaves one sum per column, and summing over axis 1 leaves one sum per row; the reduced axis disappears from the shape. With keepdims=True, the row sums keep the shape (2,1)(2, 1), so broadcasting stretches them across the three columns and the division A / sum_A scales every row to sum to 1.

A.sum(), A.sum(axis=0), A.sum(axis=1)
(tensor(15.), tensor([3., 5., 7.]), tensor([ 3., 12.]))

1.3.2.3 Keeping the Reduced Axis for Broadcasting#

To normalize each row of A (shape (2, 3)) by its row sum, A.sum(axis=1) (shape (2,)) cannot broadcast against (2, 3) because trailing dimensions 22 and 33 clash. Passing keepdims=True retains the reduced axis with length 11 so sum_A has shape (2, 1):

sum_A = A.sum(axis=1, keepdims=True)
sum_A, sum_A.shape
(tensor([[ 3.],
         [12.]]),
 torch.Size([2, 1]))

PyTorch accepts both dim/keepdim and the NumPy aliases axis/keepdims.

Because sum_A has shape (2, 1), dividing A / sum_A broadcasts each row sum across all three columns so that every row of the resulting 2×32 \times 3 matrix sums to 11:

A / sum_A
tensor([[0.0000, 0.3333, 0.6667],
        [0.2500, 0.3333, 0.4167]])

On our 256×784256 \times 784 minibatch X\mathbf{X}, subtracting per-pixel column means (axis=0, shape (784,)) broadcasts directly, whereas subtracting per-image row means (axis=1) requires keepdims=True (shape (256, 1)):

col_means = X.mean(axis=0)
row_means = X.mean(axis=1, keepdims=True)
col_means.shape, row_means.shape, (X - row_means).shape
(torch.Size([784]), torch.Size([256, 1]), torch.Size([256, 784]))

Beware: if X\mathbf{X} happens to be square (784×784784 \times 784), omitting keepdims=True in X - X.mean(axis=1) raises no error and silently subtracts image jj's mean from column jj of every image (Exercise 2).

1.3.3 Products#

1.3.3.1 Dot Products#

Given two vectors x,y∈Rd\mathbf{x}, \mathbf{y} \in \mathbb{R}^d, their dot product (or inner product) x⊤y\mathbf{x}^\top \mathbf{y} (also written ⟨x,y⟩\langle \mathbf{x}, \mathbf{y} \rangle) sums the products of corresponding entries:

x⊤y=∑i=1dxiyi.(1.3.4)\mathbf{x}^\top \mathbf{y} = \sum_{i=1}^{d} x_i y_i. \tag{1.3.4}

In code, we compute the dot product of two 1D vectors x and y directly with the framework's dot function:

y = torch.ones(3)
x, y, torch.dot(x, y)
(tensor([0., 1., 2.]), tensor([1., 1., 1.]), tensor(3.))

Equivalently, we can multiply x * y elementwise and sum the resulting products with sum (returning ∑ixi=0+1+2=3\sum_i x_i = 0 + 1 + 2 = 3 when y=1\mathbf{y} = \mathbf{1}):

torch.sum(x * y)
tensor(3.)

1.3.3.2 Matrix--Vector Products#

Partitioning A∈Rm×n\mathbf{A} \in \mathbb{R}^{m \times n} into its mm row vectors a1⊤,…,am⊤∈Rn\mathbf{a}_1^\top, \ldots, \mathbf{a}_m^\top \in \mathbb{R}^n, the matrix--vector product Ax\mathbf{A}\mathbf{x} with x∈Rn\mathbf{x} \in \mathbb{R}^n is the mm-vector of row dot products (Figure 1.3.3):

Ax=[a1⊤⋮am⊤]x=[a1⊤x⋮am⊤x]∈Rm.\mathbf{A}\mathbf{x} = \begin{bmatrix} \mathbf{a}^\top_{1} \\ \vdots \\ \mathbf{a}^\top_m \\ \end{bmatrix}\mathbf{x} = \begin{bmatrix} \mathbf{a}^\top_{1} \mathbf{x} \\ \vdots\\ \mathbf{a}^\top_{m} \mathbf{x}\\ \end{bmatrix} \in \mathbb{R}^m.
Figure 1.3.3:

The matrix--vector product Ax\mathbf{A}\mathbf{x} takes one dot product per row of A\mathbf{A}, so a 2×32\times3 matrix maps a vector of length 3 to a vector of length 2. The first row gives 0⋅0+1⋅1+2⋅2=50 \cdot 0 + 1 \cdot 1 + 2 \cdot 2 = 5.

In Python, the infix operator @ computes both matrix--vector and matrix--matrix products:

A.shape, x.shape, A @ x
(torch.Size([2, 3]), torch.Size([3]), tensor([ 5., 14.]))

Viewed column by column, Ax=∑j=1nxj(Aej)\mathbf{A}\mathbf{x} = \sum_{j=1}^n x_j (\mathbf{A}\mathbf{e}_j) is a linear combination of the columns of A\mathbf{A}, where the jthj^\textrm{th} column Aej\mathbf{A}\mathbf{e}_j is the image of the jthj^\textrm{th} standard basis vector ej\mathbf{e}_j. In R2\mathbb{R}^2, a 2×22 \times 2 matrix maps the unit square spanned by e1,e2\mathbf{e}_1, \mathbf{e}_2 onto the parallelogram spanned by its columns (Figure 1.3.4).

Figure 1.3.4:

A 2×22 \times 2 matrix maps the unit square (dashed) to the parallelogram spanned by its columns Ae1\mathbf{A}\mathbf{e}_1 and Ae2\mathbf{A}\mathbf{e}_2. From left to right: a rotation by 90∘90^\circ, a scaling by 2 along e1\mathbf{e}_1 and by 1/21/2 along e2\mathbf{e}_2, and a shear.

1.3.3.3 Matrix--Matrix Products#

Given A∈Rm×k\mathbf{A} \in \mathbb{R}^{m \times k} and B∈Rk×n\mathbf{B} \in \mathbb{R}^{k \times n}, their matrix product C=AB∈Rm×n\mathbf{C} = \mathbf{A}\mathbf{B} \in \mathbb{R}^{m \times n} has (i,j)(i, j) entry equal to the dot product of row ii of A\mathbf{A} with column jj of B\mathbf{B}:

cij=∑l=1kail blj.(1.3.5)c_{ij} = \sum_{l=1}^{k} a_{il}\, b_{lj}. \tag{1.3.5}
B = torch.ones(3, 4)
A @ B
tensor([[ 3.,  3.,  3.,  3.],
        [12., 12., 12., 12.]])

We can now evaluate our 10-class linear classifier O=XW+b\mathbf{O} = \mathbf{X}\mathbf{W} + \mathbf{b} on the 256×784256 \times 784 minibatch X and pick each image's highest-scoring category via argmax along axis 11:

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

Multiplying an m×km \times k matrix by a k×nk \times n matrix computes mnmn dot products of length kk, costing ≈2mkn\approx 2mkn FLOPs (2×256×784×10≈4×1062 \times 256 \times 784 \times 10 \approx 4 \times 10^6 FLOPs for X @ W, or 2n32n^3 FLOPs against only 3n23n^2 memory entries for two n×nn \times n matrices; see Chapter 13). Two special square matrices recur throughout linear algebra: the identity matrix I∈Rn×n\mathbf{I} \in \mathbb{R}^{n \times n} (11s on the main diagonal and 00s elsewhere), which leaves every vector unchanged (Ix=x\mathbf{I}\mathbf{x} = \mathbf{x}), and the inverse A−1\mathbf{A}^{-1} of an invertible matrix A\mathbf{A}, defined by A−1A=AA−1=I\mathbf{A}^{-1}\mathbf{A} = \mathbf{A}\mathbf{A}^{-1} = \mathbf{I} (Section 21.2.2.3).

Later models multiply a whole stack of matrices at once, one for each example in the minibatch. The @ operator does this without a loop: on tensors with more than two axes it multiplies along the last two and broadcasts over the leading ones (Section 1.1.3.2). Where @ does not fit, einsum lets us write the sum in (1.3.5) out index by index. The string 'bil,lj->bij' names the axes of each factor and of the result, and an index that is missing from the result, here l, is summed over. We stack three multiples of A and multiply them all by B:

As = torch.stack([A, 2 * A, 3 * A])  # Three 2 x 3 matrices, shape (3, 2, 3)
C = As @ B                           # B is broadcast across the batch
C.shape, (torch.einsum('bil,lj->bij', As, B) == C).all()
(torch.Size([3, 2, 4]), tensor(True))

The result holds three 2×42 \times 4 products, one per matrix in the stack, and einsum agrees with @ in every entry.

1.3.4 Norms#

Norms measure the magnitude of a vector or matrix, serving in machine learning both as loss functions (measuring prediction error y^−y\hat{\mathbf{y}} - \mathbf{y}) and as regularization penalties (constraining weight magnitude).

1.3.4.1 Euclidean Length and Angle#

The ℓ2\ell_2 norm (or Euclidean norm) of x∈Rn\mathbf{x} \in \mathbb{R}^n is

∥x∥2=x⊤x=∑i=1nxi2,(1.3.6)\|\mathbf{x}\|_2 = \sqrt{\mathbf{x}^\top \mathbf{x}} = \sqrt{\sum_{i=1}^n x_i^2}, \tag{1.3.6}

often abbreviated ∥x∥\|\mathbf{x}\|. For two planar vectors x,y\mathbf{x}, \mathbf{y} separated by angle θ\theta, equating the law of cosines ∥x−y∥2=∥x∥2+∥y∥2−2∥x∥∥y∥cos⁡θ\|\mathbf{x} - \mathbf{y}\|^2 = \|\mathbf{x}\|^2 + \|\mathbf{y}\|^2 - 2\|\mathbf{x}\|\|\mathbf{y}\|\cos\theta with the bilinear expansion (x−y)⊤(x−y)=∥x∥2−2x⊤y+∥y∥2(\mathbf{x} - \mathbf{y})^\top(\mathbf{x} - \mathbf{y}) = \|\mathbf{x}\|^2 - 2\mathbf{x}^\top\mathbf{y} + \|\mathbf{y}\|^2 yields (Figure 1.3.5)

x⊤y=∥x∥∥y∥cos⁡θ.(1.3.7)\mathbf{x}^\top \mathbf{y} = \|\mathbf{x}\| \|\mathbf{y}\| \cos\theta. \tag{1.3.7}

In arbitrary dimension dd, we read (1.3.7) in reverse to define the cosine similarity between nonzero vectors:

cos⁡θ=x⊤y∥x∥∥y∥,(1.3.8)\cos\theta = \frac{\mathbf{x}^\top \mathbf{y}}{\|\mathbf{x}\| \|\mathbf{y}\|}, \tag{1.3.8}

which depends only on direction and ranges from +1+1 (aligned) through 00 (orthogonal) to −1-1 (opposed) (Figure 1.3.6).

Figure 1.3.5:

The dot product x⊤y=∥x∥∥y∥cos⁡θ\mathbf{x}^\top\mathbf{y} = \|\mathbf{x}\|\|\mathbf{y}\|\cos\theta is the length of x\mathbf{x} times the signed length ∥y∥cos⁡θ\|\mathbf{y}\|\cos\theta of the projection of y\mathbf{y} onto the line through x\mathbf{x}.

Figure 1.3.6:

Two unit vectors at angle θ\theta: their dot product equals cos⁡θ\cos\theta, ranging from 11 (aligned) through 00 (perpendicular) to −1-1 (opposed).

The Cauchy--Schwarz inequality guarantees that ∣x⊤y∣≤∥x∥∥y∥|\mathbf{x}^\top\mathbf{y}| \leq \|\mathbf{x}\|\|\mathbf{y}\| (so cos⁡θ∈[−1,1]\cos\theta \in [-1, 1]): for unit vectors u=x/∥x∥\mathbf{u} = \mathbf{x}/\|\mathbf{x}\| and v=y/∥y∥\mathbf{v} = \mathbf{y}/\|\mathbf{y}\|, expanding 0≤∥u∓v∥2=2∓2u⊤v0 \leq \|\mathbf{u} \mp \mathbf{v}\|^2 = 2 \mp 2\mathbf{u}^\top\mathbf{v} gives ∣u⊤v∣≤1|\mathbf{u}^\top\mathbf{v}| \leq 1.

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

1.3.4.2 The ℓ1\ell_1, ℓp\ell_p, and Frobenius Norms#

The ℓ1\ell_1 norm (or Manhattan distance) sums the absolute values of the components (Figure 1.3.7):

∥x∥1=∑i=1n∣xi∣.(1.3.9)\|\mathbf{x}\|_1 = \sum_{i=1}^n |x_i|. \tag{1.3.9}
Figure 1.3.7:

The ℓ2\ell_2 norm of x\mathbf{x} is the length of the straight path to x\mathbf{x}; the ℓ1\ell_1 norm is the length of the path along the grid.

x = torch.tensor([3.0, -4.0])
torch.linalg.vector_norm(x), torch.abs(x).sum()
(tensor(5.), tensor(7.))

Because ℓ2\ell_2 squares components while ℓ1\ell_1 does not, ℓ1\ell_1 loss is more robust to large outlier errors, and ℓ1\ell_1 weight penalties drive weights to exact zero (sparsity). Both belong to the family of ℓp\ell_p norms ∥x∥p=(∑i=1n∣xi∣p)1/p\|\mathbf{x}\|_p = (\sum_{i=1}^n |x_i|^p)^{1/p} (p≥1p \geq 1), with ∥x∥∞=max⁡i∣xi∣\|\mathbf{x}\|_\infty = \max_i |x_i| as p→∞p \to \infty. Any valid norm satisfies (i) absolute homogeneity ∥αx∥=∣α∣∥x∥\|\alpha\mathbf{x}\| = |\alpha|\|\mathbf{x}\|, (ii) the triangle inequality ∥x+y∥≤∥x∥+∥y∥\|\mathbf{x} + \mathbf{y}\| \leq \|\mathbf{x}\| + \|\mathbf{y}\|, and (iii) positive definiteness (∥x∥>0\|\mathbf{x}\| > 0 for x≠0\mathbf{x} \neq \mathbf{0}).

For an m×nm \times n matrix A\mathbf{A}, the Frobenius norm computes the ℓ2\ell_2 norm of its mnmn entries:

∥A∥F=∑i=1m∑j=1naij2.(1.3.10)\|\mathbf{A}\|_\textrm{F} = \sqrt{\sum_{i=1}^m \sum_{j=1}^n a_{ij}^2}. \tag{1.3.10}
torch.linalg.matrix_norm(torch.ones(4, 9))
tensor(6.)

PyTorch separates torch.linalg.vector_norm from torch.linalg.matrix_norm; the latter treats a 3D tensor as a batch of 2D matrices.

1.3.5 Eigenvectors and Eigenvalues#

What happens when a 50-layer network multiplies an input vector x\mathbf{x} by matrices repeatedly? A nonzero vector v≠0\mathbf{v} \neq \mathbf{0} is an eigenvector of A∈Rn×n\mathbf{A} \in \mathbb{R}^{n \times n} with scalar eigenvalue λ\lambda if multiplying by A\mathbf{A} simply scales v\mathbf{v} without rotating it:

Av=λv⟹Akv=λkv.(1.3.11)\mathbf{A}\mathbf{v} = \lambda \mathbf{v} \quad \Longrightarrow \quad \mathbf{A}^k\mathbf{v} = \lambda^k\mathbf{v}. \tag{1.3.11}

For our symmetric matrix S=[2112]\mathbf{S} = \left[\begin{smallmatrix} 2 & 1 \\ 1 & 2 \end{smallmatrix}\right], (1,1)(1, 1) is an eigenvector with λ=3\lambda = 3 and (−1,1)(-1, 1) is an eigenvector with λ=1\lambda = 1 (Figure 1.3.8).

Figure 1.3.8:

Left: S\mathbf{S} maps the unit circle (dashed) to an ellipse whose axes are its eigenvectors, stretched by λ=3\lambda = 3 and λ=1\lambda = 1, while e1\mathbf{e}_1 is turned to Se1=(2,1)\mathbf{S}\mathbf{e}_1 = (2, 1). Right: the directions of Ske1\mathbf{S}^k\mathbf{e}_1 for k=0,…,4k = 0, \ldots, 4 approach the eigenvector (1,1)(1, 1) of the largest eigenvalue.

We compute eigenvalues and unit eigenvectors of a real symmetric matrix using 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]]))

By the spectral theorem (Section 21.3), every real symmetric n×nn \times n matrix A\mathbf{A} has nn real eigenvalues and a complete orthonormal basis of eigenvectors v1,…,vn\mathbf{v}_1, \ldots, \mathbf{v}_n. Expanding any vector x=∑i=1ncivi\mathbf{x} = \sum_{i=1}^n c_i \mathbf{v}_i (with ci=vi⊤xc_i = \mathbf{v}_i^\top \mathbf{x}) gives

Akx=∑i=1nciλikvi.(1.3.12)\mathbf{A}^k \mathbf{x} = \sum_{i=1}^n c_i \lambda_i^k \mathbf{v}_i. \tag{1.3.12}

As kk grows, the term with the largest ∣λi∣|\lambda_i| dominates: Akx\mathbf{A}^k\mathbf{x} aligns with the dominant eigenvector and grows by max⁡i∣λi∣\max_i |\lambda_i| per step (power iteration). For a symmetric matrix this growth rate is also the largest factor by which the matrix can stretch any vector, its spectral norm ∥A∥2=max⁡x≠0∥Ax∥/∥x∥\|\mathbf{A}\|_2 = \max_{\mathbf{x}\neq\mathbf{0}} \|\mathbf{A}\mathbf{x}\|/\|\mathbf{x}\|.

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

Returning to our 50-layer thought experiment: for M=[10.10.11]\mathbf{M} = \left[\begin{smallmatrix} 1 & 0.1 \\ 0.1 & 1 \end{smallmatrix}\right], whose eigenvalues λ1=1.1\lambda_1 = 1.1 and λ2=0.9\lambda_2 = 0.9 differ from 11 by just 10%10\%, multiplying its two unit eigenvectors by M\mathbf{M} 5050 times amplifies the first by 1.150≈117.41.1^{50} \approx 117.4 and shrinks the second to 0.950≈0.00520.9^{50} \approx 0.0052:

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

The weight matrices of a network are not symmetric, and most are not even square. Do eigenvalues still tell us how far such a matrix stretches a vector? They do not. Both eigenvalues of A=[0200]\mathbf{A} = \left[\begin{smallmatrix} 0 & 2 \\ 0 & 0 \end{smallmatrix}\right] are 00, and A2=0\mathbf{A}^2 = \mathbf{0}, yet A\mathbf{A} maps e2\mathbf{e}_2 to 2e12\mathbf{e}_1 and so doubles its length. Since ∥Ax∥22=x⊤A⊤Ax\|\mathbf{A}\mathbf{x}\|_2^2 = \mathbf{x}^\top\mathbf{A}^\top\mathbf{A}\mathbf{x}, stretching is governed by the symmetric matrix A⊤A\mathbf{A}^\top\mathbf{A}. The square roots of its eigenvalues, σi=λi(A⊤A)\sigma_i = \sqrt{\lambda_i(\mathbf{A}^\top\mathbf{A})}, are the singular values of A\mathbf{A}, and they exist for every matrix, square or not. We compute them for S\mathbf{S} and for A\mathbf{A}:

A = torch.tensor([[0.0, 2.0], [0.0, 0.0]])  # Both eigenvalues are 0
svdvals = torch.linalg.svdvals
(svdvals(S), svdvals(A), torch.linalg.eigvalsh(A.T @ A).sqrt(),
 torch.linalg.matrix_rank(A))
(tensor([3., 1.]), tensor([2., 0.]), tensor([0., 2.]), tensor(1))

For the symmetric S\mathbf{S} the singular values are 33 and 11 (up to rounding), the magnitudes of its eigenvalues: for a symmetric matrix the two notions agree. For A\mathbf{A} they are 22 and 00, and the eigenvalues of A⊤A\mathbf{A}^\top\mathbf{A} return the same two numbers in ascending order. The largest singular value is the spectral norm of any matrix. The number of nonzero singular values is its rank, the number of independent directions that survive the multiplication, which is one for A\mathbf{A}. Both facts follow from the singular value decomposition (Section 21.5).

Unless each layer's weight matrix keeps vector lengths close to 11 on average, activations and gradients explode or vanish exponentially with depth (Section 4.4).

1.3.6 Summary#

Linear algebra expresses whole-minibatch models compactly: stacking 256256 flattened images as X∈R256×784\mathbf{X} \in \mathbb{R}^{256 \times 784} computes all 2,5602{,}560 category scores via O=XW+b\mathbf{O} = \mathbf{X}\mathbf{W} + \mathbf{b}. Reductions aggregate along specified axes (keepdims=True retains the axis as length 11 for broadcasting). Dot products x⊤y=∑ixiyi\mathbf{x}^\top\mathbf{y} = \sum_i x_i y_i build matrix--vector products Ax\mathbf{A}\mathbf{x} and matrix--matrix products AB\mathbf{A}\mathbf{B} (costing ≈2mkn\approx 2mkn FLOPs). Norms (ℓ2\ell_2, ℓ1\ell_1, ℓp\ell_p, Frobenius, and spectral) measure vector and matrix magnitudes, normalized dot products give cosine similarity cos⁡θ=x⊤y/(∥x∥∥y∥)\cos\theta = \mathbf{x}^\top\mathbf{y}/(\|\mathbf{x}\|\|\mathbf{y}\|), and eigenvectors (Av=λv\mathbf{A}\mathbf{v} = \lambda\mathbf{v}) explain why repeated matrix multiplication scales components as λk\lambda^k. For a matrix that is not symmetric, the singular values measure the stretching, and the largest of them is the spectral norm.

1.3.7 Exercises#

  1. Transposes and matrix products. Prove the following algebraic identities:
    1. Show that the transpose of a matrix product reverses the order of the factors: (AB)⊤=B⊤A⊤(\mathbf{A}\mathbf{B})^\top = \mathbf{B}^\top\mathbf{A}^\top whenever AB\mathbf{A}\mathbf{B} is defined. (Write out the (i,j)(i, j) entry of both sides using (1.3.5).)
    2. Show that for any rectangular matrix X∈Rm×n\mathbf{X} \in \mathbb{R}^{m \times n}, the product XX⊤\mathbf{X}\mathbf{X}^\top is always square and symmetric (and likewise for X⊤X\mathbf{X}^\top\mathbf{X}). For our 256×784256 \times 784 image minibatch X\mathbf{X}, what is the shape of XX⊤\mathbf{X}\mathbf{X}^\top, and what does its (i,j)(i, j) entry measure?
  1. [code] Predicting reduction and broadcasting shapes. Without running any code, predict the shape (or error) of each expression below for images of shape (256,1,28,28)(256, 1, 28, 28) and X of shape (256,784)(256, 784), then verify your answers in code:
    1. What does len(images) return? What are the shapes of images.sum(axis=(2, 3)) with keepdims=False versus keepdims=True? Which of the two can divide images directly via broadcasting, and what does images / images.sum(axis=(2, 3), keepdims=True) compute?
    2. What happens when you evaluate X - X.mean(axis=1) on our 256×784256 \times 784 matrix X, and how does keepdims=True fix it?
    3. Now suppose your minibatch happens to contain n=784n = 784 images, so that X is a square 784×784784 \times 784 matrix. Show that X - X.mean(axis=1) executes without raising any error. Write out what entry (i,j)(i, j) of X - X.mean(axis=1) actually computes in terms of the entries of X, and explain why a silent broadcasting bug on a square matrix is far more dangerous than a shape error.
  1. How mutually obtuse can a set of vectors be? The following questions explore how negative all pairwise dot products among kk vectors can simultaneously be.

    1. Can three vectors u,v,w∈R2\mathbf{u}, \mathbf{v}, \mathbf{w} \in \mathbb{R}^2 in the plane satisfy u⊤v<0\mathbf{u}^\top\mathbf{v} \lt 0, v⊤w<0\mathbf{v}^\top\mathbf{w} \lt 0, and u⊤w<0\mathbf{u}^\top\mathbf{w} \lt 0 simultaneously? Provide a concrete numerical example, or prove that none exists.
    2. Suppose k≥2k \geq 2 unit vectors u1,…,uk∈Rd\mathbf{u}_1, \ldots, \mathbf{u}_k \in \mathbb{R}^d (d≥k−1d \geq k - 1) are arranged symmetrically so that every distinct pair has the exact same dot product ui⊤uj=c\mathbf{u}_i^\top\mathbf{u}_j = c for all i≠ji \neq j. By expanding 0≤∥u1+⋯+uk∥220 \leq \|\mathbf{u}_1 + \cdots + \mathbf{u}_k\|_2^2, prove that c≥−1k−1c \geq -\frac{1}{k - 1}. What does this bound imply about the pairwise cosine similarity of 1010 unit-length class templates in a 10-class classifier when all 1010 templates are separated by equal angles?

    Adapted from MIT 18.06, Problem Set 1, Section 1.2, Problem 28.

  2. [code] Norms across multiple parameter tensors. The vector-norm routines introduced in this section can also be applied to higher-order tensors.

    1. Evaluate the vector norm with default arguments on a 3D tensor of shape (2,3,4)(2, 3, 4), state in words what mathematical formula it computes, and confirm your answer by squaring, summing, and taking the square root of the entries manually.
    2. A deep neural network stores its learnable parameters across a list of weight and bias tensors of varying orders and shapes. When monitoring training or clipping gradients (Section 8.4.2), we often need the single global ℓ2\ell_2 norm of all parameters concatenated into one giant vector. Express this global ℓ2\ell_2 norm in terms of the individual tensor norms without flattening or concatenating the tensors, and verify your formula in code on three tensors of shapes (3,4)(3, 4), (4,)(4,), and (2,3,5)(2, 3, 5).
  3. Associativity of matrix multiplication and computational cost. Although matrix multiplication is associative, meaning (AB)C=A(BC)(\mathbf{A}\mathbf{B})\mathbf{C} = \mathbf{A}(\mathbf{B}\mathbf{C}) mathematically, the order in which you parenthesize a chain of matrix products can change its computational cost by orders of magnitude. Given A∈R1000×50000\mathbf{A} \in \mathbb{R}^{1000 \times 50000}, B∈R50000×20\mathbf{B} \in \mathbb{R}^{50000 \times 20}, and C∈R20×10000\mathbf{C} \in \mathbb{R}^{20 \times 10000}, calculate the total FLOP count and the number of entries in the intermediate product matrix under both (AB)C(\mathbf{A}\mathbf{B})\mathbf{C} and A(BC)\mathbf{A}(\mathbf{B}\mathbf{C}). By what factors do the two evaluation orders differ in arithmetic work and intermediate memory?

  4. [code] All-pairs Euclidean distance matrix without loops. ● Given two collections of 5050 vectors in R8\mathbb{R}^8 stacked as the rows of X∈R50×8\mathbf{X} \in \mathbb{R}^{50 \times 8} and Y∈R50×8\mathbf{Y} \in \mathbb{R}^{50 \times 8}, we want to compute the 50×5050 \times 50 matrix D\mathbf{D} of squared Euclidean distances Dij=∥xi−yj∥22D_{ij} = \|\mathbf{x}_i - \mathbf{y}_j\|_2^2 without Python loops:

    1. Compute D\mathbf{D} first via 3D broadcasting: reshape X\mathbf{X} to (50,1,8)(50, 1, 8) and Y\mathbf{Y} to (1,50,8)(1, 50, 8), subtract, square, and sum along the last axis. Second, compute D\mathbf{D} via the quadratic expansion ∥xi−yj∥22=∥xi∥22+∥yj∥22−2xi⊤yj\|\mathbf{x}_i - \mathbf{y}_j\|_2^2 = \|\mathbf{x}_i\|_2^2 + \|\mathbf{y}_j\|_2^2 - 2\mathbf{x}_i^\top\mathbf{y}_j, which requires only row-norm reductions, 2D broadcasting, and a single matrix multiplication XY⊤\mathbf{X}\mathbf{Y}^\top. Verify that both results match to floating-point precision.
    2. When X\mathbf{X} and Y\mathbf{Y} each contain 10,00010{,}000 vectors in R128\mathbb{R}^{128}, how many intermediate floating-point numbers must the 3D-broadcasting method allocate compared with the matrix-product method? Which method should you use at scale?
    3. Explain why floating-point rounding in ∥xi∥22+∥yj∥22−2xi⊤yj\|\mathbf{x}_i\|_2^2 + \|\mathbf{y}_j\|_2^2 - 2\mathbf{x}_i^\top\mathbf{y}_j can occasionally produce tiny negative numbers (such as −10−7-10^{-7}) when xi=yj\mathbf{x}_i = \mathbf{y}_j, and show how to clamp the output before taking a square root.

    Adapted from Stanford CS231n, Assignment 1 (kk-nearest-neighbor distances), and fast.ai, Deep Learning from the Foundations, Lesson 8.

  5. [code] Power iteration and convergence rate. ● Implement normalized power iteration, repeatedly updating vk+1=Avk/∥Avk∥2\mathbf{v}_{k+1} = \mathbf{A}\mathbf{v}_k / \|\mathbf{A}\mathbf{v}_k\|_2 from a random unit vector v0\mathbf{v}_0, on the 3×33 \times 3 symmetric matrix

A=[123204345].(1.3.13)\mathbf{A} = \begin{bmatrix} 1 & 2 & 3 \\ 2 & 0 & 4 \\ 3 & 4 & 5 \end{bmatrix}. \tag{1.3.13}
  1. Record the first iteration kk at which the absolute cosine similarity ∣vk⊤vk−1∣|\mathbf{v}_k^\top \mathbf{v}_{k-1}| between consecutive iterates exceeds 0.9990.999. Compare your converged vector vk\mathbf{v}_k against the dominant eigenvector returned by eigh(A), and explain why the two vectors may differ by an overall sign ±1\pm 1.
  2. At each step, measure the sine of the angle between vk\mathbf{v}_k and the true dominant eigenvector umax⁡\mathbf{u}_{\max}, sin⁡θk=1−(vk⊤umax⁡)2\sin\theta_k = \sqrt{1 - (\mathbf{v}_k^\top \mathbf{u}_{\max})^2}, and compute the per-step shrinkage ratio sin⁡θk+1/sin⁡θk\sin\theta_{k+1} / \sin\theta_k. Express this asymptotic ratio in terms of the eigenvalues of A\mathbf{A} using (1.3.12), and use it to explain why power iteration converged in so few steps.
  3. Now run power iteration on the shifted matrix B=A−9I\mathbf{B} = \mathbf{A} - 9\mathbf{I}. Which eigenvalue and eigenvector of A\mathbf{A} does power iteration converge to now, what happens to the sign of consecutive iterates vk\mathbf{v}_k and vk+1\mathbf{v}_{k+1}, and why?

Adapted from MIT 18.06, Problem Set 1, Section 2.1, Problems 29–30.

Discussions