Unit 6 of 8 · about 4 hours · implement
Datasets, data loaders and samplers
The loader decides order, batching, dtype and device of every tensor the loop ever sees. Bugs here look like model bugs downstream.
You'll be able to
- Implement a
Datasetwith init, len and getitem plus a collate and transform pipeline, and read batch shapes off the loader. - Control sampler, shuffle, worker count and seeding, and move batches to device with explicit transfer.
- State what a loader does not guarantee: ragged batching, worker-shared state and exact resume need extra code.
Covers
Read
In this order, only the parts listed
0 of 3 done
- Datasets and DataLoaders: FashionMNIST, custom Dataset, batchingPyTorch - Learn the Basics
Loading a
Dataset(root,train,download,transform); Iterating and Visualizing; Creating a CustomDataset(__init__,__len__,__getitem__withdecode_image); Preparing your data with DataLoaders (batch_size,shuffle); Iterate through theDataLoader(batch shapes[64, 1, 28, 28], Samplers link) - Transforms: v2 pipeline and Lambda label encodingPyTorch - Learn the Basics
ToImage()andToDtype()withscale=True;LambdaTransforms withone_hotlabels - Reproducibility: DataLoader worker seedingPyTorch - Autograd mechanics, serialization and reproducibility
DataLoadersection (per-worker reseeding,worker_init_fnwithtorch.initial_seed, generator seeding)Read only the DataLoader section here; the nondeterminism catalog belongs to the checkpoint unit.
Focus on
Datasetanswers one sample;DataLoaderanswers one batch. Custom datasets implement exactlyinit,lenandgetitem.- Default collate stacks equal-shape samples. Ragged samples need a custom
collate_fn; no loader pads for you. - shuffle reorders per epoch through the sampler. Workers are subprocesses: each gets a derived seed, and main-process state is not shared with them.
- Device transfer is the loop's job. Batches arrive on CPU;
.to(device)returns the moved copy.
Common mistakes · 3
- Mutating the dataset object in the main process after iteration starts and expecting workers to see it. Workers hold their own copies; non-persistent workers pick up the change only when the next epoch recreates them.
- Creating an RNG object such as
np.random.default_rng(0)in theDataset__init__. Every worker gets an identical copy, so all workers draw the same augmentation stream. The global random, torch and NumPy generators are already reseeded per worker; a private generator must be reseeded inworker_init_fnfromtorch.initial_seed(). - Leaving device transfer implicit. The tutorial batch is CPU
[64, 1, 28, 28]; the model page moves inputs explicitly, and.to()must be assigned.
Try it yourself
Closed-book, before checking anything
CSVDataset over (path, label) rows with a transform arg, wrap it in a DataLoader with batch 8, shuffle and 2 workers, and print one batch's shapes. Then add a worker_init_fn that prints each worker seed and show the seeds differ.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.What three methods must a custom
Datasetimplement, and what does each promise?Answerinit(runs once, stores paths, labels, transforms),len(sample count),getitem(loads and returns sampleidxas a tensor tuple).2.A
DataLoaderwith two workers is created aftertorch.manual_seed(0). Do the workers draw identical augmentations, and does the next run repeat this one?AnswerThe workers differ: each seeds torch and random with
base_seed + worker_idand NumPy with a state derived from both. The run repeats:base_seedcomes from the main process RNG, or from the generator you pass, which the seed fixes.3.A batch of variable-length sequences hits the default collate. What happens?Answer
It fails. Default collate stacks equal shapes; ragged input needs a custom
collate_fnwith explicit padding.4.The loader yields CPU batches and the model sits on CUDA. What is missing?Answer
An explicit transfer:
inputs = inputs.to(device), using the return value, before the forward call.
Practice
- Learn PyTorch 03: MNIST loading, visualization and DataLoaders (tasks 5 to 13)
Exercises, tasks 5 to 13: load torchvision MNIST train and test, visualize samples,
DataLoaderwithbatch_size=32,TinyVGGadaptation, CPU versus GPU timing, predictions, confusion matrix,Conv2dkernel-size probe, FashionMNIST error plotsSkip tasks 1 to 4 (industry prose and overfitting definitions). Tasks 5 to 7 are the loader core; tasks 8 to 13 rehearse the loop of the next unit and can wait for it.
You're done when
Your CSVDataset loader prints correct batch shapes with 2 workers, worker seeds differ on purpose, and a ragged input fails loudly until your collate_fn handles it.
Only when you can do this without notes.
Leads to
Notes
Resources · 2 for this unit, 5 more in the section
- PyTorch - Learn the BasicsPyTorch · primary
Complete Tensors, Datasets and DataLoaders, Transforms, Build Model, Autograd, Optimization, and Save and Load Model. Rebuild each essential example in a small src package instead of retaining a tutorial notebook.
- PyTorch - Autograd mechanics, serialization and reproducibilityPyTorch · required
Read Autograd mechanics, Serialization semantics and Reproducibility. Test leaf behavior, saved tensors, grad modes, state dictionaries and the exact tolerance promised by one interrupted and resumed run.
Also in this section
- Learn PyTorch - selected framework exercisesDaniel Bourke · required
Complete exercise 00, tasks 1-5 in 01, tasks 1-7 in 02, tasks 5-13 in 03, tasks 1-3 in 05, and exercises 1-2 in 07. Recreate solutions independently and verify behavior against current official docs.
- Deep Learning with PyTorch, 2nd edition - framework foundationsHoward Huang, Luca Antiga, Eli Stevens and Thomas Viehmann (Manning) · support
Read Sections 3.8-3.9 and 5.5 when tensor storage, strides or autograd need a second explanation, with the Chapter 3 and 5 companion notebooks for runnable cells. Inspect the Chapter 4 and 7 code only for a diagnosed data-representation or loading gap.
- NeetCode ML - PyTorch closing drillsNeetCode · optional
After the module gate, solve Pytorch Basics, Layer Normalization, Batch Normalization and RMS Normalization cold. Explain shapes, state and train-evaluation behavior aloud. These do not replace the package and resume test.
- PyTorch Automatic Mixed Precision recipe - Saving/ResumingPyTorch · reference
Read the Saving/Resuming section: save
scaler.state_dict()with the model and optimizer state, at the start of an iteration or afterscaler.update(), and how to resume with or without AMP. - Hands-On Machine Learning with Scikit-Learn and PyTorchAurelien Geron (O'Reilly, 2025) · support
Read Chapter 10, Implementing Mini-Batch Gradient Descent Using DataLoaders and Model Evaluation, for the train and evaluate loops and how batch metrics must be aggregated.