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 -dimensional arrays, which in deep learning are called tensors.
To see why specialized array containers are indispensable, consider a single minibatch of grayscale photographs of resolution pixels, containing numbers. Image files store each pixel as an integer in , which we rescale to by dividing by . In plain Python, three nested loops would execute 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 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:
- Hardware acceleration: framework tensors execute across GPUs and specialized AI accelerators, whereas NumPy runs on CPUs.
- 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).
import torch1.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 axes a -order tensor (its number of axes is its order, exposed in code as ndim). Our running minibatch of grayscale images is a -order tensor of shape : axis indexes the image in the batch, axis the color channel ( for grayscale, for RGB), axis the vertical pixel row, and axis the horizontal pixel column.
Calling arange(n) creates a 1D vector of evenly spaced values from (included) to (excluded). Newly created tensors reside in main memory for CPU computation by default; here we request 32-bit floating-point values (float32):
x = torch.arange(12, dtype=torch.float32)
xtensor([ 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
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.shapetorch.Size([12])
Figure 1.1.1 illustrates tensors of orders through . A single number (scalar) is a -order tensor with empty shape (). For any tensor, the size equals the product of the lengths in its shape tuple ( for our image minibatch).
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, bytes per element, decimal digits of precision) or 16-bit formats (float16 / bfloat16, bytes per element; see Section 5.5). Raw image pixels are typically stored as 8-bit unsigned integers (uint8, byte per pixel for ), so our -pixel minibatch occupies as uint8 and as float32.
torch.arange defaults to int64 on integer arguments; cast with x.to(torch.int32).
1.1.1.3 Initial Values#
The functions zeros and ones construct a tensor of any shape filled with s or 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.]]])
Neural network weights are typically initialized by sampling elements independently from a probability distribution (Section 4.4). Below, we draw a matrix from a standard Gaussian distribution (mean , standard deviation ):
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]])
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.
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]))
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 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]])
Finally, we construct our running synthetic minibatch images of shape (256, 1, 28, 28) and type uint8, filled with random integers in :
# 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)
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 matrix X:
Reshaping a vector of 12 elements into a matrix. The elements keep their order and fill the matrix one row at a time.
X = x.reshape(3, 4)
Xtensor([[ 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 image minibatch into a matrix with one image per row:
images.reshape(256, -1).shapetorch.Size([256, 784])
Indexing with None inserts a new singleton axis of length at that position, while squeeze removes an axis of length :
In PyTorch, image.unsqueeze(0) also inserts a singleton axis at position 0.
image = images[0]
image[None].shape, image.squeeze(0).shape(torch.Size([1, 1, 28, 28]), torch.Size([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 . Getting there from our minibatch means moving axis to the end. This is a transpose: we list the old axes in their new order, here . 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.
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.]]))
Both matrices are , but the reshape still reads 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 -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.]]))
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).
Indexing a matrix. The integer index X[-1] selects the last row and removes axis 0, leaving shape . The slice X[1:3] selects rows 1 and 2 and keeps axis 0, leaving shape .
On our image minibatch of shape , images[0] extracts the first image , images[:32] slices the first images , and images[:, 0, 14, 14] extracts the center pixel across all images :
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]))
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):
rows, cols = torch.arange(3), torch.tensor([3, 0, 2])
X[rows, cols]tensor([ 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:
mask = (X > 2) & (X < 8)
X[mask]tensor([3., 4., 5., 6., 7.])
When we instead want to preserve the 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.]])
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.
Selecting entries of the 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 and as a vector, whereas where keeps the shape of X and writes 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 ) 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.]))
In PyTorch, x[6] changed to 17. because reshape returned a view sharing storage with x.
Slicing on the left-hand side assigns to an entire block at once:
X[:2, :] = 12
Xtensor([[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.]))
Unary mathematical functions such as exp likewise apply elementwise, computing for each entry of x:
torch.exp(x)tensor([2.7183e+00, 7.3891e+00, 5.4598e+01, 2.9810e+03])
Dividing our uint8 minibatch images by 255 rescales all 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])
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 , where both equal 2.0):
x == ytensor([False, True, False, False])
Summing a tensor via sum() collapses all its entries into a single scalar ( for x); because True counts as and False as , summing the Boolean mask (x == y).sum() counts how many entries match:
x.sum(), (x == y).sum()(tensor(15.), tensor(1))
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 matrix X:
X = torch.arange(12, dtype=torch.float32).reshape(3, 4)
v = torch.tensor([100.0, 200, 300, 400])
X + vtensor([[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:
- Align shapes from the right: Prepend 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 .
- Stretch singleton axes: Virtually replicate any length- axis to match the other tensor's length without copying memory, then apply the elementwise operation.
To watch both tensors stretch simultaneously (Figure 1.1.5), let us construct a column vector a and a row vector b:
Broadcasting stretches axes of length 1. The column a of shape and the row b of shape are both expanded to shape (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]]))
Adding a + b virtually replicates a across two columns and b across three rows to produce the matrix of all pairwise sums :
a + btensor([[0, 1],
[1, 2],
[2, 3]])
If any pair of aligned dimensions differs and neither is (such as (3, 2) and (2, 3)), broadcasting raises an error:
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
Thus, subtracting a mean image from images of shape broadcasts cleanly as , whereas adding a per-image vector of shape to flattened images fails unless reshaped to a column .
An error message is the lucky outcome. Subtracting labels of shape from predictions of shape is legal under the same rules, and it returns a 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.
Broadcasting without an error message. (a) Predictions y_hat of shape minus labels y of shape give all nine pairwise differences; only the diagonal (solid) holds the three errors we wanted. (b) Once y is reshaped to , 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 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.]]))
By contrast, stack joins identically shaped tensors along a new axis, bundling X and Y into a -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]))
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:
Z = torch.zeros_like(Y)
before = id(Z)
Z[:] = X + Y
id(Z) == beforeTrue
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) == beforeTrue
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.
A = X.numpy()
B = torch.from_numpy(A)
type(A), type(B)(numpy.ndarray, torch.Tensor)
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.))
To extract a single-element (-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)
Tip: Exploring Framework APIs. Whenever you encounter an unfamiliar module or function, use
dir(obj)(or Tab completion) to list available attributes,help(fn)orfn?in Jupyter to inspect its signature and docstring (andfn??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 -dimensional arrays characterized by a shape and a dtype. Deep learning code expresses computations over whole tensors at once, rescaling all 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#
- [code] Inferred reshape axes. Suppose a minibatch of grayscale images of resolution arrives as a tensor of shape , and each image must be flattened into a row vector of pixel values. Verify each prediction below in code:
- Predict the output shape of reshaping the minibatch to
(-1, 784)versus(256, -1), first for a full minibatch of images and then for the final, smaller minibatch of an epoch with images. Which of the two target shapes works reliably for any batch size ? - Suppose the images were accidentally loaded in 3-channel RGB format of shape . What happens when you reshape that tensor to
(-1, 784)? Doesreshape(-1, 784)catch the channel-count mistake, or does it silently scramble the batch dimension?
- Predict the output shape of reshaping the minibatch to
- [code] Broadcasting shapes and silent bugs. Broadcasting aligns two shape tuples from the right.
- Construct two -order tensors
aandbwhose shapes differ along every single axis yet are broadcast-compatible. Predict the shape ofa + bby hand, then run the code to verify your prediction. - A regression model outputs a column of predictions
y_hatof shape for five examples whose ground-truth targetsyare stored as a 1D vector of shape . Predict the shape of the residualy_hat - y. Next, letyhold[0.0, 1.0, 2.0, 3.0, 4.0]and sety_hat = y.reshape(5, 1)so that every prediction equals its true label identically. Compute the mean of the squared entries ofy_hat - y, explain why this "mean squared error" is nonzero even though the predictions are perfect, and show how to reshapey(ory_hat) so that each prediction is compared only against its own label.
- Construct two -order tensors
- [code] Arithmetic limits of data types. Raw pixels in
imagesare stored as 8-bit unsigned integers (uint8), whereas neural network layers compute in floating point (float32).- Predict the numerical result of adding
100to auint8tensor entry holding the value200, and verify your prediction in code. Explain why this wrap-around occurs, and show how to brighten the first image ofimagesby intensity levels (clamped or promoted) without integer overflow. - An IEEE 754
float32number allocates bits of significand (mantissa) precision. Explain whyfloat32can represent every consecutive integer up to exactly, and verify in code that evaluatingfloat32(2**24) + float32(1)leaves the number unchanged at . If a training loop accumulates the total number of examples or tokens processed in afloat32scalar counter (incrementing by each time), after how many examples will the counter freeze completely, and what data type should be used instead?
- Predict the numerical result of adding
-
[code] In-place composition. ● Evaluate
(A + B) * (-A / 2)for two identically shapedfloat32tensorsAandBwithout allocating any intermediate tensor, using only PyTorch's in-place methods (add_,div_,neg_,mul_) orout=keyword arguments. Confirm thatA.data_ptr()andB.data_ptr()remain unchanged and that the final result matches the out-of-place expression(A + B) * (-A / 2). Explain why writingA[:] = A + Bwould not satisfy the zero-temporary-allocation requirement.Adapted from Nicolas P. Rougier, 100 numpy exercises, problem 35.
- [code] Python loops versus broadcasting. ● Given a 1D vector
aof elements and a 1D vectorbof elements, we want to compute the pairwise absolute-difference matrix with entries .- Compute first using two nested Python
forloops, and then using a single broadcasted subtraction after reshapingato(200, 1)andbto(1, 300). Verify that both matrices agree numerically, measure the wall-clock execution time of each method, and report the speedup factor. - Even though broadcasting avoids copying the inputs
aandb, the output matrix must still be materialized in memory. How many megabytes does occupy infloat32ifaandbeach contain elements? What lesson does this teach about the peak memory footprint of broadcasted outer operations?
- Compute first using two nested Python