TExcelTAD
Home › Math for Deep Learning & LLMs › Multilayer Networks: the Forward Pass

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 h(0)=x\mathbf{h}^{(0)} = \mathbf{x}, layer ll computes

a(l)=W(l)h(l−1)+b(l),h(l)=ϕ(a(l))\mathbf{a}^{(l)} = W^{(l)}\mathbf{h}^{(l-1)} + \mathbf{b}^{(l)}, \qquad \mathbf{h}^{(l)} = \phi(\mathbf{a}^{(l)})

and the network is the composition f=f(L)∘⋯∘f(1)f = f^{(L)} \circ \cdots \circ f^{(1)}, the last layer usually without ϕ\phi (it outputs logits). a\mathbf{a} are the pre-activations, h\mathbf{h} the activations or hidden units. For a batch stored as rows, H(l)=ϕ(H(l−1)W(l)T+b(l)T)H^{(l)} = \phi(H^{(l-1)}W^{(l)T} + \mathbf{b}^{(l)T}).

python · try it yourself
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 mm to nn units has nmnm weights and nn biases. The network above has (4⋅16+16)+(16⋅16+16)+(16⋅3+3)=403(4 \cdot 16 + 16) + (16 \cdot 16 + 16) + (16 \cdot 3 + 3) = 403 parameters. A forward pass costs about 2nm2nm floating-point operations per example per layer (a multiply and an add per weight), which is where the "2N2N 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.

python · try it yourself
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 4d4d (or 83d\frac{8}{3}d with SwiGLU) and project back to dd.
  • Inference engines fuse bias and activation into the matrix-multiply kernel.

Exercises

Exercise 1: Parameter count

Count the parameters of an MLP 784→256→128→10784 \to 256 \to 128 \to 10.

Answer

235,146.

Solution

784⋅256+256=200,960784 \cdot 256 + 256 = 200{,}960; 256⋅128+128=32,896256 \cdot 128 + 128 = 32{,}896; 128⋅10+10=1,290128 \cdot 10 + 10 = 1{,}290. Total 235,146235{,}146.

Exercise 2: Forward by hand

W=(1−120)W = \begin{pmatrix} 1 & -1 \\ 2 & 0 \end{pmatrix}, b=(0,−1)\mathbf{b} = (0, -1), x=(1,2)\mathbf{x} = (1, 2), ReLU. Compute h\mathbf{h}.

Answer

h=(0,1)\mathbf{h} = (0, 1).

Solution

Wx+b=(1−2,2−1)=(−1,1)W\mathbf{x} + \mathbf{b} = (1 - 2, 2 - 1) = (-1, 1); ReLU gives (0,1)(0, 1).

Exercise 3: An absolute value network (code)

Write ∣x∣\lvert x \rvert exactly as a ReLU network with 2 hidden units and check it.

Answer

∣x∣=ReLU⁡(x)+ReLU⁡(−x)\lvert x \rvert = \operatorname{ReLU}(x) + \operatorname{ReLU}(-x).

Solution

Hidden weights (1,−1)(1, -1), zero biases, output weights (1,1)(1, 1).

python · try it yourself
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?

  1. 150
  2. 5,000
  3. 5,050
  4. 5,100

The universal approximation theorem guarantees that…

  1. gradient descent finds the best network
  2. a wide enough one-hidden-layer network can approximate any continuous function on a bounded set
  3. deep networks never overfit
  4. two hidden units suffice

A one-hidden-layer ReLU network of a single input computes a function that is…

  1. polynomial
  2. piecewise linear
  3. always convex
  4. periodic