Topic 1 of 5 · 4 min read
Tensors, dtypes and devices
Goal: Predict the shape and dtype after reshape, broadcast and matmul operations and place tensors on the right device.
A tensor is an n-dimensional array with a shape, a dtype and a device, and almost every PyTorch bug is a mismatch in one of those three.
Check yourself · 1 of 3
A tensor has shape [32, 1] and another has shape [32]. You subtract one from the other. What shape comes out?
Why it matters
Every input, weight and loss in PyTorch is a tensor. If you can read a line and say "this is [32, 10], float32, on the GPU", you can catch most errors before running anything. AI assistants write tensor code fluently but often get a shape or a device wrong.
How to do it
- Create tensors with intent.
torch.zeros(3, 4),torch.tensor([[1, 2], [3, 4]])andtorch.randn(32, 10)each give a known shape. Integer literals giveint64; float literals givefloat32. - Reshape without changing data.
x.view(2, -1)orx.reshape(2, -1)keeps the element count;-1means "work it out".x.unsqueeze(0)adds a size-1 axis andx.squeeze()removes size-1 axes. - Know the broadcasting rule. Shapes are compared from the last axis backwards. Two sizes match if they are equal or one of them is 1. A
[32, 10]tensor plus a[10]bias works. A[32]tensor plus a[32, 1]tensor silently becomes[32, 32]. - Track the dtype.
float32is the default for training.bfloat16uses half the memory with a smaller mantissa, so it is common for large models but less precise. Losses and class labels have different needs:CrossEntropyLosswantsint64labels. - Pick one device and move everything to it.
device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu", thenx.to(device). Model and data must sit on the same device.
Before and after
# Weak: shape bug that does not raise an error
preds = model(x) # shape [32, 1]
loss = ((preds - y) ** 2).mean() # y has shape [32]
preds - y broadcasts [32, 1] against [32] into [32, 32]. The loss is computed over 1,024 pairs and training quietly goes wrong.
# Fixed: make the shapes agree on purpose
loss = ((preds.squeeze(1) - y) ** 2).mean()
What goes wrong
- Silent broadcasting. No error, wrong numbers. Print
.shapeafter any subtraction or multiplication of tensors with different ranks. - Device mismatch. The model is on
cudaand the batch is oncpu, which raises a runtime error about tensors on different devices. - Wrong dtype. Feeding
float32labels toCrossEntropyLoss, or doing integer division by accident, gives errors or wrong results. - View on non-contiguous data.
.viewfails after a.transpose; use.reshapeor.contiguous().
Examples
Predicting a matmul shape
a = torch.randn(8, 3, 4)
b = torch.randn(4, 5)
c = a @ b
The last axis of a (4) matches the first axis of b (4), and the leading batch axis of a is kept. c has shape [8, 3, 5] and dtype float32.
Choosing a device once
device = "cuda" if torch.cuda.is_available() else "cpu"
model = Net().to(device)
x = x.to(device)
On a MacBook, torch.backends.mps.is_available() selects the Apple GPU instead. The point is to decide once and pass device around, not to scatter .cuda() calls through the code.
Key points
- Every tensor has a shape, a dtype and a device, and most PyTorch errors are a mismatch in one of the three.
- Broadcasting compares shapes from the last axis backwards, and a [32, 1] tensor against a [32] tensor expands to [32, 32] without any error.
- Use reshape with -1 to let PyTorch infer one dimension, and unsqueeze or squeeze to add or remove size-1 axes.
- float32 is the usual training default, while bfloat16 saves memory at lower precision.
- The model and every batch must be moved to the same device with .to(device) before the forward pass.
Common mistakes
- Trusting that code runs correctly because it ran without an error, when broadcasting can hide a shape bug.
- Calling .cuda() on the model but forgetting to move the batch.
- Using .view on a transposed tensor instead of .reshape.
- Passing float labels to a classification loss that expects int64 class indices.
Check yourself · 2 of 3
Your model is on the GPU and the batch is still on the CPU. What happens at the forward pass?
Check yourself · 3 of 3
You call view on a tensor right after transpose and get an error. What is the simplest fix?
Practice items, not counted towards your mastery.
Start here
- Learn the Basics (PyTorch tutorials) (opens in a new tab)DocsFree
Official end-to-end walk through tensors, datasets, models, autograd, optimization and saving.
- PyTorch tutorials: automatic differentiation with torch.autograd (opens in a new tab)DocsFree
Short, runnable explanation of requires_grad, backward and no_grad.
- PyTorch notes: autograd mechanics (opens in a new tab)DocsFree
How the graph is built and freed and how gradients accumulate.
More for this topic
- PyTorch notes: broadcasting semantics (opens in a new tab)DocsFree
The exact rules for which shapes broadcast and what shape results.
- PyTorch notes: CUDA semantics (opens in a new tab)DocsFree
How devices, .to() and tensor placement work on CUDA GPUs.