1.3  Linear Algebra

Dividing an image minibatch by \(255\) 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 \times 28\) grayscale clothing images (Chapter 3) into \(10\) categories. Flattening each photograph yields \(28 \times 28 = 784\) pixels. Stacking a minibatch of \(256\) flattened images as the rows of a data matrix \(\mathbf{X} \in \mathbb{R}^{256 \times 784}\), arranging the \(784\) weights for each of the \(10\) categories as the columns of \(\mathbf{W} \in \mathbb{R}^{784 \times 10}\), and collecting the \(10\) category offsets into \(\mathbf{b} \in \mathbb{R}^{10}\) (\(7{,}850\) parameters in all), all \(256 \times 10 = 2{,}560\) category scores across the minibatch are given by

\[\mathbf{O} = \mathbf{X}\mathbf{W} + \mathbf{b}, \tag{1.3.1}\]

where \(\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 \(i\) of \(\mathbf{X}\) holds image \(i\), column \(j\) of \(\mathbf{W}\) holds the weights of category \(j\), and the two meet in the score \(o_{ij}\).

In this section, we build up to \(\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
import tensorflow as tf
import random
import jax
from jax import numpy as jnp
from mxnet import np as mnp, npx
npx.set_np()

1.3.1 Scalars, Vectors, Matrices, and Tensors

We already created and reshaped \(0^\textrm{th}\)-, \(1^\textrm{st}\)-, \(2^\textrm{nd}\)-, and \(4^\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, z\)). Writing \(x \in \mathbb{R}\) states that \(x\) is a real number. In code, a scalar is a \(0^\textrm{th}\)-order tensor with empty shape ():

x = torch.tensor(3.0)
x, x.shape
(tensor(3.), torch.Size([]))
x = tf.constant(3.0)
x, x.shape
(<tf.Tensor: shape=(), dtype=float32, numpy=3.0>, TensorShape([]))
x = jnp.array(3.0)
x, x.shape
(Array(3., dtype=float32, weak_type=True), ())
x = mnp.array(3.0)
x, x.shape
(array(3.), ())

1.3.1.2 Vectors

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

\[\mathbf{x} =\begin{bmatrix}x_{1} \\ \vdots \\ x_{n}\end{bmatrix}, \tag{1.3.2}\]

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

x = torch.arange(3, dtype=torch.float32)
x
tensor([0., 1., 2.])
x = tf.range(3, dtype=tf.float32)
x
<tf.Tensor: shape=(3,), dtype=float32, numpy=array([0., 1., 2.], dtype=float32)>
x = jnp.arange(3, dtype=jnp.float32)
x
Array([0., 1., 2.], dtype=float32)
x = mnp.arange(3)
x
array([0., 1., 2.])

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

x[2]
tensor(2.)
<tf.Tensor: shape=(), dtype=float32, numpy=2.0>
Array(2., dtype=float32)
array(2.)

A vector’s dimensionality \(n\) (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]))
(3, TensorShape([3]))
(3, (3,))
(3, (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 \(2^\textrm{nd}\)-order tensors, denoted by bold uppercase letters (\(\mathbf{A}, \mathbf{X}, \mathbf{W}\)). Writing \(\mathbf{A} \in \mathbb{R}^{m \times n}\) indicates \(m\) rows and \(n\) columns (when \(m = n\), \(\mathbf{A}\) is square), with entry \(a_{ij}\) in row \(i\) and column \(j\):

\[\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 \(\mathbf{X} \in \mathbb{R}^{n \times d}\) store one example per row and one feature per column. Below, we construct a \(2 \times 3\) matrix A:

A = torch.arange(6, dtype=torch.float32).reshape(2, 3)
A
tensor([[0., 1., 2.],
        [3., 4., 5.]])
A = tf.reshape(tf.range(6, dtype=tf.float32), (2, 3))
A
<tf.Tensor: shape=(2, 3), dtype=float32, numpy=
array([[0., 1., 2.],
       [3., 4., 5.]], dtype=float32)>
A = jnp.arange(6, dtype=jnp.float32).reshape(2, 3)
A
Array([[0., 1., 2.],
       [3., 4., 5.]], dtype=float32)
A = mnp.arange(6).reshape(2, 3)
A
array([[0., 1., 2.],
       [3., 4., 5.]])

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

In TensorFlow, use tf.transpose(A).

A.T
tensor([[0., 3.],
        [1., 4.],
        [2., 5.]])
tf.transpose(A)
<tf.Tensor: shape=(3, 2), dtype=float32, numpy=
array([[0., 3.],
       [1., 4.],
       [2., 5.]], dtype=float32)>
A.T
Array([[0., 3.],
       [1., 4.],
       [2., 5.]], dtype=float32)
A.T
array([[0., 3.],
       [1., 4.],
       [2., 5.]])

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

S = torch.tensor([[2.0, 1.0], [1.0, 2.0]])
(S == S.T).all()
tensor(True)
S = tf.constant([[2.0, 1.0], [1.0, 2.0]])
tf.reduce_all(S == tf.transpose(S))
<tf.Tensor: shape=(), dtype=bool, numpy=True>
S = jnp.array([[2.0, 1.0], [1.0, 2.0]])
(S == S.T).all()
Array(True, dtype=bool)
S = mnp.array([[2.0, 1.0], [1.0, 2.0]])
(S == S.T).all()
array(True)

1.3.1.4 Higher-Order Tensors

Tensors with three or more axes are denoted by sans-serif uppercase letters (\(\mathsf{X}, \mathsf{Y}, \mathsf{Z}\)). Below, we generate a synthetic 4D image minibatch images of shape \((256, 1, 28, 28)\) with entries in \([0, 1]\) and flatten each image to form the 2D matrix \(\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]))
images = tf.random.uniform((256, 1, 28, 28))
X = tf.reshape(images, (256, -1))  # One row of 784 pixels per image
images.shape, X.shape
(TensorShape([256, 1, 28, 28]), TensorShape([256, 784]))
key = jax.random.key(random.getrandbits(32))  # A new seed on each run
key, subkey = jax.random.split(key)
images = jax.random.uniform(subkey, (256, 1, 28, 28))
X = images.reshape(256, -1)  # One row of 784 pixels per image
images.shape, X.shape
((256, 1, 28, 28), (256, 784))
images = mnp.random.uniform(size=(256, 1, 28, 28))
X = images.reshape(256, -1)  # One row of 784 pixels per image
images.shape, X.shape
((256, 1, 28, 28), (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 \(\mathbf{A}, \mathbf{B} \in \mathbb{R}^{m \times n}\) is their Hadamard product \(\mathbf{A} \odot \mathbf{B}\), with entries \([\mathbf{A} \odot \mathbf{B}]_{ij} = a_{ij} b_{ij}\), computed in code with *:

A * A
tensor([[ 0.,  1.,  4.],
        [ 9., 16., 25.]])
<tf.Tensor: shape=(2, 3), dtype=float32, numpy=
array([[ 0.,  1.,  4.],
       [ 9., 16., 25.]], dtype=float32)>
Array([[ 0.,  1.,  4.],
       [ 9., 16., 25.]], dtype=float32)
array([[ 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 (\(\sum_{i=1}^m a_{ij}\)), whereas axis=1 sums over columns to produce a vector of row sums (\(\sum_{j=1}^n a_{ij}\)); omitting axis sums all entries (Figure 1.3.2):

Figure 1.3.2: Reductions of a \(2 \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)\), 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.]))
tf.reduce_sum(A), tf.reduce_sum(A, axis=0), tf.reduce_sum(A, axis=1)
(<tf.Tensor: shape=(), dtype=float32, numpy=15.0>,
 <tf.Tensor: shape=(3,), dtype=float32, numpy=array([3., 5., 7.], dtype=float32)>,
 <tf.Tensor: shape=(2,), dtype=float32, numpy=array([ 3., 12.], dtype=float32)>)
A.sum(), A.sum(axis=0), A.sum(axis=1)
(Array(15., dtype=float32),
 Array([3., 5., 7.], dtype=float32),
 Array([ 3., 12.], dtype=float32))
A.sum(), A.sum(axis=0), A.sum(axis=1)
(array(15.), array([3., 5., 7.]), array([ 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 \(2\) and \(3\) clash. Passing keepdims=True retains the reduced axis with length \(1\) 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]))
sum_A = tf.reduce_sum(A, axis=1, keepdims=True)
sum_A, sum_A.shape
(<tf.Tensor: shape=(2, 1), dtype=float32, numpy=
 array([[ 3.],
        [12.]], dtype=float32)>,
 TensorShape([2, 1]))
sum_A = A.sum(axis=1, keepdims=True)
sum_A, sum_A.shape
(Array([[ 3.],
        [12.]], dtype=float32),
 (2, 1))
sum_A = A.sum(axis=1, keepdims=True)
sum_A, sum_A.shape
(array([[ 3.],
        [12.]]),
 (2, 1))

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

TensorFlow tensors have no .sum or .mean method: use tf.reduce_sum(A, axis=1) and tf.reduce_mean(X, axis=1) instead.

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 \times 3\) matrix sums to \(1\):

A / sum_A
tensor([[0.0000, 0.3333, 0.6667],
        [0.2500, 0.3333, 0.4167]])
<tf.Tensor: shape=(2, 3), dtype=float32, numpy=
array([[0.        , 0.33333334, 0.6666667 ],
       [0.25      , 0.33333334, 0.41666666]], dtype=float32)>
Array([[0.        , 0.33333334, 0.6666667 ],
       [0.25      , 0.33333334, 0.4166667 ]], dtype=float32)
array([[0.        , 0.33333334, 0.6666667 ],
       [0.25      , 0.33333334, 0.41666666]])

On our \(256 \times 784\) minibatch \(\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]))
col_means = tf.reduce_mean(X, axis=0)
row_means = tf.reduce_mean(X, axis=1, keepdims=True)
col_means.shape, row_means.shape, (X - row_means).shape
(TensorShape([784]), TensorShape([256, 1]), TensorShape([256, 784]))
col_means = X.mean(axis=0)
row_means = X.mean(axis=1, keepdims=True)
col_means.shape, row_means.shape, (X - row_means).shape
((784,), (256, 1), (256, 784))
col_means = X.mean(axis=0)
row_means = X.mean(axis=1, keepdims=True)
col_means.shape, row_means.shape, (X - row_means).shape
((784,), (256, 1), (256, 784))

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

1.3.3 Products

1.3.3.1 Dot Products

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

\[\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:

TensorFlow computes it with tf.tensordot(x, y, axes=1).

y = torch.ones(3)
x, y, torch.dot(x, y)
(tensor([0., 1., 2.]), tensor([1., 1., 1.]), tensor(3.))
y = tf.ones(3)
x, y, tf.tensordot(x, y, axes=1)
(<tf.Tensor: shape=(3,), dtype=float32, numpy=array([0., 1., 2.], dtype=float32)>,
 <tf.Tensor: shape=(3,), dtype=float32, numpy=array([1., 1., 1.], dtype=float32)>,
 <tf.Tensor: shape=(), dtype=float32, numpy=3.0>)
y = jnp.ones(3)
x, y, jnp.dot(x, y)
(Array([0., 1., 2.], dtype=float32),
 Array([1., 1., 1.], dtype=float32),
 Array(3., dtype=float32))
y = mnp.ones(3)
x, y, mnp.dot(x, y)
(array([0., 1., 2.]), array([1., 1., 1.]), array(3.))

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

torch.sum(x * y)
tensor(3.)
tf.reduce_sum(x * y)
<tf.Tensor: shape=(), dtype=float32, numpy=3.0>
jnp.sum(x * y)
Array(3., dtype=float32)
mnp.sum(x * y)
array(3.)

1.3.3.2 Matrix–Vector Products

Partitioning \(\mathbf{A} \in \mathbb{R}^{m \times n}\) into its \(m\) row vectors \(\mathbf{a}_1^\top, \ldots, \mathbf{a}_m^\top \in \mathbb{R}^n\), the matrix–vector product \(\mathbf{A}\mathbf{x}\) with \(\mathbf{x} \in \mathbb{R}^n\) is the \(m\)-vector of row dot products (Figure 1.3.3):

\[ \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 \(\mathbf{A}\mathbf{x}\) takes one dot product per row of \(\mathbf{A}\), so a \(2\times3\) matrix maps a vector of length 3 to a vector of length 2. The first row gives \(0 \cdot 0 + 1 \cdot 1 + 2 \cdot 2 = 5\).

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

In TensorFlow, @ requires 2D matrices, so matrix–vector products use tf.linalg.matvec(A, x):

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

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.]))
A.shape, x.shape, tf.linalg.matvec(A, x).numpy()
(TensorShape([2, 3]), TensorShape([3]), array([ 5., 14.], dtype=float32))
A.shape, x.shape, A @ x
((2, 3), (3,), Array([ 5., 14.], dtype=float32))
A.shape, x.shape, A @ x
((2, 3), (3,), array([ 5., 14.]))

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

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

1.3.3.3 Matrix–Matrix Products

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

\[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.]])
B = tf.ones((3, 4))
A @ B
<tf.Tensor: shape=(2, 4), dtype=float32, numpy=
array([[ 3.,  3.,  3.,  3.],
       [12., 12., 12., 12.]], dtype=float32)>
B = jnp.ones((3, 4))
A @ B
Array([[ 3.,  3.,  3.,  3.],
       [12., 12., 12., 12.]], dtype=float32)
B = mnp.ones((3, 4))
A @ B
array([[ 3.,  3.,  3.,  3.],
       [12., 12., 12., 12.]])

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

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]))
W = 0.01 * tf.random.normal((784, 10))  # Column j: category j
b = tf.zeros(10)                        # Entry j: category j
O = X @ W + b                           # Row i: image i
O.shape, tf.argmax(O, axis=1).shape
(TensorShape([256, 10]), TensorShape([256]))
key, subkey = jax.random.split(key)
W = 0.01 * jax.random.normal(subkey, (784, 10))  # Column j: category j
b = jnp.zeros(10)                             # Entry j: category j
O = X @ W + b                                 # Row i: image i
O.shape, O.argmax(axis=1).shape
((256, 10), (256,))
W = 0.01 * mnp.random.normal(size=(784, 10))  # Column j: category j
b = mnp.zeros(10)                             # Entry j: category j
O = X @ W + b                                 # Row i: image i
O.shape, O.argmax(axis=1).shape
((256, 10), (256,))

Multiplying an \(m \times k\) matrix by a \(k \times n\) matrix computes \(mn\) dot products of length \(k\), costing \(\approx 2mkn\) FLOPs (\(2 \times 256 \times 784 \times 10 \approx 4 \times 10^6\) FLOPs for X @ W, or \(2n^3\) FLOPs against only \(3n^2\) memory entries for two \(n \times n\) matrices; see Chapter 13). Two special square matrices recur throughout linear algebra: the identity matrix \(\mathbf{I} \in \mathbb{R}^{n \times n}\) (\(1\)s on the main diagonal and \(0\)s elsewhere), which leaves every vector unchanged (\(\mathbf{I}\mathbf{x} = \mathbf{x}\)), and the inverse \(\mathbf{A}^{-1}\) of an invertible matrix \(\mathbf{A}\), defined by \(\mathbf{A}^{-1}\mathbf{A} = \mathbf{A}\mathbf{A}^{-1} = \mathbf{I}\) (Section 33.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 Equation 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))
As = tf.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, tf.reduce_all(tf.einsum('bil,lj->bij', As, B) == C)
(TensorShape([3, 2, 4]), <tf.Tensor: shape=(), dtype=bool, numpy=True>)
As = jnp.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, (jnp.einsum('bil,lj->bij', As, B) == C).all()
((3, 2, 4), Array(True, dtype=bool))
As = mnp.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, (mnp.einsum('bil,lj->bij', As, B) == C).all()
((3, 2, 4), array(True))

The result holds three \(2 \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 \(\hat{\mathbf{y}} - \mathbf{y}\)) and as regularization penalties (constraining weight magnitude).

1.3.4.1 Euclidean Length and Angle

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

\[\|\mathbf{x}\|_2 = \sqrt{\mathbf{x}^\top \mathbf{x}} = \sqrt{\sum_{i=1}^n x_i^2}, \tag{1.3.6}\]

often abbreviated \(\|\mathbf{x}\|\). For two planar vectors \(\mathbf{x}, \mathbf{y}\) separated by angle \(\theta\), equating the law of cosines \(\|\mathbf{x} - \mathbf{y}\|^2 = \|\mathbf{x}\|^2 + \|\mathbf{y}\|^2 - 2\|\mathbf{x}\|\|\mathbf{y}\|\cos\theta\) with the bilinear expansion \((\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)

\[\mathbf{x}^\top \mathbf{y} = \|\mathbf{x}\| \|\mathbf{y}\| \cos\theta. \tag{1.3.7}\]

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

\[\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\) (aligned) through \(0\) (orthogonal) to \(-1\) (opposed) (Figure 1.3.6).

Figure 1.3.5: The dot product \(\mathbf{x}^\top\mathbf{y} = \|\mathbf{x}\|\|\mathbf{y}\|\cos\theta\) is the length of \(\mathbf{x}\) times the signed length \(\|\mathbf{y}\|\cos\theta\) of the projection of \(\mathbf{y}\) onto the line through \(\mathbf{x}\).
Figure 1.3.6: Two unit vectors at angle \(\theta\): their dot product equals \(\cos\theta\), ranging from \(1\) (aligned) through \(0\) (perpendicular) to \(-1\) (opposed).

The Cauchy–Schwarz inequality guarantees that \(|\mathbf{x}^\top\mathbf{y}| \leq \|\mathbf{x}\|\|\mathbf{y}\|\) (so \(\cos\theta \in [-1, 1]\)): for unit vectors \(\mathbf{u} = \mathbf{x}/\|\mathbf{x}\|\) and \(\mathbf{v} = \mathbf{y}/\|\mathbf{y}\|\), expanding \(0 \leq \|\mathbf{u} \mp \mathbf{v}\|^2 = 2 \mp 2\mathbf{u}^\top\mathbf{v}\) gives \(|\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))
def cosine(x, y):
    return tf.tensordot(x, y, axes=1) / (tf.norm(x) * tf.norm(y))

x, y = tf.constant([1.0, 1, 1, 1]), tf.constant([1.0, 1, 1, -1])
cosine(x, y).numpy(), cosine(2 * x, y).numpy(), tf.acos(cosine(x, y)).numpy()
(np.float32(0.5), np.float32(0.5), np.float32(1.0471976))
def cosine(x, y):
    return jnp.dot(x, y) / (jnp.linalg.norm(x) * jnp.linalg.norm(y))

x, y = jnp.array([1.0, 1, 1, 1]), jnp.array([1.0, 1, 1, -1])
cosine(x, y), cosine(2 * x, y), jnp.arccos(cosine(x, y))
(Array(0.5, dtype=float32),
 Array(0.5, dtype=float32),
 Array(1.0471976, dtype=float32))
def cosine(x, y):
    return mnp.dot(x, y) / (mnp.linalg.norm(x) * mnp.linalg.norm(y))

x, y = mnp.array([1.0, 1, 1, 1]), mnp.array([1.0, 1, 1, -1])
cosine(x, y), cosine(2 * x, y), mnp.arccos(cosine(x, y))
(array(0.5), array(0.5), array(1.0471976))

1.3.4.2 The \(\ell_1\), \(\ell_p\), and Frobenius Norms

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

\[\|\mathbf{x}\|_1 = \sum_{i=1}^n |x_i|. \tag{1.3.9}\]

Figure 1.3.7: The \(\ell_2\) norm of \(\mathbf{x}\) is the length of the straight path to \(\mathbf{x}\); the \(\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.))
x = tf.constant([3.0, -4.0])
tf.norm(x).numpy(), tf.reduce_sum(tf.abs(x)).numpy()
(np.float32(5.0), np.float32(7.0))
x = jnp.array([3.0, -4.0])
jnp.linalg.norm(x), jnp.abs(x).sum()
(Array(5., dtype=float32), Array(7., dtype=float32))
x = mnp.array([3.0, -4.0])
mnp.linalg.norm(x), mnp.abs(x).sum()
(array(5.), array(7.))

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

For an \(m \times n\) matrix \(\mathbf{A}\), the Frobenius norm computes the \(\ell_2\) norm of its \(mn\) entries:

\[\|\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.)
tf.norm(tf.ones((4, 9)))
<tf.Tensor: shape=(), dtype=float32, numpy=6.0>
jnp.linalg.norm(jnp.ones((4, 9)))
Array(6., dtype=float32)
mnp.linalg.norm(mnp.ones((4, 9)))
array(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 \(\mathbf{x}\) by matrices repeatedly? A nonzero vector \(\mathbf{v} \neq \mathbf{0}\) is an eigenvector of \(\mathbf{A} \in \mathbb{R}^{n \times n}\) with scalar eigenvalue \(\lambda\) if multiplying by \(\mathbf{A}\) simply scales \(\mathbf{v}\) without rotating it:

\[\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 \(\mathbf{S} = \left[\begin{smallmatrix} 2 & 1 \\ 1 & 2 \end{smallmatrix}\right]\), \((1, 1)\) is an eigenvector with \(\lambda = 3\) and \((-1, 1)\) is an eigenvector with \(\lambda = 1\) (Figure 1.3.8).

Figure 1.3.8: Left: \(\mathbf{S}\) maps the unit circle (dashed) to an ellipse whose axes are its eigenvectors, stretched by \(\lambda = 3\) and \(\lambda = 1\), while \(\mathbf{e}_1\) is turned to \(\mathbf{S}\mathbf{e}_1 = (2, 1)\). Right: the directions of \(\mathbf{S}^k\mathbf{e}_1\) for \(k = 0, \ldots, 4\) approach the eigenvector \((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]]))
S = tf.constant([[2.0, 1.0], [1.0, 2.0]])
eigenvalues, eigenvectors = tf.linalg.eigh(S)
eigenvalues, eigenvectors
(<tf.Tensor: shape=(2,), dtype=float32, numpy=array([0.99999994, 2.9999998 ], dtype=float32)>,
 <tf.Tensor: shape=(2, 2), dtype=float32, numpy=
 array([[-0.70710677,  0.70710677],
        [ 0.70710677,  0.70710677]], dtype=float32)>)
S = jnp.array([[2.0, 1.0], [1.0, 2.0]])
eigenvalues, eigenvectors = jnp.linalg.eigh(S)
eigenvalues, eigenvectors
(Array([1., 3.], dtype=float32),
 Array([[-0.70710677,  0.70710677],
        [ 0.70710677,  0.70710677]], dtype=float32))
S = mnp.array([[2.0, 1.0], [1.0, 2.0]])
eigenvalues, eigenvectors = mnp.linalg.eigh(S)
eigenvalues, eigenvectors
(array([1., 3.]),
 array([[ 0.70710677,  0.70710677],
        [-0.70710677,  0.70710677]]))

By the spectral theorem (Section 33.3), every real symmetric \(n \times n\) matrix \(\mathbf{A}\) has \(n\) real eigenvalues and a complete orthonormal basis of eigenvectors \(\mathbf{v}_1, \ldots, \mathbf{v}_n\). Expanding any vector \(\mathbf{x} = \sum_{i=1}^n c_i \mathbf{v}_i\) (with \(c_i = \mathbf{v}_i^\top \mathbf{x}\)) gives

\[\mathbf{A}^k \mathbf{x} = \sum_{i=1}^n c_i \lambda_i^k \mathbf{v}_i. \tag{1.3.12}\]

As \(k\) grows, the term with the largest \(|\lambda_i|\) dominates: \(\mathbf{A}^k\mathbf{x}\) aligns with the dominant eigenvector and grows by \(\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 \(\|\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]))
v = tf.constant([1.0, 0.0])
for _ in range(10):
    v_prev, v = v, tf.linalg.matvec(S, v)
growth = tf.norm(v) / tf.norm(v_prev)
round(float(growth), 4), (v / tf.norm(v)).numpy().round(4)
(3.0, array([0.7071, 0.7071], dtype=float32))
v = jnp.array([1.0, 0.0])
for _ in range(10):
    v_prev, v = v, S @ v
growth = jnp.linalg.norm(v) / jnp.linalg.norm(v_prev)
growth, v / jnp.linalg.norm(v)
(Array(3.0000002, dtype=float32), Array([0.7071187, 0.7070948], dtype=float32))
v = mnp.array([1.0, 0.0])
for _ in range(10):
    v_prev, v = v, S @ v
growth = mnp.linalg.norm(v) / mnp.linalg.norm(v_prev)
growth, v / mnp.linalg.norm(v)
(array(2.9999998), array([0.7071188 , 0.70709485]))

Returning to our 50-layer thought experiment: for \(\mathbf{M} = \left[\begin{smallmatrix} 1 & 0.1 \\ 0.1 & 1 \end{smallmatrix}\right]\), whose eigenvalues \(\lambda_1 = 1.1\) and \(\lambda_2 = 0.9\) differ from \(1\) by just \(10\%\), multiplying its two unit eigenvectors by \(\mathbf{M}\) \(50\) times amplifies the first by \(1.1^{50} \approx 117.4\) and shrinks the second to \(0.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])
M = tf.constant([[1.0, 0.1], [0.1, 1.0]])
# The eigenvectors (1, 1) and (-1, 1) of M, as columns of length 1
V = tf.constant([[1.0, -1.0], [1.0, 1.0]]) / 2 ** 0.5
for _ in range(50):  # 50 "layers"
    V = M @ V
tf.norm(V, axis=0).numpy()
array([1.1739086e+02, 5.1537761e-03], dtype=float32)
M = jnp.array([[1.0, 0.1], [0.1, 1.0]])
# The eigenvectors (1, 1) and (-1, 1) of M, as columns of length 1
V = jnp.array([[1.0, -1.0], [1.0, 1.0]]) / 2 ** 0.5
for _ in range(50):  # 50 "layers"
    V = M @ V
jnp.linalg.norm(V, axis=0)
Array([1.1739086e+02, 5.1537761e-03], dtype=float32)
M = mnp.array([[1.0, 0.1], [0.1, 1.0]])
# The eigenvectors (1, 1) and (-1, 1) of M, as columns of length 1
V = mnp.array([[1.0, -1.0], [1.0, 1.0]]) / 2 ** 0.5
for _ in range(50):  # 50 "layers"
    V = M @ V
mnp.linalg.norm(V, axis=0)
array([1.1739086e+02, 5.1537761e-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 \(\mathbf{A} = \left[\begin{smallmatrix} 0 & 2 \\ 0 & 0 \end{smallmatrix}\right]\) are \(0\), and \(\mathbf{A}^2 = \mathbf{0}\), yet \(\mathbf{A}\) maps \(\mathbf{e}_2\) to \(2\mathbf{e}_1\) and so doubles its length. Since \(\|\mathbf{A}\mathbf{x}\|_2^2 = \mathbf{x}^\top\mathbf{A}^\top\mathbf{A}\mathbf{x}\), stretching is governed by the symmetric matrix \(\mathbf{A}^\top\mathbf{A}\). The square roots of its eigenvalues, \(\sigma_i = \sqrt{\lambda_i(\mathbf{A}^\top\mathbf{A})}\), are the singular values of \(\mathbf{A}\), and they exist for every matrix, square or not. We compute them for \(\mathbf{S}\) and for \(\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))
A = tf.constant([[0.0, 2.0], [0.0, 0.0]])  # Both eigenvalues are 0
svdvals = lambda M: tf.linalg.svd(M, compute_uv=False)
(svdvals(S), svdvals(A), tf.sqrt(tf.linalg.eigvalsh(tf.transpose(A) @ A)),
 tf.linalg.matrix_rank(A))
(<tf.Tensor: shape=(2,), dtype=float32, numpy=array([2.9999998 , 0.99999994], dtype=float32)>,
 <tf.Tensor: shape=(2,), dtype=float32, numpy=array([2., 0.], dtype=float32)>,
 <tf.Tensor: shape=(2,), dtype=float32, numpy=array([0., 2.], dtype=float32)>,
 <tf.Tensor: shape=(), dtype=int32, numpy=1>)
A = jnp.array([[0.0, 2.0], [0.0, 0.0]])  # Both eigenvalues are 0
(jnp.linalg.svdvals(S), jnp.linalg.svdvals(A),
 jnp.sqrt(jnp.linalg.eigvalsh(A.T @ A)), jnp.linalg.matrix_rank(A))
(Array([3., 1.], dtype=float32),
 Array([2., 0.], dtype=float32),
 Array([0., 2.], dtype=float32),
 Array(1, dtype=int32))
A = mnp.array([[0.0, 2.0], [0.0, 0.0]])  # Both eigenvalues are 0
# The middle output of svd holds the singular values
(mnp.linalg.svd(S)[1], mnp.linalg.svd(A)[1],
 mnp.sqrt(mnp.linalg.eigvalsh(A.T @ A)), mnp.linalg.matrix_rank(A))
(array([2.9999998, 1.       ]),
 array([2., 0.]),
 array([0., 2.]),
 array(1, dtype=int64))

For the symmetric \(\mathbf{S}\) the singular values are \(3\) and \(1\) (up to rounding), the magnitudes of its eigenvalues: for a symmetric matrix the two notions agree. For \(\mathbf{A}\) they are \(2\) and \(0\), and the eigenvalues of \(\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 \(\mathbf{A}\). Both facts follow from the singular value decomposition (Section 33.5).

Unless each layer’s weight matrix keeps vector lengths close to \(1\) 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 \(256\) flattened images as \(\mathbf{X} \in \mathbb{R}^{256 \times 784}\) computes all \(2{,}560\) category scores via \(\mathbf{O} = \mathbf{X}\mathbf{W} + \mathbf{b}\). Reductions aggregate along specified axes (keepdims=True retains the axis as length \(1\) for broadcasting). Dot products \(\mathbf{x}^\top\mathbf{y} = \sum_i x_i y_i\) build matrix–vector products \(\mathbf{A}\mathbf{x}\) and matrix–matrix products \(\mathbf{A}\mathbf{B}\) (costing \(\approx 2mkn\) FLOPs). Norms (\(\ell_2\), \(\ell_1\), \(\ell_p\), Frobenius, and spectral) measure vector and matrix magnitudes, normalized dot products give cosine similarity \(\cos\theta = \mathbf{x}^\top\mathbf{y}/(\|\mathbf{x}\|\|\mathbf{y}\|)\), and eigenvectors (\(\mathbf{A}\mathbf{v} = \lambda\mathbf{v}\)) explain why repeated matrix multiplication scales components as \(\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: \((\mathbf{A}\mathbf{B})^\top = \mathbf{B}^\top\mathbf{A}^\top\) whenever \(\mathbf{A}\mathbf{B}\) is defined. (Write out the \((i, j)\) entry of both sides using Equation 1.3.5.)
    2. Show that for any rectangular matrix \(\mathbf{X} \in \mathbb{R}^{m \times n}\), the product \(\mathbf{X}\mathbf{X}^\top\) is always square and symmetric (and likewise for \(\mathbf{X}^\top\mathbf{X}\)). For our \(256 \times 784\) image minibatch \(\mathbf{X}\), what is the shape of \(\mathbf{X}\mathbf{X}^\top\), and what does its \((i, j)\) entry measure?
  2. [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)\) and X of shape \((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 \times 784\) matrix X, and how does keepdims=True fix it?
    3. Now suppose your minibatch happens to contain \(n = 784\) images, so that X is a square \(784 \times 784\) matrix. Show that X - X.mean(axis=1) executes without raising any error. Write out what entry \((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.
  3. How mutually obtuse can a set of vectors be? The following questions explore how negative all pairwise dot products among \(k\) vectors can simultaneously be.

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

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

  4. [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)\), 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 \(\ell_2\) norm of all parameters concatenated into one giant vector. Express this global \(\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)\), \((4,)\), and \((2, 3, 5)\).
  5. Associativity of matrix multiplication and computational cost. Although matrix multiplication is associative, meaning \((\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 \(\mathbf{A} \in \mathbb{R}^{1000 \times 50000}\), \(\mathbf{B} \in \mathbb{R}^{50000 \times 20}\), and \(\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 \((\mathbf{A}\mathbf{B})\mathbf{C}\) and \(\mathbf{A}(\mathbf{B}\mathbf{C})\). By what factors do the two evaluation orders differ in arithmetic work and intermediate memory?

  6. [code] All-pairs Euclidean distance matrix without loops. ● Given two collections of \(50\) vectors in \(\mathbb{R}^8\) stacked as the rows of \(\mathbf{X} \in \mathbb{R}^{50 \times 8}\) and \(\mathbf{Y} \in \mathbb{R}^{50 \times 8}\), we want to compute the \(50 \times 50\) matrix \(\mathbf{D}\) of squared Euclidean distances \(D_{ij} = \|\mathbf{x}_i - \mathbf{y}_j\|_2^2\) without Python loops:

    1. Compute \(\mathbf{D}\) first via 3D broadcasting: reshape \(\mathbf{X}\) to \((50, 1, 8)\) and \(\mathbf{Y}\) to \((1, 50, 8)\), subtract, square, and sum along the last axis. Second, compute \(\mathbf{D}\) via the quadratic expansion \(\|\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 \(\mathbf{X}\mathbf{Y}^\top\). Verify that both results match to floating-point precision.
    2. When \(\mathbf{X}\) and \(\mathbf{Y}\) each contain \(10{,}000\) vectors in \(\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 \(\|\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}\)) when \(\mathbf{x}_i = \mathbf{y}_j\), and show how to clamp the output before taking a square root.

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

  7. [code] Power iteration and convergence rate. ● Implement normalized power iteration, repeatedly updating \(\mathbf{v}_{k+1} = \mathbf{A}\mathbf{v}_k / \|\mathbf{A}\mathbf{v}_k\|_2\) from a random unit vector \(\mathbf{v}_0\), on the \(3 \times 3\) symmetric matrix

    \[\mathbf{A} = \begin{bmatrix} 1 & 2 & 3 \\ 2 & 0 & 4 \\ 3 & 4 & 5 \end{bmatrix}. \tag{1.3.13}\]

    1. Record the first iteration \(k\) at which the absolute cosine similarity \(|\mathbf{v}_k^\top \mathbf{v}_{k-1}|\) between consecutive iterates exceeds \(0.999\). Compare your converged vector \(\mathbf{v}_k\) against the dominant eigenvector returned by eigh(A), and explain why the two vectors may differ by an overall sign \(\pm 1\).
    2. At each step, measure the sine of the angle between \(\mathbf{v}_k\) and the true dominant eigenvector \(\mathbf{u}_{\max}\), \(\sin\theta_k = \sqrt{1 - (\mathbf{v}_k^\top \mathbf{u}_{\max})^2}\), and compute the per-step shrinkage ratio \(\sin\theta_{k+1} / \sin\theta_k\). Express this asymptotic ratio in terms of the eigenvalues of \(\mathbf{A}\) using Equation 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 \(\mathbf{B} = \mathbf{A} - 9\mathbf{I}\). Which eigenvalue and eigenvector of \(\mathbf{A}\) does power iteration converge to now, what happens to the sign of consecutive iterates \(\mathbf{v}_k\) and \(\mathbf{v}_{k+1}\), and why?

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

  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: \((\mathbf{A}\mathbf{B})^\top = \mathbf{B}^\top\mathbf{A}^\top\) whenever \(\mathbf{A}\mathbf{B}\) is defined. (Write out the \((i, j)\) entry of both sides using Equation 1.3.5.)
    2. Show that for any rectangular matrix \(\mathbf{X} \in \mathbb{R}^{m \times n}\), the product \(\mathbf{X}\mathbf{X}^\top\) is always square and symmetric (and likewise for \(\mathbf{X}^\top\mathbf{X}\)). For our \(256 \times 784\) image minibatch \(\mathbf{X}\), what is the shape of \(\mathbf{X}\mathbf{X}^\top\), and what does its \((i, j)\) entry measure?
  2. [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)\) (cast to float32) and X of shape \((256, 784)\), then verify your answers in code:

    1. What does len(images) return? What are the shapes of tf.reduce_sum(images, axis=(2, 3)) with keepdims=False versus keepdims=True? Which of the two can divide images directly via broadcasting, and what does images / tf.reduce_sum(images, axis=(2, 3), keepdims=True) compute?
    2. What happens when you evaluate X - tf.reduce_mean(X, axis=1) on our \(256 \times 784\) matrix X, and how does keepdims=True fix it?
    3. Now suppose your minibatch happens to contain \(n = 784\) images, so that X is a square \(784 \times 784\) matrix. Show that X - tf.reduce_mean(X, axis=1) executes without raising any error. Write out what entry \((i, j)\) of X - tf.reduce_mean(X, 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.
  3. How mutually obtuse can a set of vectors be? The following questions explore how negative all pairwise dot products among \(k\) vectors can simultaneously be.

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

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

  4. [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)\), 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 \(\ell_2\) norm of all parameters concatenated into one giant vector. Express this global \(\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)\), \((4,)\), and \((2, 3, 5)\).
  5. Associativity of matrix multiplication and computational cost. Although matrix multiplication is associative, meaning \((\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 \(\mathbf{A} \in \mathbb{R}^{1000 \times 50000}\), \(\mathbf{B} \in \mathbb{R}^{50000 \times 20}\), and \(\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 \((\mathbf{A}\mathbf{B})\mathbf{C}\) and \(\mathbf{A}(\mathbf{B}\mathbf{C})\). By what factors do the two evaluation orders differ in arithmetic work and intermediate memory?

  6. [code] All-pairs Euclidean distance matrix without loops. ● Given two collections of \(50\) vectors in \(\mathbb{R}^8\) stacked as the rows of \(\mathbf{X} \in \mathbb{R}^{50 \times 8}\) and \(\mathbf{Y} \in \mathbb{R}^{50 \times 8}\), we want to compute the \(50 \times 50\) matrix \(\mathbf{D}\) of squared Euclidean distances \(D_{ij} = \|\mathbf{x}_i - \mathbf{y}_j\|_2^2\) without Python loops:

    1. Compute \(\mathbf{D}\) first via 3D broadcasting: reshape \(\mathbf{X}\) to \((50, 1, 8)\) and \(\mathbf{Y}\) to \((1, 50, 8)\), subtract, square, and sum along the last axis. Second, compute \(\mathbf{D}\) via the quadratic expansion \(\|\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 \(\mathbf{X}\mathbf{Y}^\top\). Verify that both results match to floating-point precision.
    2. When \(\mathbf{X}\) and \(\mathbf{Y}\) each contain \(10{,}000\) vectors in \(\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 \(\|\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}\)) when \(\mathbf{x}_i = \mathbf{y}_j\), and show how to clamp the output before taking a square root.

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

  7. [code] Power iteration and convergence rate. ● Implement normalized power iteration, repeatedly updating \(\mathbf{v}_{k+1} = \mathbf{A}\mathbf{v}_k / \|\mathbf{A}\mathbf{v}_k\|_2\) from a random unit vector \(\mathbf{v}_0\), on the \(3 \times 3\) symmetric matrix

    \[\mathbf{A} = \begin{bmatrix} 1 & 2 & 3 \\ 2 & 0 & 4 \\ 3 & 4 & 5 \end{bmatrix}.\]

    1. Record the first iteration \(k\) at which the absolute cosine similarity \(|\mathbf{v}_k^\top \mathbf{v}_{k-1}|\) between consecutive iterates exceeds \(0.999\). Compare your converged vector \(\mathbf{v}_k\) against the dominant eigenvector returned by eigh(A), and explain why the two vectors may differ by an overall sign \(\pm 1\).
    2. At each step, measure the sine of the angle between \(\mathbf{v}_k\) and the true dominant eigenvector \(\mathbf{u}_{\max}\), \(\sin\theta_k = \sqrt{1 - (\mathbf{v}_k^\top \mathbf{u}_{\max})^2}\), and compute the per-step shrinkage ratio \(\sin\theta_{k+1} / \sin\theta_k\). Express this asymptotic ratio in terms of the eigenvalues of \(\mathbf{A}\) using Equation 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 \(\mathbf{B} = \mathbf{A} - 9\mathbf{I}\). Which eigenvalue and eigenvector of \(\mathbf{A}\) does power iteration converge to now, what happens to the sign of consecutive iterates \(\mathbf{v}_k\) and \(\mathbf{v}_{k+1}\), and why?

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

  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: \((\mathbf{A}\mathbf{B})^\top = \mathbf{B}^\top\mathbf{A}^\top\) whenever \(\mathbf{A}\mathbf{B}\) is defined. (Write out the \((i, j)\) entry of both sides using Equation 1.3.5.)
    2. Show that for any rectangular matrix \(\mathbf{X} \in \mathbb{R}^{m \times n}\), the product \(\mathbf{X}\mathbf{X}^\top\) is always square and symmetric (and likewise for \(\mathbf{X}^\top\mathbf{X}\)). For our \(256 \times 784\) image minibatch \(\mathbf{X}\), what is the shape of \(\mathbf{X}\mathbf{X}^\top\), and what does its \((i, j)\) entry measure?
  2. [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)\) and X of shape \((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 \times 784\) matrix X, and how does keepdims=True fix it?
    3. Now suppose your minibatch happens to contain \(n = 784\) images, so that X is a square \(784 \times 784\) matrix. Show that X - X.mean(axis=1) executes without raising any error. Write out what entry \((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.
  3. How mutually obtuse can a set of vectors be? The following questions explore how negative all pairwise dot products among \(k\) vectors can simultaneously be.

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

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

  4. [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)\), 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 \(\ell_2\) norm of all parameters concatenated into one giant vector. Express this global \(\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)\), \((4,)\), and \((2, 3, 5)\).
  5. Associativity of matrix multiplication and computational cost. Although matrix multiplication is associative, meaning \((\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 \(\mathbf{A} \in \mathbb{R}^{1000 \times 50000}\), \(\mathbf{B} \in \mathbb{R}^{50000 \times 20}\), and \(\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 \((\mathbf{A}\mathbf{B})\mathbf{C}\) and \(\mathbf{A}(\mathbf{B}\mathbf{C})\). By what factors do the two evaluation orders differ in arithmetic work and intermediate memory?

  6. [code] All-pairs Euclidean distance matrix without loops. ● Given two collections of \(50\) vectors in \(\mathbb{R}^8\) stacked as the rows of \(\mathbf{X} \in \mathbb{R}^{50 \times 8}\) and \(\mathbf{Y} \in \mathbb{R}^{50 \times 8}\), we want to compute the \(50 \times 50\) matrix \(\mathbf{D}\) of squared Euclidean distances \(D_{ij} = \|\mathbf{x}_i - \mathbf{y}_j\|_2^2\) without Python loops:

    1. Compute \(\mathbf{D}\) first via 3D broadcasting: reshape \(\mathbf{X}\) to \((50, 1, 8)\) and \(\mathbf{Y}\) to \((1, 50, 8)\), subtract, square, and sum along the last axis. Second, compute \(\mathbf{D}\) via the quadratic expansion \(\|\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 \(\mathbf{X}\mathbf{Y}^\top\). Verify that both results match to floating-point precision.
    2. When \(\mathbf{X}\) and \(\mathbf{Y}\) each contain \(10{,}000\) vectors in \(\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 \(\|\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}\)) when \(\mathbf{x}_i = \mathbf{y}_j\), and show how to clamp the output before taking a square root.

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

  7. [code] Power iteration and convergence rate. ● Implement normalized power iteration, repeatedly updating \(\mathbf{v}_{k+1} = \mathbf{A}\mathbf{v}_k / \|\mathbf{A}\mathbf{v}_k\|_2\) from a random unit vector \(\mathbf{v}_0\), on the \(3 \times 3\) symmetric matrix

    \[\mathbf{A} = \begin{bmatrix} 1 & 2 & 3 \\ 2 & 0 & 4 \\ 3 & 4 & 5 \end{bmatrix}.\]

    1. Record the first iteration \(k\) at which the absolute cosine similarity \(|\mathbf{v}_k^\top \mathbf{v}_{k-1}|\) between consecutive iterates exceeds \(0.999\). Compare your converged vector \(\mathbf{v}_k\) against the dominant eigenvector returned by eigh(A), and explain why the two vectors may differ by an overall sign \(\pm 1\).
    2. At each step, measure the sine of the angle between \(\mathbf{v}_k\) and the true dominant eigenvector \(\mathbf{u}_{\max}\), \(\sin\theta_k = \sqrt{1 - (\mathbf{v}_k^\top \mathbf{u}_{\max})^2}\), and compute the per-step shrinkage ratio \(\sin\theta_{k+1} / \sin\theta_k\). Express this asymptotic ratio in terms of the eigenvalues of \(\mathbf{A}\) using Equation 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 \(\mathbf{B} = \mathbf{A} - 9\mathbf{I}\). Which eigenvalue and eigenvector of \(\mathbf{A}\) does power iteration converge to now, what happens to the sign of consecutive iterates \(\mathbf{v}_k\) and \(\mathbf{v}_{k+1}\), and why?

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

  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: \((\mathbf{A}\mathbf{B})^\top = \mathbf{B}^\top\mathbf{A}^\top\) whenever \(\mathbf{A}\mathbf{B}\) is defined. (Write out the \((i, j)\) entry of both sides using Equation 1.3.5.)
    2. Show that for any rectangular matrix \(\mathbf{X} \in \mathbb{R}^{m \times n}\), the product \(\mathbf{X}\mathbf{X}^\top\) is always square and symmetric (and likewise for \(\mathbf{X}^\top\mathbf{X}\)). For our \(256 \times 784\) image minibatch \(\mathbf{X}\), what is the shape of \(\mathbf{X}\mathbf{X}^\top\), and what does its \((i, j)\) entry measure?
  2. [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)\) and X of shape \((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 \times 784\) matrix X, and how does keepdims=True fix it?
    3. Now suppose your minibatch happens to contain \(n = 784\) images, so that X is a square \(784 \times 784\) matrix. Show that X - X.mean(axis=1) executes without raising any error. Write out what entry \((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.
  3. How mutually obtuse can a set of vectors be? The following questions explore how negative all pairwise dot products among \(k\) vectors can simultaneously be.

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

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

  4. [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)\), 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 \(\ell_2\) norm of all parameters concatenated into one giant vector. Express this global \(\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)\), \((4,)\), and \((2, 3, 5)\).
  5. Associativity of matrix multiplication and computational cost. Although matrix multiplication is associative, meaning \((\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 \(\mathbf{A} \in \mathbb{R}^{1000 \times 50000}\), \(\mathbf{B} \in \mathbb{R}^{50000 \times 20}\), and \(\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 \((\mathbf{A}\mathbf{B})\mathbf{C}\) and \(\mathbf{A}(\mathbf{B}\mathbf{C})\). By what factors do the two evaluation orders differ in arithmetic work and intermediate memory?

  6. [code] All-pairs Euclidean distance matrix without loops. ● Given two collections of \(50\) vectors in \(\mathbb{R}^8\) stacked as the rows of \(\mathbf{X} \in \mathbb{R}^{50 \times 8}\) and \(\mathbf{Y} \in \mathbb{R}^{50 \times 8}\), we want to compute the \(50 \times 50\) matrix \(\mathbf{D}\) of squared Euclidean distances \(D_{ij} = \|\mathbf{x}_i - \mathbf{y}_j\|_2^2\) without Python loops:

    1. Compute \(\mathbf{D}\) first via 3D broadcasting: reshape \(\mathbf{X}\) to \((50, 1, 8)\) and \(\mathbf{Y}\) to \((1, 50, 8)\), subtract, square, and sum along the last axis. Second, compute \(\mathbf{D}\) via the quadratic expansion \(\|\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 \(\mathbf{X}\mathbf{Y}^\top\). Verify that both results match to floating-point precision.
    2. When \(\mathbf{X}\) and \(\mathbf{Y}\) each contain \(10{,}000\) vectors in \(\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 \(\|\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}\)) when \(\mathbf{x}_i = \mathbf{y}_j\), and show how to clamp the output before taking a square root.

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

  7. [code] Power iteration and convergence rate. ● Implement normalized power iteration, repeatedly updating \(\mathbf{v}_{k+1} = \mathbf{A}\mathbf{v}_k / \|\mathbf{A}\mathbf{v}_k\|_2\) from a random unit vector \(\mathbf{v}_0\), on the \(3 \times 3\) symmetric matrix

    \[\mathbf{A} = \begin{bmatrix} 1 & 2 & 3 \\ 2 & 0 & 4 \\ 3 & 4 & 5 \end{bmatrix}.\]

    1. Record the first iteration \(k\) at which the absolute cosine similarity \(|\mathbf{v}_k^\top \mathbf{v}_{k-1}|\) between consecutive iterates exceeds \(0.999\). Compare your converged vector \(\mathbf{v}_k\) against the dominant eigenvector returned by eigh(A), and explain why the two vectors may differ by an overall sign \(\pm 1\).
    2. At each step, measure the sine of the angle between \(\mathbf{v}_k\) and the true dominant eigenvector \(\mathbf{u}_{\max}\), \(\sin\theta_k = \sqrt{1 - (\mathbf{v}_k^\top \mathbf{u}_{\max})^2}\), and compute the per-step shrinkage ratio \(\sin\theta_{k+1} / \sin\theta_k\). Express this asymptotic ratio in terms of the eigenvalues of \(\mathbf{A}\) using Equation 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 \(\mathbf{B} = \mathbf{A} - 9\mathbf{I}\). Which eigenvalue and eigenvector of \(\mathbf{A}\) does power iteration converge to now, what happens to the sign of consecutive iterates \(\mathbf{v}_k\) and \(\mathbf{v}_{k+1}\), and why?

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