Multilayer Perceptrons: the Forward Pass
A multilayer perceptron (MLP), or feedforward network, chains affine maps and activations. It is the building block inside every larger architecture: the feed-forward half of a transformer block is an MLP, and so is the head of most classifiers. This lesson writes the forward pass in matrix form, counts its parameters and states what such networks can represent. For the linear-algebra view of a layer see Neural Network Layers.
Layers as function composition
With input , layer computes
and the network is the composition , the last layer usually without (it outputs logits). are the pre-activations, the activations or hidden units. For a batch stored as rows, .
import numpy as np
rng = np.random.default_rng(0)
sizes = [4, 16, 16, 3] # input, two hidden layers, 3 classes
params = [(rng.normal(0, np.sqrt(2 / m), (n, m)), np.zeros(n)) for m, n in zip(sizes[:-1], sizes[1:])]
def forward(X):
H = X
for i, (W, b) in enumerate(params):
A = H @ W.T + b
H = np.maximum(0, A) if i < len(params) - 1 else A
print(f"layer {i + 1}: {W.shape[1]} -> {W.shape[0]}, output batch shape {H.shape}")
return H
X = rng.normal(size=(5, 4))
logits = forward(X)
P = np.exp(logits - logits.max(1, keepdims=True)); P /= P.sum(1, keepdims=True)
print("class probabilities of example 0:", np.round(P[0], 3))
print("parameters:", sum(W.size + b.size for W, b in params))layer 1: 4 -> 16, output batch shape (5, 16)
layer 2: 16 -> 16, output batch shape (5, 16)
layer 3: 16 -> 3, output batch shape (5, 3)
class probabilities of example 0: [0.261 0.435 0.304]
parameters: 403
Counting parameters
A layer from to units has weights and biases. The network above has parameters. A forward pass costs about floating-point operations per example per layer (a multiply and an add per weight), which is where the " FLOPs per token" rule for transformers comes from (Counting Parameters and FLOPs).
What an MLP can represent
The universal approximation theorem: an MLP with one hidden layer and a non-polynomial activation can approximate any continuous function on a bounded region to any accuracy, given enough hidden units. It says nothing about how many units are needed or whether training finds them. Each ReLU unit contributes one "kink", so a one-hidden-layer ReLU network in 1-D is a piecewise linear function, and enough pieces approximate any curve.
import numpy as np
# Build a ReLU network by hand that interpolates sin on [0, pi] at 9 knots
knots = np.linspace(0, np.pi, 9); vals = np.sin(knots)
slopes = np.diff(vals) / np.diff(knots)
coef = np.concatenate([[slopes[0]], np.diff(slopes)]) # change of slope at each knot
f = lambda x: vals[0] + sum(c * np.maximum(0, x - k) for c, k in zip(coef, knots[:-1]))
x = np.linspace(0, np.pi, 1001)
print("hidden units:", len(coef))
print(f"max error vs sin: {np.max(np.abs(f(x) - np.sin(x))):.4f}")hidden units: 8
max error vs sin: 0.0188
With 8 hidden units the error is already small, and doubling the units roughly quarters it. Depth helps further: a deep ReLU network can create exponentially many linear pieces with a linear number of units (XOR and Why Depth Helps).
In software
nn.Sequential(nn.Linear(4, 16), nn.ReLU(), nn.Linear(16, 16), nn.ReLU(), nn.Linear(16, 3))is the network above;sum(p.numel() for p in model.parameters())counts its parameters.- Transformer MLPs widen the hidden layer to (or with SwiGLU) and project back to .
- Inference engines fuse bias and activation into the matrix-multiply kernel.
Exercises
Exercise 1: Parameter count
Count the parameters of an MLP .
Answer
235,146.
Solution
; ; . Total .
Exercise 2: Forward by hand
, , , ReLU. Compute .
Answer
.
Solution
; ReLU gives .
Exercise 3: An absolute value network (code)
Write exactly as a ReLU network with 2 hidden units and check it.
Answer
.
Solution
Hidden weights , zero biases, output weights .
import numpy as np
x = np.linspace(-2, 2, 9)
W1, w2 = np.array([[1.0], [-1.0]]), np.array([1.0, 1.0])
out = np.maximum(0, x[:, None] @ W1.T) @ w2
print(np.allclose(out, np.abs(x)))True
Test yourself
A dense layer from 100 to 50 units has how many parameters?
- 150
- 5,000
- 5,050
- 5,100
The universal approximation theorem guarantees that…
- gradient descent finds the best network
- a wide enough one-hidden-layer network can approximate any continuous function on a bounded set
- deep networks never overfit
- two hidden units suffice
A one-hidden-layer ReLU network of a single input computes a function that is…
- polynomial
- piecewise linear
- always convex
- periodic