1.1  Data Manipulation

To get anything done in machine learning, we need a way to store and manipulate data efficiently in memory. We start with \(n\)-dimensional arrays, which in deep learning are called tensors.

To see why specialized array containers are indispensable, consider a single minibatch of \(256\) grayscale photographs of resolution \(28 \times 28\) pixels, containing \(256 \times 28 \times 28 = 200{,}704\) numbers. Image files store each pixel as an integer in \(\{0, \ldots, 255\}\), which we rescale to \([0, 1]\) by dividing by \(255\). In plain Python, three nested loops would execute \(200{,}704\) separate scalar divisions in the interpreter. In a tensor library, the single expression images / 255 dispatches to compiled C++ or CUDA kernels that divide all \(200{,}704\) numbers in parallel on a CPU or GPU. Throughout deep learning, we operate on whole tensors at once rather than iterating over individual scalar elements in Python loops.

Across all modern deep learning frameworks, the tensor class closely mirrors NumPy’s ndarray (Harris et al. 2020), with two crucial additions:

  1. Hardware acceleration: framework tensors execute across GPUs and specialized AI accelerators, whereas NumPy runs on CPUs.
  2. Automatic differentiation: frameworks track computations on tensors and compute gradients automatically via backpropagation (Section 1.5).

In PyTorch the tensor class is torch.Tensor. We import PyTorch (torch).

In TensorFlow the tensor class is tf.Tensor. We import TensorFlow under its customary alias tf.

In JAX the tensor class is jax.Array. We import jax and its NumPy-compatible array interface jax.numpy as jnp.

In MXNet the tensor class is ndarray. We import MXNet’s NumPy-compatible array module as mnp (keeping np for standard NumPy) along with npx (numpy_extension), and call npx.set_np() to activate NumPy-compatible tensor semantics.

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.1.1 Tensor Creation

1.1.1.1 Shape

A tensor arranges numerical values along one or more axes. A tensor with one axis is a vector, with two axes a matrix, and with \(k > 2\) axes a \(k^\textrm{th}\)-order tensor (its number of axes is its order, exposed in code as ndim). Our running minibatch of grayscale images is a \(4^\textrm{th}\)-order tensor of shape \((256, 1, 28, 28)\): axis \(0\) indexes the image in the batch, axis \(1\) the color channel (\(1\) for grayscale, \(3\) for RGB), axis \(2\) the vertical pixel row, and axis \(3\) the horizontal pixel column.

Calling arange(n) creates a 1D vector of evenly spaced values from \(0\) (included) to \(n\) (excluded). Newly created tensors reside in main memory for CPU computation by default; here we request 32-bit floating-point values (float32):

In TensorFlow, this function is named tf.range.

x = torch.arange(12, dtype=torch.float32)
x
tensor([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10., 11.])
x = tf.range(12, dtype=tf.float32)
x
<tf.Tensor: shape=(12,), dtype=float32, numpy=
array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10., 11.],
      dtype=float32)>
x = jnp.arange(12, dtype=jnp.float32)
x
Array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10., 11.],      dtype=float32)
x = mnp.arange(12)
x
array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10., 11.])

Each value in a tensor is an element. We can query the total number of elements in x (its size):

In PyTorch, the total element count is returned by numel().

x.numel()
12
tf.size(x)
<tf.Tensor: shape=(), dtype=int32, numpy=12>
x.size
12
x.size
12

Next, we inspect the tensor’s shape tuple via x.shape, which lists its length along each axis (here a 1-tuple (12,) for our 12-element vector):

x.shape
torch.Size([12])
TensorShape([12])
(12,)
(12,)

Figure 1.1.1 illustrates tensors of orders \(0\) through \(3\). A single number (scalar) is a \(0^\textrm{th}\)-order tensor with empty shape (). For any tensor, the size equals the product of the lengths in its shape tuple (\(256 \times 1 \times 28 \times 28 = 200{,}704\) for our image minibatch).

Figure 1.1.1: Tensors with zero, one, two, and three axes. The shape lists the length of each axis, and the size is the product of these lengths: 1, 4, 12, and 24 elements.

1.1.1.2 Data Types

Every tensor carries a data type (dtype) specifying the binary representation of each element. Deep learning models perform most arithmetic in 32-bit floating point (float32, \(4\) bytes per element, \(\approx 7\) decimal digits of precision) or 16-bit formats (float16 / bfloat16, \(2\) bytes per element; see Section 5.5). Raw image pixels are typically stored as 8-bit unsigned integers (uint8, \(1\) byte per pixel for \(\{0, \ldots, 255\}\)), so our \(200{,}704\)-pixel minibatch occupies \(0.2\textrm{ MB}\) as uint8 and \(0.8\textrm{ MB}\) as float32.

torch.arange defaults to int64 on integer arguments; cast with x.to(torch.int32).

tf.range defaults to int32 on integer arguments; cast with tf.cast(x, tf.int32).

jnp.arange defaults to int32 on integer arguments; cast with x.astype(jnp.int32).

MXNet defaults to float32; cast with x.astype('int32').

1.1.1.3 Initial Values

The functions zeros and ones construct a tensor of any shape filled with \(0\)s or \(1\)s (used for biases or buffers):

torch.zeros((2, 3, 4))
tensor([[[0., 0., 0., 0.],
         [0., 0., 0., 0.],
         [0., 0., 0., 0.]],

        [[0., 0., 0., 0.],
         [0., 0., 0., 0.],
         [0., 0., 0., 0.]]])
tf.zeros((2, 3, 4))
<tf.Tensor: shape=(2, 3, 4), dtype=float32, numpy=
array([[[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.]],

       [[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.]]], dtype=float32)>
jnp.zeros((2, 3, 4))
Array([[[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.]],

       [[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.]]], dtype=float32)
mnp.zeros((2, 3, 4))
array([[[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.]],

       [[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.]]])

Neural network weights are typically initialized by sampling elements independently from a probability distribution (Section 4.4). Below, we draw a \(3 \times 4\) matrix from a standard Gaussian distribution (mean \(0\), standard deviation \(1\)):

torch.randn(3, 4)
tensor([[ 0.2763, -0.8037, -1.2709,  0.2572],
        [ 0.3519, -1.3422, -0.7240,  0.4446],
        [ 1.1666,  0.8201,  0.8971,  0.9919]])
tf.random.normal(shape=[3, 4])
<tf.Tensor: shape=(3, 4), dtype=float32, numpy=
array([[ 0.11727553, -0.54910284,  0.14498505,  0.57360584],
       [ 0.6783801 ,  0.06603131,  1.7456502 ,  1.3581957 ],
       [-0.8750357 ,  0.15835263, -1.0798163 , -0.36096498]],
      dtype=float32)>
# A key determines the sample: the same key always gives the same numbers
key = jax.random.key(random.getrandbits(32))  # A new seed on each run
jax.random.normal(key, (3, 4))
Array([[ 0.21832727,  1.0848601 ,  0.29606727, -0.6687802 ],
       [-0.3902798 ,  0.5969642 , -0.4338682 , -0.09060081],
       [-0.19822368, -0.5707412 , -0.9283469 , -2.4065652 ]],      dtype=float32)
mnp.random.normal(0, 1, size=(3, 4))
array([[ 1.9079436e+00, -1.6749787e-01, -5.4943734e-01, -8.5341364e-01],
       [ 1.6303962e-01,  1.1756606e+00, -1.4357455e+00, -1.9653924e+00],
       [ 2.8941140e-01, -1.7361869e-01, -1.7458964e-04,  3.9381307e-01]])

Computer-generated random numbers are pseudorandom: a deterministic algorithm computes them from an integer seed, so starting again from the same seed reproduces the exact same sequence (a and c below match, whereas b does not):

PyTorch resets its global generator via torch.manual_seed.

TensorFlow resets its global generator via tf.random.set_seed.

JAX is purely functional and has no global random state: every random function takes an explicit PRNG key, and jax.random.split derives new independent subkeys deterministically. Below, c reuses key_a, so it repeats a.

MXNet resets its global generator via mnp.random.seed.

torch.manual_seed(42)
a = torch.randn(3)
b = torch.randn(3)  # The generator has moved on
torch.manual_seed(42)
c = torch.randn(3)  # Same seed: c repeats a
a, b, c
(tensor([0.3367, 0.1288, 0.2345]),
 tensor([ 0.2303, -1.1229, -0.1863]),
 tensor([0.3367, 0.1288, 0.2345]))
tf.random.set_seed(42)
a = tf.random.normal([3])
b = tf.random.normal([3])  # The generator has moved on
tf.random.set_seed(42)
c = tf.random.normal([3])  # Same seed: c repeats a
print(a, b, c, sep='\n')
tf.Tensor([ 0.3274685 -0.8426258  0.3194337], shape=(3,), dtype=float32)
tf.Tensor([ 0.08422458 -0.86090374  0.37812304], shape=(3,), dtype=float32)
tf.Tensor([ 0.3274685 -0.8426258  0.3194337], shape=(3,), dtype=float32)
key_a, key_b = jax.random.split(jax.random.key(42))
a = jax.random.normal(key_a, (3,))
b = jax.random.normal(key_b, (3,))  # A different key
c = jax.random.normal(key_a, (3,))  # Same key: c repeats a
a, b, c
(Array([ 0.07592554, -0.48634264,  1.2903206 ], dtype=float32),
 Array([ 0.60576403,  0.7990441 , -0.908927  ], dtype=float32),
 Array([ 0.07592554, -0.48634264,  1.2903206 ], dtype=float32))
mnp.random.seed(42)
a = mnp.random.normal(size=3)
b = mnp.random.normal(size=3)  # The generator has moved on
mnp.random.seed(42)
c = mnp.random.normal(size=3)  # Same seed: c repeats a
a, b, c
(array([0.5294428, 0.7030335, 1.9753686]),
 array([ 0.29129395,  1.6645737 , -0.25185385]),
 array([0.5294428, 0.7030335, 1.9753686]))

When we know the exact entries of a small tensor ahead of time, we can construct it directly from nested Python lists (here creating a \(3 \times 4\) matrix where the outer list gives the three rows and each inner list supplies four columns):

torch.tensor([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
tensor([[2, 1, 4, 3],
        [1, 2, 3, 4],
        [4, 3, 2, 1]])
tf.constant([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
<tf.Tensor: shape=(3, 4), dtype=int32, numpy=
array([[2, 1, 4, 3],
       [1, 2, 3, 4],
       [4, 3, 2, 1]], dtype=int32)>
jnp.array([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
Array([[2, 1, 4, 3],
       [1, 2, 3, 4],
       [4, 3, 2, 1]], dtype=int32)
mnp.array([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
array([[2., 1., 4., 3.],
       [1., 2., 3., 4.],
       [4., 3., 2., 1.]])

Finally, we construct our running synthetic minibatch images of shape (256, 1, 28, 28) and type uint8, filled with random integers in \(\{0, \ldots, 255\}\):

# 256 grayscale images of 28 x 28 pixels, each pixel an integer in [0, 255]
images = torch.randint(0, 256, (256, 1, 28, 28), dtype=torch.uint8)
images.shape, images.dtype
(torch.Size([256, 1, 28, 28]), torch.uint8)
# 256 grayscale images of 28 x 28 pixels, each pixel an integer in [0, 255];
# TensorFlow draws random integers as int32 or int64, so we cast them
images = tf.random.uniform((256, 1, 28, 28), maxval=256, dtype=tf.int32)
images = tf.cast(images, tf.uint8)
images.shape, images.dtype
(TensorShape([256, 1, 28, 28]), tf.uint8)
# 256 grayscale images of 28 x 28 pixels, each pixel an integer in [0, 255]
key, subkey = jax.random.split(key)
images = jax.random.randint(subkey, (256, 1, 28, 28), 0, 256,
                            dtype=jnp.uint8)
images.shape, images.dtype
((256, 1, 28, 28), dtype('uint8'))
# 256 grayscale images of 28 x 28 pixels, each pixel an integer in [0, 255]
images = mnp.random.randint(0, 256, size=(256, 1, 28, 28)).astype('uint8')
images.shape, images.dtype
((256, 1, 28, 28), dtype('uint8'))

1.1.2 Reshaping and Indexing

1.1.2.1 Reshaping

Calling reshape reconfigures a tensor’s axes while preserving its element count and row-major order in memory (Figure 1.1.2). Here we reshape our 12-element vector x into a \(3 \times 4\) matrix X:

Figure 1.1.2: Reshaping a vector of 12 elements into a \(3 \times 4\) matrix. The elements keep their order and fill the matrix one row at a time.
X = x.reshape(3, 4)
X
tensor([[ 0.,  1.,  2.,  3.],
        [ 4.,  5.,  6.,  7.],
        [ 8.,  9., 10., 11.]])
X = tf.reshape(x, (3, 4))
X
<tf.Tensor: shape=(3, 4), dtype=float32, numpy=
array([[ 0.,  1.,  2.,  3.],
       [ 4.,  5.,  6.,  7.],
       [ 8.,  9., 10., 11.]], dtype=float32)>
X = x.reshape(3, 4)
X
Array([[ 0.,  1.,  2.,  3.],
       [ 4.,  5.,  6.,  7.],
       [ 8.,  9., 10., 11.]], dtype=float32)
X = x.reshape(3, 4)
X
array([[ 0.,  1.,  2.,  3.],
       [ 4.,  5.,  6.,  7.],
       [ 8.,  9., 10., 11.]])

Because the total size is fixed, passing -1 for one dimension lets the framework infer its length automatically; for example, we can flatten our \((256, 1, 28, 28)\) image minibatch into a \((256, 784)\) matrix with one image per row:

In TensorFlow, reshape is a function tf.reshape(x, (-1, 4)).

images.reshape(256, -1).shape
torch.Size([256, 784])
tf.reshape(images, (256, -1)).shape
TensorShape([256, 784])
images.reshape(256, -1).shape
(256, 784)
images.reshape(256, -1).shape
(256, 784)

Indexing with None inserts a new singleton axis of length \(1\) at that position, while squeeze removes an axis of length \(1\):

In PyTorch, image.unsqueeze(0) also inserts a singleton axis at position 0.

In TensorFlow, squeeze is called as tf.squeeze.

image = images[0]
image[None].shape, image.squeeze(0).shape
(torch.Size([1, 1, 28, 28]), torch.Size([28, 28]))
image = images[0]
image[None].shape, tf.squeeze(image, 0).shape
(TensorShape([1, 1, 28, 28]), TensorShape([28, 28]))
image = images[0]
image[None].shape, image.squeeze(0).shape
((1, 1, 28, 28), (28, 28))
image = images[0]
image[None].shape, image.squeeze(0).shape
((1, 1, 28, 28), (28, 28))

A reshape keeps the elements in their order and only regroups them, so it can never exchange two axes. Some libraries expect an image minibatch with the channel axis last, as \((256, 28, 28, 1)\). Getting there from our \((256, 1, 28, 28)\) minibatch means moving axis \(1\) to the end. This is a transpose: we list the old axes in their new order, here \((0, 2, 3, 1)\). A matrix has only one such reordering, the exchange of rows and columns, written X.T. We compare it with a reshape to the same shape:

In PyTorch, the method that reorders all axes is called permute; transpose(i, j) exchanges only the two axes i and j.

In TensorFlow, tf.transpose(x, perm) takes the new order of the axes as perm, and tf.transpose(X) stands in for X.T.

images.permute(0, 2, 3, 1).shape, X.reshape(4, 3), X.T
(torch.Size([256, 28, 28, 1]),
 tensor([[ 0.,  1.,  2.],
         [ 3.,  4.,  5.],
         [ 6.,  7.,  8.],
         [ 9., 10., 11.]]),
 tensor([[ 0.,  4.,  8.],
         [ 1.,  5.,  9.],
         [ 2.,  6., 10.],
         [ 3.,  7., 11.]]))
tf.transpose(images, (0, 2, 3, 1)).shape, tf.reshape(X, (4, 3)), tf.transpose(X)
(TensorShape([256, 28, 28, 1]),
 <tf.Tensor: shape=(4, 3), dtype=float32, numpy=
 array([[ 0.,  1.,  2.],
        [ 3.,  4.,  5.],
        [ 6.,  7.,  8.],
        [ 9., 10., 11.]], dtype=float32)>,
 <tf.Tensor: shape=(4, 3), dtype=float32, numpy=
 array([[ 0.,  4.,  8.],
        [ 1.,  5.,  9.],
        [ 2.,  6., 10.],
        [ 3.,  7., 11.]], dtype=float32)>)
images.transpose(0, 2, 3, 1).shape, X.reshape(4, 3), X.T
((256, 28, 28, 1),
 Array([[ 0.,  1.,  2.],
        [ 3.,  4.,  5.],
        [ 6.,  7.,  8.],
        [ 9., 10., 11.]], dtype=float32),
 Array([[ 0.,  4.,  8.],
        [ 1.,  5.,  9.],
        [ 2.,  6., 10.],
        [ 3.,  7., 11.]], dtype=float32))
images.transpose(0, 2, 3, 1).shape, X.reshape(4, 3), X.T
((256, 28, 28, 1),
 array([[ 0.,  1.,  2.],
        [ 3.,  4.,  5.],
        [ 6.,  7.,  8.],
        [ 9., 10., 11.]]),
 array([[ 0.,  4.,  8.],
        [ 1.,  5.,  9.],
        [ 2.,  6., 10.],
        [ 3.,  7., 11.]]))

Both matrices are \(4 \times 3\), but the reshape still reads \(0, 1, 2, \ldots\) along its rows, whereas the transpose has turned the rows of X into columns. Since the shapes agree, a reshape written where a transpose was meant raises no error. It only hands the next layer the right numbers in the wrong places.

1.1.2.2 Indexing and Slicing

Elements and sub-tensors are accessed via \(0\)-based integer indexing (negative indices count backward from the end) and half-open slices start:stop (including start, excluding stop), separated by commas across axes:

X[-1], X[1:3]
(tensor([ 8.,  9., 10., 11.]),
 tensor([[ 4.,  5.,  6.,  7.],
         [ 8.,  9., 10., 11.]]))
(<tf.Tensor: shape=(4,), dtype=float32, numpy=array([ 8.,  9., 10., 11.], dtype=float32)>,
 <tf.Tensor: shape=(2, 4), dtype=float32, numpy=
 array([[ 4.,  5.,  6.,  7.],
        [ 8.,  9., 10., 11.]], dtype=float32)>)
(Array([ 8.,  9., 10., 11.], dtype=float32),
 Array([[ 4.,  5.,  6.,  7.],
        [ 8.,  9., 10., 11.]], dtype=float32))
(array([ 8.,  9., 10., 11.]),
 array([[ 4.,  5.,  6.,  7.],
        [ 8.,  9., 10., 11.]]))

Notice the shape difference (Figure 1.1.3): an integer index (X[-1]) collapses that axis to return a vector of shape (4,), whereas a slice (X[1:3]) preserves the axis to return a matrix of shape (2, 4).

Figure 1.1.3: Indexing a \(3 \times 4\) matrix. The integer index X[-1] selects the last row and removes axis 0, leaving shape \((4,)\). The slice X[1:3] selects rows 1 and 2 and keeps axis 0, leaving shape \((2, 4)\).

On our image minibatch of shape \((256, 1, 28, 28)\), images[0] extracts the first image \((1, 28, 28)\), images[:32] slices the first \(32\) images \((32, 1, 28, 28)\), and images[:, 0, 14, 14] extracts the center pixel across all \(256\) images \((256,)\):

images[0].shape, images[:32].shape, images[:, 0, 14, 14].shape
(torch.Size([1, 28, 28]), torch.Size([32, 1, 28, 28]), torch.Size([256]))
(TensorShape([1, 28, 28]), TensorShape([32, 1, 28, 28]), TensorShape([256]))
((1, 28, 28), (32, 1, 28, 28), (256,))
((1, 28, 28), (32, 1, 28, 28), (256,))

We can also index a tensor using integer index tensors (gather): passing two 1D integer tensors rows = (0, 1, 2) and cols = (3, 0, 2) selects entries (0, 3), (1, 0), and (2, 2):

In TensorFlow, tf.gather(X, cols, batch_dims=1) gathers entry cols[i] from each row i of X:

rows, cols = torch.arange(3), torch.tensor([3, 0, 2])
X[rows, cols]
tensor([ 3.,  4., 10.])
cols = tf.constant([3, 0, 2])
tf.gather(X, cols, batch_dims=1)
<tf.Tensor: shape=(3,), dtype=float32, numpy=array([ 3.,  4., 10.], dtype=float32)>
rows, cols = jnp.arange(3), jnp.array([3, 0, 2])
X[rows, cols]
Array([ 3.,  4., 10.], dtype=float32)
rows, cols = mnp.arange(3), mnp.array([3, 0, 2])
X[rows, cols]
array([ 3.,  4., 10.])

Similarly, an elementwise comparison produces a Boolean mask of True/False values (combinable with &, |, ~). Indexing X[mask] extracts all entries where mask is True into a flattened 1D vector:

Because the output length of X[mask] is data-dependent, Boolean mask indexing works only in eager mode; inside jax.jit-compiled functions, use jnp.where.

mask = (X > 2) & (X < 8)
X[mask]
tensor([3., 4., 5., 6., 7.])
<tf.Tensor: shape=(5,), dtype=float32, numpy=array([3., 4., 5., 6., 7.], dtype=float32)>
Array([3., 4., 5., 6., 7.], dtype=float32)
array([3., 4., 5., 6., 7.])

When we instead want to preserve the \(3 \times 4\) shape of X, where(mask, X, 0) selects from X wherever mask is True and fills all remaining positions with 0:

torch.where(mask, X, 0)
tensor([[0., 0., 0., 3.],
        [4., 5., 6., 7.],
        [0., 0., 0., 0.]])
tf.where(mask, X, 0)
<tf.Tensor: shape=(3, 4), dtype=float32, numpy=
array([[0., 0., 0., 3.],
       [4., 5., 6., 7.],
       [0., 0., 0., 0.]], dtype=float32)>
jnp.where(mask, X, 0)
Array([[0., 0., 0., 3.],
       [4., 5., 6., 7.],
       [0., 0., 0., 0.]], dtype=float32)
mnp.where(mask, X, 0)
array([[0., 0., 0., 3.],
       [4., 5., 6., 7.],
       [0., 0., 0., 0.]])

Figure 1.1.4 sets the three selections side by side. They differ in the shape they return: index tensors give one entry per row, a mask gives a vector whose length depends on the data, and where gives a tensor shaped like X.

Figure 1.1.4: Selecting entries of the \(3 \times 4\) matrix X. (a) The index tensors rows = (0, 1, 2) and cols = (3, 0, 2) select one entry from each row. (b) The mask (X > 2) & (X < 8) extracts the five entries between \(2\) and \(8\) as a vector, whereas where keeps the shape of X and writes \(0\) everywhere else.

1.1.2.3 Writing Elements

Whether a tensor can be overwritten in place depends on the framework’s design:

PyTorch tensors are mutable: X[i, j] = val overwrites memory in place. Moreover, reshape returned a zero-copy view sharing the original buffer, so mutating X also mutates x. We assign 17 to X[1, 2] (flat index \(6\)) and inspect both X and x:

TensorFlow tensors are immutable. Learnable parameters live in mutable tf.Variable containers updated via .assign():

JAX arrays are immutable. JAX provides functional updates X.at[1, 2].set(17), returning a new array while leaving X unchanged:

MXNet tensors are mutable: X[i, j] = val overwrites memory in place. We assign 17 to X[1, 2] (flat index \(6\)) and inspect both X and x:

X[1, 2] = 17
X, x
(tensor([[ 0.,  1.,  2.,  3.],
         [ 4.,  5., 17.,  7.],
         [ 8.,  9., 10., 11.]]),
 tensor([ 0.,  1.,  2.,  3.,  4.,  5., 17.,  7.,  8.,  9., 10., 11.]))
X_var = tf.Variable(X)
X_var[1, 2].assign(17)
X_var
<tf.Variable 'Variable:0' shape=(3, 4) dtype=float32, numpy=
array([[ 0.,  1.,  2.,  3.],
       [ 4.,  5., 17.,  7.],
       [ 8.,  9., 10., 11.]], dtype=float32)>
X_new = X.at[1, 2].set(17)  # X is unchanged
X_new
Array([[ 0.,  1.,  2.,  3.],
       [ 4.,  5., 17.,  7.],
       [ 8.,  9., 10., 11.]], dtype=float32)
X[1, 2] = 17
X, x
(array([[ 0.,  1.,  2.,  3.],
        [ 4.,  5., 17.,  7.],
        [ 8.,  9., 10., 11.]]),
 array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10., 11.]))

In PyTorch, x[6] changed to 17. because reshape returned a view sharing storage with x.

In MXNet, x[6] remains 6.0 because reshape allocated a copy.

Slicing on the left-hand side assigns to an entire block at once:

X[:2, :] = 12
X
tensor([[12., 12., 12., 12.],
        [12., 12., 12., 12.],
        [ 8.,  9., 10., 11.]])
X_var[:2, :].assign(12)
X_var
<tf.Variable 'Variable:0' shape=(3, 4) dtype=float32, numpy=
array([[12., 12., 12., 12.],
       [12., 12., 12., 12.],
       [ 8.,  9., 10., 11.]], dtype=float32)>
X_new = X_new.at[:2, :].set(12)
X_new
Array([[12., 12., 12., 12.],
       [12., 12., 12., 12.],
       [ 8.,  9., 10., 11.]], dtype=float32)
X[:2, :] = 12
X
array([[12., 12., 12., 12.],
       [12., 12., 12., 12.],
       [ 8.,  9., 10., 11.]])

1.1.3 Operations

1.1.3.1 Elementwise Operations

Standard binary arithmetic operators (+, -, *, /, **) lift scalar arithmetic to act independently on every pair of corresponding elements of two identically shaped tensors x and y:

x = torch.tensor([1.0, 2, 4, 8])
y = torch.tensor([2.0, 2, 2, 2])
x + y, x - y, x * y, x / y, x ** y
(tensor([ 3.,  4.,  6., 10.]),
 tensor([-1.,  0.,  2.,  6.]),
 tensor([ 2.,  4.,  8., 16.]),
 tensor([0.5000, 1.0000, 2.0000, 4.0000]),
 tensor([ 1.,  4., 16., 64.]))
x = tf.constant([1.0, 2, 4, 8])
y = tf.constant([2.0, 2, 2, 2])
x + y, x - y, x * y, x / y, x ** y
(<tf.Tensor: shape=(4,), dtype=float32, numpy=array([ 3.,  4.,  6., 10.], dtype=float32)>,
 <tf.Tensor: shape=(4,), dtype=float32, numpy=array([-1.,  0.,  2.,  6.], dtype=float32)>,
 <tf.Tensor: shape=(4,), dtype=float32, numpy=array([ 2.,  4.,  8., 16.], dtype=float32)>,
 <tf.Tensor: shape=(4,), dtype=float32, numpy=array([0.5, 1. , 2. , 4. ], dtype=float32)>,
 <tf.Tensor: shape=(4,), dtype=float32, numpy=array([ 1.,  4., 16., 64.], dtype=float32)>)
x = jnp.array([1.0, 2, 4, 8])
y = jnp.array([2.0, 2, 2, 2])
x + y, x - y, x * y, x / y, x ** y
(Array([ 3.,  4.,  6., 10.], dtype=float32),
 Array([-1.,  0.,  2.,  6.], dtype=float32),
 Array([ 2.,  4.,  8., 16.], dtype=float32),
 Array([0.5, 1. , 2. , 4. ], dtype=float32),
 Array([ 1.,  4., 16., 64.], dtype=float32))
x = mnp.array([1.0, 2, 4, 8])
y = mnp.array([2.0, 2, 2, 2])
x + y, x - y, x * y, x / y, x ** y
(array([ 3.,  4.,  6., 10.]),
 array([-1.,  0.,  2.,  6.]),
 array([ 2.,  4.,  8., 16.]),
 array([0.5, 1. , 2. , 4. ]),
 array([ 1.,  4., 16., 64.]))

Unary mathematical functions such as exp likewise apply elementwise, computing \(e^{x_i}\) for each entry of x:

torch.exp(x)
tensor([2.7183e+00, 7.3891e+00, 5.4598e+01, 2.9810e+03])
tf.exp(x)
<tf.Tensor: shape=(4,), dtype=float32, numpy=
array([2.7182817e+00, 7.3890562e+00, 5.4598148e+01, 2.9809580e+03],
      dtype=float32)>
jnp.exp(x)
Array([2.7182817e+00, 7.3890562e+00, 5.4598148e+01, 2.9809580e+03],      dtype=float32)
mnp.exp(x)
array([2.7182820e+00, 7.3890557e+00, 5.4598145e+01, 2.9809583e+03])

Dividing our uint8 minibatch images by 255 rescales all \(200{,}704\) pixels at once and promotes the result to float32:

scaled = images / 255
print(scaled.dtype, images[0, 0, 0, :4], scaled[0, 0, 0, :4], sep='\n')
torch.float32
tensor([102, 121, 210, 214], dtype=torch.uint8)
tensor([0.4000, 0.4745, 0.8235, 0.8392])
<dtype: 'float32'>
tf.Tensor([210 103 211 170], shape=(4,), dtype=uint8)
tf.Tensor([0.8235294  0.40392157 0.827451   0.6666667 ], shape=(4,), dtype=float32)
float32
[204 119 139 153]
[0.79999995 0.46666664 0.545098   0.59999996]
float32
[204 245  76  87]
[0.8        0.9607843  0.29803923 0.34117648]

Relational operators such as x == y also act elementwise, returning a Boolean tensor with True at positions where x and y agree (here only index \(1\), where both equal 2.0):

x == y
tensor([False,  True, False, False])
<tf.Tensor: shape=(4,), dtype=bool, numpy=array([False,  True, False, False])>
Array([False,  True, False, False], dtype=bool)
array([False,  True, False, False])

Summing a tensor via sum() collapses all its entries into a single scalar (\(1 + 2 + 4 + 8 = 15\) for x); because True counts as \(1\) and False as \(0\), summing the Boolean mask (x == y).sum() counts how many entries match:

In TensorFlow, use tf.reduce_sum (casting Booleans via tf.cast first).

x.sum(), (x == y).sum()
(tensor(15.), tensor(1))
tf.reduce_sum(x), tf.reduce_sum(tf.cast(x == y, tf.int32))
(<tf.Tensor: shape=(), dtype=float32, numpy=15.0>,
 <tf.Tensor: shape=(), dtype=int32, numpy=1>)
x.sum(), (x == y).sum()
(Array(15., dtype=float32), Array(1, dtype=int32))
x.sum(), (x == y).sum()
(array(15.), array(1, dtype=int64))

1.1.3.2 Broadcasting

Often we combine tensors of different shapes, such as adding a 4-element bias vector v to every row of a \(3 \times 4\) matrix X:

X = torch.arange(12, dtype=torch.float32).reshape(3, 4)
v = torch.tensor([100.0, 200, 300, 400])
X + v
tensor([[100., 201., 302., 403.],
        [104., 205., 306., 407.],
        [108., 209., 310., 411.]])
X = tf.reshape(tf.range(12, dtype=tf.float32), (3, 4))
v = tf.constant([100.0, 200, 300, 400])
X + v
<tf.Tensor: shape=(3, 4), dtype=float32, numpy=
array([[100., 201., 302., 403.],
       [104., 205., 306., 407.],
       [108., 209., 310., 411.]], dtype=float32)>
X = jnp.arange(12, dtype=jnp.float32).reshape(3, 4)
v = jnp.array([100.0, 200, 300, 400])
X + v
Array([[100., 201., 302., 403.],
       [104., 205., 306., 407.],
       [108., 209., 310., 411.]], dtype=float32)
X = mnp.arange(12).reshape(3, 4)
v = mnp.array([100.0, 200, 300, 400])
X + v
array([[100., 201., 302., 403.],
       [104., 205., 306., 407.],
       [108., 209., 310., 411.]])

Rather than materializing physical copies, tensor libraries apply a two-step broadcasting rule:

  1. Align shapes from the right: Prepend \(1\)s on the left of the lower-order tensor’s shape tuple until both shapes have the same length. Two aligned dimensions are compatible if they are equal or if one of them is \(1\).
  2. Stretch singleton axes: Virtually replicate any length-\(1\) axis to match the other tensor’s length \(k > 1\) without copying memory, then apply the elementwise operation.

To watch both tensors stretch simultaneously (Figure 1.1.5), let us construct a \(3 \times 1\) column vector a and a \(1 \times 2\) row vector b:

Figure 1.1.5: Broadcasting stretches axes of length 1. The column a of shape \((3, 1)\) and the row b of shape \((1, 2)\) are both expanded to shape \((3, 2)\) (dashed: virtual copies) before the elementwise addition.
a = torch.arange(3).reshape(3, 1)
b = torch.arange(2).reshape(1, 2)
a, b
(tensor([[0],
         [1],
         [2]]),
 tensor([[0, 1]]))
a = tf.reshape(tf.range(3), (3, 1))
b = tf.reshape(tf.range(2), (1, 2))
a, b
(<tf.Tensor: shape=(3, 1), dtype=int32, numpy=
 array([[0],
        [1],
        [2]], dtype=int32)>,
 <tf.Tensor: shape=(1, 2), dtype=int32, numpy=array([[0, 1]], dtype=int32)>)
a = jnp.arange(3).reshape(3, 1)
b = jnp.arange(2).reshape(1, 2)
a, b
(Array([[0],
        [1],
        [2]], dtype=int32),
 Array([[0, 1]], dtype=int32))
a = mnp.arange(3).reshape(3, 1)
b = mnp.arange(2).reshape(1, 2)
a, b
(array([[0.],
        [1.],
        [2.]]),
 array([[0., 1.]]))

Adding a + b virtually replicates a across two columns and b across three rows to produce the \(3 \times 2\) matrix of all pairwise sums \(a_{i0} + b_{0j}\):

a + b
tensor([[0, 1],
        [1, 2],
        [2, 3]])
<tf.Tensor: shape=(3, 2), dtype=int32, numpy=
array([[0, 1],
       [1, 2],
       [2, 3]], dtype=int32)>
Array([[0, 1],
       [1, 2],
       [2, 3]], dtype=int32)
array([[0., 1.],
       [1., 2.],
       [2., 3.]])

If any pair of aligned dimensions differs and neither is \(1\) (such as (3, 2) and (2, 3)), broadcasting raises an error:

We print the exception class name:

We print the final summary line of MXNet’s exception:

try:
    torch.ones((3, 2)) + torch.ones((2, 3))
except Exception as e:
    print(e)
The size of tensor a (2) must match the size of tensor b (3) at non-singleton dimension 1
try:
    tf.ones((3, 2)) + tf.ones((2, 3))
except Exception as e:
    print(type(e).__name__)
InvalidArgumentError
try:
    jnp.ones((3, 2)) + jnp.ones((2, 3))
except Exception as e:
    print(e)
add got incompatible shapes for broadcasting: (3, 2), (2, 3).
try:
    mnp.ones((3, 2)) + mnp.ones((2, 3))
except Exception as e:
    print(str(e).splitlines()[-1].rsplit(': ', 1)[-1])
operands could not be broadcast together with shapes [3,2] [2,3]

Thus, subtracting a \((28, 28)\) mean image from images of shape \((256, 1, 28, 28)\) broadcasts cleanly as \((1, 1, 28, 28)\), whereas adding a per-image vector of shape \((256,)\) to flattened images \((256, 784)\) fails unless reshaped to a column \((256, 1)\).

An error message is the lucky outcome. Subtracting labels of shape \((3,)\) from predictions of shape \((3, 1)\) is legal under the same rules, and it returns a \(3 \times 3\) matrix of all pairwise differences where we wanted three errors (Figure 1.1.6). A loss averaged over that matrix is still a single number, so nothing looks wrong until the model fails to learn.

Figure 1.1.6: Broadcasting without an error message. (a) Predictions y_hat of shape \((3, 1)\) minus labels y of shape \((3,)\) give all nine pairwise differences; only the diagonal (solid) holds the three errors we wanted. (b) Once y is reshaped to \((3, 1)\), the same subtraction returns those three errors and nothing else.

1.1.3.3 Concatenation

concatenate (or cat / concat) joins tensors end to end along an existing axis (all other axes must have matching lengths): joining two \(3 \times 4\) matrices X and Y along axis=0 stacks their rows into shape (6, 4), whereas axis=1 joins their columns into shape (3, 8):

X = torch.arange(12, dtype=torch.float32).reshape(3, 4)
Y = torch.tensor([[2.0, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
torch.cat((X, Y), dim=0), torch.cat((X, Y), dim=1)
(tensor([[ 0.,  1.,  2.,  3.],
         [ 4.,  5.,  6.,  7.],
         [ 8.,  9., 10., 11.],
         [ 2.,  1.,  4.,  3.],
         [ 1.,  2.,  3.,  4.],
         [ 4.,  3.,  2.,  1.]]),
 tensor([[ 0.,  1.,  2.,  3.,  2.,  1.,  4.,  3.],
         [ 4.,  5.,  6.,  7.,  1.,  2.,  3.,  4.],
         [ 8.,  9., 10., 11.,  4.,  3.,  2.,  1.]]))
X = tf.reshape(tf.range(12, dtype=tf.float32), (3, 4))
Y = tf.constant([[2.0, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
tf.concat([X, Y], axis=0), tf.concat([X, Y], axis=1)
(<tf.Tensor: shape=(6, 4), dtype=float32, numpy=
 array([[ 0.,  1.,  2.,  3.],
        [ 4.,  5.,  6.,  7.],
        [ 8.,  9., 10., 11.],
        [ 2.,  1.,  4.,  3.],
        [ 1.,  2.,  3.,  4.],
        [ 4.,  3.,  2.,  1.]], dtype=float32)>,
 <tf.Tensor: shape=(3, 8), dtype=float32, numpy=
 array([[ 0.,  1.,  2.,  3.,  2.,  1.,  4.,  3.],
        [ 4.,  5.,  6.,  7.,  1.,  2.,  3.,  4.],
        [ 8.,  9., 10., 11.,  4.,  3.,  2.,  1.]], dtype=float32)>)
X = jnp.arange(12, dtype=jnp.float32).reshape(3, 4)
Y = jnp.array([[2.0, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
jnp.concatenate((X, Y), axis=0), jnp.concatenate((X, Y), axis=1)
(Array([[ 0.,  1.,  2.,  3.],
        [ 4.,  5.,  6.,  7.],
        [ 8.,  9., 10., 11.],
        [ 2.,  1.,  4.,  3.],
        [ 1.,  2.,  3.,  4.],
        [ 4.,  3.,  2.,  1.]], dtype=float32),
 Array([[ 0.,  1.,  2.,  3.,  2.,  1.,  4.,  3.],
        [ 4.,  5.,  6.,  7.,  1.,  2.,  3.,  4.],
        [ 8.,  9., 10., 11.,  4.,  3.,  2.,  1.]], dtype=float32))
X = mnp.arange(12).reshape(3, 4)
Y = mnp.array([[2, 1, 4, 3], [1, 2, 3, 4], [4, 3, 2, 1]])
mnp.concatenate([X, Y], axis=0), mnp.concatenate([X, Y], axis=1)
(array([[ 0.,  1.,  2.,  3.],
        [ 4.,  5.,  6.,  7.],
        [ 8.,  9., 10., 11.],
        [ 2.,  1.,  4.,  3.],
        [ 1.,  2.,  3.,  4.],
        [ 4.,  3.,  2.,  1.]]),
 array([[ 0.,  1.,  2.,  3.,  2.,  1.,  4.,  3.],
        [ 4.,  5.,  6.,  7.,  1.,  2.,  3.,  4.],
        [ 8.,  9., 10., 11.,  4.,  3.,  2.,  1.]]))

By contrast, stack joins identically shaped tensors along a new axis, bundling X and Y into a \(3^\textrm{rd}\)-order tensor of shape (2, 3, 4) by default (axis=0) or (3, 4, 2) when stacked along axis=2:

torch.stack((X, Y)).shape, torch.stack((X, Y), dim=2).shape
(torch.Size([2, 3, 4]), torch.Size([3, 4, 2]))
tf.stack([X, Y]).shape, tf.stack([X, Y], axis=2).shape
(TensorShape([2, 3, 4]), TensorShape([3, 4, 2]))
jnp.stack((X, Y)).shape, jnp.stack((X, Y), axis=2).shape
((2, 3, 4), (3, 4, 2))
mnp.stack([X, Y]).shape, mnp.stack([X, Y], axis=2).shape
((2, 3, 4), (3, 4, 2))

1.1.4 Memory and Conversion

1.1.4.1 Allocation and In-Place Updates

Standard expressions like Y = Y + X allocate a new buffer and rebind Y to the new address, as verified with Python’s id():

before = id(Y)
Y = Y + X
id(Y) == before
False

For models with gigabytes of parameters, unnecessary allocations waste memory bandwidth and can leave other references pointing to stale buffers (though inside forward passes, you must not overwrite activations still needed by automatic differentiation; see Section 1.5).

In MXNet and PyTorch, slice assignment Z[:] = X + Y writes the result into an existing preallocated buffer Z so id(Z) never changes:

In TensorFlow, Z.assign(X + Y) updates a mutable tf.Variable buffer Z in place so id(Z) remains unchanged:

In JAX, arrays are immutable; buffer reuse is handled automatically by the XLA compiler under @jax.jit.

In MXNet and PyTorch, slice assignment Z[:] = X + Y writes the result into an existing preallocated buffer Z so id(Z) never changes:

Z = torch.zeros_like(Y)
before = id(Z)
Z[:] = X + Y
id(Z) == before
True
Z = tf.Variable(tf.zeros_like(Y))
before = id(Z)
Z.assign(X + Y)
id(Z) == before
True
Z = mnp.zeros_like(Y)
before = id(Z)
Z[:] = X + Y
id(Z) == before
True

When the old value of X is no longer needed, augmented assignment X += Y asks for the sum to be written into X itself; id(X) shows whether the framework could do so:

before = id(X)
X += Y
id(X) == before
True
False
False
True

id(X) == before is True: X was updated in place.

Because X is an immutable tensor, id(X) == before is False.

Because X is an immutable tensor, id(X) == before is False.

id(X) == before is True: X was updated in place.

1.1.4.2 Conversion to Other Python Objects

Converting between framework tensors and NumPy arrays is routine at the boundary with plotting or data libraries, but frameworks differ in whether conversion shares memory or copies:

On the CPU, X.numpy() and torch.from_numpy(A) share the exact same underlying memory buffer, so mutating one in place immediately modifies the other: after the write below, both X[0, 0] and B[0, 0] change to 100.0.

X.numpy() and tf.constant(A) each allocate an independent copy, so after the write below both X[0, 0] and B[0, 0] stay unchanged.

jax.device_get(X) returns a read-only NumPy array (potentially zero-copy on CPU), and jax.device_put(A) transfers it back. Because the NumPy view is read-only, the write below raises a ValueError.

X.asnumpy() and mnp.array(A) each allocate an independent copy, so after the write below both X[0, 0] and B[0, 0] stay unchanged.

A = X.numpy()
B = torch.from_numpy(A)
type(A), type(B)
(numpy.ndarray, torch.Tensor)
A = X.numpy()
B = tf.constant(A)
type(A), type(B)
(numpy.ndarray, tensorflow.python.framework.ops.EagerTensor)
A = jax.device_get(X)
B = jax.device_put(A)
type(A), type(B)
(numpy.ndarray, jaxlib._jax.ArrayImpl)
A = X.asnumpy()
B = mnp.array(A)
type(A), type(B)
(numpy.ndarray, mxnet.numpy.ndarray)

We can verify whether A, B, and X share memory by overwriting A[0, 0] = 100 in the NumPy array and inspecting X[0, 0] and B[0, 0]:

A[0, 0] = 100  # Write to the NumPy array
X[0, 0], B[0, 0]
(tensor(100.), tensor(100.))
A[0, 0] = 100  # Write to the NumPy copy
X[0, 0].numpy(), B[0, 0].numpy()
(np.float32(2.0), np.float32(2.0))
try:
    A[0, 0] = 100
except ValueError as e:
    print(e)
assignment destination is read-only
A[0, 0] = 100  # Write to the NumPy copy
X[0, 0], B[0, 0]
(array(2.), array(2.))

To extract a single-element (\(0^\textrm{th}\)-order) tensor into a Python float or int (for example, when logging the scalar loss), call .item(), float(), or int(), noting that doing so forces the CPU to synchronize with any pending GPU kernels:

To extract a single-element (\(0^\textrm{th}\)-order) tensor into a Python float or int (for example, when logging the scalar loss), call .numpy(), float(), or int(), noting that doing so forces the CPU to synchronize with any pending GPU kernels:

To extract a single-element (\(0^\textrm{th}\)-order) tensor into a Python float or int (for example, when logging the scalar loss), call .item(), float(), or int(), noting that doing so forces the CPU to synchronize with any pending GPU kernels:

To extract a single-element (\(0^\textrm{th}\)-order) tensor into a Python float or int (for example, when logging the scalar loss), call .item(), float(), or int(), noting that doing so forces the CPU to synchronize with any pending GPU kernels:

a = torch.tensor(3.5)
a, a.item(), float(a), int(a)
(tensor(3.5000), 3.5, 3.5, 3)
a = tf.constant(3.5)
a, a.numpy(), float(a), int(a)
(<tf.Tensor: shape=(), dtype=float32, numpy=3.5>, np.float32(3.5), 3.5, 3)
a = jnp.array(3.5)
a, a.item(), float(a), int(a)
(Array(3.5, dtype=float32, weak_type=True), 3.5, 3.5, 3)
a = mnp.array(3.5)
a, a.item(), float(a), int(a)
(array(3.5), 3.5, 3.5, 3)

Tip: Exploring Framework APIs. Whenever you encounter an unfamiliar module or function, use dir(obj) (or Tab completion) to list available attributes, help(fn) or fn? in Jupyter to inspect its signature and docstring (and fn?? to view its Python source), and verify your understanding with a tiny test input whose expected output you can predict by hand.

1.1.5 Summary

Tensors store inputs, parameters, activations, and gradients as \(n\)-dimensional arrays characterized by a shape and a dtype. Deep learning code expresses computations over whole tensors at once, rescaling all \(200{,}704\) pixels of a minibatch in a single compiled operation (images / 255). We reconfigure axes with reshape, extract or modify subsets with integer indices, slices, and Boolean masks (where), join tensors with concatenate and stack, and combine differently shaped tensors via broadcasting (aligning shapes from the right and stretching singleton axes). Finally, where tensors are mutable, in-place updates (Z[:] = ..., X += Y) reuse memory; otherwise mutable containers or the compiler take over that role.

1.1.6 Exercises

  1. [code] Inferred reshape axes. Suppose a minibatch of \(n\) grayscale images of resolution \(28 \times 28\) arrives as a tensor of shape \((n, 1, 28, 28)\), and each image must be flattened into a row vector of \(784\) pixel values. Verify each prediction below in code:

    1. Predict the output shape of reshaping the minibatch to (-1, 784) versus (256, -1), first for a full minibatch of \(n = 256\) images and then for the final, smaller minibatch of an epoch with \(n = 100\) images. Which of the two target shapes works reliably for any batch size \(n\)?
    2. Suppose the images were accidentally loaded in 3-channel RGB format of shape \((n, 3, 28, 28)\). What happens when you reshape that tensor to (-1, 784)? Does reshape(-1, 784) catch the channel-count mistake, or does it silently scramble the batch dimension?
  2. [code] Broadcasting shapes and silent bugs. Broadcasting aligns two shape tuples from the right.

    1. Construct two \(3^\textrm{rd}\)-order tensors a and b whose shapes differ along every single axis yet are broadcast-compatible. Predict the shape of a + b by hand, then run the code to verify your prediction.
    2. A regression model outputs a column of predictions y_hat of shape \((5, 1)\) for five examples whose ground-truth targets y are stored as a 1D vector of shape \((5,)\). Predict the shape of the residual y_hat - y. Next, let y hold [0.0, 1.0, 2.0, 3.0, 4.0] and set y_hat = y.reshape(5, 1) so that every prediction equals its true label identically. Compute the mean of the squared entries of y_hat - y, explain why this “mean squared error” is nonzero even though the predictions are perfect, and show how to reshape y (or y_hat) so that each prediction is compared only against its own label.
  3. [code] Arithmetic limits of data types. Raw pixels in images are stored as 8-bit unsigned integers (uint8), whereas neural network layers compute in floating point (float32).

    1. Predict the numerical result of adding 100 to a uint8 tensor entry holding the value 200, and verify your prediction in code. Explain why this wrap-around occurs, and show how to brighten the first image of images by \(100\) intensity levels (clamped or promoted) without integer overflow.
    2. An IEEE 754 float32 number allocates \(24\) bits of significand (mantissa) precision. Explain why float32 can represent every consecutive integer up to \(2^{24} = 16{,}777{,}216\) exactly, and verify in code that evaluating float32(2**24) + float32(1) leaves the number unchanged at \(16{,}777{,}216\). If a training loop accumulates the total number of examples or tokens processed in a float32 scalar counter (incrementing by \(1\) each time), after how many examples will the counter freeze completely, and what data type should be used instead?
  4. [code] In-place composition. ● Evaluate (A + B) * (-A / 2) for two identically shaped float32 tensors A and B without allocating any intermediate tensor, using only PyTorch’s in-place methods (add_, div_, neg_, mul_) or out= keyword arguments. Confirm that A.data_ptr() and B.data_ptr() remain unchanged and that the final result matches the out-of-place expression (A + B) * (-A / 2). Explain why writing A[:] = A + B would not satisfy the zero-temporary-allocation requirement.

    Adapted from Nicolas P. Rougier, 100 numpy exercises, problem 35.

  5. [code] Python loops versus broadcasting. ● Given a 1D vector a of \(200\) elements and a 1D vector b of \(300\) elements, we want to compute the \(200 \times 300\) pairwise absolute-difference matrix \(D\) with entries \(d_{ij} = |a_i - b_j|\).

    1. Compute \(D\) first using two nested Python for loops, and then using a single broadcasted subtraction after reshaping a to (200, 1) and b to (1, 300). Verify that both matrices agree numerically, measure the wall-clock execution time of each method, and report the speedup factor.
    2. Even though broadcasting avoids copying the inputs a and b, the output matrix \(D\) must still be materialized in memory. How many megabytes does \(D\) occupy in float32 if a and b each contain \(10{,}000\) elements? What lesson does this teach about the peak memory footprint of broadcasted outer operations?
  1. [code] Inferred reshape axes. Suppose a minibatch of \(n\) grayscale images of resolution \(28 \times 28\) arrives as a tensor of shape \((n, 1, 28, 28)\), and each image must be flattened into a row vector of \(784\) pixel values. Verify each prediction below in code:

    1. Predict the output shape of reshaping the minibatch to (-1, 784) versus (256, -1), first for a full minibatch of \(n = 256\) images and then for the final, smaller minibatch of an epoch with \(n = 100\) images. Which of the two target shapes works reliably for any batch size \(n\)?
    2. Suppose the images were accidentally loaded in 3-channel RGB format of shape \((n, 3, 28, 28)\). What happens when you reshape that tensor to (-1, 784)? Does reshape(-1, 784) catch the channel-count mistake, or does it silently scramble the batch dimension?
  2. [code] Broadcasting shapes and silent bugs. Broadcasting aligns two shape tuples from the right.

    1. Construct two \(3^\textrm{rd}\)-order tensors a and b whose shapes differ along every single axis yet are broadcast-compatible. Predict the shape of a + b by hand, then run the code to verify your prediction.
    2. A regression model outputs a column of predictions y_hat of shape \((5, 1)\) for five examples whose ground-truth targets y are stored as a 1D vector of shape \((5,)\). Predict the shape of the residual y_hat - y. Next, let y hold [0.0, 1.0, 2.0, 3.0, 4.0] and set y_hat = tf.reshape(y, (5, 1)) so that every prediction equals its true label identically. Compute the mean of the squared entries of y_hat - y, explain why this “mean squared error” is nonzero even though the predictions are perfect, and show how to reshape y (or y_hat) so that each prediction is compared only against its own label.
  3. [code] Arithmetic limits of data types. Raw pixels in images are stored as 8-bit unsigned integers (uint8), whereas neural network layers compute in floating point (float32).

    1. Predict the numerical result of adding 100 to a uint8 tensor entry holding the value 200, and verify your prediction in code. Explain why this wrap-around occurs, and show how to brighten the first image of images by \(100\) intensity levels (clamped or promoted) without integer overflow.
    2. An IEEE 754 float32 number allocates \(24\) bits of significand (mantissa) precision. Explain why float32 can represent every consecutive integer up to \(2^{24} = 16{,}777{,}216\) exactly, and verify in code that evaluating float32(2**24) + float32(1) leaves the number unchanged at \(16{,}777{,}216\). If a training loop accumulates the total number of examples or tokens processed in a float32 scalar counter (incrementing by \(1\) each time), after how many examples will the counter freeze completely, and what data type should be used instead?
  4. [code] In-place composition. ● Because ordinary TensorFlow tensors are immutable, every arithmetic operator allocates a new tensor. Wrap two identically shaped float32 tensors A and B in tf.Variable containers and compute (A + B) * (-A / 2) so that the final result is stored inside one of the two variables, using assign, assign_add, and related variable methods. List each step of your calculation, identify which steps still allocate a temporary Tensor under eager execution, and explain why eager execution cannot eliminate those temporaries without @tf.function graph compilation.

    Adapted from Nicolas P. Rougier, 100 numpy exercises, problem 35.

  5. [code] Python loops versus broadcasting. ● Given a 1D vector a of \(200\) elements and a 1D vector b of \(300\) elements, we want to compute the \(200 \times 300\) pairwise absolute-difference matrix \(D\) with entries \(d_{ij} = |a_i - b_j|\).

    1. Compute \(D\) first using two nested Python for loops, and then using a single broadcasted subtraction after reshaping a to (200, 1) and b to (1, 300). Verify that both matrices agree numerically, measure the wall-clock execution time of each method, and report the speedup factor.
    2. Even though broadcasting avoids copying the inputs a and b, the output matrix \(D\) must still be materialized in memory. How many megabytes does \(D\) occupy in float32 if a and b each contain \(10{,}000\) elements? What lesson does this teach about the peak memory footprint of broadcasted outer operations?
  1. [code] Inferred reshape axes. Suppose a minibatch of \(n\) grayscale images of resolution \(28 \times 28\) arrives as a tensor of shape \((n, 1, 28, 28)\), and each image must be flattened into a row vector of \(784\) pixel values. Verify each prediction below in code:

    1. Predict the output shape of reshaping the minibatch to (-1, 784) versus (256, -1), first for a full minibatch of \(n = 256\) images and then for the final, smaller minibatch of an epoch with \(n = 100\) images. Which of the two target shapes works reliably for any batch size \(n\)?
    2. Suppose the images were accidentally loaded in 3-channel RGB format of shape \((n, 3, 28, 28)\). What happens when you reshape that tensor to (-1, 784)? Does reshape(-1, 784) catch the channel-count mistake, or does it silently scramble the batch dimension?
  2. [code] Broadcasting shapes and silent bugs. Broadcasting aligns two shape tuples from the right.

    1. Construct two \(3^\textrm{rd}\)-order tensors a and b whose shapes differ along every single axis yet are broadcast-compatible. Predict the shape of a + b by hand, then run the code to verify your prediction.
    2. A regression model outputs a column of predictions y_hat of shape \((5, 1)\) for five examples whose ground-truth targets y are stored as a 1D vector of shape \((5,)\). Predict the shape of the residual y_hat - y. Next, let y hold [0.0, 1.0, 2.0, 3.0, 4.0] and set y_hat = y.reshape(5, 1) so that every prediction equals its true label identically. Compute the mean of the squared entries of y_hat - y, explain why this “mean squared error” is nonzero even though the predictions are perfect, and show how to reshape y (or y_hat) so that each prediction is compared only against its own label.
  3. [code] Arithmetic limits of data types. Raw pixels in images are stored as 8-bit unsigned integers (uint8), whereas neural network layers compute in floating point (float32).

    1. Predict the numerical result of adding 100 to a uint8 tensor entry holding the value 200, and verify your prediction in code. Explain why this wrap-around occurs, and show how to brighten the first image of images by \(100\) intensity levels (clamped or promoted) without integer overflow.
    2. An IEEE 754 float32 number allocates \(24\) bits of significand (mantissa) precision. Explain why float32 can represent every consecutive integer up to \(2^{24} = 16{,}777{,}216\) exactly, and verify in code that evaluating float32(2**24) + float32(1) leaves the number unchanged at \(16{,}777{,}216\). If a training loop accumulates the total number of examples or tokens processed in a float32 scalar counter (incrementing by \(1\) each time), after how many examples will the counter freeze completely, and what data type should be used instead?
  4. [code] In-place composition and compiler fusion. ● Because JAX arrays are immutable, every eager arithmetic operation allocates a new array. Write (A + B) * (-A / 2) inside a Python function f(A, B) and count how many intermediate arrays eager evaluation creates. Then compile f with jax.jit(f) and inspect the lowered HLO program via jax.jit(f).lower(A, B).compile().as_text() to see how many fused kernels remain. Compare this compiled execution with a mutable NumPy in-place implementation that overwrites A: which eager intermediate allocations does jax.jit eliminate automatically, and when does the compiled function still allocate an output buffer (unless donate_argnums is specified)?

    Adapted from Nicolas P. Rougier, 100 numpy exercises, problem 35.

  5. [code] Python loops versus broadcasting. ● Given a 1D vector a of \(200\) elements and a 1D vector b of \(300\) elements, we want to compute the \(200 \times 300\) pairwise absolute-difference matrix \(D\) with entries \(d_{ij} = |a_i - b_j|\).

    1. Compute \(D\) first using two nested Python for loops, and then using a single broadcasted subtraction after reshaping a to (200, 1) and b to (1, 300). Verify that both matrices agree numerically, measure the wall-clock execution time of each method, and report the speedup factor.
    2. Even though broadcasting avoids copying the inputs a and b, the output matrix \(D\) must still be materialized in memory. How many megabytes does \(D\) occupy in float32 if a and b each contain \(10{,}000\) elements? What lesson does this teach about the peak memory footprint of broadcasted outer operations?
  1. [code] Inferred reshape axes. Suppose a minibatch of \(n\) grayscale images of resolution \(28 \times 28\) arrives as a tensor of shape \((n, 1, 28, 28)\), and each image must be flattened into a row vector of \(784\) pixel values. Verify each prediction below in code:

    1. Predict the output shape of reshaping the minibatch to (-1, 784) versus (256, -1), first for a full minibatch of \(n = 256\) images and then for the final, smaller minibatch of an epoch with \(n = 100\) images. Which of the two target shapes works reliably for any batch size \(n\)?
    2. Suppose the images were accidentally loaded in 3-channel RGB format of shape \((n, 3, 28, 28)\). What happens when you reshape that tensor to (-1, 784)? Does reshape(-1, 784) catch the channel-count mistake, or does it silently scramble the batch dimension?
  2. [code] Broadcasting shapes and silent bugs. Broadcasting aligns two shape tuples from the right.

    1. Construct two \(3^\textrm{rd}\)-order tensors a and b whose shapes differ along every single axis yet are broadcast-compatible. Predict the shape of a + b by hand, then run the code to verify your prediction.
    2. A regression model outputs a column of predictions y_hat of shape \((5, 1)\) for five examples whose ground-truth targets y are stored as a 1D vector of shape \((5,)\). Predict the shape of the residual y_hat - y. Next, let y hold [0.0, 1.0, 2.0, 3.0, 4.0] and set y_hat = y.reshape(5, 1) so that every prediction equals its true label identically. Compute the mean of the squared entries of y_hat - y, explain why this “mean squared error” is nonzero even though the predictions are perfect, and show how to reshape y (or y_hat) so that each prediction is compared only against its own label.
  3. [code] Arithmetic limits of data types. Raw pixels in images are stored as 8-bit unsigned integers (uint8), whereas neural network layers compute in floating point (float32).

    1. Predict the numerical result of adding 100 to a uint8 tensor entry holding the value 200, and verify your prediction in code. Explain why this wrap-around occurs, and show how to brighten the first image of images by \(100\) intensity levels (clamped or promoted) without integer overflow.
    2. An IEEE 754 float32 number allocates \(24\) bits of significand (mantissa) precision. Explain why float32 can represent every consecutive integer up to \(2^{24} = 16{,}777{,}216\) exactly, and verify in code that evaluating float32(2**24) + float32(1) leaves the number unchanged at \(16{,}777{,}216\). If a training loop accumulates the total number of examples or tokens processed in a float32 scalar counter (incrementing by \(1\) each time), after how many examples will the counter freeze completely, and what data type should be used instead?
  4. [code] In-place composition. ● Evaluate (A + B) * (-A / 2) for two identically shaped float32 arrays A and B without allocating any intermediate array, using only the in-place augmented assignment operators +=, *=, and /=. Confirm that the final result matches the out-of-place expression (A + B) * (-A / 2), and explain why writing A[:] = A + B would not satisfy the zero-temporary-allocation requirement.

    Adapted from Nicolas P. Rougier, 100 numpy exercises, problem 35.

  5. [code] Python loops versus broadcasting. ● Given a 1D vector a of \(200\) elements and a 1D vector b of \(300\) elements, we want to compute the \(200 \times 300\) pairwise absolute-difference matrix \(D\) with entries \(d_{ij} = |a_i - b_j|\).

    1. Compute \(D\) first using two nested Python for loops, and then using a single broadcasted subtraction after reshaping a to (200, 1) and b to (1, 300). Verify that both matrices agree numerically, measure the wall-clock execution time of each method, and report the speedup factor.
    2. Even though broadcasting avoids copying the inputs a and b, the output matrix \(D\) must still be materialized in memory. How many megabytes does \(D\) occupy in float32 if a and b each contain \(10{,}000\) elements? What lesson does this teach about the peak memory footprint of broadcasted outer operations?