TExcelTAD
Home › Deep Learning: Neural Networks, Architectures & PyTorch › Tensors: Shapes, dtypes and Views

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 (5,5)(5, 5) 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 (N,C,H,W)(N, C, H, W) 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 (d0,d1,…,dk−1)(d_0, d_1, \dots, d_{k-1}) lives in one flat block of memory, its storage. The strides (s0,…,sk−1)(s_0, \dots, s_{k-1}) say how many elements to skip in that block to move one step along each axis. The element at index (i0,…,ik−1)(i_0, \dots, i_{k-1}) sits at

offset(i0,…,ik−1)=o+∑j=0k−1ij sj\text{offset}(i_0, \dots, i_{k-1}) = o + \sum_{j=0}^{k-1} i_j \, s_j

where oo 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, sj=∏m>jdms_j = \prod_{m > j} d_m. For shape (2,3,4)(2, 3, 4) that gives strides (12,4,1)(12, 4, 1).

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.

python · try it yourself
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 (48,16,4)(48, 16, 4) are the element strides (12,4,1)(12, 4, 1) times 4 bytes per float32, and 1⋅12+1⋅4+2⋅1=181 \cdot 12 + 1 \cdot 4 + 2 \cdot 1 = 18 is the flat position of x[1,1,2]. The transpose only swapped two strides. Broadcasting the mean of shape (4,)(4,) to (2,3,4)(2, 3, 4) also costs nothing: stride 0 means "stay on the same element while this index moves".

dtypes: PyTorch is float32, NumPy is float64

python · try it yourself
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 float32 unless they come from NumPy. torch.tensor(np_array) keeps NumPy's float64, and a float64 input to a float32 model raises mat1 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.CrossEntropyLoss wants integer class indices, not floats and not one-hot vectors. In the browser, NumPy's default integer is int32 (Pyodide is 32-bit), so pass dtype=torch.int64 explicitly when labels come from NumPy.
  • torch.from_numpy shares memory; torch.tensor copies. Writing either side of a from_numpy pair changes the other, and so does tensor.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

python · try it yourself
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 (2,3,4)(2, 3, 4) tensor has strides (12,4,1)(12, 4, 1). After permute(0, 2, 1) the strides are (12,1,4)(12, 1, 4): 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 (12,3,1)(12, 3, 1) a fresh (2,4,3)(2, 4, 3) tensor would have.

Where this matters in practice: an image batch from NumPy or OpenCV is (N,H,W,C)(N, H, W, C), convolution layers want (N,C,H,W)(N, C, H, W), 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 (5,3)(5, 3) with (3,)(3,) gives (5,3)(5, 3), and (3,1)(3, 1) with (4,)(4,) gives (3,4)(3, 4). The rule is exactly NumPy's.

python · try it yourself
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 (5,3)+(5,)(5, 3) + (5,): 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 (5,1)(5, 1), which is what keepdim=True is for. The dangerous case is the one that does not raise: a prediction of shape (N,1)(N, 1) minus a target of shape (N,)(N,) broadcasts to (N,N)(N, N), 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: 2,3,7,10,142, 3, 7, 10, 14. 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

  • float64 sneaking in from NumPy or pandas. It doubles memory, slows CPU math, and fails against float32 weights. Convert at the data boundary.
  • Labels as floats or with shape (N,1)(N, 1). Cross-entropy wants int64 of shape (N,)(N,); 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.
  • view after permute/transpose. Use reshape, or contiguous() first.
  • Editing a NumPy array behind torch.from_numpy. The tensor changes too; take a copy with torch.tensor(arr) if the array is reused.
  • Accumulating tensors instead of numbers. running += loss.item(), not running += loss.

Practice

  1. A tensor x of shape (4,5,6)(4, 5, 6) is contiguous. What are its strides? What are the strides of x.permute(0, 2, 1), and is x.permute(0, 2, 1).view(4, 30) allowed? What about x.permute(2, 0, 1).view(6, 20)?
Answer

Strides (30,6,1)(30, 6, 1). permute(0, 2, 1) gives shape (4,6,5)(4, 6, 5) with strides (30,1,6)(30, 1, 6). 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 1=5⋅61 = 5 \cdot 6, so view(4, 30) raises and reshape copies. permute(2, 0, 1) gives shape (6,4,5)(6, 4, 5) with strides (1,30,6)(1, 30, 6); merging the last two axes needs 30=5⋅630 = 5 \cdot 6, which holds, so view(6, 20) works even though the tensor is not contiguous.

  1. pred has shape (64,1)(64, 1) and y has shape (64,)(64,). What shape does pred - y have, and how many numbers does ((pred - y) ** 2).mean() average?
Answer

(64,64)(64, 64): aligned from the right, (64,1)(64, 1) and (1,64)(1, 64) broadcast to a full matrix. The mean is over 64⋅64=409664 \cdot 64 = 4096 numbers, every prediction against every target. Use pred.squeeze(1) or y.unsqueeze(1).

  1. Write one line that turns a NumPy batch of images imgs of shape (N,H,W,3)(N, H, W, 3) and dtype=uint8 into a contiguous float32 tensor of shape (N,3,H,W)(N, 3, H, W) with values in [0,1][0, 1].
Answer
python
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?

  1. torch.float32
  2. torch.float64
  3. torch.float16
  4. torch.int64

Why does x.permute(0, 2, 1).view(2, 12) fail for a contiguous x of shape (2,3,4)(2, 3, 4)?

  1. permute copies the data
  2. The permuted tensor's strides (12,1,4)(12, 1, 4) cannot be described as a (2,12)(2, 12) view without copying
  3. view only works on 2-D tensors
  4. The number of elements changes

After t = torch.from_numpy(a), you run a[0] = 5. What is t[0]?

  1. The old value: from_numpy copies
  2. 5: the tensor and the array share memory
  3. An error is raised
  4. It depends on the dtype

Which result is a copy rather than a view of x?

  1. x[1:3]
  2. x.t()
  3. x[[0, 2]]
  4. x.expand(4, -1) for x of shape (1,5)(1, 5)