Skip to content
mentoor

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?

Choose one answer

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

  1. Create tensors with intent. torch.zeros(3, 4), torch.tensor([[1, 2], [3, 4]]) and torch.randn(32, 10) each give a known shape. Integer literals give int64; float literals give float32.
  2. Reshape without changing data. x.view(2, -1) or x.reshape(2, -1) keeps the element count; -1 means "work it out". x.unsqueeze(0) adds a size-1 axis and x.squeeze() removes size-1 axes.
  3. 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].
  4. Track the dtype. float32 is the default for training. bfloat16 uses half the memory with a smaller mantissa, so it is common for large models but less precise. Losses and class labels have different needs: CrossEntropyLoss wants int64 labels.
  5. 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", then x.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 .shape after any subtraction or multiplication of tensors with different ranks.
  • Device mismatch. The model is on cuda and the batch is on cpu, which raises a runtime error about tensors on different devices.
  • Wrong dtype. Feeding float32 labels to CrossEntropyLoss, or doing integer division by accident, gives errors or wrong results.
  • View on non-contiguous data. .view fails after a .transpose; use .reshape or .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?

Choose one answer

Check yourself · 3 of 3

You call view on a tensor right after transpose and get an error. What is the simplest fix?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic