Tensors: Shapes, dtypes and Views
Your NumPy autograd from the previous section wrapped a NumPy array. A PyTorch torch.Tensor is the same kind of object: a block of memory plus a description of how to read it (shape, strides, dtype, device), with autograd built in. Most bugs in a first PyTorch project are not about the model at all. They are a float64 that met a float32, a view after a permute, a broadcast that silently produced a matrix instead of a vector, or a tensor that shares memory with a NumPy array you later changed. This lesson takes those apart one by one.
The shape algebra itself (what a batch of images of shape means, einsum, the broadcasting rules) is in the Mathematics track: tensors and shapes and einsum and broadcasting. Here the focus is on what PyTorch does in memory.
A tensor is storage plus strides
A tensor with shape lives in one flat block of memory, its storage. The strides say how many elements to skip in that block to move one step along each axis. The element at index sits at
where is the tensor's starting offset in the storage. A freshly created tensor is contiguous (row-major, "C order"): the last axis has stride 1 and each earlier stride is the product of the sizes after it, . For shape that gives strides .
Many operations do not move any data; they only produce new strides over the same storage. These results are views:
| Operation | What changes | Copies data? |
|---|---|---|
x.view(...), x.reshape(...) on a contiguous tensor |
shape and strides | no |
x.permute(...), x.t(), x.transpose(a, b) |
strides reordered | no, but the result is not contiguous |
x[1:3], x[:, 0] (basic slicing) |
offset, shape | no |
x.expand(...), broadcasting |
stride 0 on the repeated axis | no |
x.contiguous() on a non-contiguous tensor |
new storage in row-major order | yes |
x[[1, 2]], x[mask] (advanced indexing) |
new tensor | yes |
A view is cheap, but writing into it writes into the original. That is the source of both the speed and the surprises.
Strides in NumPy first
NumPy uses the same model, except its strides are counted in bytes. This example runs in the browser: it computes an element's position from the strides by hand, transposes without copying, and shows when a reshape has to copy.
import numpy as np
x = np.arange(24, dtype=np.float32).reshape(2, 3, 4)
print("shape", x.shape, "strides (bytes)", x.strides, "itemsize", x.itemsize)
i, j, k = 1, 1, 2
offset = (i * x.strides[0] + j * x.strides[1] + k * x.strides[2]) // x.itemsize
print("x[1,1,2] =", float(x[i, j, k]), "= flat element", offset, "->", float(x.ravel()[offset]))
t = x.transpose(0, 2, 1) # like torch permute(0, 2, 1)
print("transposed shape", t.shape, "strides", t.strides)
print("view of x:", np.shares_memory(t, x), "| C-contiguous:", t.flags["C_CONTIGUOUS"])
r = t.reshape(2, 12) # cannot be a view here, so NumPy copies
print("reshape shares memory:", np.shares_memory(r, x))
c = np.ascontiguousarray(t)
print("ascontiguousarray strides", c.strides)
mu = x.mean(axis=(0, 1)) # shape (4,)
b = np.broadcast_to(mu, (2, 3, 4))
print("broadcast_to strides", b.strides, "(no copy: stride 0 repeats the row)")
print("(3,1) + (4,) ->", (np.ones((3, 1)) + np.ones(4)).shape)shape (2, 3, 4) strides (bytes) (48, 16, 4) itemsize 4
x[1,1,2] = 18.0 = flat element 18 -> 18.0
transposed shape (2, 4, 3) strides (48, 4, 16)
view of x: True | C-contiguous: False
reshape shares memory: False
ascontiguousarray strides (48, 12, 4)
broadcast_to strides (0, 0, 4) (no copy: stride 0 repeats the row)
(3,1) + (4,) -> (3, 4)
The byte strides are the element strides times 4 bytes per float32, and is the flat position of x[1,1,2]. The transpose only swapped two strides. Broadcasting the mean of shape to also costs nothing: stride 0 means "stay on the same element while this index moves".
dtypes: PyTorch is float32, NumPy is float64
import numpy as np
import torch
torch.manual_seed(0)
a = torch.tensor([1.0, 2.0, 3.0])
b = torch.tensor([1, 2, 3])
n = np.array([1.0, 2.0, 3.0])
print("python floats ->", a.dtype, "| python ints ->", b.dtype)
print("numpy default ->", n.dtype, "| torch.tensor(n) ->", torch.tensor(n).dtype)
print("zeros", torch.zeros(2, 3).dtype, "| arange", torch.arange(5).dtype, "| rand", torch.rand(2).dtype)
x = torch.tensor(n, dtype=torch.float32)
print("bytes per element:", x.element_size(), torch.tensor(n).element_size(), torch.tensor([1, 2], dtype=torch.uint8).element_size())
labels = torch.tensor([0, 2, 1])
print("labels", labels.dtype, "| float labels ->", labels.float().dtype)
# shared memory vs copy
arr = np.zeros(3)
shared = torch.from_numpy(arr)
copied = torch.tensor(arr)
arr[0] = 7.0
print("from_numpy sees", shared.tolist(), "| tensor copy sees", copied.tolist())
shared[1] = 5.0
print("numpy array after writing the tensor:", arr.tolist())
back = shared.numpy()
print("numpy() shares too:", np.shares_memory(back, arr))
s = torch.tensor([[1.5, 2.5], [3.5, 4.5]]).sum()
print("sum is a tensor:", s.shape, s.dtype, "| .item():", s.item(), type(s.item()).__name__)
print(".tolist():", torch.arange(6).reshape(2, 3).tolist())python floats -> torch.float32 | python ints -> torch.int64
numpy default -> float64 | torch.tensor(n) -> torch.float64
zeros torch.float32 | arange torch.int64 | rand torch.float32
bytes per element: 4 8 1
labels torch.int64 | float labels -> torch.float32
from_numpy sees [7.0, 0.0, 0.0] | tensor copy sees [0.0, 0.0, 0.0]
numpy array after writing the tensor: [7.0, 5.0, 0.0]
numpy() shares too: True
sum is a tensor: torch.Size([]) torch.float32 | .item(): 12.0 float
.tolist(): [[0, 1, 2], [3, 4, 5]]
Three rules to remember from this output:
- Floats are
float32unless they come from NumPy.torch.tensor(np_array)keeps NumPy'sfloat64, and afloat64input to afloat32model raisesmat1 and mat2 must have the same dtype. Convert once, at the boundary:torch.tensor(X, dtype=torch.float32). - Class labels are
int64(torch.long).nn.CrossEntropyLosswants integer class indices, not floats and not one-hot vectors. In the browser, NumPy's default integer isint32(Pyodide is 32-bit), so passdtype=torch.int64explicitly when labels come from NumPy. torch.from_numpyshares memory;torch.tensorcopies. Writing either side of afrom_numpypair changes the other, and so doestensor.numpy(). Sharing is what you want for a large array you only read; a copy is what you want when the array keeps changing.
A reduction such as .sum() returns a 0-dimensional tensor (torch.Size([])), not a number. .item() turns it into a Python float or int and .tolist() does the same for any shape. Use them for logging: keeping a 0-d tensor that is part of the graph (total += loss instead of total += loss.item()) keeps the whole graph of every batch alive.
view, reshape, permute, contiguous
import torch
x = torch.arange(24).reshape(2, 3, 4)
print("shape", tuple(x.shape), "stride", x.stride(), "contiguous", x.is_contiguous())
v = x.view(6, 4)
v[0, 0] = 100
print("view shares storage: x[0,0,0] =", x[0, 0, 0].item())
p = x.permute(0, 2, 1)
print("permute: shape", tuple(p.shape), "stride", p.stride(), "contiguous", p.is_contiguous())
print("same storage:", p.data_ptr() == x.data_ptr())
try:
p.view(2, 12)
except RuntimeError as e:
print("RuntimeError:", str(e))
r = p.reshape(2, 12)
print("reshape copied:", r.data_ptr() != x.data_ptr())
c = p.contiguous()
print("contiguous(): stride", c.stride(), "view ok", tuple(c.view(2, 12).shape))
t = torch.arange(6).reshape(2, 3).t()
print("transpose: stride", t.stride(), "| flatten ->", t.flatten().tolist())
print("unsqueeze", tuple(x.unsqueeze(0).shape), "squeeze", tuple(torch.zeros(1, 3, 1).squeeze().shape))
print("expand stride", torch.tensor([1, 2, 3]).expand(4, 3).stride())shape (2, 3, 4) stride (12, 4, 1) contiguous True
view shares storage: x[0,0,0] = 100
permute: shape (2, 4, 3) stride (12, 1, 4) contiguous False
same storage: True
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.
reshape copied: True
contiguous(): stride (12, 3, 1) view ok (2, 12)
transpose: stride (1, 3) | flatten -> [0, 3, 1, 4, 2, 5]
unsqueeze (1, 2, 3, 4) squeeze (3,)
expand stride (0, 1)
PyTorch reports strides in elements, so the same tensor has strides . After permute(0, 2, 1) the strides are : no longer row-major, so view(2, 12) has no way to describe the result with one stride per axis and refuses. reshape copies when it must and returns a view when it can, which makes it the safe default; view is the assertion "this must not copy". contiguous() makes the row-major copy explicitly, with the strides a fresh tensor would have.
Where this matters in practice: an image batch from NumPy or OpenCV is , convolution layers want , so x.permute(0, 3, 1, 2) is followed by .contiguous() (or by any op that copies anyway). Flattening the output of a convolution for a linear layer uses x.flatten(1) or x.reshape(len(x), -1), which works on any strides.
Broadcasting, indexing and masks
Broadcasting compares shapes from the right. Two sizes are compatible when they are equal or one of them is 1; a missing axis counts as 1. So with gives , and with gives . The rule is exactly NumPy's.
import torch
torch.manual_seed(0)
X = torch.randn(5, 3)
mu = X.mean(dim=0) # shape (3,)
sd = X.std(dim=0)
Z = (X - mu) / sd # (5,3) with (3,)
print("broadcast shapes", tuple(X.shape), tuple(mu.shape), "->", tuple(Z.shape))
print("column means", [round(v, 4) + 0.0 for v in Z.mean(0).tolist()])
col = torch.tensor([[1.0], [2.0], [3.0]])
row = torch.tensor([10.0, 20.0, 30.0, 40.0])
print("(3,1)+(4,) ->", tuple((col + row).shape))
try:
torch.ones(5, 3) + torch.ones(5)
except RuntimeError as e:
print("RuntimeError:", str(e))
print("keepdim:", tuple(X.sum(dim=1).shape), tuple(X.sum(dim=1, keepdim=True).shape))
y = torch.tensor([3, 0, 7, 0, 5])
mask = y > 0
print("mask", mask.tolist(), mask.dtype)
print("y[mask]", y[mask].tolist(), "| fancy y[[4, 0]]", y[[4, 0]].tolist())
logits = torch.arange(15.0).reshape(5, 3)
labels = torch.tensor([2, 0, 1, 1, 2])
print("picked logits", logits[torch.arange(5), labels].tolist())
sl = logits[1:3]
sl[0, 0] = -1.0
print("slice is a view: logits[1,0] =", logits[1, 0].item())
fi = logits[[1, 2]]
fi[0, 0] = -99.0
print("fancy index copies: logits[1,0] =", logits[1, 0].item())
w = torch.ones(3)
w.add_(2.0)
w.mul_(0.5)
print("in place", w.tolist())
w2 = w.clamp_(min=0, max=1.2)
print("clamp_ returns the same tensor:", w2 is w, [round(v, 4) for v in w.tolist()])
q = torch.ones(2, requires_grad=True)
try:
q.add_(1.0)
except RuntimeError as e:
print("RuntimeError:", str(e))broadcast shapes (5, 3) (3,) -> (5, 3)
column means [0.0, 0.0, 0.0]
(3,1)+(4,) -> (3, 4)
RuntimeError: The size of tensor a (3) must match the size of tensor b (5) at non-singleton dimension 1
keepdim: (5,) (5, 1)
mask [True, False, True, False, True] torch.bool
y[mask] [3, 7, 5] | fancy y[[4, 0]] [5, 3]
picked logits [2.0, 3.0, 7.0, 10.0, 14.0]
slice is a view: logits[1,0] = -1.0
fancy index copies: logits[1,0] = -1.0
in place [1.5, 1.5, 1.5]
clamp_ returns the same tensor: True [1.2, 1.2, 1.2]
RuntimeError: a leaf Variable that requires grad is being used in an in-place operation.
Read the error for : aligned from the right, 3 meets 5. The intended "subtract a per-row value" needs a column, X.sum(dim=1, keepdim=True) of shape , which is what keepdim=True is for. The dangerous case is the one that does not raise: a prediction of shape minus a target of shape broadcasts to , and ((pred - y) ** 2).mean() returns a perfectly plausible number that is the wrong loss.
logits[torch.arange(5), labels] picks one entry per row, here the logit of each example's true class: . It is the indexing behind cross-entropy. Basic slices are views (writing sl changed logits), advanced indexing with a list or mask copies (writing fi did not).
In-place operations
Methods ending in _ (add_, mul_, clamp_, zero_, copy_, normal_) modify the tensor and return it. They save memory, and the optimizers use them internally (param.add_(grad, alpha=-lr)). Two rules:
- Autograd forbids in-place changes to a leaf that requires grad, the last error above. To initialise or update weights by hand, wrap the code in
with torch.no_grad():. - In-place changes to a tensor that autograd saved for backward raise "one of the variables needed for gradient computation has been modified by an inplace operation" at
backward(). Autograd keeps a version counter on each tensor to catch this. Out-of-place code (x = x + 1) is always safe; switch to in-place only where memory matters.
Pitfalls
float64sneaking in from NumPy or pandas. It doubles memory, slows CPU math, and fails againstfloat32weights. Convert at the data boundary.- Labels as floats or with shape . Cross-entropy wants
int64of shape ;y.squeeze(1).long()fixes both. (Debugging a network shows the exact errors.) - Silent broadcasting. Assert shapes before a loss:
assert pred.shape == y.shape. viewafterpermute/transpose. Usereshape, orcontiguous()first.- Editing a NumPy array behind
torch.from_numpy. The tensor changes too; take a copy withtorch.tensor(arr)if the array is reused. - Accumulating tensors instead of numbers.
running += loss.item(), notrunning += loss.
Practice
- A tensor
xof shape is contiguous. What are its strides? What are the strides ofx.permute(0, 2, 1), and isx.permute(0, 2, 1).view(4, 30)allowed? What aboutx.permute(2, 0, 1).view(6, 20)?
Answer
Strides . permute(0, 2, 1) gives shape with strides . Two neighbouring axes can be merged into one view axis only if the outer stride equals the inner size times the inner stride. For the last two axes that would need , so view(4, 30) raises and reshape copies. permute(2, 0, 1) gives shape with strides ; merging the last two axes needs , which holds, so view(6, 20) works even though the tensor is not contiguous.
predhas shape andyhas shape . What shape doespred - yhave, and how many numbers does((pred - y) ** 2).mean()average?
Answer
: aligned from the right, and broadcast to a full matrix. The mean is over numbers, every prediction against every target. Use pred.squeeze(1) or y.unsqueeze(1).
- Write one line that turns a NumPy batch of images
imgsof shape anddtype=uint8into a contiguousfloat32tensor of shape with values in .
Answer
x = torch.from_numpy(imgs).permute(0, 3, 1, 2).float().div(255).contiguous().float() already copies into new row-major storage, so .contiguous() is a no-op here, but it documents the intent.
Test yourself
What does torch.tensor(np.array([1.0, 2.0])).dtype print?
torch.float32torch.float64torch.float16torch.int64
Why does x.permute(0, 2, 1).view(2, 12) fail for a contiguous x of shape ?
permutecopies the data- The permuted tensor's strides cannot be described as a view without copying
viewonly works on 2-D tensors- The number of elements changes
After t = torch.from_numpy(a), you run a[0] = 5. What is t[0]?
- The old value:
from_numpycopies - 5: the tensor and the array share memory
- An error is raised
- It depends on the dtype
Which result is a copy rather than a view of x?
x[1:3]x.t()x[[0, 2]]x.expand(4, -1)forxof shape