Topic 3 of 5 · 4 min read
Models with nn.Module and DataLoader
Goal: Write an nn.Module and DataLoader for a small dataset and switch correctly between train and eval mode.
An nn.Module owns the layers and defines the forward pass, a Dataset serves one example at a time, and a DataLoader turns those into shuffled batches.
Check yourself · 1 of 3
Which two methods must a custom torch Dataset implement?
Why it matters
These three classes are the skeleton of nearly every PyTorch project, from a toy classifier to a fine-tuning script. Most "my model is not learning" reports come from how they are wired: a layer that was never registered, a loader that never shuffles, or a model left in the wrong mode.
How to do it
- Define layers in
__init__, use them inforward. Layers assigned as attributes of annn.Moduleare registered, somodel.parameters()finds them and.to(device)moves them. A layer stored in a plain Python list is not registered. - Return raw scores. For classification, end with
nn.Linearand letnn.CrossEntropyLossapply the softmax internally. Adding your own softmax first double-applies it. - Write a Dataset with two methods.
__len__returns the size and__getitem__(i)returns one(features, label)pair. - Wrap it in a DataLoader.
DataLoader(ds, batch_size=32, shuffle=True)for training, andshuffle=Falsefor validation. - Switch modes.
model.train()enables dropout and batch-norm updates.model.eval()disables them. Call the right one before each phase.
Before and after
class Net(nn.Module):
def __init__(self):
super().__init__()
self.layers = [nn.Linear(4, 16), nn.ReLU(), nn.Linear(16, 3)]
def forward(self, x):
for l in self.layers:
x = l(x)
return x
This runs, but list(Net().parameters()) is empty. The optimizer has nothing to update and the loss never moves.
class Net(nn.Module):
def __init__(self):
super().__init__()
self.layers = nn.Sequential(nn.Linear(4, 16), nn.ReLU(), nn.Linear(16, 3))
def forward(self, x):
return self.layers(x)
nn.Sequential (or nn.ModuleList) registers its children.
What goes wrong
- Unregistered layers in plain lists or dicts.
- Forgotten eval(). Dropout keeps randomly zeroing units during validation, so metrics are noisy and low.
- Unshuffled training data. If the file is sorted by class, every batch holds one class.
- Softmax before CrossEntropyLoss. Training still runs but learns more slowly.
Examples
A minimal Dataset and DataLoader
class Pts(Dataset):
def __init__(self, X, y):
self.X, self.y = X, y
def __len__(self):
return len(self.X)
def __getitem__(self, i):
return self.X[i], self.y[i]
loader = DataLoader(Pts(X, y), batch_size=32, shuffle=True)
With 1,000 examples and batch size 32, the loader yields 32 batches, and the last one holds 8 examples.
Finding the missing parameters
print(sum(p.numel() for p in model.parameters()))
If this prints 0 for a model that should have layers, they were not registered. Run this check once on any model an assistant wrote for you.
Key points
- Layers assigned as attributes of an nn.Module are registered, while layers kept in a plain Python list are not.
- A Dataset needs len and getitem, and a DataLoader groups examples into batches and shuffles the training set.
- Classification models should output raw scores, because CrossEntropyLoss applies softmax internally.
- model.train() and model.eval() change the behaviour of dropout and batch normalisation, so call them before each phase.
- Shuffle training data but not validation data.
Common mistakes
- Storing layers in a Python list or dict instead of nn.ModuleList or nn.Sequential.
- Leaving the model in train mode while measuring validation accuracy.
- Applying softmax in forward and then also using CrossEntropyLoss.
- Setting shuffle=True on the validation loader and expecting predictions to line up with the original row order.
Check yourself · 2 of 3
You put layers in a plain Python list inside an nn.Module. What is the consequence?
Check yourself · 3 of 3
Why call model.eval() before measuring validation accuracy?
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 tutorials: build the neural network (opens in a new tab)DocsFree
Shows nn.Module, nn.Sequential and how parameters are registered.
- PyTorch tutorials: datasets and dataloaders (opens in a new tab)DocsFree
Covers custom Datasets, batching and shuffling with DataLoader.