Module contents
Lesson 3 of 22Core 90 min

Multilayer perceptrons and forward propagation

Stacking layers with intermediate nonlinearities gives a multilayer perceptron (MLP). We formalize forward propagation in batch notation, prove that depth collapses to an affine model without nonlinearities, and study how hidden layers transform the space to make the problem linearly separable in the last layer. We conclude with parameter-space symmetries (neuron permutations and ReLU rescaling), which recur in initialization, loss landscapes, and model merging.

After this lesson you can

  • Write forward propagation for an L-layer MLP in batched matrix form and count its parameters and FLOPs.
  • Prove that a composition of affine layers is affine and explain the role of nonlinearity.
  • Solve XOR with an MLP with two hidden neurons by choosing weights by hand.
  • Visualize hidden-layer representations and explain why the problem becomes linearly separable in the last layer.
  • Implement a generic MLP in NumPy with an arbitrary number of layers.
  • Prove that permuting hidden neurons or rescaling a ReLU neuron preserves the function and count equivalent configurations.

Before you start

Learning features

For XOR, a line in the two inputs is not enough. The previous lesson added the product x1x2x_1x_2 by hand. What if, instead of choosing features before training, we learn the weights that construct them? One layer transforms each point; the next learns a separation in the resulting coordinates. This is the multilayer perceptron, or MLP.

InteractiveXOR in two spaces
Input: two activation lines
Hidden layer: ReLU coordinates
  • XOR = 1
  • XOR = 0
  • Neuron 1 line
  • Neuron 2 line
  • Output boundary
Each label identifies an input: 10 is (1,0)(1,0). Each neuron has hi=max⁡(0,wi⋅x+bi)h_i=\max(0,\vb{w}_i\cdot\vb{x}+b_i); the lines mark zero preactivation. The output predicts 1 if v1h1+v2h2+c>0v_1h_1+v_2h_2+c>0. Coincident points share a label; if they belong to different classes, a ring in the second color appears. Correct predictions evaluate only the selected output.
45°
45°
1.0
-2.0
-0.5
Neuron 1 bias0.00
Neuron 2 bias−1.00
Correct with this output4 / 4
h(00)(0.00, 0.00)
h(10)(1.00, 0.00)
h(01)(1.00, 0.00)
h(11)(2.00, 1.00)
Change the two hidden neurons and observe where the same four points land. The linear output acts on the space on the right: a poor output does not by itself show that this space is inseparable.

The initial configuration is an exact solution with ReLU ϕ(t)=max⁡(0,t)\phi(t)=\max(0,t):

h1=ReLU⁡(x1+x2),h2=ReLU⁡(x1+x2−1),z=h1−2h2−0.5.h_1=\relu(x_1+x_2),\qquad h_2=\relu(x_1+x_2-1),\qquad z=h_1-2h_2-0.5.

For (0,0),(1,0),(0,1),(1,1)(0,0),(1,0),(0,1),(1,1), the representations are respectively (0,0),(1,0),(1,0),(2,1)(0,0),(1,0),(1,0),(2,1) and the logits are −0.5,0.5,0.5,−0.5-0.5,0.5,0.5,-0.5. A threshold at zero implements XOR. The two positive inputs coincide in hidden space and are separated from the negatives by the line h1−2h2−0.5=0h_1-2h_2-0.5=0. In the figure, change an activation line and follow the points: the representation and the output are different objects.

In this architecture two neurons are also necessary. With only one, the output would be aReLU⁡(w⊤x+b)+ca\relu(\vb{w}\T\vb{x}+b)+c. As a function of the single scalar t=w⊤x+bt=\vb{w}\T\vb{x}+b, it is monotonic or constant: it increases if a>0a>0 and decreases if a<0a<0. Its threshold splits the values of tt into a half-line, or assigns the same class to all. In the input plane, that decision is a half-plane or a constant classification, and the previous lesson’s XOR proof rules out both. The argument depends on ReLU and a thresholded affine output; it does not claim that two units are minimal for every imaginable activation function.

One layer at a time

A hidden layer lies between input and output. If there are LL layers with parameters, we set d0=dd_0=d and dL=kd_L=k. With the batch convention, H(0)=X∈RB×d0\mat{H}^{(0)}=\mat{X}\in\R^{B\times d_0} and for ℓ=1,…,L\ell=1,\ldots,L

Z(ℓ)=H(ℓ−1)W(ℓ)+1Bb(ℓ)⊤,H(ℓ)=ϕℓ(Z(ℓ)),\mat{Z}^{(\ell)}=\mat{H}^{(\ell-1)}\mat{W}^{(\ell)}+\vb{1}_B\vb{b}^{(\ell)\T},\qquad \mat{H}^{(\ell)}=\phi_\ell(\mat{Z}^{(\ell)}),

with W(ℓ)∈Rdℓ−1×dℓ\mat{W}^{(\ell)}\in\R^{d_{\ell-1}\times d_\ell} and b(ℓ)∈Rdℓ\vb{b}^{(\ell)}\in\R^{d_\ell}. This sequence is forward propagation. Width is the number of units in a layer; here depth means the number of layers with weights, including the output layer. Other sources count only hidden layers: state the convention before comparing.

For multiclass classification, the output is usually left as the identity and Z(L)\mat{Z}^{(L)} treated as logits; the loss then combines softmax and cross-entropy stably. Applying ReLU to those logits imposes a constraint the model did not require. Identity can also be used for regression, but the appropriate output depends on the task.

Each layer has dℓ−1dℓ+dℓd_{\ell-1}d_\ell+d_\ell parameters. If a multiplication and an addition count as two FLOPs, the batch product costs approximately 2Bdℓ−1dℓ2Bd_{\ell-1}d_\ell FLOPs; adding biases and applying the activation cost O(Bdℓ)O(Bd_\ell) additional operations. This convention ignores implementation details and does not measure actual time. Storing all forward activations for backpropagation requires, for those tensors alone, B∑ℓ=0LdℓB\sum_{\ell=0}^{L}d_\ell numbers; it excludes preactivations, gradients, optimizer states and temporary memory. At four bytes per number float32, multiply that count by four to get bytes. During inference, activations that are no longer needed can be released.

Depth without activation

InteractiveSwitching nonlinearity on and off
  • Zero logit: decision boundary
  • Test point

The network uses two inputs, two units per hidden layer and an output without activation. Weights and biases are fixed and defined in the code: every change recalculates the network. The red boundary joins points with zero logit; with ReLU it is calculated by sampling and can have bends. With one layer there is no hidden layer to apply ReLU to.

Without ReLU, the equivalent matrix is the product W₁W₂⋯Wₗ and has shape 2 × 1. The equivalent bias accumulates biases after propagating them through subsequent layers. The readouts show their components and the difference between logits calculated both ways; parameters are rounded to four decimals.

3
Hidden layers2
Point logit0.2000
Equivalent weight, input 10.8000
Equivalent weight, input 2−0.6000
Equivalent bias−0.3000
Difference between the two logits< 10⁻¹²
Add layers and toggle ReLU. Without activations, the composition computes the equivalent matrix and bias; an affine function can have a straight boundary, an empty boundary or the entire plane in degenerate cases.
Proof

By induction, take A0=Id0\mat{A}_0=\mat{I}_{d_0} and c0=0\vb{c}_0=\vb{0}. If H(ℓ−1)=XAℓ−1+1Bcℓ−1⊤\mat{H}^{(\ell-1)}=\mat{X}\mat{A}_{\ell-1}+\vb{1}_B\vb{c}_{\ell-1}\T, then

H(ℓ)=X(Aℓ−1W(ℓ))+1B(cℓ−1⊤W(ℓ)+b(ℓ)⊤).\mat{H}^{(\ell)}=\mat{X}(\mat{A}_{\ell-1}\mat{W}^{(\ell)})+ \vb{1}_B(\vb{c}_{\ell-1}\T\mat{W}^{(\ell)}+\vb{b}^{(\ell)\T}).

Thus Aℓ=Aℓ−1W(ℓ)\mat{A}_\ell=\mat{A}_{\ell-1}\mat{W}^{(\ell)} and cℓ⊤=cℓ−1⊤W(ℓ)+b(ℓ)⊤\vb{c}_\ell\T=\vb{c}_{\ell-1}\T\mat{W}^{(\ell)}+\vb{b}^{(\ell)\T}. Induction gives the result for LL.

∎

This linear collapse of depth means collapse to an affine map, not necessarily a linear one when biases are present. A bottleneck may restrict the rank of the equivalent matrix, so a given architecture cannot represent every affine input-to-output map. ReLU can break the collapse to a global affine map: it is piecewise linear, but different inputs can activate different patterns. Adding it does not guarantee a non-affine result either; for example, ReLU⁡(x)−ReLU⁡(−x)=x\relu(x)-\relu(-x)=x.

Following a real representation

InteractiveSpirals through the network
  • Spiral 0
  • Spiral 1

Weights obtained in the reproducible run of this lesson’s training cell. Each stage applies the actual transformation to the same spirals and grid; axis scales adjust to each view. Projections of 16 dimensions hide information. The line appears only when the last representation has two dimensions and represents the logit threshold.

Stage
RepresentationInput
Full dimensions2
Training examples120
Step through each affine transformation and ReLU in the network trained in the cell. Wide layers are projected onto their first two coordinates; the last representation has exactly two and the line is the output boundary.

The grid lines are input points passed through the same network, not an independent illustration. A projection of a 16-dimensional representation cannot determine whether the classes are separable in all 16 dimensions: it can hide information. Only in the final hidden layer of width two does the plane show the entire representation, allowing the output line to be interpreted directly. ReLU can collapse distinct regions onto the same coordinate, so “warping” does not imply an invertible transformation. Scales change between stages to show the geometry; comparing lengths across panels requires looking at the axes.

At each affine step the visible coordinates come from weighted sums of all input coordinates to that layer. When showing only the first two of 16, the image of a grid no longer necessarily preserves the geometry of all 16 dimensions. Then ReLU sets each negative component to zero separately; points with a negative first coordinate, for example, are projected onto the view’s vertical axis. That loss of information can help the task, but does not by itself ensure that classes separate. The observed separation concerns the training examples; new examples must be evaluated to judge generalization.

Parameter symmetries

InteractiveSame function, different weights

Reference network: with u=x1+x2u=x_1+x_2, it computes h1=ReLU⁡(u)h_1=\operatorname{ReLU}(u), h2=ReLU⁡(−u)h_2=\operatorname{ReLU}(-u) and f=h1−h2=uf=h_1-h_2=u. The other endpoint rescales the first neuron and, if you enable the switch, swaps both neurons together with their output weights.

Output of the interpolated network
  • f>0f>0
  • f<0f<0

The points are the four examples. Gray indicates zero output; the dashed line is the reference network boundary.

Loss during interpolation
  • Selected endpoint
  • With aligned neurons

MSE on (1,0)(1,0), (0,1)(0,1), (−1,0)(-1,0) and (0,−1)(0,-1), with target uu. The dashed curve undoes the permutation before interpolation; it retains the rescaling.

Endpoint equivalence follows because ReLU⁡(αu)=αReLU⁡(u)\operatorname{ReLU}(\alpha u)=\alpha\operatorname{ReLU}(u) if α>0\alpha>0. In the initial case, interpolation with permutation sets every weight to zero at t=0.5t=0.5 and loss is 1; when aligned, both networks coincide. Alignment does not guarantee removal of barriers between arbitrary networks.

1.00
0.50
Current loss1.000
Output at x1+x2=1x_1+x_2=10.000
Output at x1+x2=−1x_1+x_2=-10.000
Permute or rescale ReLU neurons and observe the output. Then interpolate the parameters of two equivalent representations: the intermediate network's loss is calculated at the indicated points, not inferred from the outputs at the endpoints.

Parameter-space symmetries produce identical functions with different descriptions. For a hidden layer H=ReLU⁡(XW+1b⊤)\mat{H}=\relu(\mat{X}\mat{W}+\vb{1}\vb{b}\T) and output HV+1c⊤\mat{H}\mat{V}+\vb{1}\vb{c}\T, let P\mat{P} be a permutation matrix. Replacing W\mat{W} by WP\mat{W}\mat{P}, b⊤\vb{b}\T by b⊤P\vb{b}\T\mat{P} and V\mat{V} by P⊤V\mat{P}\T\mat{V} does not change the output: ReLU acts componentwise and ReLU⁡(ZP)=ReLU⁡(Z)P\relu(\mat{Z}\mat{P})=\relu(\mat{Z})\mat{P}, while PP⊤=I\mat{P}\mat{P}\T=\mat{I}. Under our convention incoming columns and outgoing rows are permuted; if matrices are stored transposed, as in PyTorch, those descriptions are reversed.

For a ReLU neuron, multiplying its incoming weights and its bias by α>0\alpha>0 multiplies its activation by α\alpha. Dividing all its outgoing weights by α\alpha preserves the function, because ReLU⁡(αz)=αReLU⁡(z)\relu(\alpha z)=\alpha\relu(z). This does not generally hold for α<0\alpha<0 or an arbitrary activation. There are n!n! permutations of a layer of width nn, but they can give fewer than n!n! distinct parameter vectors if neurons are indistinguishable. With parameters fixed by no symmetries, the n!n! permutations do produce distinct vectors.

These equivalences explain why two solutions may be far apart in coordinates without representing different functions. They do not guarantee that linear interpolation of parameters keeps loss low: it can misalign features, as the interactive shows. Entezari and colleagues empirically study connectivity after permutation and propose a conjecture; Ainsworth and colleagues present alignment methods and limits of a strong version of that idea. This is no universal guarantee that averaging two networks works.

If you initialize all hidden neurons with the same parameters and apply identical deterministic updates, their symmetry can persist: they learn the same feature. Asymmetric initialization breaks that coincidence; its detailed study comes later.

Weights produced by another network

A hypernetwork gψ(c)g_\psi(\vb{c}) receives a context and generates some or all parameters θ\theta of a target network fθf_\theta. For example, θ=gψ(c)\theta=g_\psi(\vb{c}) and y^=fgψ(c)(x)\hat y=f_{g_\psi(\vb{c})}(\vb{x}). The chain rule carries the gradient to the hypernetwork:

∇ψL=(∂gψ(c)∂ψ)⊤∇θL.\nabla_\psi L=\left(\frac{\partial g_\psi(\vb{c})}{\partial\psi}\right)\T\nabla_\theta L.

The Jacobian is understood with vectorized parameters; normally it is not built in full. The generated output changes with c\vb{c}, while ψ\psi is shared across contexts. Generating weights can save stored parameters compared with keeping a separate network for each context, but this depends on the size of gψg_\psi, what is generated and how many contexts are compared: savings are not guaranteed. HyperNetworks presents this mechanism and concrete examples, not a general bound on savings.

Lab: generic forward pass and XOR

We use examples as rows and a list of pairs (W, b). The last layer returns logits without ReLU. The XOR parameters are fixed by hand, so you can calculate each output without relying on training.

[ ]Generic MLP in NumPyBrowser
import numpy as np

class MLP:
    def __init__(self, params):
        self.params = [(np.asarray(W, dtype=float), np.asarray(b, dtype=float)) for W, b in params]

    def forward(self, X):
        H = np.asarray(X, dtype=float)
        activations = [H]
        for i, (W, b) in enumerate(self.params):
            Z = H @ W + b
            H = np.maximum(Z, 0) if i < len(self.params) - 1 else Z
            activations.append(H)
        return H, activations

    def nparams(self):
        return sum(W.size + b.size for W, b in self.params)

Xxor = np.array([[0, 0], [1, 0], [0, 1], [1, 1]], dtype=float)
model = MLP([(np.array([[1, 1], [1, 1]]), np.array([0, -1])),
             (np.array([[1], [-2]]), np.array([-0.5]))])
z, hs = model.forward(Xxor)
print('XOR activaciones', hs[1].tolist(), 'logits', z.ravel().tolist())
print('parámetros XOR', model.nparams())
print('parámetros 784-512-256-10', 784*512+512 + 512*256+256 + 256*10+10)

Compare the same convention with PyTorch: nn.Linear(d_in, d_out) stores weights transposed relative to those in this lesson. This snippet is for a local PyTorch installation; it is not used in the browser lab.

import torch
from torch import nn

net = nn.Sequential(nn.Linear(2, 2), nn.ReLU(), nn.Linear(2, 1))
with torch.no_grad():
    net[0].weight.copy_(torch.tensor([[1., 1.], [1., 1.]]))
    net[0].bias.copy_(torch.tensor([0., -1.]))
    net[2].weight.copy_(torch.tensor([[1., -2.]]))
    net[2].bias.copy_(torch.tensor([-0.5]))
print(net(torch.tensor([[0., 0.], [1., 0.], [0., 1.], [1., 1.]])))

Reproducing the spiral network

This small run uses only NumPy: 120 deterministic points on two spirals, three hidden layers of widths 16, 16 and 2, and one logit. It trains for 2000 full steps with Adam from seed 42. The printed accuracy is on the same training points, not an estimate of generalization. The printed weights feed the figure; they are not a paper’s benchmark result. Here step starts at 1 because Adam’s bias corrections use that index.

[ ]Train the network that transforms the spiralsBrowser
import json

rng = np.random.default_rng(42)
n = 60
t = np.linspace(0.35, 2.5 * np.pi, n)
r = t / (2.5 * np.pi)
Xspiral = np.vstack([np.column_stack((r * np.cos(t), r * np.sin(t))),
                     np.column_stack((-r * np.cos(t), -r * np.sin(t)))])
yspiral = np.r_[np.zeros(n), np.ones(n)][:, None]
sizes = [2, 16, 16, 2, 1]
params = []
for a, b in zip(sizes[:-1], sizes[1:]):
    params.extend([rng.normal(0, np.sqrt(2 / a), (a, b)), np.zeros((1, b))])
m = [np.zeros_like(p) for p in params]
v = [np.zeros_like(p) for p in params]
for step in range(1, 2001):
    hs = [Xspiral]
    for i in range(0, 6, 2):
        hs.append(np.maximum(0, hs[-1] @ params[i] + params[i + 1]))
    z = hs[-1] @ params[6] + params[7]
    p = 1 / (1 + np.exp(-np.clip(z, -40, 40)))
    delta = (p - yspiral) / len(Xspiral)
    grads = [None] * len(params)
    for layer in range(3, -1, -1):
        i = 2 * layer
        grads[i] = hs[layer].T @ delta
        grads[i + 1] = delta.sum(axis=0, keepdims=True)
        if layer:
            delta = (delta @ params[i].T) * (hs[layer] > 0)
    for j in range(len(params)):
        m[j] = 0.9 * m[j] + 0.1 * grads[j]
        v[j] = 0.999 * v[j] + 0.001 * grads[j] ** 2
        params[j] -= 0.01 * (m[j] / (1 - 0.9 ** step)) / (np.sqrt(v[j] / (1 - 0.999 ** step)) + 1e-8)
H = Xspiral
for i in range(0, 6, 2):
    H = np.maximum(0, H @ params[i] + params[i + 1])
z = H @ params[6] + params[7]
print('pérdida y exactitud de entrenamiento', np.mean(np.logaddexp(0, z) - yspiral*z), np.mean((z > 0) == yspiral))
print('pesos de la figura', json.dumps([p.tolist() for p in params], separators=(',', ':')))

To explore what happens outside those points, generate other data and compare representations without fitting any parameters using their labels. The training above demonstrates one particular representation, not that every network with that architecture or seed separates any spiral.

[ ]Moons and circles: random versus fixed weightsBrowser
from sklearn.datasets import make_moons, make_circles
import matplotlib.pyplot as plt

moons, ym = make_moons(n_samples=120, noise=0.04, random_state=7)
circles, yc = make_circles(n_samples=120, noise=0.04, factor=0.45, random_state=7)
random_rng = np.random.default_rng(3)
random_W = random_rng.normal(size=(2, 2))
fixed_W = np.array([[1., 1.], [1., -1.]])
fig, axes = plt.subplots(2, 2, figsize=(7, 6))
for row, (Xdata, labels) in enumerate(((moons, ym), (circles, yc))):
    for col, matrix in enumerate((random_W, fixed_W)):
        hidden = np.maximum(0, Xdata @ matrix + np.array([0., -0.5]))
        axes[row, col].scatter(hidden[:, 0], hidden[:, 1], c=labels, s=9, cmap='coolwarm')
        axes[row, col].set_title(('Lunas' if row == 0 else 'Círculos') + (' aleatorio' if col == 0 else ' fijado'))
plt.tight_layout()
plt.show()

These fixed weights are a geometric choice, not a supervised fit to the moons or circles. An apparently overlapping cloud in a projection does not prove that the original input is inseparable. Compare how ReLU takes negative components to zero and what information it no longer distinguishes.

Exercises

NumericCounting weights and biases
Calculate the total number of parameters in a 784-512-256-10 MLP with a bias in every layer.
QuizWidth for XOR
In the described MLP with ReLU in one hidden layer and a thresholded affine output, which statement about XOR is correct?
ProofComposition without nonlinearity
Prove: Prove by induction that a composition of L affine layers is equivalent to a single affine map.
0
With examples as rows, write H = XA + 1cᵀ before the next layer.

Step 1 of 2. What happens when W and b are applied?

ProofRescaling a neuron
Prove: Prove that scaling the incoming weights and bias of a ReLU neuron by α > 0 and dividing its outgoing weights by α does not change the function.
0
The neuron's activation is ReLU(z).

Step 1 of 4. How does the activation change?

CodeBatch propagation
Implement mlp_forward(X, params, act). Each pair in params is (W,b); apply act to every layer except the last, which returns logits. Return the output and a list containing X and every subsequent activation.
import numpy as np

def mlp_forward(X, params, act):
  pass
Shift+Enter to run
Key idea

An MLP learns representations through affine layers and activations. Without nonlinearity the entire composition remains affine; with ReLU, regions can fold and XOR can be separated in hidden space. The same function can have multiple equivalent parameters, so comparing or averaging weights requires accounting for those symmetries.