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.
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
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.
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.
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.
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.
pred has shape (64, 1) and y has shape (64,). What shape does pred - y have?Chapter 1
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:
float32 uses 4 bytes per number; int64 uses 8.(3, 4) means 3 rows of 4.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:
Address equals offset, plus i-zero times s-zero, plus i-one times s-one, and so on up to the last dimension.
x.storage_offset().x.stride().Multiply each index i-k by its stride s-k. Add the products, then add the offset. That sum is the address.
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:
s-sub-d-minus-one equals one, and s-k equals n-k-plus-one times s-k-plus-one.
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.
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.
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.
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]])
Chapter 2
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:
transpose and permute reorder the shape and the strides together.a:b:c moves the offset and multiplies the stride (the equation below).x[1], moves the offset and drops that dimension.unsqueeze adds a dimension of size 1. expand stretches a size-1 dimension with stride 0.diagonal() of a 3 × 4 tensor has stride 4 + 1 = 5: one step down and one step right.view and, when it can, reshape regroup the dimensions (Chapter 3).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:
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.
x[::-1] is an error; torch.flip copies instead.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.
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.
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.
We checked every verdict in PyTorch 2.10 by comparing result.untyped_storage().data_ptr() with x.untyped_storage().data_ptr().
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
Chapter 3
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:
s-k must equal n-k-plus-one times s-k-plus-one.
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.
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.
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 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
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:
unsqueeze.)For one dimension, call the two sizes na and nb, and the result size nout:
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.
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.
(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.
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.
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:
x - x.max(dim=1).values on a (B, C) tensor lines the (B,) result up with C, not B. If B equals C it runs and is wrong (Chapter 8).mask[:, None].small += big fails, because the result would not fit in small's shape.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.
Chapter 5
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:
| dtype | Bytes | Holds | Typical use |
|---|---|---|---|
float32 | 4 | real numbers, about 7 significant digits | the default for weights and activations |
bfloat16, float16 | 2 | real numbers, 2 to 3 digits (Chapter 6) | mixed-precision training and inference |
float64 | 8 | about 16 digits | numerics checks; NumPy's default |
int64 | 8 | whole numbers to about 9.2 × 1018 | class labels, token ids, indices |
uint8 | 1 | 0 to 255 | raw image pixels |
bool | 1 | True or False | masks |
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".
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.
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".
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:
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.
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.
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.
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.
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.
t with shape (3,). What dtype is t + 2.5?Chapter 6
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:
Value equals minus one to the s, times two to the E minus bias, times one plus M over two to the m.
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.
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.
| Format | Bits: sign, exponent, mantissa | Largest | Smallest normal | Epsilon |
|---|---|---|---|---|
float32 | 1, 8, 23 | 3.40 × 1038 | 1.18 × 10−38 | 1.19 × 10−7 |
float16 | 1, 5, 10 | 65,504 | 6.10 × 10−5 | 9.77 × 10−4 |
bfloat16 | 1, 8, 7 | 3.39 × 1038 | 1.18 × 10−38 | 7.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.
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.
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.
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.
Chapter 7
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.
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.
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.
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
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:
Out at i, j equals x at row i, column idx at i, j.
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.
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.
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.
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
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:
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:
C at i, j equals the sum over k of A at i, k times B at k, j.
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.
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.
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.
torch.einsum("bhqd,bhkd->bhqk", q, k), which letter is summed away?Chapter 10
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:
Bytes equals numel times element-size, and time is about bytes over bandwidth.
t.numel().t.element_size().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.
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.
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.
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).
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).
small = big[:10] from a 1 GB tensor and then del big. How much memory stays allocated?Chapter 11
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).
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.
| Idea | In one line |
|---|---|
| A tensor | Storage + dtype + shape + stride + offset. address = offset + Σ ik·sk. |
| Contiguous strides | slast = 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 when | every merged group of dims is one even run: sk = nk+1·sk+1. Else use reshape (may copy). |
| Broadcasting | Align right, pad with 1s, sizes equal or 1, size 1 stretches with stride 0. Assert shapes in losses. |
| Promotion | bool < int < float. Dims beat 0-dim beat Python numbers; a lower operand counts only if its category is higher. |
| Floats | fp32 1/8/23, fp16 1/5/10 (max 65,504), bf16 1/8/7 (fp32 range). Epsilon = 2−mantissa bits. |
| Integers | Wrap silently: uint8 200 + 100 = 44. Convert images to float before arithmetic. |
| In-place | Trailing _ and +=. Every alias sees it. Version counter guards autograd. Duplicates: use index_add_. |
| Reductions | dim disappears; keepdim keeps size 1 for broadcasting back. max(dim) returns (values, indices). |
| gather / scatter | out[i, j] = x[i, idx[i, j]]; scatter writes the reverse. Cross-entropy = logsumexp − gather. |
| einsum | Shared letters multiply, missing letters sum, output order is the shape. Attention: "bhqd,bhkd->bhqk". |
| Memory and moving | bytes = numel × element_size. PCIe tens of GB/s, HBM thousands. Move once; slices keep storage alive. |
t.shape, t.stride(), t.storage_offset() and t.dtype.untyped_storage().data_ptr() before you trust a write to stay local.reshape or contiguous().view after a transpose or permute.keepdim=True before you broadcast back.numel() * element_size(); clone() small slices you keep.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)
reshape copies and some promotion corner cases. If it matters, check it with untyped_storage().data_ptr() or torch.result_type.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.
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.
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.