Linear layers and MLPs

Why stacking linear layers buys nothing, and how one ReLU between them changes everything.

What you'll learn
  • Write the five-step PyTorch training loop from memory
  • Show that any stack of linear layers collapses to a single one
  • Explain what a nonlinearity adds, geometrically

nn.Linear(in_dim, out_dim) computes \(\mathbf{y} = W\mathbf{x} + \mathbf{b}\) with a learned \(W\) of shape (out_dim, in_dim). linear_model.py fits one to map a random 3-vector to the targets \((1, 2)\), using the loop every PyTorch script in this course repeats:

for epoch in range(epochs):
    optimizer.zero_grad()                              # 1. clear old gradients
    outputs = linear_model(inps.unsqueeze(0))          # 2. forward pass
    loss = F.l1_loss(outputs.squeeze(), tgts)          # 3. loss
    loss.backward()                                    # 4. gradients
    optimizer.step()                                   # 5. update

Forget step 1 and gradients accumulate across iterations. The unsqueeze(0) adds a batch dimension of one; nn.Linear would accept the bare vector, but the habit keeps shapes honest for layers that care. This loop reappears, line for line, in C++ in lesson 8.

Ten layers, one matrix

simple_mlp.py builds ten linear layers and runs this forward pass:

def forward(self, tensor):
    for i, l in enumerate(self.layers):
        tensor = self.layers[i // 2](tensor) + l(tensor)
    return tensor

Every operation here is affine: each layer is \(W_i\mathbf{x} + \mathbf{b}_i\), and the sum of two affine maps of the same input is affine. So the whole ten-layer forward pass is a single map \(\mathbf{x} \mapsto A\mathbf{x} + \mathbf{c}\) — one 3×3 matrix and one bias. Checked numerically: replacing the model by the \(A\) and \(\mathbf{c}\) read off from its outputs reproduces it to \(4 \times 10^{-16}\). However many layers are stacked, without a nonlinearity between them the network can only ever learn what a single linear layer can.

The geometric picture makes the reason plain. A linear map sends a grid to a grid: straight lines stay straight and parallel lines stay parallel. Compose as many as you like and that stays true.

A grid pushed through two 2×2 layers. With nothing in between, the result is one linear map — still a grid. With a ReLU in between, every point with a negative coordinate is flattened onto an axis: the plane is folded, and no single matrix can do that.

What the ReLU buys

\(\mathrm{ReLU}(z) = \max(0, z)\) is piecewise linear, yet it breaks the collapse. It folds space along \(z_i = 0\), and the next layer can stretch and rotate the folded sheet before the next fold. Enough folds can approximate any continuous function — this is what makes depth worth having.

fancy_mlp.py builds a proper MLP, with a ReLU after every layer except the last:

tensor = F.relu(layer(tensor)) if i < self.num_layers - 1 else layer(tensor)

The last layer stays linear so the output can take any real value, including the negative ones a ReLU would clip.

One detail in that script is worth catching: it creates an SGD optimizer and then immediately replaces it.

optimizer = optim.SGD(mlp_model.parameters(), lr=1e-5, momentum=0.9)
optimizer = optim.Adam(mlp_model.parameters(), lr=1e-5, )

Only Adam ever runs. Comparing optimizers needs one line commented out, as simple_mlp.py does.

Try it yourself. In simple_mlp.py, after training, recover the collapsed map: c = model(torch.zeros(3)) and A = torch.stack([model(e) - c for e in torch.eye(3)], 1). Check that A @ x + c matches model(x) for a random x. Then insert torch.relu into the forward pass and show that the same test now fails.

View source on GitHub →