PyTorch Tensors

A tensor is one flat line of numbers in memory, plus a few small numbers that say how to read it. Transpose, slice and expand change only those few numbers. They copy nothing, so they take the same time for 12 numbers or 12 billion.

Take a tensor apart into storage, dtype, shape, stride and offset. Learn when two tensors share memory, why view() fails, how broadcasting works, what each dtype can hold, and what it costs to move data.

Press Walk and watch the read head move through memory. Then transpose, slice or expand the view. The memory below never changes. Only the path through it does.

You need Python, lists and a table of numbers, and the ML maths lesson helps. We build the rest from zero.

Walk the storage

Ready
x

x = torch.arange(12).view(3, 4) and y = torch.arange(24).view(2, 3, 4), so every value equals its storage address. Each shape, stride, offset and "contiguous?" answer is what PyTorch 2.10 reports for the same calls. Tap a view cell to put the read head on it.

Chapter 0

The loss went down. The model learned nothing.

Train a tiny model with one silent shape bug, and find the hidden layer behind it: how a tensor reads its memory

You fit a straight line to 64 points that follow y = 3x + 1. The code runs and the loss falls. No error appears. But the model predicts almost the same number for every input.

nn.Linear returns predictions with shape (64, 1): one row per point. The targets have shape (64,): a plain list. The loss line ((pred - y) ** 2).mean() does not pair each prediction with its target.

PyTorch stretches both tensors into a 64 × 64 table and subtracts every target from every prediction. The cheapest way to make that loss small is to predict the average target everywhere. So the model learns a flat line. Try it.

Train with the bug

Pick the shape of the targets, then press Train. The left panel shows the data and the fitted line. The right panel shows the tensor pred - y that the loss averages.

64 points on y = 3x + 1 plus noise of spread 0.3, x from −2 to 2. The model is one weight and one bias, trained by plain gradient descent with learning rate 0.1, the same as nn.Linear(1, 1) with torch.optim.SGD. The noise is illustrative.

Why nothing crashed

By PyTorch's rules, that subtraction was legal. The rules are called broadcasting: stretching a size-1 dimension to match the other tensor. Broadcasting, transpose, slicing and view work the same way. They leave the numbers in memory alone and change a few small numbers that say how to read them.

When you can see those small numbers, a family of bugs becomes easy to spot. Two tensors share memory. A view refuses to work. A half-precision sum stops growing. A count wraps from 127 to −128.

The road map of this lesson

  1. Five numbers and a line of memory: storage, dtype, shape, stride and offset.
  2. Views share, copies don't: which operations allocate memory, and how to prove it.
  3. Contiguous, and when view() says no: the rule behind the famous error.
  4. Broadcasting is expand with stride 0: the rules, and today's bug, fixed.
  5. Dtypes and the promotion rules: what a mixed operation returns, and integer wrap-around.
  6. float32, float16, bfloat16: bits, range and precision.
  7. In-place ops and aliasing: which writes reach which data.
  8. Reductions, gather, scatter and masks: dim, keepdim and picking values.
  9. einsum: one language for shapes: matmul, attention and dot products in one line.
  10. Memory math and moving data: bytes, PCIe, GPU memory and NumPy.
  11. Field guide: the cheat sheet, a checklist, the core code and the rest of the series.

PyTorch, Zero to Expert

This is lesson 1 of an eleven-part series inside The Builder's Toolkit. Each lesson has Code Labs that run PyTorch code in your browser.

  1. PyTorch Tensors: Storage, Strides and Views (this lesson).
  2. Autograd: the Graph Behind backward()
  3. nn.Module Inside Out
  4. Datasets and DataLoaders
  5. The Training Loop, Line by Line
  6. Debugging Training: When the Loss Won't Go Down
  7. Memory and Mixed Precision
  8. Making PyTorch Fast
  9. Distributed PyTorch: DDP and FSDP from the Inside
  10. PyTorch Internals: From a Python Call to a Kernel
  11. Build PyTorch from Scratch
pred has shape (64, 1) and y has shape (64,). What shape does pred - y have?

Chapter 1

Five numbers and a line of memory

Take a tensor apart into five parts and turn any index into a memory address by hand

Computer memory is one long line of numbered boxes. PyTorch lays a 3 × 4 table along it row by row: row 0, then row 1, then row 2. This order is called row-major order.

So a tensor is that line of numbers plus a rule for finding element [i, j] in it. It has five parts:

Which storage cell holds a given element? Call your index along dimension k ik and the stride of that dimension sk. Call the storage offset offset. The answer is the address:

Say it aloud

Address equals offset, plus i-zero times s-zero, plus i-one times s-one, and so on up to the last dimension.

address
address the position of the element in the storage, counted in elements from the start.
offset
offset where element [0, 0, …] sits in the storage. Read it with x.storage_offset().
ik
i-k your index along dimension k, counted from 0.
sk
s-k the stride of dimension k, in elements (not bytes). Read it with x.stride().
d
d the number of dimensions. We count them from 0 to d − 1.
In plain words

Multiply each index i-k by its stride s-k. Add the products, then add the offset. That sum is the address.

With numbers

x = torch.arange(12).view(3, 4) has stride (4, 1) and offset 0. For x[2, 1]: 0 + 2 × 4 + 1 × 1 = 9. The value there is 9, as arange promised. At 8 bytes per int64, that is 72 bytes past the start.

Where do the strides of a fresh tensor come from? Call the size of dimension k nk. The last dimension steps one element at a time. Each dimension to its left jumps over one whole block of everything to its right. A tensor laid out this way, with no gaps, is contiguous:

Say it aloud

s-sub-d-minus-one equals one, and s-k equals n-k-plus-one times s-k-plus-one.

sd−1
s-sub-d-minus-one the stride of the last dimension. It is always 1 element.
sk
s-k the stride of dimension k in a contiguous tensor.
nk+1
n-k-plus-one the size of the next dimension to the right.
sk+1
s-k-plus-one the stride of that next dimension, found one step earlier.
In plain words

Give the last dimension stride 1. Move one dimension left, and multiply the stride you have by the size n-k-plus-one you just passed. Repeat until the first dimension.

With numbers

An image batch of shape (N, C, H, W) = (2, 3, 4, 5). Stride of W: 1. H: 5 × 1 = 5. C: 4 × 5 = 20. N: 3 × 20 = 60. So the stride is (60, 20, 5, 1), and pixel [1, 2, 3, 4] sits at 60 + 40 + 15 + 4 = 119, the last of 120 cells.

Strides from a shape

Shape (2, 3, 4, 4): 2 images, 3 colour channels, 4 × 4 pixels. Move the sliders to see which storage cell an index reads. Then switch to channels-last and watch the same pixel move.

1
2
1
3

Strides are what torch.empty(2, 3, 4, 4).stride() and .to(memory_format=torch.channels_last).stride() return in PyTorch 2.10: (48, 16, 4, 1) and (48, 1, 12, 3). The shade of a storage cell shows its channel, darkest for channel 0.

Channels-last keeps the shape (2, 3, 4, 4) but stores the three colour values of each pixel side by side. Only the strides change. Many GPU convolution kernels run faster on it, because they read one pixel's channels together. This code shows all five parts:

import torch

x = torch.arange(12).view(3, 4)
print(x.shape, x.dtype)          # torch.Size([3, 4]) torch.int64
print(x.stride())                # (4, 1)   in elements
print(x.storage_offset())        # 0
print(x.element_size())          # 8 bytes per int64
print(x.untyped_storage().nbytes())  # 96 = 12 elements x 8 bytes

# the address rule, checked against PyTorch's own as_strided
flat = x.flatten()
v = torch.as_strided(flat, size=(2, 2), stride=(4, 1), storage_offset=5)
print(v)                         # tensor([[5, 6], [9, 10]])
A contiguous tensor has shape (2, 3, 4). At what storage address is element [1, 2, 3]?

Chapter 2

Views share, copies don't

Sort common operations into views that reuse the storage and copies that allocate new memory, and prove which is which

A view is a new tensor object with its own shape, stride and offset that points at an existing storage. It costs a few bytes of bookkeeping, whatever the size of the data. A copy allocates new storage and moves every element into it. For a 4 GB tensor, that is 4 GB of new memory and real time.

Most shape operations are views, because new strides can describe them:

What does a slice do to the metadata? Take one dimension with stride s. Slice it from start a to stop b (not included) with step c. Three numbers change: the offset, the stride and the size:

Say it aloud

Offset-prime equals offset plus a times s. s-prime equals c times s. n-prime equals the ceiling of b minus a, over c.

a
a the start of the slice.
b
b the stop, not included, clipped to the size.
c
c the step. PyTorch allows only positive steps, so x[::-1] is an error; torch.flip copies instead.
s
s the old stride of that dimension.
offset′
offset-prime the new storage offset.
s′
s-prime the new stride.
n′
n-prime the new size: how many elements the slice keeps.
⌈ ⌉
the ceiling of round up to the next whole number.
In plain words

Move the offset forward by a steps of size s. Multiply the stride by the step c. Count how many steps of c fit between a and b, rounding up. Nothing in storage moves.

With numbers

torch.arange(10)[1:8:3]: offset 0 + 1 × 1 = 1, stride 3 × 1 = 3, size the ceiling of 7 / 3 = 3. It reads addresses 1, 4 and 7, and PyTorch prints tensor([1, 4, 7]).

Some results need more than one stride per dimension. Then PyTorch must copy. Advanced indexing is the main case: indexing with a list, a tensor of indices or a boolean mask. x[[0, 2]] picks rows 0 and 2. No single stride jumps from row 0 to row 2 and stops. clone(), arithmetic, .to() a new dtype or device and torch.tensor(data) also copy.

View or copy? Call it

Each card applies one operation to x = torch.arange(12).view(3, 4). Call it first: does the result share x's storage, or own new memory? The diagram then shows where each result cell reads from.

x.t()

We checked every verdict in PyTorch 2.10 by comparing result.untyped_storage().data_ptr() with x.untyped_storage().data_ptr().

How to prove it

Two tensors share memory when they point at the same storage block. Compare the storage pointers, not the tensors' own pointers:

import torch

def shares(a, b):
    return a.untyped_storage().data_ptr() == b.untyped_storage().data_ptr()

x = torch.arange(12).view(3, 4)
s = x[:, 1:3]
print(x.data_ptr() == s.data_ptr())   # False: s starts 1 element later
print(shares(x, s))                  # True: same storage block
print(shares(x, x[[0, 2]]))           # False: advanced indexing copies
s[0, 0] = 100
print(x[0, 1])                       # tensor(100): the write went through the view
Which of these allocates new memory?

Chapter 3

Contiguous, and when view() says no

Learn what contiguous means, find the exact rule that makes view() refuse a shape, and see when reshape() quietly copies

Go back to the hero and press Walk on the plain x. The read head steps through storage cells 0, 1, 2, 3 with no gaps and no jumps. That tensor is contiguous: its strides equal the contiguous strides of its shape (Chapter 1). Transpose it and walk again. The head jumps 4 cells, then 4 more, then back 7.

view(new_shape) promises never to copy, so it must find strides for the new shape over the same storage. Splitting a dimension always works: 12 evenly spaced elements can always be read as 3 runs of 4. Merging two neighbouring dimensions is the hard case.

Call the outer dimension k, with stride sk. Call the inner one k + 1, with size nk+1 and stride sk+1. The two merge only if each block of the inner dimension ends where the next one starts:

Say it aloud

s-k must equal n-k-plus-one times s-k-plus-one.

sk
s-k the stride of the outer dimension: the jump from one block to the next.
nk+1
n-k-plus-one the size of the inner dimension: how many elements one block holds.
sk+1
s-k-plus-one the stride of the inner dimension: the gap between elements inside one block.
In plain words

One block of the inner dimension covers n-k-plus-one times s-k-plus-one cells. If the outer stride s-k is exactly that length, the two dimensions form one even run, and view can merge them. If not, it refuses.

With numbers

x.t() has shape (4, 3) and stride (1, 4). To merge into 12: is s-zero = n-one × s-one? 1 against 3 × 4 = 12: no, so x.t().view(12) fails. For the plain x, stride (4, 1): 4 against 4 × 1 = 4: yes.

Learn the error PyTorch 2.10 raises by sight:

RuntimeError: view size is not compatible with input tensor's size and stride
(at least one dimension spans across two contiguous subspaces). Use .reshape(...) instead.

Will view() work?

Start from y = torch.arange(24).view(2, 3, 4). Pick how to rearrange it, then a target shape. The boxes group the dimensions into evenly spaced runs. A target dimension must fit inside one run.

The verdict uses the same algorithm as PyTorch's computeStride (declared in ATen/TensorUtils.h). We checked every case shown against PyTorch 2.10.

reshape, contiguous and the attention bug

reshape tries view first. If that fails, it calls contiguous(), which copies the data into a fresh row-major storage, and views the copy. So reshape sometimes copies, and the code does not tell you. On a tensor that is already contiguous, contiguous() copies nothing.

This bites most in multi-head attention. Each head's output has shape (B, H, T, D). To join the heads you swap H and T, then merge H and D:

import torch
B, H, T, D = 2, 4, 5, 8
out = torch.randn(B, H, T, D)             # one output per head
y = out.transpose(1, 2)                  # (B, T, H, D), stride (160, 8, 40, 1)
# y.view(B, T, H * D)                     # RuntimeError: H (stride 40) and D (stride 1) are not one run
merged = y.reshape(B, T, H * D)            # works: copies, (2, 5, 32)
merged = y.contiguous().view(B, T, H * D)  # the same, written out
x is a contiguous 3 × 4 tensor. What does x.t().view(12) do?

Chapter 4

Broadcasting is expand with stride 0

Derive the broadcasting rules from strides, read shapes from the right, and fix the (N,) versus (N, 1) bug from Chapter 0

You want to add a bias of 4 numbers to every row of a 3 × 4 matrix. You could copy the bias 3 times. PyTorch does something cheaper: it makes a view of the bias with shape (3, 4) and stride (0, 1).

Stride 0 means "a step down a row does not move in memory". Every row reads the same 4 numbers, so the view looks like 12 numbers but stores 4. bias.expand(3, 4) returns this view. Broadcasting is expand, applied for you before an element-wise operation.

Expand can only stretch a dimension of size 1, by giving it stride 0. The rules follow:

  1. Line the two shapes up from the right.
  2. If one shape is shorter, pad it on the left with 1s. (That is a free unsqueeze.)
  3. For each dimension, the two sizes must be equal, or one of them must be 1.
  4. A size-1 dimension stretches to the other size, with stride 0.

For one dimension, call the two sizes na and nb, and the result size nout:

Say it aloud

n-out equals the max of n-a and n-b, allowed only if n-a equals n-b, or the min of the two is one.

na
n-a the size of tensor a in this dimension, after lining up from the right and padding with 1s.
nb
n-b the size of tensor b in the same dimension.
max
the max of the larger of the two.
min
the min of the smaller of the two.
1
one a size-1 dimension. It stretches with stride 0, so every step reads the same element.
nout
n-out the size of the result in this dimension. Any other pair of sizes raises an error.
In plain words

For each dimension, compare n-a and n-b. If they match, keep that size. If one is 1, take the other. If neither, stop with an error.

With numbers

(64, 1) against (64,). Pad: (64, 1) and (1, 64). Dimension 0: n-a 64, n-b 1, so n-out = 64. Dimension 1: 1 and 64, so 64. The result is (64, 64): the Chapter 0 bug.

Broadcast two shapes

Pick a pair. The table lines the shapes up from the right. Below it, each tensor appears as expand sees it: real cells solid, stride-0 copies dashed. The bottom row is the result.

Expanded strides are what a.expand(out_shape).stride() returns in PyTorch 2.10, for contiguous a and b. For the 3-D pair we draw only the last two dimensions.

Fixing the bug, and spotting its cousins

The fix for Chapter 0 is one call before the subtraction: pred.squeeze(1), which turns (N, 1) into (N,), or y.unsqueeze(1), which turns (N,) into (N, 1). Then assert the shapes, so the next mistake fails loudly.

Broadcasting bugs share one feature: the code runs. Look for these first:

Broadcasting on purpose: pairwise distances

Broadcasting also compares every item with every other item. (N, 1, D) minus (1, M, D) broadcasts to (N, M, D): every difference, with no Python loop. Square, sum over D and take the root to get an N × M distance matrix.

What shape does a (5, 1, 4) tensor plus a (3, 1) tensor give?

Chapter 5

Dtypes and the promotion rules

Pick the right dtype, predict the dtype a mixed operation returns, and watch integers wrap around without a warning

The dtype says how to turn bytes into a number. Deep learning uses a handful:

dtypeBytesHoldsTypical use
float324real numbers, about 7 significant digitsthe default for weights and activations
bfloat16, float162real numbers, 2 to 3 digits (Chapter 6)mixed-precision training and inference
float648about 16 digitsnumerics checks; NumPy's default
int648whole numbers to about 9.2 × 1018class labels, token ids, indices
uint810 to 255raw image pixels
bool1True or Falsemasks

Two defaults catch everyone. torch.tensor([1, 2]) is int64 and torch.tensor([1.0]) is float32. NumPy defaults to float64, so torch.tensor(np.array([0.5])) is float64. A float32 nn.Linear then fails with "mat1 and mat2 must have the same dtype, but got Double and Float".

Mixing dtypes: type promotion

What does an int64 tensor plus 2.5 return? PyTorch decides by type promotion. It ranks dtypes in three categories: bool, then integers, then floats. It also ranks operands: a tensor with dimensions beats a zero-dimensional tensor, which beats a plain Python number.

So int64 tensor + 2.5 gives float32: a float beats an integer. A float16 tensor + a float32 zero-dimensional tensor stays float16: same category, and the tensor with dimensions decides. So x * 0.5 keeps your half-precision activations in half precision.

Predict the result dtype

Pick the left operand (a tensor with dimensions) and the right operand: its kind and its dtype. The result and the rule that decided it update live.

The rule is PyTorch's torch.result_type logic. For a Python number only the category matters: True is bool, 2 is an integer, 2.5 is a float. We checked every combination here against PyTorch 2.10.

Two more rules. Division with / always returns a float: torch.tensor([7]) / 2 is 3.5. Use // for floor division. An in-place operation cannot change a dtype: int_tensor += 2.5 raises "result type Float can't be cast to the desired output type Long".

Integers wrap around

An integer dtype has a fixed number of bits. When a result does not fit, PyTorch keeps only the lowest bits, with no error and no warning. The number wraps around, like a car's odometer rolling past 99,999. Call the true result v and the number of bits b. The stored value is:

Say it aloud

Unsigned: v mod two to the b. Signed: v plus two to the b-minus-one, mod two to the b, then minus two to the b-minus-one.

v
v the true mathematical result, before storing.
b
b the number of bits: 8 for uint8 and int8, 32 for int32.
2b
two to the b how many values the dtype can hold: 256 for 8 bits.
2b−1
two to the b-minus-one half of that: 128 for 8 bits. It shifts the signed range so it starts at −128.
mod
mod the remainder after division: 300 mod 256 is 44.
unsigned
unsigned uint8 holds 0 to 255; after 255 comes 0.
signed
signed int8 holds −128 to 127; after 127 comes −128.
In plain words

Unsigned: divide v by two to the b and keep the remainder. Signed: shift v up by half the range, take the remainder, and shift back down.

With numbers

uint8 pixels 200 + 100: v = 300, b = 8, so 300 mod 256 = 44. int8 127 + 1: v = 128, so (128 + 128) mod 256 − 128 = 0 − 128 = −128. PyTorch 2.10 prints both.

Count past the top

The ring holds every value the dtype can store. Pick a start and an amount to add; the arc shows the walk. Past the top it comes back around.

200
100

This bites when you add or multiply raw uint8 images. Convert first: img.float() / 255. sum() of an integer tensor is safe, because it returns int64. mean() of an integer tensor is an error: PyTorch will not guess a float dtype.

An int64 tensor t with shape (3,). What dtype is t + 2.5?

Chapter 6

float32, float16, bfloat16: bits, range and precision

Lay out the sign, exponent and mantissa bits, and see what each format rounds or loses

A float stores a number like scientific notation: 1.25 × 23. One bit holds the sign. The exponent bits hold the power of 2 and set the range. The mantissa bits hold the digits after the point and set the precision. The three formats split their bits differently.

Call the sign bit s, the exponent bits read as a whole number E, and the mantissa bits read as a whole number M. Call the number of mantissa bits m. A fixed bias lets the exponent go negative. The stored value is:

Say it aloud

Value equals minus one to the s, times two to the E minus bias, times one plus M over two to the m.

value
value the number the bits stand for.
s
s the sign bit: 0 for positive, 1 for negative.
E
E the exponent bits read as a whole number. The patterns all 0s and all 1s stand for zero, tiny numbers, infinity and NaN.
bias
bias 127 for 8 exponent bits, 15 for 5. Subtracting it lets the power of 2 go negative.
M
M the mantissa bits read as a whole number.
2m
two to the m m is the count of mantissa bits. The gap between neighbouring numbers near 1 is 1 / 2m: the machine epsilon.
In plain words

Turn M into a fraction between 0 and 1 by dividing by two to the m, and add 1. Scale that by two to the power E minus bias. Make it negative if s is 1.

With numbers

float16 (5 exponent bits, m = 10, bias 15) stores 10 as s = 0, E = 18, M = 256: 23 × (1 + 256/1024) = 8 × 1.25 = 10. The largest float16 has E = 30 and M = 1023: 215 × (1 + 1023/1024) = 65,504.

FormatBits: sign, exponent, mantissaLargestSmallest normalEpsilon
float321, 8, 233.40 × 10381.18 × 10−381.19 × 10−7
float161, 5, 1065,5046.10 × 10−59.77 × 10−4
bfloat161, 8, 73.39 × 10381.18 × 10−387.81 × 10−3

The values come from torch.finfo in PyTorch 2.10. bfloat16 is the top 16 bits of a float32: the same range, but only 7 mantissa bits. float16 has more mantissa bits and a small range.

See the bits

Pick a number. Each row shows its bits, the value that comes back and the relative error. Yellow bits are the exponent, pink bits the mantissa.

0.1

Rounding is round-to-nearest-even, as in PyTorch's casts from float32. The device first rounds the number to float32, as torch.tensor(v) does. float16 stores numbers below 6.1 × 10−5 as subnormals, with fewer mantissa bits.

What the bits do to your training

Overflow. 70,000 does not fit in float16: it becomes inf. In bfloat16 it becomes 70,144, rounded but finite.

Underflow. 10−8 becomes exactly 0 in float16: its smallest positive number is about 6 × 10−8. Small gradients vanish. So float16 training uses a loss scaler. It multiplies the loss by a large factor before backward, which lifts small gradients into range. It skips any step whose gradients overflow (lesson 7). bfloat16 has float32's range and usually needs no scaler.

Swamping. A small number added to a big one can vanish: 256 + 1 = 256 in bfloat16, and 2048 + 1 = 2048 in float16. Add 0.0001 to a running total 10,000 times: float16 stops at 0.25, bfloat16 at 0.03125, not 1. So matrix multiplies and sum() accumulate in float32 inside the kernel: torch.full((10000,), 1e-4, dtype=torch.float16).sum() returns 1.0.

In bfloat16, what is 256 + 1?

Chapter 7

In-place ops and aliasing

Tell names from tensors and tensors from storage, trace which writes reach which data, and meet the guards that protect autograd

Three layers hide behind one line of PyTorch. A Python name, like b, points at a tensor object. A tensor holds shape, stride and offset, and points at a storage. The storage holds the numbers. Two names on one tensor, or two tensors on one storage, are both aliasing.

An in-place operation writes into the existing storage instead of making a new tensor. A trailing underscore marks it: add_, mul_, zero_. +=, *= and x[i] = v are in-place too. Every alias of that storage sees the change.

Trace the aliases

Pick a program and press Step. A band marks the current line. On the right, names point at storage blocks, and an outline marks the cells the line just wrote. A warm block is new memory.

We checked each program's values by running it in PyTorch 2.10.

The errors that protect you

Every tensor carries a version counter, shared with all its views. Each in-place write adds 1. Autograd records the version of each tensor it saves for the backward pass. If the version changed before backward() runs, PyTorch refuses to compute a wrong gradient:

RuntimeError: one of the variables needed for gradient computation has been modified
by an inplace operation: [torch.FloatTensor [3]], which is output 0 of SigmoidBackward0, ...

Two more guards. An in-place op on a leaf that requires grad raises "a leaf Variable that requires grad is being used in an in-place operation". An in-place op on an expanded tensor raises "more than one element of the written-to tensor refers to a single memory location": one storage cell stands for many elements.

Duplicate indices do not add up

x[idx] += 1 reads x[idx], adds 1 and writes back. If an index appears twice, both writes land on the same cell and the last one wins. x.index_add_(0, idx, src) accumulates: it adds every value src[j] into cell idx[j], repeats included.

x = zeros(5), idx = (0, 0, 1), src = ones. index_add_ → (2, 1, 0, 0, 0). x[idx] += 1 → (1, 1, 0, 0, 0).

Histograms and scatter-sums built the second way undercount. The symptom is a total smaller than the number of items. Check it with assert counts.sum() == len(idx).

x = torch.arange(6.).view(2, 3); row = x[0]; row.mul_(10). What is x now?

Chapter 8

Reductions, gather, scatter and masks

Collapse a dimension with dim and keepdim, pick one value per row with gather, write values with scatter, and blank entries with masks

A reduction turns many numbers into one: sum, mean, max, logsumexp. The dim argument names the dimension that disappears. On a (3, 5) tensor, sum(dim=0) adds down the columns and returns 5 numbers. sum(dim=1) adds along each row and returns 3.

keepdim=True keeps the reduced dimension with size 1: (3, 5) becomes (3, 1). Then x - x.max(dim=1, keepdim=True).values subtracts each row's maximum from that row. Without keepdim, the (3,) result lines up with the 5 columns: an error, or a silent wrong answer if the tensor is square.

Three operations pick or place values by index:

How does gather pick? Call the source tensor x and the index tensor idx. Along dim 1, the output at row i and column j is:

Say it aloud

Out at i, j equals x at row i, column idx at i, j.

out[i, j]
out at i, j one output element. The output has the shape of idx.
x
x the source, for example logits of shape (B, C).
i
i the row. Gather copies it as is.
idx[i, j]
idx at i, j an int64 number that names the column to read. idx has as many dimensions as x.
In plain words

For each position in idx, stay on the same row i of x. Read the column that idx names there. Put that value in out.

With numbers

x = [[1, 2, 3], [0, 0, 5]] and targets [2, 0], so idx = [[2], [0]]. Row 0 reads column 2: 3. Row 1 reads column 0: 0. Cross-entropy is logsumexp of the row minus the picked value: 3.408 − 3 = 0.408 and 5.013 − 0 = 5.013, mean 2.71, the same as F.cross_entropy.

Collapse, pick, place

Pick an operation on the 3 × 5 matrix. The cells it uses light up, and the output appears below with its shape. Compare sum(dim=1) with keepdim=True.

x = [[1, 4, 2, 0, 3], [5, 1, 1, 2, 6], [0, 2, 7, 1, 1]] as float32; idx = [2, 4, 2]; the mask marks x > 4. Outputs are what PyTorch 2.10 returns.

Why logsumexp, not log(sum(exp))

exp(1000) is inf in float32, so x.exp().sum(1).log() on the row [1000, 0] gives inf. logsumexp first subtracts the row's maximum from every entry. It takes the log of the sum of exponentials, then adds the maximum back. No exponent is above 0, so nothing overflows: it returns 1000. F.cross_entropy and softmax do the same inside.

x has shape (8, 10). What is x.sum(dim=1, keepdim=True).shape?

Chapter 9

einsum: one language for shapes

Name every dimension with a letter, let three rules multiply and sum, and write matmul and attention in one line each

Matrix multiply, batched matmul, transposes, dot products, outer products and traces look different in code. They are one idea: multiply some numbers and add some up. torch.einsum lets you say which, by naming each dimension with a letter.

torch.einsum("ik,kj->ij", A, B) reads: A has dimensions i and k, B has k and j, and the output keeps i and j. Three rules do the rest:

  1. A letter shared by two inputs lines them up: einsum multiplies the elements along it.
  2. einsum sums away a letter missing from the output.
  3. The output's letters, in order, give its shape. Reordering them transposes.

For "ik,kj->ij", call the two inputs A and B and the output C. Both inputs have the letter k and the output does not, so:

Say it aloud

C at i, j equals the sum over k of A at i, k times B at k, j.

C[i, j]
C at i, j one output element, for each pair (i, j) the output keeps.
Σk
the sum over k add one term for each value of k.
k
k the shared letter. It is not in the output, so einsum sums over it. Its sizes in A and B must match.
A[i, k]
A at i, k an element of the first input, named by its letters.
B[k, j]
B at k, j an element of the second input.
In plain words

For each output pair (i, j), walk along k. Multiply A at i, k by B at k, j and add the products. The cost is one multiply-add for every combination of all the letters: i times j times k.

With numbers

A = [[1, 2], [3, 4]] and B = [[5], [6]]. C[0, 0] = 1 × 5 + 2 × 6 = 17. C[1, 0] = 3 × 5 + 4 × 6 = 39. Cost: 2 × 1 × 2 = 4 multiply-adds.

Read an einsum

Pick a spec. Kept letters are green; a line crosses out summed letters. Below is the plain loop that computes the same thing, and the cost in multiply-adds.

Sizes used for the counts: b = 2, h = 4, i = 3, j = 4, k = 5, q = 6 queries and 6 keys, d = 8, t = 6, e = 8. Illustrative sizes; the rules are exact.

Learn the attention spec by heart: "bhqd,bhkd->bhqk". For each batch b and head h, einsum dots every query q with every key k over the head dimension d. d is missing from the output, so einsum sums it. The line equals q @ k.transpose(-2, -1); the letter order does the transpose.

In torch.einsum("bhqd,bhkd->bhqk", q, k), which letter is summed away?

Chapter 10

Memory math and the cost of moving data

Count the bytes of any tensor, compare the PCIe bus with GPU memory, and share memory with NumPy on purpose

How much memory does a tensor need, and how long does it take to move? Call its number of elements numel and the bytes per element element_size. Call the speed of the link bandwidth, in bytes per second:

Say it aloud

Bytes equals numel times element-size, and time is about bytes over bandwidth.

bytes
bytes what the tensor looks like it holds. Its storage can be smaller (expand) or larger (a slice of something big).
numel
numel the number of elements: the product of the shape. t.numel().
element_size
element-size bytes per element: 4 for float32, 2 for bfloat16, 1 for uint8. t.element_size().
time
time how long one pass over the bytes takes on that link.
≈
is about real transfers add a small fixed delay.
bandwidth
bandwidth bytes per second on a link: the bus between CPU and GPU, or the GPU's own memory.
In plain words

Multiply the shape out to get numel. Multiply by element-size to get bytes. Divide by the bandwidth of the link to get the time.

With numbers

32 RGB images at 224 × 224: numel = 32 × 3 × 224 × 224 = 4,816,896. In float32, bytes = 4,816,896 × 4 = 19.3 MB. Over a PCIe 4.0 ×16 link at about 25 GB/s: 19.3 MB / 25 GB/s = 0.77 ms. As uint8 it is 4.8 MB and 0.19 ms.

The GPU has its own memory, called HBM (high-bandwidth memory). It is close to a hundred times faster than the bus between GPU and CPU. So data should cross the bus once and stay on the GPU. A batch moved each step is fine. A tensor moved back and forth inside the loop is not, and neither is a .item() call that waits for the GPU each step.

What a batch costs to move

Set a batch of images. The bars compare how long one pass over it takes on three links, on a log scale. Try sending uint8 and converting on the GPU.

32
224

Illustrative bandwidths, right in order of magnitude. PCIe 4.0 ×16: about 32 GB/s each way in theory, 25 in practice. PCIe 5.0 ×16: about 50 in practice. GPU HBM: about 2,000 GB/s (A100 cards 1.6 to 2.0 TB/s, H100 SXM 3.35 TB/s).

NumPy: share on purpose, copy on purpose

torch.from_numpy(a) wraps the NumPy array's memory: no copy, and a write on either side shows on the other. t.numpy() does the reverse for a CPU tensor. torch.as_tensor(a) shares when it can. torch.tensor(a) always copies. The shared tensor keeps NumPy's dtype, usually float64.

import numpy as np
import torch

a = np.arange(6.0)               # float64
t = torch.from_numpy(a)          # shares a's memory, dtype float64
c = torch.tensor(a)              # a copy
a[0] = 100
print(t[0].item(), c[0].item())     # 100.0 0.0
x = torch.from_numpy(a).float()  # float32 for a model: this .float() makes a copy

Run this on a machine with PyTorch and a CUDA GPU

import torch, time
x = torch.randint(0, 256, (32, 3, 224, 224), dtype=torch.uint8)
for name, t in [("pageable", x), ("pinned", x.pin_memory())]:
    torch.cuda.synchronize(); t0 = time.perf_counter()
    for _ in range(50):
        g = t.to("cuda", non_blocking=True)   # host to device over PCIe
    torch.cuda.synchronize()                   # wait, or you time nothing
    dt = (time.perf_counter() - t0) / 50
    print(name, f"{x.nbytes / dt / 1e9:.1f} GB/s")
img = g.float().div_(255)                      # convert on the GPU: 4x less to send

Pinned memory is CPU memory the operating system promises not to move, so the GPU can copy from it directly. With pageable memory, the driver first copies into a pinned buffer. DataLoader(pin_memory=True) plus .to("cuda", non_blocking=True) lets the copy overlap with compute (lesson 4).

You keep small = big[:10] from a 1 GB tensor and then del big. How much memory stays allocated?

Chapter 11

Field guide

Ask any tensor the right question, keep a one-screen cheat sheet and a checklist, and follow the series onward

Every idea in this lesson is one picture: a flat storage, and a small record of how to read it. When a tensor surprises you, a one-line question settles it. Pick a question to ask it of t = x.t(), where x = torch.arange(12.).view(3, 4).

Ask the tensor

Each button is a question you will ask often while debugging. The card shows the call and what PyTorch 2.10 answers for t, the transposed 3 × 4 tensor.

x = torch.arange(12.).view(3, 4) and t = x.t(), a float32 tensor of shape (4, 3). Answers are what PyTorch 2.10 prints.

The cheat sheet

IdeaIn one line
A tensorStorage + dtype + shape + stride + offset. address = offset + Σ ik·sk.
Contiguous stridesslast = 1, sk = nk+1·sk+1. (2, 3, 4) → (12, 4, 1).
Views (share)transpose, permute, slicing, integer index, unsqueeze, squeeze, expand, diagonal, view, reshape when it can, detach, from_numpy.
Copies (allocate)advanced indexing (lists, index tensors, masks), clone, contiguous on non-contiguous input, .to a new dtype or device, arithmetic, torch.tensor.
view() works whenevery merged group of dims is one even run: sk = nk+1·sk+1. Else use reshape (may copy).
BroadcastingAlign right, pad with 1s, sizes equal or 1, size 1 stretches with stride 0. Assert shapes in losses.
Promotionbool < int < float. Dims beat 0-dim beat Python numbers; a lower operand counts only if its category is higher.
Floatsfp32 1/8/23, fp16 1/5/10 (max 65,504), bf16 1/8/7 (fp32 range). Epsilon = 2−mantissa bits.
IntegersWrap silently: uint8 200 + 100 = 44. Convert images to float before arithmetic.
In-placeTrailing _ and +=. Every alias sees it. Version counter guards autograd. Duplicates: use index_add_.
Reductionsdim disappears; keepdim keeps size 1 for broadcasting back. max(dim) returns (values, indices).
gather / scatterout[i, j] = x[i, idx[i, j]]; scatter writes the reverse. Cross-entropy = logsumexp − gather.
einsumShared letters multiply, missing letters sum, output order is the shape. Attention: "bhqd,bhkd->bhqk".
Memory and movingbytes = numel × element_size. PCIe tens of GB/s, HBM thousands. Move once; slices keep storage alive.

The checklist, when a tensor surprises you

  1. Print t.shape, t.stride(), t.storage_offset() and t.dtype.
  2. Assert the shapes of both sides before every element-wise loss or metric.
  3. Compare untyped_storage().data_ptr() before you trust a write to stay local.
  4. Use reshape or contiguous().view after a transpose or permute.
  5. Convert uint8 to float before arithmetic; reduce with keepdim=True before you broadcast back.
  6. Count bytes with numel() * element_size(); clone() small slices you keep.

The core, in code

def address(index, stride, offset):          # Chapter 1
    return offset + sum(i * s for i, s in zip(index, stride))

def contiguous_strides(shape):              # Chapter 1
    strides, s = [], 1
    for n in reversed(shape):
        strides.insert(0, s); s *= n
    return tuple(strides)

def broadcast_shape(a, b):                 # Chapter 4
    a, b = (1,) * (len(b) - len(a)) + a, (1,) * (len(a) - len(b)) + b
    assert all(x == y or 1 in (x, y) for x, y in zip(a, b))
    return tuple(max(x, y) for x, y in zip(a, b))

print(address((2, 1), (4, 1), 0))           # 9
print(contiguous_strides((2, 3, 4, 5)))     # (60, 20, 5, 1)
print(broadcast_shape((64, 1), (64,)))     # (64, 64)

Honest limits

Where to go next

The rest of PyTorch, Zero to Expert builds on this picture:

Related lessons on the site: Backbone + Head (shapes like B × T × D in a real model), backpropagation, loss functions, normalisation (keepdim in practice), CS336 resource accounting and distributed training.

The takeaway. A tensor is a flat storage plus shape, stride, offset and dtype. Views change the small numbers and share the storage; copies allocate. Broadcasting is expand with stride 0. Dtypes decide range, precision and wrap-around. Once you see the five parts, most tensor bugs explain themselves.
Your attention code does out.transpose(1, 2).view(B, T, H * D) and crashes. What is the best fix?

Now press Present or Teach and explain, out loud and from memory, why x.t().view(12) fails while x.view(12) works. Then go back to the hero, transpose and slice the 3 × 4 tensor, and predict each stride before you press the button.

PyTorch Tensors: Storage, Strides and Views. Lesson 1 of PyTorch, Zero to Expert, part of The Builder's Toolkit. Every default, shape, stride, dtype, error message and number about PyTorch on this page was checked against PyTorch 2.10. Sources: the PyTorch documentation pages "Tensor Views", "Broadcasting semantics", "Tensor Attributes" (type promotion) and "Type Info" (torch.finfo), at docs.pytorch.org; IEEE 754-2019 for the float16 and float32 formats; bandwidth figures are illustrative orders of magnitude from the PCI-SIG PCIe 4.0 and 5.0 link rates and NVIDIA's published A100 and H100 memory bandwidths.
Back to Gleams