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 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.
The initial configuration is an exact solution with ReLU :
For , the representations are respectively and the logits are . A threshold at zero implements XOR. The two positive inputs coincide in hidden space and are separated from the negatives by the line . 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 . As a function of the single scalar , it is monotonic or constant: it increases if and decreases if . Its threshold splits the values of 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 layers with parameters, we set and . With the batch convention, and for
with and . 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 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 parameters. If a multiplication and an addition count as two FLOPs, the batch product costs approximately FLOPs; adding biases and applying the activation cost additional operations. This convention ignores implementation details and does not measure actual time. Storing all forward activations for backpropagation requires, for those tensors alone, 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
Proof
By induction, take and . If , then
Thus and . Induction gives the result for .
∎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, .
Following a real representation
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
Parameter-space symmetries produce identical functions with different descriptions. For a hidden layer and output , let be a permutation matrix. Replacing by , by and by does not change the output: ReLU acts componentwise and , while . 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 multiplies its activation by . Dividing all its outgoing weights by preserves the function, because . This does not generally hold for or an arbitrary activation. There are permutations of a layer of width , but they can give fewer than distinct parameter vectors if neurons are indistinguishable. With parameters fixed by no symmetries, the 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 receives a context and generates some or all parameters of a target network . For example, and . The chain rule carries the gradient to the hypernetwork:
The Jacobian is understood with vectorized parameters; normally it is not built in full. The generated output changes with , while 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 , 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.
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.
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.
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
Step 1 of 2. What happens when W and b are applied?
Step 1 of 4. How does the activation change?
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):
passAn 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.