PyTorch Tensors, Autograd & DataLoaders
Build PyTorch data pipelines with tensors, autograd, Datasets, and DataLoaders.
In plain words
A tensor is a box of numbers, autograd remembers what you did with the numbers so it can work out how to improve them, and a DataLoader serves the numbers to the model in neat batches.
Think of it like…
A kitchen line. Tensors are the ingredient trays with a fixed layout, autograd is the recipe card that records every step so the chef can trace a bad taste back to the responsible step, and the DataLoader is the prep team that must hand out trays fast enough that the chef is never waiting.
Where you’ve seen it
An image classifier receives batches of shape (N, C, H, W) = (32, 3, 224, 224): 32 × 3 × 50,176 = 4,816,896 values, which in float32 (4 bytes each) is 19,267,584 bytes, about 18.4 MiB per batch before any activations. A scalar example shows autograd: with x = torch.tensor(3.0, requires_grad=True) and y = x**2 + 2*x, calling y.backward() sets x.grad to 2x + 2 = 8; calling backward() again without clearing gives 16, which is why training loops call optimizer.zero_grad() each step. For the dataset of 50,000 images and batch size 128 the loader yields ceil(50,000 / 128) = 391 batches per epoch (390 with drop_last=True, since 390 × 128 = 49,920 leaves 80 samples). Profiling showed a step took 40 ms on the GPU but 120 ms to load and augment a batch in the main process, so throughput was 128 / 0.12 = 1,067 images/s. Setting num_workers=4 makes loading effectively 120 / 4 = 30 ms per batch, below the 40 ms compute time, so the GPU becomes the bottleneck and throughput rises to 128 / 0.04 = 3,200 images/s. They also set pin_memory=True and persistent_workers=True, and run validation under torch.no_grad() so no graph is built.
Words you’ll hear
- Tensor
- An n-dimensional array with a dtype, shape and device.
- requires_grad
- A flag telling autograd to track operations and compute gradients for a tensor.
- Dataset
- An object that returns one example by index and reports its length.
- DataLoader
- An iterator that batches, shuffles and loads examples, optionally in worker processes.
Visual diagram
Theory & deep dive
Tensors and autograd
A tensor's shape tells you how to interpret it: for images PyTorch expects (N, C, H, W), for sequences often (N, T, D) or (T, N, D). The dtype matters for memory and numerics (float32 by default, float16 or bfloat16 for mixed precision, int64 for class labels used by cross-entropy) and mixing dtypes raises errors. The device must be shared by every tensor in an operation. torch.from_numpy shares memory with the NumPy array, so in-place changes show up on both sides; use .clone() when you need a copy. Broadcasting rules apply as in NumPy, and silent broadcasting is a classic source of wrong results (a (32,) tensor minus a (32, 1) tensor yields (32, 32)).
Autograd builds a graph while you compute. For y = x² + 2x at x = 3, the forward value is 15 and y.backward() stores dy/dx = 2x + 2 = 8 in x.grad. Gradients accumulate into .grad, so a second call without clearing gives 16; use optimizer.zero_grad() (or set_to_none=True) before each backward pass. Use torch.no_grad() for inference and validation to save memory, .detach() to cut a tensor from the graph (for example when logging a loss with .item()) and avoid in-place operations on tensors the backward pass still needs.
Shape (32, 3, 224, 224) → 32 × 3 × 224 × 224 = 4,816,896 elements × 4 bytes = 19,267,584 bytes ≈ 18.4 MiB. The same batch in float16 takes about 9.2 MiB; a batch of 256 takes about 147 MiB in float32 before the first layer.
Datasets, DataLoaders and throughput
A custom Dataset should do the cheap, per-example work in __getitem__ (load, decode, transform) and keep expensive state, such as a file index, in __init__. The DataLoader then wraps it: batch_size, shuffle=True for training only, num_workers for parallel loading, pin_memory=True for faster GPU copies, drop_last to avoid a tiny final batch (important for BatchNorm) and collate_fn to batch variable-length data by padding. For 50,000 samples and batch size 128 the epoch has ceil(50,000 / 128) = 391 steps, or 390 with drop_last=True.
Throughput follows the slower of loading and compute. If each batch takes 120 ms to load in one process and 40 ms on the GPU, the GPU idles two thirds of the time and you get 1,067 images/s. With four workers the loading cost per batch becomes about 30 ms, so the GPU sets the pace at 3,200 images/s. Tune num_workers empirically (more is not always better because of memory and CPU contention), cache decoded data when it fits, use fast image decoders, and set a seed and a worker-seeding function when augmentation randomness must be reproducible. Fit preprocessing statistics (such as means and standard deviations) on the training split and reuse them for validation and inference.
Loading 120 ms/batch, compute 40 ms/batch. 1 worker: step time 120 ms → 1,067 img/s. 4 workers: loading 30 ms, step time 40 ms → 3,200 img/s, a 3× speed-up from one setting.
How it works, step by step
Step 1 of 41. Wrap the data in a Dataset
Implement __len__ and __getitem__ so each example comes back as tensors with the right dtype and shape.
- Keep
- transforms per example
When to use it & trade-offs
What it is
PyTorch is built on three ideas. Tensors are n-dimensional arrays with a dtype, a shape and a device (CPU or GPU). Autograd records operations on tensors created with requires_grad=True and computes gradients when you call backward(), storing them in each tensor's .grad. Datasets and DataLoaders turn raw data into batches: a Dataset implements __len__ and __getitem__ for one example, and a DataLoader handles batching, shuffling, parallel loading and (optionally) pinned memory for fast host-to-GPU transfer. Together they form the input pipeline that feeds every training loop.
Why it matters: Most deep-learning bugs are tensor bugs: a wrong shape, a float64 where float32 was expected, a tensor on the CPU while the model sits on the GPU, gradients that accumulate or silently stop because of a detach. Input pipelines are a second hidden cost: a model that could process 3,200 images per second may be fed only 1,067 because loading is single-threaded. Knowing how tensors, autograd and loaders fit together lets you size memory, debug shapes quickly and keep the GPU busy.
When to reach for it
- A Dataset per source with a thin __getitem__
- Multiple workers when loading is slower than compute
- no_grad for validation and inference
When to avoid or be careful
- Shuffling validation or test loaders
- Mixing CPU and GPU tensors in one operation
- Keeping loss tensors (with graphs) in a Python list instead of using item()
Loading strategies
Strengths: Simple stack traces.
Watch out: Loading blocks the GPU.
Strengths: Overlaps loading with compute.
Watch out: Uses more CPU and RAM; needs seeding care.
Strengths: Fastest access.
Watch out: Less flexible augmentation.
Interview signals & numbers to know
When this topic comes up
- “My GPU utilisation is low”
- Why gradients accumulate
- Shape, dtype and device errors
- What no_grad and detach do
- How to batch variable-length sequences
Benchmarks & rules of thumb
- (N, C, H, W)
- PyTorch image batch layout
- 391 batches
- 50,000 samples at batch size 128 (390 with drop_last)
- 1,067 → 3,200 img/s
- effect of four workers when loading is the bottleneck
Common mistakes & follow-ups
Common interview mistakes
- Forgetting zero_grad so gradients pile up across steps.
- Appending loss tensors to a list and keeping every graph alive.
- Computing normalisation statistics on validation data.
Likely interviewer follow-ups
- How would you debug low GPU utilisation?
- What does detach do and when do you need it?
- How do you batch sequences of different lengths?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply PyTorch Tensors, Autograd & DataLoaders with data science interview Q&A and hands-on practice.