Build the Network: Layers, ReLU and nn.Module

A model made of one set of weights and biases turns each input straight into one score per class. A neural network puts a layer of its own invented values in between, and a small function between the layers lets that extra step do real work. PyTorch packages each set of weights as a ready-made layer, and lets you describe the whole network as one class that finds all of its own parameters, so the training loop stays exactly as it was.

The linear layer: weighted sums as a building block

Recall how a score is made: every input value is multiplied by its own weight, the products are added up, and a bias is added. Each output gets its own set of weights and its own bias. Writing this by hand means creating the weight and bias tensors yourself, filling them with small random numbers and marking them as needing gradients.

nn.Linear does all of that in one object. You tell it two sizes: how many values each input has (in_features) and how many outputs you want (out_features). It creates its weights and its biases itself, with small random starting values, and keeps them inside. Calling the layer on a tensor computes every weighted sum at once.

Here is the smallest useful case: an input of 3 values and 2 outputs. Each output has 3 weights and 1 bias.

One input through a layer with 3 inputs and 2 outputs
OutputIts weightsIts biasWeighted sum for the input (1, 2, 3)Result
10.5, -1, 0.210.5 x 1 + (-1) x 2 + 0.2 x 3 + 10.1
20.1, 0.3, -0.400.1 x 1 + 0.3 x 2 + (-0.4) x 3 + 0-0.5

The layer stores those weights as a table with one row per output and one column per input, so its shape is (outputs, inputs): here 2 by 3. That is the other way round from a weight matrix written by hand for x @ weights, which has one row per input. The layer takes care of the order when it multiplies, so the order only matters when you look at the weights yourself.

import torch
from torch import nn

layer = nn.Linear(3, 2)          # 3 values in, 2 scores out
print(layer.weight.shape)        # torch.Size([2, 3])
print(layer.bias.shape)          # torch.Size([2])

batch = torch.rand(5, 3)         # 5 examples of 3 values each
print(layer(batch).shape)        # torch.Size([5, 2])

The last line shows what makes the layer convenient on batches: it works on the last dimension only, so 5 examples of 3 values come out as 5 examples of 2 values. A layer for images of 28 by 28 pixels laid out as 784 values, with 10 classes, is nn.Linear(784, 10): a weight of shape (10, 784) and a bias of 10 values, 7,850 numbers in all, which is exactly the model you would otherwise build by hand.

True or false?

The weight of nn.Linear(784, 10) has the shape (784, 10).

False. A linear layer stores one row of weights per output, so the shape is (out_features, in_features): (10, 784).

A new nn.Linear layer already holds random starting weights and biases, before any training.

True. The layer creates and fills its own parameters with small random values when it is made, so you never write them by hand.

A hidden layer: features the network invents

A single layer has to read the answer straight off the raw input. For an image, that means each class score is one weighted sum of pixel brightnesses, and a pixel can only push a score up or down by the same amount every time, whatever the rest of the image looks like.

A network adds a layer in between. The first layer turns the input into a set of new values, and the second layer computes the class scores from those values instead of from the raw input. The values in the middle are not the answer and nobody tells the network what they should be. Training adjusts the first layer so that its values become useful features for the second: for a digit, perhaps something like "a stroke across the top" or "a closed loop at the bottom", though the network finds its own and they rarely have such tidy names. Because nobody sees or sets these values, the layer that makes them is called a hidden layer.

  • Input values
  • Hidden layer
  • Class scores
  • x1
  • x2
  • x3
  • h1
  • h2
  • h3
  • score A
  • score B
  • Linear(3, 3)
  • Linear(3, 2)

Every line in the picture is one weight: each hidden value is a weighted sum of all the inputs, and each score is a weighted sum of all the hidden values. The two layers have to fit together. The first layer's number of outputs is the second layer's number of inputs, so a network from 784 values through 128 hidden values to 10 scores is nn.Linear(784, 128) followed by nn.Linear(128, 10). The hidden size, 128 here, is a choice you make: more hidden values can capture more features but mean more weights to train. No size is right for every task.

Why an activation function goes between the layers

Stacking two linear layers directly, one after the other, gains nothing. Take the smallest possible case: one input \(x\), a first layer that computes \(h = 2x + 1\), and a second that computes \(y = 3h - 4\). Put the first into the second and \(y = 3(2x + 1) - 4 = 6x - 1\). That is again a single weighted sum with a bias, a weight of 6 and a bias of -1. One layer could have learned it directly.

The same happens with any number of inputs and outputs: a weighted sum of weighted sums can always be rewritten as one weighted sum. So ten linear layers stacked without anything between them can describe exactly the same inputs-to-scores rules as one layer. The hidden values would add weights to train, but no new ability.

The fix is to bend each hidden value with a simple function that is not a weighted sum, a non-linear function, before the next layer reads it. This is the activation function. One of the most widely used is ReLU (rectified linear unit), and it is about as simple as a function can be: a positive value passes through unchanged, and a negative value becomes zero.

$$\mathrm{ReLU}(x) = \max(0,\ x)$$

keep positives, turn negatives into zero

ReLU applied to each value of a tensor
  1. -2
  2. -0.5
  3. 0
  4. 0.1
  5. 3
  6. 0
  7. 0
  8. 0
  9. 0.1
  10. 3

Why does something this simple break the collapse? Because a hidden value now switches off whenever its weighted sum is negative, and which values are switched off depends on the input. Here is a two-unit example. The first hidden unit computes \(\mathrm{ReLU}(x)\), the second \(\mathrm{ReLU}(-x)\), and the output adds them.

Two hidden units with ReLU, added together
Input xReLU(x)ReLU(-x)Output
-2022
-1011
0000
1101
2202
ReLU

output against input

  • ReLU(x)
Two ReLU units added

output against input

  • ReLU(x) + ReLU(-x)

The output falls and then rises again, in a V shape. A single weighted sum \(y = wx + b\) can only draw a straight line, so no choice of one weight and one bias gives this. With many hidden units, each switching on at a different point, a network can build up bends wherever it needs them, and that is what lets a hidden layer represent rules a single layer cannot.

ReLU has no weights or bias of its own: it is a fixed rule applied to each value separately, and its output has the same shape as its input. It also keeps training simple. When a value is switched on, ReLU passes it through unchanged, so nudging a weight in front of it moves the loss as it would without ReLU. When a value is switched off, it stays at zero whatever those weights do, so that example gives them no change. Other activation functions exist, and ReLU is a common first choice between linear layers. In PyTorch it is nn.ReLU(), a layer object, or torch.nn.functional.relu, the same operation as a plain function.

True or false?

Three nn.Linear layers called one after another with nothing between them can describe rules that one nn.Linear layer cannot.

False. A weighted sum of weighted sums is still one weighted sum, so the stack can be rewritten as a single linear layer. An activation between the layers is what adds new ability.

ReLU turns the values -1.5, 0 and 2 into 0, 0 and 2.

True. ReLU keeps a positive value as it is and turns a negative value into zero; zero stays zero.

nn.ReLU() adds its own weights to the network that training has to learn.

False. ReLU is a fixed rule with no parameters. Only the linear layers around it hold weights and biases.

A network as a module

A network with several layers needs somewhere to keep them, and a description of the order the data goes through them. PyTorch's answer is to write the network as a Python class built on nn.Module, the base class for every network and every layer. (nn.Module is a class, not to be confused with a Python module, the file of code you import.)

A class is a template for making objects: you describe once what each object holds and what it can do, then make as many objects from it as you like. A network class has two parts.

  • The constructor, __init__, runs once when the network is made. It first calls super().__init__(), which sets up the machinery nn.Module provides, and then creates each layer and stores it on the object as self.something. This call has to come before the first layer is stored.
  • The forward method describes the path of the data: it receives a batch x, passes it through the stored layers in order and returns the scores.
A network with one hidden layer
import torch
from torch import nn

class Net(nn.Module):
    def __init__(self):
        super().__init__()
        self.flatten = nn.Flatten()
        self.hidden = nn.Linear(784, 128)
        self.relu = nn.ReLU()
        self.output = nn.Linear(128, 10)

    def forward(self, x):
        x = self.flatten(x)                # (N, 1, 28, 28) -> (N, 784)
        x = self.relu(self.hidden(x))      # (N, 128) hidden features
        return self.output(x)              # (N, 10) scores

model = Net()
images = torch.rand(64, 1, 28, 28)         # a batch of 64 images
scores = model(images)
print(scores.shape)                        # torch.Size([64, 10])

nn.Flatten() lays each image out as one row of values and keeps the first dimension, the batch, as it is, so 64 images of 28 by 28 become 64 rows of 784. The layers are made once, with their random starting weights, when Net() runs. Every batch afterwards goes through those same layers, so their weights are what training improves.

The network is used by calling it like a function: model(images). Behind the scenes, calling the object runs forward together with some bookkeeping PyTorch needs, so you never call model.forward(images) yourself. The scores that come out are raw scores, one per class, not probabilities. That is exactly what a cross-entropy loss expects, so the network needs no softmax at its end for training.

You write no method for the backward pass either: the gradients are worked out from the record of the operations, as with any tensors.

print(model) lists the layers the network holds, which is a quick way to check that the sizes chain as you meant.

True or false?

model(x) and model.forward(x) are interchangeable ways to run a network.

False. Calling the object runs forward plus the background work nn.Module adds. Calling forward directly skips that work, so the documentation says to call the object.

The layers of a network are created once, in the constructor, and reused for every batch.

True. forward only uses the stored layers. If it created new layers, every batch would start again from fresh random weights and nothing would be learned.

Parameters: the module finds them all

Storing a layer on self in the constructor does more than keep it. nn.Module notices the assignment and records the layer as part of the network. From then on, model.parameters() gives you every weight and every bias of every layer, in a fixed order, and model.named_parameters() gives each one with a name made from the attribute it lives in.

for name, p in model.named_parameters():
    print(name, tuple(p.shape))

print(sum(p.numel() for p in model.parameters()))
hidden.weight (128, 784)
hidden.bias (128,)
output.weight (10, 128)
output.bias (10,)
101770

p.numel() counts the numbers in one tensor, and adding the counts gives the size of the whole network. You can check the total by hand: a linear layer with \(a\) inputs and \(b\) outputs holds \(a \times b\) weights and \(b\) biases.

Counting the parameters of the network
LayerWeightsBiasesTotal
Linear(784, 128)100,352128100,480
ReLU000
Linear(128, 10)1,280101,290
Network101,632138101,770

That is about thirteen times as many numbers as the 7,850 of a single nn.Linear(784, 10): the price of the hidden layer. ReLU and Flatten add nothing, because they have no parameters.

The same call hands the parameters to an optimizer, however many layers the network has:

optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
loss_fn = nn.CrossEntropyLoss()

for images, labels in loader:
    scores = model(images)
    loss = loss_fn(scores, labels)
    loss.backward()
    optimizer.step()
    optimizer.zero_grad()

Nothing in the loop knows how the model is built. It calls the model, measures the loss, computes the gradients, lets the optimizer step and clears the gradients. So a single linear layer, a network with one hidden layer or a much deeper one all train with the same lines; only the class changes. The learning rate of 0.1 is an example value, and a network with a hidden layer may need a different one, or more epochs, than a single layer did.

One limit is worth knowing. Only layers, and tensors created as nn.Parameter, are recorded this way. A plain tensor stored on self, such as self.w = torch.randn(784, 10), is not a parameter: parameters() does not list it, so the optimizer never updates it.

True or false?

model.parameters() includes the weights and biases of every layer stored on the network in its constructor.

True. nn.Module registers every layer assigned as an attribute, and parameters() goes through all of them, so one call covers the whole network.

A tensor made with torch.randn and stored on self is trained by the optimizer like the weights of a layer.

False. Only nn.Parameter objects and the parameters of stored layers are registered. A plain tensor is not in parameters(), so the optimizer never sees it.