In Part 1 of this series, we saw why a single perceptron gets stuck on curved or diagonal patterns like XOR: one weighted neuron can only draw one flat straight cut across its inputs. Adding even one hidden layer with a nonlinear step such as ReLU bends the space so a network can carve out nonlinear regions.
Mathematical theory pushes that observation to a striking conclusion. A feedforward network with just one hidden layer and a suitable nonlinear activation can approximate a remarkably broad class of functions as closely as you want, provided you give it enough hidden units. Taken at face value, that invites an obvious question: why build deep networks with dozens of layers if one sufficiently wide hidden layer can represent almost anything?
The answer starts with accounting. Every neuron you add to a layer expands what the network must store in memory and how much arithmetic it executes on every pass. Once you derive parameter counts and floating-point operations (FLOPs) straight from a layer's matrix dimensions, widening a layer stops feeling abstract or free.
What universal approximation promises
In 1989, George Cybenko proved a foundational version of what is now called the Universal Approximation Theorem: a feedforward neural network with a single internal hidden layer and a continuous S-shaped (sigmoidal) activation can uniformly approximate any continuous function defined on the unit hypercube to arbitrary accuracy. Later proofs extended that same density property to other non-polynomial activations, including modern piecewise-linear functions like ReLU.
Before relying on that statement, unpack two mathematical conditions hidden inside it:
- Continuous function: a smooth or connected curve with no sudden jumps or tears where outputs teleport instantaneously.
- Compact domain (such as the unit hypercube
[0, 1]^d): a closed, bounded box of inputs. The theorem promises close approximation inside that bounded region, never unbounded extrapolation outside the range of data the network saw.
How does summing simple hidden units actually reconstruct a bumpy curve? With ReLU (ReLU(z) = max(0, z)), the mechanism is transparent. Each hidden unit computes a_i * ReLU(w_i * x + b_i). Before x crosses the threshold where w_i * x + b_i = 0, the unit outputs zero and contributes nothing. Once x crosses that breakpoint, the unit switches on as a straight line with slope a_i * w_i. Combining just two shifted units, such as h1 = +ReLU(x + 1) turning upward at x = -1 and h2 = -2 * ReLU(x - 0.5) turning downward at x = +0.5, builds an isolated triangular tent peaking at (0.5, 1.5) and returning to 0 at x = 2:
Stacking N hidden units simply places N hinge points across an interval, turning a one-hidden-layer ReLU network into a continuous piecewise-linear curve. With 2 linear segments across [-3, 3], the fit captures only a coarse triangle. Raising resolution to 8 segments narrows the largest gaps, and 32 segments trace the smooth target closely:
Computed on [-3, 3] for sin(1.2x) + 0.4 cos(2.7x) - 0.15
Piecewise-linear ReLU fits across [-3, 3]. Maximum absolute error drops from 1.77 with 2 linear pieces to 0.28 with 8 pieces and 0.02 with 32 pieces. Toggle series in the legend to compare fits directly against the target.
| input x | Target curve | 2 linear pieces (err 1.77) | 8 linear pieces (err 0.28) | 32 linear pieces (err 0.02) |
|---|---|---|---|---|
| -3 | 0.195 | 0.195 | 0.195 | 0.195 |
| -2.75 | 0.174 | 0.2 | 0.068 | 0.168 |
| -2.5 | 0.066 | 0.204 | -0.059 | 0.057 |
| -2.25 | -0.186 | 0.209 | -0.186 | -0.186 |
| -2 | -0.572 | 0.213 | -0.581 | -0.574 |
| -1.75 | -1.008 | 0.218 | -0.975 | -1.004 |
| -1.5 | -1.37 | 0.223 | -1.37 | -1.37 |
| -1.25 | -1.537 | 0.227 | -1.283 | -1.52 |
| -1 | -1.444 | 0.232 | -1.196 | -1.428 |
| -0.75 | -1.109 | 0.236 | -1.109 | -1.109 |
| -0.5 | -0.627 | 0.241 | -0.656 | -0.627 |
| -0.25 | -0.133 | 0.245 | -0.203 | -0.14 |
| 0 | 0.25 | 0.25 | 0.25 | 0.25 |
| 0.25 | 0.458 | 0.172 | 0.319 | 0.448 |
| 0.5 | 0.502 | 0.093 | 0.389 | 0.496 |
| 0.75 | 0.458 | 0.015 | 0.458 | 0.458 |
| 1 | 0.42 | -0.063 | 0.498 | 0.426 |
| 1.25 | 0.458 | -0.142 | 0.538 | 0.464 |
| 1.5 | 0.578 | -0.22 | 0.578 | 0.578 |
| 1.75 | 0.718 | -0.298 | 0.608 | 0.713 |
| 2 | 0.779 | -0.377 | 0.638 | 0.769 |
| 2.25 | 0.669 | -0.455 | 0.669 | 0.669 |
| 2.5 | 0.348 | -0.533 | 0.216 | 0.338 |
| 2.75 | -0.141 | -0.612 | -0.237 | -0.146 |
| 3 | -0.69 | -0.69 | -0.69 | -0.69 |
Notice the qualifier right at the heart of the theorem: it proves a wide single hidden layer can approximate, not that it can learn easily or run cheaply. In real problems with dozens or thousands of input dimensions, covering every fold individually in a single layer can demand an astronomical width. Before judging depth against width, let us measure the exact price tag of a concrete network layer by layer.
Why a linear layer stores a 64 by 20 matrix
Take the exact three-step multi-layer perceptron from Part 1: it accepts 20 numerical input features, transforms them into 64 hidden values, clamps negatives with ReLU, and scores 10 output classes:
import torch.nn as nnmodel = nn.Sequential(nn.Linear(20, 64), # index 0nn.ReLU(), # index 1nn.Linear(64, 10), # index 2)
If you inspect model[0].weight.shape in PyTorch (where model[0] selects the first layer, nn.Linear(20, 64)), the printed tuple is (64, 20), not (20, 64). That flipped order catches almost every newcomer off guard, yet it follows straight from matrix multiplication.
Suppose a single input example arrives as a vertical column of 20 numbers (x, shape 20 x 1), and we want our first layer to output a column of 64 numbers (y, shape 64 x 1). When you multiply a matrix W on the left of column vector x (Wx + b), matrix multiplication requires the number of columns in W to equal the number of rows in x:
To compute the first output number y[0], row 0 of W walks across all 20 weights (W[0, 0] through W[0, 19]), multiplies each one by the matching input entry (x[0] through x[19]), adds those products together, and shifts the sum by b[0]. Row 1 does the exact same arithmetic with its own 20 weights and bias b[1], and so on down to row 63. Each row of W therefore belongs to one output neuron, while each column corresponds to one input feature. That fixes weight.shape == (d_out, d_in) and bias.shape == (d_out,):
Why does nn.Linear(20, 64) still work when you pass batched tensors shaped (32, 20) where each example sits horizontally as a row instead of a column? Under the hood, PyTorch computes X @ W.T + b. Transposing W (W.T) flips (64, 20) into (20, 64), so (32, 20) @ (20, 64) matches along 20 and returns (32, 64). The 1D bias vector b of shape (64,) is automatically broadcast (copied virtually across all 32 rows) so b_j is added to column j of every example. Even with batched execution, PyTorch keeps W stored as (out_features, in_features). Note also that if you initialize a layer with bias=False, no bias tensor is created at all, leaving only the (d_out, d_in) weight matrix:
Counting trainable parameters from layer shapes
In PyTorch, a trainable parameter is a stored tensor marked for optimization (requires_grad=True by default on nn.Linear), meaning gradient descent updates its numbers during training. Once you see W as a d_out x d_in grid plus a d_out-element bias vector, counting parameters is pure rectangle arithmetic:
- First linear layer
nn.Linear(20, 64): its64 x 20weight grid stores64 * 20 = 1,280weights, and its bias vector adds64offsets, totaling1,344trainable parameters. - Activation
nn.ReLU(): computesmax(0, z)with a fixed threshold at zero. Because it holds no learned weights or offsets, it stores0parameters. - Second linear layer
nn.Linear(64, 10): maps64hidden values to10class scores using a(10, 64)weight grid (640weights) plus10biases, giving650parameters.
Summing the layers (1,344 + 0 + 650) reveals 1,994 trainable parameters in total. Writing the dimensions symbolically as d_in inputs and d_out outputs yields the general rule for any linear layer with bias:
Why does parameter count matter operationally? Because parameters set the model's stored memory footprint. Each standard 32-bit float (float32) takes 4 bytes. For our tiny 1,994-parameter network, storing the weights takes 1,994 * 4 = 7,976 bytes (about 8 KB). During training, memory grows multiple times larger because each parameter also needs space for its computed gradient (+4 bytes in FP32) and optimizer tracking buffers, such as the running momentum and squared-gradient estimates kept by Adam (+8 bytes more per parameter in FP32, bringing parameter, gradient, and Adam state to 16 bytes per parameter, or 31,904 bytes before activations). At billion-parameter scale, those exact multipliers decide whether a model fits on a GPU:
Counting forward FLOPs per example and per batch
Knowing how many numbers a network stores does not tell you how much arithmetic it executes when processing inputs. To measure computation, we count floating-point operations (FLOPs) performed during a forward pass.
Trace a single output neuron inside nn.Linear(20, 64) step by step. Computing y[0] = W[0, 0]*x[0] + W[0, 1]*x[1] + ... + W[0, 19]*x[19] + b[0] takes 20 multiplications (W[0, j] * x[j]), 19 additions to fold those 20 products into one sum, and 1 final addition for the bias b[0]. Notice the exact cancellation: 20 + 19 + 1 = 40 = 2 * 20 FLOPs for one output value. Replacing 20 with d_in explains the clean factor of 2: d_in + (d_in - 1) + 1 = 2 * d_in operations per output neuron (and without bias, (2 * d_in - 1)).
Because the first layer computes 64 output neurons in parallel for every input example, one example costs 2 * 20 * 64 = 2,560 forward linear FLOPs. Notice that 2,560 is nearly double the layer's 1,344 parameters because every weight performs both a multiplication and participates in a sum. Applying the same formula to Linear(64, 10) adds 2 * 64 * 10 = 1,280 FLOPs, bringing one forward pass per example to 2,560 + 1,280 = 3,840 linear FLOPs.
In real training and inference, we group examples into a mini-batch of size B rather than feeding one item at a time. Passing B = 32 examples shaped (32, 20) runs (32, 20) @ (20, 64) -> (32, 64) followed by (32, 64) @ (64, 10) -> (32, 10). Each of the 32 examples executes the exact same linear arithmetic, so batch FLOPs scale linearly with B:
For B = 32, one forward pass executes 32 * 3,840 = 122,880 operations across both linear layers. That immediately raises a practical hardware question: if 32 examples execute 32 times the FLOPs, why do GPUs finish a batch of 32 so much faster than 32 sequential single-example calls? The answer is weight reuse. Loading 1,344 weights from chip memory into fast compute units is often slower than the math itself. In one dense matrix multiply (GEMM), the processor reads each weight once and applies it across all 32 rows simultaneously, turning memory-bound single-vector work into high-throughput parallel arithmetic.
Keep one scope reminder in mind as well: these numbers cover the forward pass only (inference). During training, backpropagation reverses through each hidden linear layer using two extra matrix multiplications of matching cost, one to compute gradients with respect to the inputs ((B, d_out) @ (d_out, d_in)) and one for the weights ((d_out, B) @ (B, d_in)), multiplying total linear arithmetic by roughly 2 to 3 times forward FLOPs.
| Layer | Weight shape | Bias shape | Parameters | Forward FLOPs (per example) |
|---|---|---|---|---|
nn.Linear(20, 64) | (64, 20) | (64,) | 1,344 | 2,560 |
nn.ReLU() | none | none | 0 | omitted (64 max ops) |
nn.Linear(64, 10) | (10, 64) | (10,) | 650 | 1,280 |
| Total model | 1,994 | 3,840 |
Model size vs. computational work
Separating parameters from FLOPs clears up a persistent systems mistake: parameters measure how much state a model stores, whereas FLOPs measure how much arithmetic a pass performs. Both numbers follow from the layer dimensions (20, 64, 10), yet they behave independently whenever an architecture reuses weights across inputs:
- Batching: raising
Bfrom1to128keeps parameters pinned at1,994, while forward compute grows128-fold because every example reuses the same weights. - Shared layers across tokens or pixels: applying the same dense projection across every token in a
1,000-token sequence (as inside a Transformer) or sliding one convolutional filter across a high-resolution image multiplies FLOPs without adding a single parameter. - Embedding lookup tables: a large language model's vocabulary table stores millions of parameters (
vocab_size * d_model), yet fetching one row vector for each token executes virtually zero FLOPs.
Computed for Linear(20, 64) -> ReLU -> Linear(64, 10)
Increasing batch size from 1 to 128 leaves parameter count flat at 1.99K while scaling forward arithmetic from 3.84K to 491.52K FLOPs.
| batch size (B) | Parameters (K) | Forward FLOPs (K) |
|---|---|---|
| B = 1 | 1.99 | 3.84 |
| B = 8 | 1.99 | 30.72 |
| B = 16 | 1.99 | 61.44 |
| B = 32 | 1.99 | 122.88 |
| B = 64 | 1.99 | 245.76 |
| B = 128 | 1.99 | 491.52 |
Widening the hidden layer from 64 to 128
Put the shape rules to work with a prediction check before calculating. Suppose you double the hidden layer width from 64 to 128, turning the network into Linear(20, 128) -> ReLU -> Linear(128, 10). Does the total parameter count double from 1,994 to 3,988?
It does not. Changing the hidden width affects two layers unevenly. Layer 1 (Linear(20, 128)) has 128 outputs instead of 64, so both its weights (128 * 20 = 2,560) and its biases (128) double cleanly to 2,688 (2 * 1,344). Layer 2 (Linear(128, 10)), however, keeps the exact same 10 class outputs while accepting 128 inputs instead of 64. Its weight grid doubles from 640 to 1,280, yet its bias vector stays fixed at 10, giving 1,290 parameters instead of 1,300.
Adding both layers gives 2,688 + 1,290 = 3,978 parameters (10 fewer than 3,988). Forward linear FLOPs do double (5,120 + 2,560 = 7,680 per example) because 2 * d_in * d_out already accounts for one bias add per output rather than counting bias tensors separately, and the internal hidden vector doubles from 64 to 128 numbers. One final caveat matters just as much: giving a network 3,978 parameters instead of 1,994 increases capacity, not accuracy. Only training and measuring on held-out validation data reveals whether wider layers actually help or simply overfit:
| Quantity | Hidden = 64 | Hidden = 128 | Change |
|---|---|---|---|
| Layer 1 parameters | 1,344 | 2,688 | 2.00x (weights and biases double) |
| Layer 2 parameters | 650 | 1,290 | weights double, 10 biases unchanged |
| Total parameters | 1,994 | 3,978 | 10 fewer than 3,988 |
| Forward FLOPs (per example) | 3,840 | 7,680 | 2.00x |
| Forward FLOPs (batch of 32) | 122,880 | 245,760 | 2.00x |
| Hidden representation size | 64 | 128 | 2.00x |
In PyTorch, you can confirm exact parameter counts directly from instantiated tensors in one expression. Calling model.parameters() yields every trainable weight and bias tensor across the sequential layers, and calling .numel() (number of elements) multiplies each tensor's shape dimensions (64 * 20 = 1,280, 64, 10 * 64 = 640, 10) before sum(...) totals them:
import torch.nn as nnfor hidden in (64, 128):model = nn.Sequential(nn.Linear(20, hidden),nn.ReLU(),nn.Linear(hidden, 10),)total = sum(p.numel() for p in model.parameters())print(f"hidden={hidden}: layer0={tuple(model[0].weight.shape)}, "f"layer2={tuple(model[2].weight.shape)}, total={total}")# Verified with PyTorch 2.9.1:# hidden=64: layer0=(64, 20), layer2=(10, 64), total=1994# hidden=128: layer0=(128, 20), layer2=(10, 128), total=3978
Below is a standalone pure-Python calculator that walks any list of layer widths (zip(dims, dims[1:]) pairs each layer's (d_in, d_out) automatically) and computes parameter counts, per-example FLOPs, and batch FLOPs. Try replacing [20, 128, 10] with the three-layer architecture [50, 128, 32, 4] (Layer 1: 6,528 params / 12,800 FLOPs, Layer 2: 4,128 params / 8,192 FLOPs, Layer 3: 132 params / 256 FLOPs, totaling 10,788 params and 21,248 FLOPs) or a Transformer feedforward block [768, 3072, 768] (4,722,432 params and 9,437,184 FLOPs per token):
def analyze_mlp(dims: list[int], batch_size: int = 32) -> None:total_params = 0total_flops = 0for idx, (d_in, d_out) in enumerate(zip(dims, dims[1:]), start=1):params = d_out * (d_in + 1)flops = 2 * d_in * d_outtotal_params += paramstotal_flops += flopsprint(f"Layer {idx} Linear({d_in}, {d_out}): "f"W=({d_out}, {d_in}), b=({d_out},) -> "f"{params:,} params, {flops:,} FLOPs/ex")print(f"Total params: {total_params:,}")print(f"FLOPs / example: {total_flops:,}")print(f"Batch ({batch_size}) FLOPs: {batch_size * total_flops:,}")print("=== Baseline MLP ===")analyze_mlp([20, 64, 10], batch_size=32)print("\n=== Widened hidden layer (try changing dims) ===")analyze_mlp([20, 128, 10], batch_size=32)
Where universal approximation falls short
Return now to our opening question: if one wide hidden layer can represent continuous functions arbitrarily closely, why do real models stack depth instead? Because representable in theory tells you nothing about three engineering realities:
- Representable is not efficiently learnable: gradient-based optimizers have to discover useful weights from finite batches of noisy examples, and flat ultra-wide layers often need far more units or steps to converge cleanly than structured deep stacks.
- Learnable is not generalizing well: generalization means performing accurately on unseen examples outside the training data. A giant shallow layer with abundant piecewise bends can memorize idiosyncratic training noise (overfitting) instead of learning shared structure.
- Generalizing is not production-efficient: real networks stack layers sequentially so later transformations reuse intermediate features built by earlier ones. Breaking a task into composed stages can achieve rich expressive power with dramatically fewer parameters, less memory, and lower FLOPs than one massive hidden layer.
Once this shape-first accounting becomes automatic, larger architectures stop looking opaque. Whether you inspect a small MLP or nn.Linear(768, 3072) inside a Transformer block, you can derive tensor dimensions, stored parameters, memory multipliers, and forward arithmetic straight from the layer definitions.
Brain Link on YouTube
How to Calculate Neural Network Parameters and FLOPs
Watch the full animated Brain Link episode covering universal approximation fits, the 64 by 20 grid, FLOPs counting per neuron and batch, and widening from 64 to 128.
Notice one piece in the middle of our 1,994-parameter network that added 0 trainable weights and only minimal comparisons next to dense matrix multiplies, yet prevented every Linear layer from collapsing into one linear transformation: nn.ReLU(). Because activations sit at the exact boundary between linear collapse and stable training, choosing which activation function to use turns out to matter enormously. In Part 3 of this series, we compare sigmoid, tanh, ReLU, and Leaky ReLU through their slopes and see why gradients either vanish or survive across depth.
References
- [1]Approximation by superpositions of a sigmoidal function · George Cybenko, Mathematics of Control, Signals, and Systems (1989)Foundational universal approximation theorem for single-hidden-layer feedforward networks.
- [2]Deep Feedforward Networks (Chapter 6, Deep Learning) · Ian Goodfellow, Yoshua Bengio, and Aaron CourvilleCovers universal approximation properties, depth vs. width, and piecewise-linear activations.
- [3]torch.nn.Linear documentation · PyTorch documentationSpecifies weight shape (out_features, in_features) and bias shape (out_features).
- [4]torch.nn.ReLU documentation · PyTorch documentationFixed element-wise max(0, x) nonlinearity with zero learnable parameters.
- [5]torch.Tensor.numel documentation · PyTorch documentationReturns the total element count used when summing model parameter tensors.
- [6]How to Calculate Neural Network Parameters and FLOPs (video) · Brain Link on YouTube
- [7]Deep Learning Fundamentals playlist · Brain Link on YouTube







