Maths on Whole Tensors: No Loops Needed
A tensor can hold thousands or millions of numbers, and almost everything a neural network does to them is simple arithmetic: scale them, add to them, count them, average them. PyTorch lets you write each of these jobs as one short expression on the whole tensor instead of a Python loop over its elements. Knowing the shape and the data type of what each expression returns is what keeps that code correct.
One expression for every element
Suppose a small tensor holds six brightness values, as whole numbers from 0 to 255, and you want each one as a fraction between 0 and 1. With plain Python you would visit every element in a loop and divide it by 255. With PyTorch you write the division once, on the whole tensor:
import torch
x = torch.tensor([[0, 51, 102],
[153, 204, 255]], dtype=torch.uint8)
# The loop way: one Python step per element
rows = []
for row in x.tolist():
rows.append([value / 255 for value in row])
slow = torch.tensor(rows)
# The whole-tensor way: one expression
fast = x / 255
print(fast.shape) # torch.Size([2, 3])
print(fast.dtype) # torch.float32The expression x / 255 divides every element by 255 and returns a new tensor of the same shape. Nothing is visited one by one in your code. The same holds for +, -, *, / and comparisons such as >: between a tensor and a number, or between two tensors of the same shape, they work element by element and the result has the shape of the input.
- 0
- 51
- 102
- 153
- 204
- 255
- 0.0
- 0.2
- 0.4
- 0.6
- 0.8
- 1.0
The short version is easier to read, and it is also much faster. A Python loop runs the Python interpreter once for every element: it fetches the value, works out what type it is, divides, and stores the result, millions of times for a large tensor. A whole-tensor expression hands the entire job to PyTorch's pre-compiled code, which runs the same small step over all the numbers with none of that per-element overhead. How much faster depends on the machine and the size of the tensor, so time it yourself when you want a number; for large tensors the gap is typically many times over.
Whole numbers become floating-point numbers
Every tensor has one data type for all its elements. Images are usually stored as torch.uint8, whole numbers from 0 to 255, because that is compact. A model, however, computes with floating-point numbers, numbers that can have a fractional part, such as 0.2 or -1.37. In PyTorch the usual floating-point type is torch.float32, and it is the default type for floating-point tensors. So one of the first things done to whole-number data is to convert it.
There are two common ways. x.float() converts to torch.float32 and keeps the values (255 becomes 255.0). Dividing with / converts too, because / is true division, as in Python: when its inputs are whole numbers, the result is always a floating-point tensor. That is why x / 255 above both rescales to the range 0 to 1 and produces float32 in one step.
counts = torch.tensor([3, 7, 10]) # whole numbers: torch.int64
(counts + 5).dtype # torch.int64: a whole number keeps the type
(counts * 1.5).dtype # torch.float32: a float number makes it float
(counts / 2).dtype # torch.float32: / always gives floats
(counts // 2).dtype # torch.int64: // is whole-number division
counts.float().dtype # torch.float32The rule behind these results: when a tensor is combined with a plain Python number, the result changes type only when the number is of a more general kind than the tensor's elements. A floating-point number can hold a fractional part and a whole number cannot, so a float number combined with a whole-number tensor gives a float32 result. A whole number combined with a whole-number tensor leaves its type as it was. PyTorch decides this from the types alone, never from the values, so counts * 2.0 is a float32 tensor even though every result happens to be whole.
True or false?
Dividing a tensor of whole numbers by the whole number 2 with / gives a tensor of whole numbers.
False. The / operator is true division and always gives floating-point results for whole-number inputs. Whole-number division is //.
x.float() on a uint8 tensor holding 255 gives 255.0, not 1.0.
True. Converting the type keeps the values. Rescaling to the range 0 to 1 is a separate step, such as dividing by 255.
Adding the whole number 5 to a whole-number tensor turns it into float32.
False. A whole number is of the same kind as the tensor, so the type stays as it was. Only a float number would change it.
Broadcasting: a smaller tensor reused for every row
In x / 255 the 255 is a single number, yet it is used against all six elements. PyTorch treats it as if it were a tensor of the same shape as x, filled with 255. This reuse of a smaller operand across a larger one is called broadcasting, and it works for more than single numbers.
Take a table of three rows and four columns, and one row of four numbers to add to it. Written as table + row, the row is added to every row of the table: its first number to the first column, its second to the second column, and so on. No copies of the row are made in memory; PyTorch only reads the same four numbers again for each row.
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 10
- 20
- 30
- 40
- 11
- 22
- 33
- 44
- 15
- 26
- 37
- 48
- 19
- 30
- 41
- 52
Which shapes can be combined
PyTorch decides by lining the two shapes up from the right, the last dimension first, and comparing them one dimension at a time. Each pair of sizes must be one of these:
- equal, such as 4 and 4;
- one of them is 1, and that size is stretched to match the other;
- one of them is missing, because that tensor has fewer dimensions, and it counts as 1.
If any pair breaks the rule, the operation stops with a RuntimeError saying the size of one tensor must match the size of the other at a given dimension. When it succeeds, each size of the result is the larger of the two.
| Shape A | Shape B | Compared from the right | Result |
|---|---|---|---|
| (3, 4) | (4,) | 4 and 4 equal; 3 and missing | (3, 4) |
| (3, 4) | (3, 1) | 4 and 1; 3 and 3 equal | (3, 4) |
| (2, 3, 4) | (3, 1) | 4 and 1; 3 and 3; 2 and missing | (2, 3, 4) |
| (4, 1) | (4,) | 1 and 4; 4 and missing | (4, 4) |
| (3, 4) | (3,) | 4 and 3 differ, neither is 1 | error |
Two lines of this table deserve a second look. The last one: a tensor of shape (3,) holds one number per row of a (3, 4) table, but it cannot be added to it directly, because lined up from the right, its 3 meets the table's 4. Giving it the shape (3, 1), a column, makes the shapes fit, and then each row's number is added across that row.
The (4, 1) and (4,) line shows the opposite danger. Both sizes stretch, and the result is a (4, 4) table with no error at all. When a result comes out larger than you expected, broadcasting is the usual reason, so check the shape.
True or false?
A row of shape (5,) can be added to a tensor of shape (10, 5).
True. From the right, 5 meets 5, and the missing first dimension counts as 1. The result has shape (10, 5).
A tensor of shape (10,) can be added to a tensor of shape (10, 5).
False. Shapes are compared from the right, so 10 meets 5. A column of shape (10, 1) would fit.
Broadcasting copies the smaller tensor in memory once for every row.
False. The stretching only describes the result. PyTorch reads the same numbers again without making copies.
Reshaping: the same numbers in a new arrangement
Sometimes the numbers are right but their arrangement is not. A small image stored as a grid of 2 rows and 3 columns can be laid out as one row of 6 numbers, or as 3 rows of 2. reshape does this. It keeps every number and their order, reading the old tensor row by row, left to right, and fills the new shape in that same order.
- 0
- 1
- 2
- 3
- 4
- 5
- 0
- 1
- 2
- 3
- 4
- 5
- 0
- 1
- 2
- 3
- 4
- 5
grid = torch.arange(6).reshape(2, 3) # [[0, 1, 2], [3, 4, 5]]
grid.reshape(6).shape # torch.Size([6])
grid.reshape(3, 2).shape # torch.Size([3, 2])
grid.reshape(-1).shape # torch.Size([6]): -1 is worked out
grid.numel() # 6, the number of elements
grid.reshape(4) # RuntimeError: 4 places for 6 numbersThe one rule is that the number of elements stays the same: the product of the sizes in the new shape must equal the product in the old one. Six numbers fit (6,), (3, 2) or (1, 6), never (4,). numel() tells you how many elements a tensor has. One size in the new shape may be written as -1, and PyTorch works it out from the others, so reshape(-1) always means "one long row".
Flattening a stack of grids
A common case is a stack of images, such as a tensor of shape (100, 8, 8): 100 images of 8 by 8 pixels. To give each image as one row of 64 numbers, keep the first dimension and merge the other two. images.reshape(100, 64), images.reshape(100, -1) and images.flatten(start_dim=1) all give shape (100, 64). flatten merges every dimension from start_dim onwards, and with no argument it merges them all into one.
The result of reshape may share its numbers with the original tensor or be a separate copy; PyTorch chooses, and code should not depend on which. If you change elements of a reshaped tensor and need the original untouched, make a copy yourself with .clone().
True or false?
A tensor of shape (4, 6) can be reshaped to (3, 8).
True. Both shapes hold 24 elements, which is all reshape requires.
reshape can add zeros to fill a larger shape.
False. The new shape must hold exactly the same number of elements; otherwise reshape raises an error.
In reshape(10, -1), the -1 is replaced by whatever size makes the element count match.
True. Only one size may be -1, and PyTorch works it out from the total and the other sizes.
Reducing: summing, averaging and counting along a dimension
The last family of operations turns many numbers into fewer: a total, an average, a largest value, a count. These are called reductions. With no argument, a reduction covers the whole tensor and returns a tensor with a single element. Given the argument dim, which names one dimension by its position in the shape (0 for the first), it works along that dimension only, and that dimension disappears from the result.
For a table of shape (2, 3), dim=0 is the first dimension, the one of size 2 that counts the rows. Summing along it adds the rows together, column by column, so 2 rows of 3 become one row of 3: shape (3,). dim=1 is the second dimension, the one of size 3 that counts the columns. Summing along it adds across each row, so each row becomes one number: shape (2,). A quick way to predict the result: cross out the size at position dim in the shape, and what is left is the shape of the result.
- 1
- 2
- 3
- 4
- 5
- 6
- 5
- 7
- 9
- 6
- 15
t = torch.tensor([[1., 2., 3.],
[4., 5., 6.]])
t.sum() # 21.0, a tensor with one element
t.sum().item() # 21.0 as a plain Python number
t.sum(dim=0) # [5., 7., 9.] shape (3,)
t.mean(dim=1) # [2., 5.] shape (2,)
t.max() # 6.0
t.max(dim=1) # values [3., 6.] and indices [2, 2]
t.argmax(dim=1) # [2, 2]: where each row's largest value sitsA few details matter in practice:
- A reduction over the whole tensor still returns a tensor, of shape
(): a tensor with no dimensions that holds one number..item()turns a one-element tensor into a plain Python number, for printing or for anif. meanneeds floating-point input. On auint8orint64tensor, convert first, for examplex.float().mean().maxwithdimreturns two tensors: the largest values and their positions along that dimension. When you only need the positions,argmaxreturns them directly. If two values tie, the position of the first one is given.- Adding
keepdim=Truekeeps the reduced dimension with size 1, so a(2, 3)table summed alongdim=1gives(2, 1). That column then broadcasts back against the original table, for example to divide each row by its own total.
Counting
Counting is a reduction too. A comparison such as t > 3 gives a tensor of True and False of the same shape, and summing it counts the True values, because each True counts as 1 and each False as 0. So (t > 3).sum() is 3, and (t > 3).sum(dim=1) gives a count per row, [0, 3]. To count how often each whole number appears in a one-dimensional tensor of non-negative integers, torch.bincount returns one count per value from 0 up to the largest:
labels = torch.tensor([3, 1, 3, 0, 3])
torch.bincount(labels) # tensor([1, 1, 0, 3]): one 0, one 1, no 2, three 3sTrue or false?
Summing a tensor of shape (5, 4) along dim=0 gives a result of shape (4,).
True. The reduced dimension, of size 5, is removed, leaving one total per column.
t.sum() returns a plain Python number.
False. It returns a tensor with one element. .item() gives the Python number.
t.max(dim=1) returns only the largest value of each row.
False. With dim it returns the values and their positions. argmax gives only the positions.
(t > 0).sum() counts how many elements of t are positive.
True. The comparison gives True or False per element, and summing counts each True as 1.