Skip to content
mentoor

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?

Choose one answer

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

  1. Define layers in __init__, use them in forward. Layers assigned as attributes of an nn.Module are registered, so model.parameters() finds them and .to(device) moves them. A layer stored in a plain Python list is not registered.
  2. Return raw scores. For classification, end with nn.Linear and let nn.CrossEntropyLoss apply the softmax internally. Adding your own softmax first double-applies it.
  3. Write a Dataset with two methods. __len__ returns the size and __getitem__(i) returns one (features, label) pair.
  4. Wrap it in a DataLoader. DataLoader(ds, batch_size=32, shuffle=True) for training, and shuffle=False for validation.
  5. 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?

Choose one answer

Check yourself · 3 of 3

Why call model.eval() before measuring validation accuracy?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic