Skip to content
Deep learning Foundation 27 min read

Neurons, perceptrons and MLPs

An artificial neuron is a weighted sum followed by a bend. Stack layers of them and the bends compound: a multilayer perceptron can carve input space into exponentially many pieces and approximate any continuous function. Everything else in deep learning is a variation on this one move.

10,000 ft

The multilayer perceptron (MLP) is the atom of deep learning. A convolutional network is an MLP whose weights are shared across positions (CNNs); a transformer block is attention followed by an MLP that holds about two-thirds of the block's parameters (the transformer block). The ideas on this page, affine maps, nonlinearities, depth versus width, the shapes of the tensors, are the vocabulary every later page assumes. What this page cannot do is train an MLP with more than one layer: that needed a way to assign blame to hidden units, which is backpropagation.

2,000 ft

A neuron computes \(z = \mathbf{w}^\top\mathbf{x} + b\) (which side of a hyperplane is the input on, and how far?) and passes it through a nonlinearity \(\phi\). A layer is many neurons reading the same input, so it is one matrix multiply: \(\mathbf{h} = \phi(W\mathbf{x} + \mathbf{b})\). An MLP alternates these affine maps and nonlinearities; the last layer is a linear "head" read by a loss.

A two-layer MLP: affine, bend, affine, bend, read out
A two-layer MLP: affine, bend, affine, bend, read out. input x (d values), affine W₁x + b₁, nonlinearity Ο† (ReLU, GELU…), affine Wβ‚‚h₁ + bβ‚‚, nonlinearity Ο†, linear head logits, loss (MSE or cross-entropy)A two-layer MLP: affine, bend, affine, bend, read out. input x (d values), affine W₁x + b₁, nonlinearity Ο† (ReLU, GELU…), affine Wβ‚‚h₁ + bβ‚‚, nonlinearity Ο†, linear head logits, loss (MSE or cross-entropy)

  1. Each neuron is a hyperplane detector: the sign of \(z\) says which side, the size says how far.
  2. A single neuron can only draw one straight boundary, so it cannot solve XOR.
  3. A hidden layer re-maps the input into a space where the classes are separable.
  4. Without the nonlinearity, any stack of layers collapses to one linear map.
  5. With it, one wide hidden layer can approximate any continuous function; depth makes the same job exponentially cheaper.

Ground level

One neuron: a weighted vote with a threshold

A neuron takes a vector \(\mathbf{x} \in \mathbb{R}^d\), multiplies each coordinate by a weight, adds them up, adds a bias and applies a function:

\[ z = \mathbf{w}^\top \mathbf{x} + b = \sum_{i=1}^{d} w_i x_i + b, \qquad a = \phi(z). \]

\(z\) is the pre-activation (or logit), \(a\) the activation. Three choices of \(\phi\) give three classical models you already know:

\(\phi\) Model Output means Usual loss
identity linear regression a real number squared error
sigmoid \(\sigma(z) = 1/(1+e^{-z})\) logistic regression \(P(y=1\mid\mathbf{x})\) binary cross-entropy
step \(\operatorname{sign}(z)\) Rosenblatt's perceptron a hard class \(\pm1\) perceptron rule (no smooth loss)

The affine core is identical; only the bend and the loss differ. A worked number: with \(\mathbf{x} = (2, 1)\), \(\mathbf{w} = (0.5, -1)\) and \(b = 0.25\), the neuron computes \(z = 0.5\cdot2 - 1\cdot1 + 0.25 = 0.25\). A sigmoid neuron outputs \(\sigma(0.25) = 0.562\), a mild "yes"; a step neuron outputs \(+1\).

The geometry is what matters. The set \(\{\mathbf{x} : \mathbf{w}^\top\mathbf{x} + b = 0\}\) is a hyperplane (a line in 2-D). \(\mathbf{w}\) is its normal vector, pointing towards the side where \(z > 0\), and the signed distance from \(\mathbf{x}\) to the hyperplane is \(z / \lVert\mathbf{w}\rVert\). In the example, \(\lVert\mathbf{w}\rVert = \sqrt{0.25 + 1} = 1.118\), so \(\mathbf{x}\) sits \(0.25/1.118 = 0.224\) units on the positive side. A neuron is therefore a feature detector for a direction: it fires in proportion to how far the input lies along \(\mathbf{w}\) past the offset \(-b/\lVert\mathbf{w}\rVert\). (If dot products as "alignment" are new, read vectors and the geometry of meaning first.)

Keep this picture

A neuron is a hyperplane plus a ruler. The weights choose the hyperplane's orientation, the bias slides it, and the activation decides what to do with the ruler reading: pass it through, squash it to a probability, or clip the negative side to zero.

The perceptron learning rule

Rosenblatt's perceptron (1958) learns \(\mathbf{w}\) and \(b\) from labelled examples \((\mathbf{x}_n, y_n)\) with \(y_n \in \{-1, +1\}\). Fold the bias into the weights by appending a constant 1 to every input, so the prediction is \(\operatorname{sign}(\mathbf{w}^\top\mathbf{x})\). Then loop over the data:

\[ \text{if } y_n\, \mathbf{w}^\top \mathbf{x}_n \le 0 \;(\text{a mistake}): \qquad \mathbf{w} \leftarrow \mathbf{w} + y_n \mathbf{x}_n . \]

Why that update? After it, \(y_n \mathbf{w}^\top\mathbf{x}_n\) grows by \(y_n^2\lVert\mathbf{x}_n\rVert^2 = \lVert\mathbf{x}_n\rVert^2 > 0\): the hyperplane rotates towards classifying that point correctly. It is also exactly stochastic gradient descent with step size 1 on the perceptron loss \(\max(0, -y\,\mathbf{w}^\top\mathbf{x})\), whose gradient is \(-y\mathbf{x}\) on a mistake and \(0\) otherwise. So the oldest learning rule in the field is already gradient descent on a piecewise-linear loss.

The remarkable fact is that it terminates when the data can be separated. Novikoff's theorem (1962) bounds the number of mistakes by \((R/\gamma)^2\), where \(R\) is the largest input norm and \(\gamma\) is the margin of the best separating hyperplane; the proof is short and is in the maths. The bound does not depend on the number of points or the dimension. In the run in Build it, 179 points need 11 mistakes against a bound of 167.5: the bound is loose, but it is a guarantee.

XOR: the wall a single neuron hits

Now give the perceptron XOR: inputs \((0,0)\) and \((1,1)\) are class 0, \((0,1)\) and \((1,0)\) class 1. No line separates them, and you can prove it in four inequalities. Suppose some \(w_1, w_2, b\) worked, with class 1 meaning \(z > 0\):

  • \((0,0)\) in class 0: \(b \le 0\).
  • \((1,1)\) in class 0: \(w_1 + w_2 + b \le 0\).
  • \((0,1)\) and \((1,0)\) in class 1: \(w_2 + b > 0\) and \(w_1 + b > 0\).

Adding the last two gives \(w_1 + w_2 + 2b > 0\), so \(w_1 + w_2 + b > -b \ge 0\), contradicting the second line. The perceptron rule on XOR cycles forever. Minsky and Papert's Perceptrons (1969) made this kind of limit rigorous for a whole family of predicates, which helped push neural-network research out of fashion for more than a decade.

The fix was already known in principle: add a hidden layer. Take two ReLU units (\(\operatorname{ReLU}(z) = \max(0, z)\)) that both look along the direction \((1,1)\) but with different thresholds, and combine them:

\[ h_1 = \operatorname{ReLU}(x_1 + x_2), \qquad h_2 = \operatorname{ReLU}(x_1 + x_2 - 1), \qquad y = h_1 - 2h_2 . \]
\((x_1, x_2)\) \(h_1\) \(h_2\) \(y\)
(0, 0) 0 0 0
(0, 1) 1 0 1
(1, 0) 1 0 1
(1, 1) 2 1 0

The hidden layer has moved the points. In \((h_1, h_2)\) coordinates the two class-1 inputs land on the same spot, \((1, 0)\), and the class-0 points sit at \((0,0)\) and \((2,1)\), so a single line separates them. That is the whole idea of representation learning in miniature: a layer learns coordinates in which the next layer's job is easy.

input space (x₁, xβ‚‚) hidden space (h₁, hβ‚‚) (0,0)(1,1)(0,1)(1,0) (0,0)(1,0) Γ—2(2,1) h₁ βˆ’ 2hβ‚‚ = Β½ class 1
Left: XOR's class-1 points (cyan) lie in a band between two parallel lines, which no single line can carve out. Right: after the two hidden ReLUs, both cyan points land on (1, 0) and one straight line separates the classes.

Layers are matrix multiplies

Put \(m\) neurons side by side, all reading the same \(d\)-dimensional input. Stack their weight vectors as the rows of \(W \in \mathbb{R}^{m \times d}\) and their biases into \(\mathbf{b} \in \mathbb{R}^m\); the layer is

\[ \mathbf{h} = \phi(W\mathbf{x} + \mathbf{b}), \qquad \mathbf{h} \in \mathbb{R}^m, \]

with \(\phi\) applied element by element. In code you process a batch of \(B\) examples at once, stored as rows of \(X \in \mathbb{R}^{B \times d}\), and the convention flips to \(H = \phi(XW + \mathbf{b})\) with \(W \in \mathbb{R}^{d \times m}\) and the bias broadcast across rows (broadcasting). PyTorch's nn.Linear(d, m) stores the weight as \(m \times d\) and computes \(XW^\top + \mathbf{b}\); whichever convention you use, write the shapes next to every line until it is automatic.

An \(L\)-layer MLP is

\[ \mathbf{h}_0 = \mathbf{x}, \qquad \mathbf{h}_\ell = \phi(W_\ell \mathbf{h}_{\ell-1} + \mathbf{b}_\ell) \;\; (\ell = 1, \dots, L-1), \qquad \hat{\mathbf{y}} = W_L \mathbf{h}_{L-1} + \mathbf{b}_L . \]

The final layer has no \(\phi\): it produces logits, and the loss decides how to read them.

Counting is worth doing once by hand. A 784–512–256–10 MLP for MNIST digits has \(784\cdot512 + 512 = 401{,}920\) parameters in the first layer, \(131{,}328\) in the second and \(2{,}570\) in the head: 535,818 in total. A forward pass costs about two floating-point operations per weight per example (one multiply, one add), so about 1.07 million FLOPs. That "2 Γ— parameters per token" rule survives all the way up to compute maths for LLMs.

Why the nonlinearity is not optional

Delete \(\phi\) and stack two layers: \(W_2(W_1\mathbf{x} + \mathbf{b}_1) + \mathbf{b}_2 = (W_2W_1)\mathbf{x} + (W_2\mathbf{b}_1 + \mathbf{b}_2)\). That is one affine map with weight \(W_2W_1\). A hundred linear layers are still one linear layer (with a rank no larger than the narrowest layer's width), so depth buys nothing. The nonlinearity is what stops the composition from collapsing. Which nonlinearity is a real design choice with its own page: activation functions.

Deep linear networks are not useless to study

Their function class is trivial but their training dynamics are not: gradient descent on \(W_2W_1\) shows plateaus and sudden drops that look a lot like real networks. Saxe, McClelland and Ganguli (2013) solved those dynamics exactly; it is one of the best ways into the theory of initialisation.

ReLU networks are piecewise linear

With ReLU, each hidden unit is a hinge: zero on one side of its hyperplane, linear on the other. A network built from hinges and affine maps is a continuous piecewise-linear function. Each pattern of which units are on or off defines a region of input space, and inside one region the whole network is a single affine map. Training moves the region boundaries and the slopes within them.

In one dimension this gives a constructive picture of what a hidden layer can do. One ReLU makes a kink. Three make a "hat":

\[ \operatorname{hat}(x) = \operatorname{ReLU}(x) - 2\operatorname{ReLU}(x - 1) + \operatorname{ReLU}(x - 2), \]

which is 0 left of 0, rises to 1 at \(x=1\), falls back to 0 at \(x=2\) and stays there. Sum shifted, scaled hats and you can draw any piecewise-linear curve through any set of points, which is to say, approximate any continuous function on an interval as closely as you like by using enough hats. A one-hidden-layer ReLU network with \(n\) units on a 1-D input has at most \(n+1\) linear pieces.

Universal approximation, and what it does not promise

That hat argument is the 1-D shadow of the universal approximation theorem. Cybenko (1989) proved that for any continuous sigmoidal \(\sigma\), sums \(\sum_{j=1}^{n} \alpha_j \sigma(\mathbf{w}_j^\top\mathbf{x} + b_j)\) are dense in the continuous functions on \([0,1]^d\); Hornik, Stinchcombe and White (1989) proved it for general squashing functions; Leshno, Lin, Pinkus and Schocken (1993) closed the question: a one-hidden-layer network with a (locally bounded, piecewise continuous) activation is universal if and only if the activation is not a polynomial. ReLU, GELU, tanh all qualify.

Read the theorem's small print, because it is where the interesting questions live:

  • It says nothing about size. The number of units \(n\) needed can grow exponentially with the input dimension \(d\) for generic functions.
  • It says nothing about learning. The weights exist; whether gradient descent finds them is a separate question (optimisers).
  • It says nothing about generalisation. A network that fits the training points perfectly may still be wrong between them (regularisation).

So universality is a floor, not an explanation. Lookup tables are universal too.

Depth versus width: composition is exponential

Why go deep rather than wide? Take the tent map on \([0, 1]\), built from two ReLUs:

\[ t(x) = 2\operatorname{ReLU}(x) - 4\operatorname{ReLU}(x - \tfrac12), \]

which rises from 0 to 1 on \([0, \frac12]\) and falls back to 0 on \([\frac12, 1]\). Compose it with itself. Each application folds the interval in half, so \(t^{(k)} = t \circ \dots \circ t\) is a sawtooth with \(2^k\) linear pieces, built from just \(2k\) ReLUs in \(k\) layers. A single hidden layer needs at least \(2^k - 1\) units to make that many pieces, because each unit adds at most one kink. The code in Build it counts it: 12 ReLUs in 6 layers make 64 pieces.

t(x): 2 ReLUs, 2 pieces t(t(x)): 4 ReLUs, 4 pieces t(t(t(x))): 6 ReLUs, 8 pieces depth 1depth 2depth 3
Depth multiplies, width adds. Each extra layer of two ReLUs doubles the number of linear pieces; a single wide layer would need one unit per kink.

Telgarsky (2016) turned this into a theorem: there are functions computed by networks with \(\Theta(k^3)\) layers and constant width that any network with \(O(k)\) layers can only approximate with \(\Omega(2^k)\) units. MontΓΊfar et al. (2014) showed the number of linear regions of a deep ReLU network can grow exponentially in depth. The width story has a mirror image: Lu et al. (2017) proved that ReLU networks of width \(d + 4\) (input dimension plus four) are universal if you allow arbitrary depth, and that width \(d\) is not enough. The practical moral: depth lets a network reuse intermediate features, so real tasks built from parts of parts (edges, textures, objects; characters, words, phrases) are cheap for deep networks and expensive for shallow ones.

Heads and losses: the last layer decides what the numbers mean

The final affine layer outputs logits \(\mathbf{z}\). Three pairings cover almost everything:

Task Head Loss \(\partial \mathcal{L} / \partial \mathbf{z}\)
regression identity, \(\hat y = z\) \(\tfrac12(\hat y - y)^2\) \(\hat y - y\)
binary classification sigmoid, \(p = \sigma(z)\) \(-y\log p - (1-y)\log(1-p)\) \(p - y\)
\(K\)-way classification softmax, \(\mathbf{p} = \operatorname{softmax}(\mathbf{z})\) \(-\log p_y\) \(\mathbf{p} - \mathbf{e}_y\)

The last column is not a coincidence. Each pair is a canonical link for an exponential-family distribution, so the gradient with respect to the logits is always "prediction minus target". That clean error signal is where backpropagation starts, and it is why you should always hand the loss raw logits (PyTorch's CrossEntropyLoss, BCEWithLogitsLoss) rather than probabilities: the library can then use the stable log-sum-exp form (numerical computing).

The MLP inside every transformer

The position-wise feed-forward network in a transformer is a two-layer MLP applied to each token independently: \(d \to 4d \to d\) with a GELU between. For GPT-2 small (\(d = 768\)) that is \(4{,}722{,}432\) parameters per block, against \(2{,}362{,}368\) in the four attention projections: 66.7% of the block. Modern LLMs usually swap it for a gated variant (SwiGLU: \((\operatorname{SiLU}(\mathbf{x}W_1) \odot \mathbf{x}W_3)W_2\), with the hidden width cut to about \(\tfrac{8}{3}d\) so the parameter count stays the same; Shazeer, 2020). Interpretability work treats these MLPs as the place where much factual association is stored (mechanistic interpretability). Mastering the humble MLP is not a detour from LLMs; it is most of the parameters.

History

From logic gates to learned features, 1943–1989

1943. Warren McCulloch and Walter Pitts model a neuron as a threshold logic unit and show that networks of them can compute any Boolean function. No learning yet: the weights are designed. 1958. Frank Rosenblatt's perceptron adds a learning rule and runs on custom hardware, the Mark I Perceptron; the press coverage promised far more than one layer could deliver. 1962. Novikoff proves the convergence theorem. 1969. Marvin Minsky and Seymour Papert's Perceptrons proves what single-layer perceptrons cannot compute. Multilayer networks were known to be more powerful, but nobody had a practical way to train the hidden layer. 1986. Rumelhart, Hinton and Williams popularise backpropagation and show hidden units learning useful features (backpropagation). 1989. Cybenko and Hornik et al. prove universal approximation; LeCun et al. train a convolutional MLP on handwritten zip codes. The full arc is told in before the boom.

First principles

Why should the building block be "affine map, then elementwise nonlinearity"? Work backwards from what learning needs.

We need a parameterised family that gradient descent can move through. That requires the output to be differentiable (almost everywhere) in the parameters, and cheap to differentiate. Affine maps are the simplest such family: the derivative of \(W\mathbf{x}\) with respect to \(W\) is just \(\mathbf{x}\).

We need it to be fast on real hardware. A layer applied to a batch is one matrix multiply, the single operation GPUs and TPUs are built around (how a GPU works). An elementwise \(\phi\) adds negligible cost. Almost every architecture since has kept this split: put the parameters in matmuls, put the nonlinearity in cheap pointwise functions.

We need the family to be rich. Composition of affine maps is affine, so some nonlinearity is required; the Leshno et al. theorem says any non-polynomial one suffices. Why not polynomials? A polynomial of degree \(p\) composed \(L\) times is a polynomial of degree \(p^L\); for any fixed architecture that is a finite-dimensional space of functions, which cannot be dense in all continuous functions. The non-polynomial bend is what lets finite networks approach anything.

We need the family to exploit structure. Real functions are compositional, so a model that composes is efficient: depth multiplies the number of regions, width only adds. This is the strongest argument for deep learning as opposed to wide learning, and the sawtooth makes it concrete.

What breaks if we change things? Remove biases and every hyperplane passes through the origin (the network can no longer place a threshold). Make the nonlinearity bounded and saturating (sigmoid) and gradients shrink as they pass through many layers, the problem the activations and initialisation pages solve. Share weights across positions and you get convolution; let the weights depend on the input and you get attention. Each later architecture is this block with one assumption changed.

The maths

Notation. Input \(\mathbf{x} \in \mathbb{R}^{d_0}\). Layer \(\ell\) has width \(d_\ell\), weights \(W_\ell \in \mathbb{R}^{d_\ell \times d_{\ell-1}}\), bias \(\mathbf{b}_\ell \in \mathbb{R}^{d_\ell}\). Pre-activations \(\mathbf{z}_\ell = W_\ell\mathbf{h}_{\ell-1} + \mathbf{b}_\ell\), activations \(\mathbf{h}_\ell = \phi(\mathbf{z}_\ell)\), with \(\mathbf{h}_0 = \mathbf{x}\) and no \(\phi\) on the last layer. With a batch \(X \in \mathbb{R}^{B \times d_0}\) in row convention, \(Z_\ell = H_{\ell-1}W_\ell^\top + \mathbf{1}\mathbf{b}_\ell^\top \in \mathbb{R}^{B \times d_\ell}\).

Parameter count and cost. \(P = \sum_{\ell=1}^{L} d_\ell(d_{\ell-1} + 1)\). Forward cost \(\approx 2B\sum_\ell d_\ell d_{\ell-1}\) FLOPs; the backward pass costs about twice that, so training costs about \(6 \times\) parameters FLOPs per example, the rule behind scaling-law budgets.

Geometry of one unit. The decision boundary is the hyperplane \(\mathbf{w}^\top\mathbf{x} + b = 0\); the signed distance of \(\mathbf{x}\) from it is \((\mathbf{w}^\top\mathbf{x} + b)/\lVert\mathbf{w}\rVert\).

Theorem (Novikoff, 1962): the perceptron makes at most (R/Ξ³)Β² mistakes

Assume a unit vector \(\mathbf{u}\) and margin \(\gamma > 0\) with \(y_n\,\mathbf{u}^\top\mathbf{x}_n \ge \gamma\) for all \(n\), and \(\lVert\mathbf{x}_n\rVert \le R\) (bias folded into \(\mathbf{x}\)). Start at \(\mathbf{w}_0 = \mathbf{0}\) and let \(\mathbf{w}_k\) be the weights after the \(k\)-th mistake, made on some \((\mathbf{x}, y)\).

Progress along u. \(\mathbf{u}^\top\mathbf{w}_k = \mathbf{u}^\top\mathbf{w}_{k-1} + y\,\mathbf{u}^\top\mathbf{x} \ge \mathbf{u}^\top\mathbf{w}_{k-1} + \gamma\), so by induction \(\mathbf{u}^\top\mathbf{w}_k \ge k\gamma\).

Bounded growth. \(\lVert\mathbf{w}_k\rVert^2 = \lVert\mathbf{w}_{k-1}\rVert^2 + 2y\,\mathbf{w}_{k-1}^\top\mathbf{x} + \lVert\mathbf{x}\rVert^2 \le \lVert\mathbf{w}_{k-1}\rVert^2 + R^2\), because the middle term is \(\le 0\) on a mistake. So \(\lVert\mathbf{w}_k\rVert^2 \le kR^2\).

Combine with Cauchy–Schwarz, \(\mathbf{u}^\top\mathbf{w}_k \le \lVert\mathbf{w}_k\rVert\):

\[ k\gamma \le \sqrt{k}\,R \quad\Longrightarrow\quad k \le \left(\frac{R}{\gamma}\right)^2 . \]

The weight vector's component along the true direction grows linearly with mistakes while its length grows only like a square root, so the angle to \(\mathbf{u}\) must keep closing and the mistakes must stop.

Theorem (universal approximation, Cybenko 1989; Leshno et al. 1993)

Let \(\phi:\mathbb{R}\to\mathbb{R}\) be locally bounded and piecewise continuous. The set

\[ \mathcal{N}_\phi = \Big\{ \mathbf{x} \mapsto \sum_{j=1}^{n} \alpha_j\, \phi(\mathbf{w}_j^\top\mathbf{x} + b_j) \;:\; n \in \mathbb{N},\; \alpha_j, b_j \in \mathbb{R},\; \mathbf{w}_j \in \mathbb{R}^d \Big\} \]

is dense in \(C(K)\) for every compact \(K \subset \mathbb{R}^d\) (uniform norm) if and only if \(\phi\) is not a polynomial (almost everywhere).

Why polynomials fail. If \(\phi\) is a polynomial of degree \(p\), every element of \(\mathcal{N}_\phi\) is a polynomial of degree at most \(p\), a finite-dimensional space, which cannot be dense.

1-D sketch for ReLU. Given a continuous \(f\) on \([a, c]\) and \(\varepsilon > 0\), uniform continuity gives a grid \(a = t_0 < \dots < t_m = c\) on which the piecewise-linear interpolant \(g\) of \(f\) is within \(\varepsilon\). Write \(g(x) = f(t_0) + s_0\operatorname{ReLU}(x - t_0) + \sum_{i=1}^{m-1}(s_i - s_{i-1})\operatorname{ReLU}(x - t_i)\), where \(s_i\) is the slope on \([t_i, t_{i+1}]\). That is a one-hidden-layer ReLU network with \(m\) units (plus a constant bias). The \(d\)-dimensional proofs replace hats by ridge functions and use Fourier or Hahn–Banach arguments.

XOR is not linearly separable, by the four-inequality argument in Ground level. More generally, the parity of \(d\) bits needs a hidden layer; a single threshold unit computes only linearly separable Boolean functions.

Linear regions. A one-hidden-layer ReLU network on \(\mathbb{R}\) with \(n\) units has at most \(n + 1\) pieces. The \(k\)-fold tent composition has \(2^k\) pieces from \(2k\) units, so any shallow network matching it exactly needs at least \(2^k - 1\) units.

Build it

NumPy, three experiments: the perceptron rule with its mistake bound, a hand-wired XOR network, and the depth-versus-width sawtooth.

import numpy as np
# perceptron on linearly separable data, compare mistakes to Novikoff bound
rng = np.random.default_rng(0)
w_true = np.array([1.0, -2.0]); b_true = 0.5
X = rng.uniform(-1, 1, size=(200, 2))
margin_raw = X @ w_true + b_true
keep = np.abs(margin_raw) > 0.3            # enforce a margin
X, y = X[keep], np.sign(margin_raw[keep])
Xa = np.hstack([X, np.ones((len(X), 1))])  # fold the bias into w
w = np.zeros(3); mistakes = 0
for epoch in range(100):
    errs = 0
    for xi, yi in zip(Xa, y):
        if yi * (w @ xi) <= 0:
            w += yi * xi; errs += 1
    mistakes += errs
    if errs == 0: break
u = np.array([*w_true, b_true]); u /= np.linalg.norm(u)
gamma = np.min(y * (Xa @ u)); R = np.max(np.linalg.norm(Xa, axis=1))
print(f"{len(X)} points, converged after epoch {epoch+1}, {mistakes} mistakes")
print(f"Novikoff bound (R/gamma)^2 = {(R/gamma)**2:.1f}")
print("learned w, b:", np.round(w, 2))
179 points, converged after epoch 3, 11 mistakes
Novikoff bound (R/gamma)^2 = 167.5
learned w, b: [ 1.2  -3.09  1.  ]

The learned \((1.2, -3.09, 1.0)\) is not the true \((1, -2, 0.5)\), and need not be: any separating hyperplane is a fixed point of the rule. Next, XOR by hand and the sawtooth.

import numpy as np
relu = lambda z: np.maximum(z, 0)

# XOR with two hidden ReLUs, weights set by hand
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=float)
W1 = np.array([[1.0, 1.0],
               [1.0, 1.0]])          # shape (2 inputs, 2 hidden)
b1 = np.array([0.0, -1.0])
W2 = np.array([1.0, -2.0])           # shape (2 hidden,)
H = relu(X @ W1 + b1)                # hidden layer, shape (4, 2)
print("hidden h:\n", H)
print("output  :", H @ W2)           # XOR: 0 1 1 0

# depth vs width: compose a tent map k times and count linear pieces
tent = lambda x: 2 * relu(x) - 4 * relu(x - 0.5)   # 2 ReLUs per layer
x = np.linspace(0, 1, 2**12 + 1)
f = x.copy()
for k in range(1, 7):
    f = tent(f)
    slopes = np.round(np.diff(f) / np.diff(x), 6)
    pieces = 1 + np.count_nonzero(np.diff(slopes))
    print(f"depth {k}: {2*k:2d} ReLUs -> {pieces:3d} linear pieces")
hidden h:
 [[0. 0.]
 [1. 0.]
 [1. 0.]
 [2. 1.]]
output  : [0. 1. 1. 0.]
depth 1:  2 ReLUs ->   2 linear pieces
depth 2:  4 ReLUs ->   4 linear pieces
depth 3:  6 ReLUs ->   8 linear pieces
depth 4:  8 ReLUs ->  16 linear pieces
depth 5: 10 ReLUs ->  32 linear pieces
depth 6: 12 ReLUs ->  64 linear pieces

Finally, count parameters and FLOPs, and check the transformer FFN share:

import numpy as np
sizes = [784, 512, 256, 10]
params = [(m * n, n) for m, n in zip(sizes[:-1], sizes[1:])]
for (w, b), (m, n) in zip(params, zip(sizes[:-1], sizes[1:])):
    print(f"layer {m:>3} -> {n:>3}: weights {w:>7,}  biases {b:>3}")
total = sum(w + b for w, b in params)
print(f"total parameters: {total:,}")
print(f"forward FLOPs per example ~ 2 x weights = {2*sum(w for w,_ in params):,}")

d = 768                                   # GPT-2 small width
ffn  = d * 4*d + 4*d + 4*d * d + d        # two linear layers with biases
attn = 4 * (d * d + d)                    # Q, K, V and output projections
print(f"GPT-2 small block: FFN {ffn:,}  attention {attn:,}  FFN share {ffn/(ffn+attn):.1%}")
layer 784 -> 512: weights 401,408  biases 512
layer 512 -> 256: weights 131,072  biases 256
layer 256 ->  10: weights   2,560  biases  10
total parameters: 535,818
forward FLOPs per example ~ 2 x weights = 1,070,080
GPT-2 small block: FFN 4,722,432  attention 2,362,368  FFN share 66.7%

Things to try

  • Run the perceptron on XOR (four points, labels \(\pm1\)) and print errs per epoch. It never reaches zero; plot the weight vector and watch it cycle.
  • Shrink the margin filter from 0.3 to 0.01. The bound \((R/\gamma)^2\) explodes; does the actual mistake count?
  • Replace relu with the identity in the XOR network. Prove to yourself no choice of W1, b1, W2 can work.
  • Build the 1-D universal approximator: fit \(\sin(x)\) on \([0, 2\pi]\) with \(m\) hand-placed ReLUs using the interpolation formula in the maths section, and plot the max error as \(m\) doubles. It should fall roughly as \(1/m^2\).
  • Write the forward pass of the 784–512–256–10 MLP for a batch of 64 random inputs and assert every intermediate shape.

Check yourself

A neuron has w = (3, 4) and b = βˆ’5. Where is its decision boundary, and how far from it is the point (1, 1)?

The boundary is the line \(3x_1 + 4x_2 = 5\). At \((1, 1)\), \(z = 3 + 4 - 5 = 2\) and \(\lVert\mathbf{w}\rVert = 5\), so the point is \(2/5 = 0.4\) units away on the positive side.

Why does stacking ten linear layers give no more expressive power than one?

The composition of affine maps is affine: \(W_{10}\cdots W_1\mathbf{x}\) plus a constant. The only thing depth changes is the parameterisation (and the rank can only drop to the narrowest width), not the set of functions.

The perceptron update is described as gradient descent. On which loss, and why doesn't the logistic-regression update look the same?

On the perceptron loss \(\max(0, -y\,\mathbf{w}^\top\mathbf{x})\), with step size 1: its gradient is \(-y\mathbf{x}\) on a mistake and zero otherwise. Logistic regression minimises cross-entropy, whose gradient \((\sigma(z) - y)\mathbf{x}\) (with \(y \in \{0,1\}\)) is non-zero for every example, weighted by how wrong the probability is, so even correctly classified points keep pushing the boundary towards a larger margin.

How many linear pieces can a one-hidden-layer ReLU network with 50 units have on a 1-D input? How could a deeper network with the same 50 units do better?

At most 51: each unit contributes one kink. Arranged as 25 layers of 2 units each computing a tent map, the same 50 units can produce a sawtooth with \(2^{25} \approx 33.5\) million pieces. Depth multiplies regions; width adds them.

The universal approximation theorem is true. Why doesn't it settle whether neural networks will work on a given problem?

It is an existence statement. It gives no bound on how many units you need (which can be exponential in the input dimension), no guarantee that gradient descent finds the approximating weights, and no guarantee that a network fitted to finite data generalises. Polynomials and lookup tables are universal approximators too.

Why is sin a valid activation for universal approximation, but xΒ³ is not?

The Leshno et al. condition is "not a polynomial". \(x^3\) is a polynomial, so a one-hidden-layer network with it computes only cubic polynomials. \(\sin\) is not a polynomial (and networks of sines form Fourier-like sums), so they are dense.

In a transformer with d = 4096 and a SwiGLU FFN with hidden width 11008, how many parameters are in the FFN of one block (no biases)? Compare with a plain 4d MLP.

SwiGLU has three matrices, \(W_1, W_3 \in \mathbb{R}^{d\times h}\) and \(W_2 \in \mathbb{R}^{h \times d}\): \(3 \times 4096 \times 11008 = 135{,}266{,}304\). A plain \(d \to 4d \to d\) MLP has \(2 \times 4096 \times 16384 = 134{,}217{,}728\). The hidden width \(11008 \approx \tfrac{8}{3}\cdot 4096\) (rounded up to a hardware-friendly multiple) is chosen to keep the two close.

Hard: give a two-layer network with threshold units that computes the parity of three bits.

Let \(s = x_1 + x_2 + x_3\). Hidden units \(h_k = [s \ge k]\) for \(k = 1, 2, 3\). Then parity \(= h_1 - h_2 + h_3\): for \(s = 0,1,2,3\) it gives \(0, 1, 0, 1\). In general parity of \(d\) bits needs \(d\) hidden threshold units in one hidden layer, and the alternating-sign readout is exactly the XOR trick generalised.

Go deeper

Papers

Videos and lectures

Articles and blog posts

Courses and books

  • Understanding Deep Learning β€” Simon Prince, 2023. Chapters 3 and 4 (shallow and deep networks) are the best modern treatment of linear regions; free PDF.
  • Deep Learning β€” Goodfellow, Bengio and Courville, 2016. Chapter 6, deep feedforward networks, including the XOR example.
  • Dive into Deep Learning β€” Zhang et al. Chapter on multilayer perceptrons, with runnable PyTorch/JAX code.

Where this leads