Neural Network Basics: From Linear Layers to Backpropagation
A neural network chains linear maps and nonlinearities. Backpropagation (the chain rule) gives the loss gradient for every parameter, and training steps against it. This page builds a two-layer net in NumPy, checks its gradients, and runs learning-rate and initialization experiments.
After this page you will be able to
- Name the basic parts of a neural network (linear layers, nonlinear activations, the loss) and where each one appears inside an LLM.
- Explain why stacking linear layers without a nonlinearity collapses to a single layer, and verify it on XOR.
- Derive backpropagation for a two-layer network, remember that softmax plus cross-entropy has gradient p − y with respect to the logits, and check gradients with finite differences and autograd.
- Use learning-rate and initialization experiments to explain why training diverges and why activations explode or vanish.
On this page
- Why an LLM course starts here
- One neuron and one layer
- Why a nonlinearity is mandatory
- The loss: what training minimizes
- Backpropagation: bookkeeping along the graph, backwards
- Gradient descent and the learning rate
- Initialization: keeping the signal moving
- Summary and exercises
- Quick self-test
- Further reading
- FAQ
A neural network is a differentiable function built by stacking “linear map plus nonlinearity” over and over. Training repeats three steps: a forward pass computes the loss, backpropagation applies the chain rule to get the gradient of the loss for every parameter, and each parameter moves a small step against its gradient. A Transformer does not replace this machinery. It makes it very large and very deep and adds three new parts: attention, residual connections and normalization.
If you are new to this topic, start with Python and tensor shapes.
Why an LLM course starts here
Almost every line of a Transformer formula is one of the parts on this page. If you already know deep learning, read only the table below and then the learning-rate and initialization experiments.
| Part on this page | Where it shows up in an LLM | Where this site covers it |
|---|---|---|
| Linear layer | The Q, K, V and O projections of attention, the two matrices of the feed-forward network, the output layer | Transformer Block |
| Nonlinear activation | GELU or SwiGLU in the feed-forward network | Modern LLM Architecture |
| Softmax plus cross-entropy | Next-token prediction and the training loss | Language Modeling, Information Theory Refresher |
| Backpropagation plus gradient descent | The core training loop; AdamW is its improved version | Optimizers and Training Stability |
| Initialization | Decides whether signals and gradients survive the trip through many layers | Transformer Block |
All code on this page is one script cut into pieces. It ran in a single process, from top to bottom, and each output is pasted right after its piece. Environment: CPU of an Apple M2 Max, Python 3.14, NumPy 2.4 and PyTorch 2.10 (used once, to check gradients). Seeds are fixed, but the last digits may differ on another machine.
One neuron and one layer
A neuron takes a weighted sum of the input vector , adds a bias , and passes the result through a nonlinear function :
Put neurons side by side and you get a layer, , where the weight matrix has shape and each row holds one neuron’s weights. The part without , , is a linear layer (nn.Linear in PyTorch) with parameters. Stack such layers one after another and you have a multilayer perceptron (MLP).
Why a nonlinearity is mandatory
Start with an experiment: is two linear layers in a row stronger than one?
import numpy as np
import torch
import torch.nn.functional as F
rng = np.random.default_rng(0)
W1, W2 = rng.normal(size=(4, 3)), rng.normal(size=(2, 4))
x = rng.normal(size=3)
gap = np.abs(W2 @ (W1 @ x) - (W2 @ W1) @ x).max()
print(f"two linear maps vs. the merged matrix W2·W1: max difference {gap:.1e}")
two linear maps vs. the merged matrix W2·W1: max difference 1.1e-16
The difference is floating-point rounding at the level. The reason is plain: , and a product of two matrices is again a matrix. Without a nonlinearity, any number of layers is equivalent to one layer, so the network can only represent linear functions. An activation function cuts the layers apart so that stacking means something:
| Activation | Formula | Property | Where you meet it |
|---|---|---|---|
| ReLU | Simplest; gradient is exactly 0 for negative inputs | Early deep networks, vision models | |
| tanh | Output in , saturates at both ends | The examples on this page, recurrent networks | |
| GELU | ( is the standard normal CDF) | A smooth ReLU | GPT-2, BERT |
| SiLU | ( is the sigmoid) | Smooth and non-monotonic | The gate branch of SwiGLU in Llama-style models |
The classic example is XOR: the inputs and have label 0, the inputs and have label 1, and no straight line separates the two classes. Below we train a model without a hidden layer (equivalent to logistic regression) and a two-layer network with a tanh hidden layer, each configuration once for each of 10 random seeds:
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=float)
y = np.array([0, 1, 1, 0], dtype=float)
sigmoid = lambda z: 1 / (1 + np.exp(-z))
def fit(hidden, seed, steps=4000, lr=0.5):
r = np.random.default_rng(seed)
if hidden: # with a hidden layer: tanh
W1, b1 = r.normal(size=(2, hidden)), np.zeros(hidden)
W2, b2 = r.normal(size=(hidden, 1)), np.zeros(1)
else: # no hidden layer: logistic reg.
W2, b2 = r.normal(size=(2, 1)), np.zeros(1)
for _ in range(steps):
a = np.tanh(X @ W1 + b1) if hidden else X
p = sigmoid(a @ W2 + b2).ravel()
d2 = ((p - y) / len(y))[:, None] # sigmoid + cross-entropy: p - y
if hidden:
d1 = (d2 @ W2.T) * (1 - a ** 2)
W1 -= lr * X.T @ d1
b1 -= lr * d1.sum(0)
W2 -= lr * a.T @ d2
b2 -= lr * d2.sum(0)
a = np.tanh(X @ W1 + b1) if hidden else X
p = sigmoid(a @ W2 + b2).ravel()
loss = -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))
return loss, ((p > 0.5) == y).all()
for hidden in (0, 2, 4):
runs = [fit(hidden, s) for s in range(10)]
mean = np.mean([loss for loss, _ in runs])
solved = sum(ok for _, ok in runs)
print(f"{hidden} hidden units: mean loss {mean:.4f}, "
f"{solved} of 10 seeds get all 4 points right")
0 hidden units: mean loss 0.6931, 0 of 10 seeds get all 4 points right
2 hidden units: mean loss 0.1744, 5 of 10 seeds get all 4 points right
4 hidden units: mean loss 0.0357, 9 of 10 seeds get all 4 points right
Without a hidden layer the loss sticks at , which means guessing 0.5 for every point; a hidden layer is what makes the classes separable. With few hidden units training is not reliable: with 2 units only half of the seeds succeed, with 4 units 9 of 10 do, and more units succeed more often. This tiny experiment cannot tell whether the cause is too little capacity or hard optimization; we meet the same pattern again in the moons experiment below.
The universal approximation theorem states that a network with one hidden layer that is wide enough can approximate any continuous function on a bounded region to any accuracy (Cybenko 1989 proved it for sigmoid-type activations, Hornik 1991 extended it to more general activations). It only guarantees that suitable parameters exist. It does not say how wide the layer must be, nor that gradient descent will find them. In practice we use deep, well-structured networks instead of one infinitely wide layer.
The loss: what training minimizes
A loss function compresses “how wrong is the model right now” into one number. Regression often uses the mean squared error; classification, including next-token prediction, uses softmax plus cross-entropy. Let the outputs of the last layer (the logits) be and the true class be :
Differentiate with respect to : the first term contributes only when , and the derivative of the second term is exactly the softmax:
The gradient of softmax plus cross-entropy with respect to the logits is “the predicted probability minus the one-hot label”. It is remarkably clean and it is where backpropagation starts. A language model sets the number of classes to the vocabulary size and to the true next token, so the initial gradient at every position of LLM training is this expression. For what the loss and perplexity mean, see Information Theory Refresher and Language Modeling.
Backpropagation: bookkeeping along the graph, backwards
Read the two-layer loss and backward pass
Training needs the gradient of the loss for every parameter. Backpropagation is not magic: the forward pass breaks the computation into simple steps, and the backward pass starts at the loss and walks back, multiplying at each step “the gradient coming from behind” by “this step’s own local derivative” and handing the product to the step in front.
In matrix form, the forward pass is:
and the backward pass (the loss is the mean over a batch, is the one-hot labels, is element-wise multiplication) is:
The gradient of a bias is the matching summed over the batch. Three rules let you write the backward pass of any network:
- A gradient has the same shape as its parameter. If the shapes do not match, something is wrong.
- Every step is “upstream gradient times local derivative”. For a matrix product the local derivatives are: multiply by for , and by for . For an element-wise function such as tanh, multiply element by element.
- Intermediate results from the forward pass are needed again backward (the dashed lines). This is why training needs so much more memory than inference: those cached activations must be kept until the backward pass, see the Compute and Memory Ledger.
Here are the formulas, written as code:
def init(d, h, k, seed):
r = np.random.default_rng(seed)
return {"W1": r.normal(size=(d, h)) * 0.5, "b1": np.zeros(h),
"W2": r.normal(size=(h, k)) * 0.5, "b2": np.zeros(k)}
def forward(P, X, y):
a1 = np.tanh(X @ P["W1"] + P["b1"])
z2 = a1 @ P["W2"] + P["b2"]
e = np.exp(z2 - z2.max(1, keepdims=True)) # subtract the max: stable
p = e / e.sum(1, keepdims=True)
return a1, p, -np.log(p[np.arange(len(y)), y]).mean()
def backward(P, X, y):
a1, p, _ = forward(P, X, y)
d2 = p.copy()
d2[np.arange(len(y)), y] -= 1 # p - onehot
d2 /= len(y)
d1 = (d2 @ P["W2"].T) * (1 - a1 ** 2) # pass back, times tanh'
return {"W1": X.T @ d1, "b1": d1.sum(0), "W2": a1.T @ d2, "b2": d2.sum(0)}
How do you know it is right? The standard tool is the gradient check: nudge each parameter a tiny amount, estimate its gradient with the central difference , and compare with the backpropagation result. We also compute the gradient once more with PyTorch autograd. Everything uses float64:
rng = np.random.default_rng(1)
Xs, ys = rng.normal(size=(5, 3)), rng.integers(0, 3, size=5)
P = init(3, 4, 3, seed=1)
grad = backward(P, Xs, ys)
def numeric(name, eps=1e-6): # central differences
g = np.zeros_like(P[name])
for i in np.ndindex(*P[name].shape):
old = P[name][i]
P[name][i] = old + eps
up = forward(P, Xs, ys)[2]
P[name][i] = old - eps
down = forward(P, Xs, ys)[2]
P[name][i] = old
g[i] = (up - down) / (2 * eps)
return g
T = {k: torch.tensor(v, requires_grad=True) for k, v in P.items()}
z2 = torch.tanh(torch.tensor(Xs) @ T["W1"] + T["b1"]) @ T["W2"] + T["b2"]
F.cross_entropy(z2, torch.tensor(ys)).backward()
for name in P:
g_num = numeric(name)
rel = np.abs(g_num - grad[name]).max() / np.abs(g_num).max()
auto = np.abs(T[name].grad.numpy() - grad[name]).max()
print(f"{name}: relative error vs finite differences {rel:.1e}, "
f"max diff vs autograd {auto:.1e}")
W1: relative error vs finite differences 1.5e-09, max diff vs autograd 1.4e-17
b1: relative error vs finite differences 1.5e-09, max diff vs autograd 2.1e-17
W2: relative error vs finite differences 1.2e-09, max diff vs autograd 2.9e-17
b2: relative error vs finite differences 6.2e-10, max diff vs autograd 5.6e-17
The relative error against finite differences is around , about the best a central difference can do given its truncation and rounding error, so the check passes. The difference to autograd is only around , plain float64 rounding. An autograd framework does the same thing, except that it records the graph and derives the local derivatives by itself. Once you have written the backward pass by hand, it becomes clear why gradients vanish and why memory must hold the activations.
The widget below turns that diagram into a ledger you can page through: one sample through a 2→2→3 network, where “Next” shows how every forward and backward number is multiplied out of the earlier ones — through tanh’s 1 − a₁² and back into the first layer, always reusing the activations cached by the forward pass — while the hand-written gradients are checked against central differences live, with relative errors of order 10⁻⁹ as above. Switch the preset to “Exercise 2” for the answer to exercise 2: p = (0.665, 0.245, 0.090), δ₂ = (−0.335, 0.245, 0.090).
Gradient descent and the learning rate
With the gradient in hand, gradient descent steps in the opposite direction:
is the learning rate. We use a two-dimensional moons dataset (two interlocking half-circles, 100 training points per class, noise standard deviation 0.2, and 2,000 independent test points) and train a 2→16→2 tanh network with full-batch gradient descent for 1000 steps, changing only the learning rate:
def moons(n, noise, rng):
t = rng.uniform(0, np.pi, n)
upper = np.c_[np.cos(t), np.sin(t)]
lower = np.c_[1 - np.cos(t), 0.5 - np.sin(t)]
X = np.r_[upper, lower] + rng.normal(scale=noise, size=(2 * n, 2))
return X, np.r_[np.zeros(n), np.ones(n)].astype(int)
rng = np.random.default_rng(0)
Xtr, ytr = moons(100, 0.2, rng)
Xte, yte = moons(1000, 0.2, rng)
def train(lr, hidden=16, steps=1000, seed=0):
P = init(2, hidden, 2, seed)
curve = []
for _ in range(steps):
g = backward(P, Xtr, ytr)
for k in P:
P[k] -= lr * g[k]
curve.append(forward(P, Xtr, ytr)[2])
acc = (forward(P, Xte, yte)[1].argmax(1) == yte).mean()
return curve, acc
print(f"loss before training {forward(init(2, 16, 2, 0), Xtr, ytr)[2]:.3f}")
for lr in (0.003, 0.03, 0.3, 3.0, 10.0, 30.0):
curve, acc = train(lr)
print(f"lr {lr:<6}: step 100 {curve[99]:.3f}, step 1000 "
f"{curve[-1]:.3f}, peak {max(curve):.3f}, test acc {acc:.3f}")
se = (0.96 * 0.04 / len(yte)) ** 0.5 # sampling std. error at 0.96
print(f"on {len(yte)} test points an accuracy of 0.96 has a standard "
f"error of about {se:.3f}")
loss before training 0.521
lr 0.003 : step 100 0.452, step 1000 0.334, peak 0.520, test acc 0.826
lr 0.03 : step 100 0.333, step 1000 0.290, peak 0.512, test acc 0.866
lr 0.3 : step 100 0.290, step 1000 0.071, peak 0.443, test acc 0.960
lr 3.0 : step 100 0.106, step 1000 0.032, peak 0.801, test acc 0.956
lr 10.0 : step 100 0.048, step 1000 0.037, peak 26.714, test acc 0.962
lr 30.0 : step 100 48.268, step 1000 18.527, peak 79.333, test acc 0.862
on 2000 test points an accuracy of 0.96 has a standard error of about 0.004
- Too small: slow. With a learning rate of 0.003 the loss falls only from 0.521 to 0.334 in 1000 steps, and the test accuracy is 0.826.
- Moderate: fastest. With 0.3 and 3.0 the loss after 1000 steps is 0.071 and 0.032, and the test accuracy is 0.960 and 0.956. The gap of 0.004 is about the sampling error of the test set (standard error about 0.004), so you cannot read it as “0.3 beats 3”.
- Unstable: spikes, then falls back. With a learning rate of 10 the training loss shot up to 26.714 at some point, yet after 1000 steps it was back at 0.037 with a test accuracy of 0.962. Loss spikes in LLM training have the same shape, although their causes are more complicated; see Optimizers and Training Stability.
- Larger still: possibly no way back. With 30 the loss at step 100 is 48.268, higher than before training (0.521), it is still 18.527 after 1000 steps, and the test accuracy drops to 0.862; whether it comes back depends on the initialisation (the widget below tries 16 initialisation seeds, and in about half the loss is still above 1 after 1000 steps). For a quadratic function, a learning rate above ( is the largest eigenvalue of the Hessian) always diverges. A neural network’s loss surface is not quadratic, which is why an in-between state of “spike, then recover” exists, but the intuition that the step cannot be arbitrarily large is the same.
This is full-batch gradient descent. Real LLM training uses mini-batches and AdamW, and the learning rate first warms up and then decays; those topics are in Optimizers and Training Stability.
Now the width of the network. Fix the learning rate at 0.3 and change only the number of hidden units:
for hidden in (1, 2, 4, 16, 64):
curve, acc = train(0.3, hidden)
print(f"{hidden:<3} hidden units: loss at step 1000 {curve[-1]:.3f}, "
f"test acc {acc:.3f}")
for hidden, steps in ((2, 20000), (4, 5000)): # more steps for small nets
curve, acc = train(0.3, hidden, steps)
print(f"{hidden:<3} hidden units: loss after {steps} steps "
f"{curve[-1]:.3f}, test acc {acc:.3f}")
1 hidden units: loss at step 1000 0.300, test acc 0.862
2 hidden units: loss at step 1000 0.298, test acc 0.862
4 hidden units: loss at step 1000 0.297, test acc 0.862
16 hidden units: loss at step 1000 0.071, test acc 0.960
64 hidden units: loss at step 1000 0.052, test acc 0.961
2 hidden units: loss after 20000 steps 0.270, test acc 0.834
4 hidden units: loss after 5000 steps 0.047, test acc 0.962
With 1, 2 or 4 hidden units the loss after 1000 steps sits near 0.3 and the test accuracy is the same 0.862; giving 2 units 20000 steps ends at a loss of 0.270 and a test accuracy of 0.834, no improvement. 4 units trained for 5000 steps reach a loss of 0.047 and a test accuracy of 0.962, and 16 units are enough within 1000 steps. This experiment, too, does not separate “not enough expressive power” from “slow optimization”. It only shows that in this setting a wider hidden layer trains better in the same number of steps.
Initialization: keeping the signal moving
Parameters cannot all start at 0 (neurons in a layer would stay identical forever), and their scale cannot be arbitrary either. The reason follows from a variance argument. For one layer with independent entries of of mean 0 and variance , and an input with components, the second moment of the output is about times that of the input (ReLU cuts away half). Every layer multiplies by this factor once, so with many layers the signal is amplified or shrunk exponentially. Setting the factor to 1 gives He initialization, (He et al., 2015, for ReLU). Xavier initialization uses (Glorot and Bengio, 2010, for tanh and linear units), which is when input and output have the same width. Below, a batch of random inputs goes through 30 ReLU layers of width 256, and we look at how large the final activations are:
def final_std(scale, depth=30, width=256, seed=0):
r = np.random.default_rng(seed)
a = r.normal(size=(512, width))
for _ in range(depth):
a = np.maximum(a @ (r.normal(size=(width, width)) * scale(width)), 0)
return a.std()
rules = {"N(0, 1)": lambda n: 1.0,
"N(0, 0.01²)": lambda n: 0.01,
"Xavier 1/√n": lambda n: np.sqrt(1 / n),
"He √(2/n)": lambda n: np.sqrt(2 / n)}
for name, rule in rules.items():
print(f"{name:>12}: activation std after 30 ReLU layers "
f"{final_std(rule):.3g}")
N(0, 1): activation std after 30 ReLU layers 4.92e+31
N(0, 0.01²): activation std after 30 ReLU layers 4.92e-29
Xavier 1/√n: activation std after 30 ReLU layers 3.7e-05
He √(2/n): activation std after 30 ReLU layers 1.21
- N(0, 1): each layer amplifies by about , so after 30 layers the activations have exploded to .
- N(0, 0.01²): each layer shrinks by a factor of about , so after 30 layers only is left. The first two rows share the same leading digits because ReLU satisfies : scaling every layer’s weights by 0.01 scales the output after 30 layers by .
- Xavier: too small for ReLU, each layer shrinks the signal by , which gives a result of order after 30 layers.
- He: the standard deviation of the activations stays near 1 (with some fluctuation: over 12 random seeds it ends between 0.50 and 1.21 after 30 layers).
On the backward pass the gradient is multiplied layer by layer by factors of the same magnitude, so an exploding forward pass goes with exploding gradients, and a vanishing forward pass with vanishing gradients (this page does not measure the gradients separately; it is the conclusion of the same argument). Real Transformers add normalization layers and residual connections as a safety net on top of initialization, and GPT-2 additionally scales the weights at the end of each residual branch by at initialization ( is the number of residual layers, Radford et al., 2019); see Transformer Block.
The widget below repeats both experiments in the browser: drag the learning rate, change the width and the initialisation seed and watch the loss curve and the decision boundary; then follow the activation standard deviation layer by layer under the four rules. It uses its own random numbers, and two things differ slightly from the page’s single runs, for the reasons given in its notes: a learning rate of 30 does not stay lost for every initialisation (about half of 16 seeds), and the standard deviation after 30 He layers also varies with the seed, between 0.5 and 1.2.
Summary and exercises
Key points:
- A neural network stacks “linear layer plus nonlinear activation”. Without the nonlinearity any number of layers equals one layer (experiment: on XOR the loss without a hidden layer sticks at ).
- The gradient of softmax plus cross-entropy with respect to the logits is ; backpropagation starts from it and multiplies by local derivatives layer by layer, and a gradient always has the shape of its parameter.
- A hand-written backward pass must be checked with finite differences; a relative error around passes, and autograd does the same thing.
- A learning rate that is too small converges slowly and one that is too large diverges; a poor initialization makes the activations after 30 layers explode to or vanish to , while He initialization keeps them near 1.21.
Quick self-test
1. You stack 10 linear layers with no activation function in between. What is the representational power of the network?
- Ten times that of one linear layer
- That of a single linear layer
- That of a two-layer network with ReLU
- It depends on the number of hidden units
W₁₀⋯W₁·x = (W₁₀⋯W₁)·x: a product of matrices is still one matrix. In the XOR experiment the model without a hidden layer sticks at a loss of ln 2, and only the tanh hidden layer separates the classes.
2. For softmax plus cross-entropy, what is the gradient of the loss with respect to the logit zᵢ?
- log pᵢ
- zᵢ − 1[i=y]
- pᵢ − 1[i=y]
- p_y − 1 (the same for every i)
L = −z_y + log Σⱼ exp(zⱼ), and its derivative with respect to zᵢ is −1[i=y] + pᵢ. The true class gets p_y − 1 (negative), every other class gets pᵢ (positive), and the components sum to 0.
3. When you write backpropagation by hand, what should the shape of the gradient ∂L/∂W₁ match?
- The input X
- W₁ itself
- The hidden activation a₁
- The loss (a scalar)
A gradient is the partial derivative of the loss with respect to each parameter, one number per parameter, so its shape must equal the parameter’s shape. If it does not, a formula or a transpose is wrong.
4. In the moons experiment, a learning rate of 30 gives a loss of 48.268 at step 100, higher than 0.521 before training, and it is still 18.527 after 1000 steps. What does this show?
- The model has too little capacity
- The data is too noisy
- The step is too large: every step jumps over the valley and training diverges
- The hidden layer is too narrow
With the same network and data, learning rates of 0.3 and 3.0 reach losses of 0.071 and 0.032 after 1000 steps, and only 30 fails to recover, so the problem is the step size, not the capacity or the data.
5. Why does He initialization for ReLU networks use variance 2/n instead of 1/n?
- Because the output of ReLU is always positive
- Because ReLU zeroes half of the inputs, which halves the second moment, so the variance is doubled to compensate
- Because 2/n is cheaper to compute
- Because the derivative of ReLU is 2
The second moment of a layer’s output is about nσ²/2 times that of its input, and setting it to 1 gives σ² = 2/n. In the experiment Xavier (1/n) is too small for ReLU and leaves only 3.7e-05 after 30 layers, while He stays at 1.21.
Exercises:
- How many parameters does a 784→128→10 two-layer network (with biases) have?
- The logits are and the true class is class 0. Compute the softmax output and the gradient of the loss with respect to the logits. What do the three components of the gradient sum to?
- In the moons experiment, the run with learning rate 10 shot up to a very high loss and then came back. Change the learning rate to 15 and to 20 and the number of steps to 5000, and watch the loss curve: at which steps do the spikes appear, and does the loss recover? And with 30?
Reference answers
- The first layer has parameters and the second , 101,770 in total (checked by the code above).
- The softmax is and the gradient is . The three components sum to 0: the softmax output sums to 1, the one-hot label also sums to 1, and their difference sums to 0. So the gradient only changes the logits relative to each other, and adding the same constant to all logits leaves the loss unchanged.
- There is no standard answer; the point is to observe it yourself, for example by storing the loss of every step in an array and plotting it. The table above gives a reference: with learning rate 10 the largest loss during training is 26.714 and the final loss falls back to 0.037; with 30 it is still 18.527 after 1000 steps. Whether a spike is followed by recovery depends on the learning rate, the initialization and the data, so do not draw a conclusion from a single run; try several random seeds.
Further reading
- Rumelhart, Hinton and Williams, Learning representations by back-propagating errors (Nature, 1986): the classic paper on training multilayer networks with backpropagation.
- Cybenko, Approximation by superpositions of a sigmoidal function (1989); Hornik, Approximation capabilities of multilayer feedforward networks (1991): the universal approximation theorem.
- Glorot and Bengio, Understanding the difficulty of training deep feedforward neural networks (2010); He et al., Delving Deep into Rectifiers (2015): Xavier and He initialization.
- Radford et al., Language Models are Unsupervised Multitask Learners (GPT-2, 2019): the initialization that scales residual-layer weights by .
- Karpathy, micrograd and the companion video The spelled-out intro to neural networks and backpropagation: automatic differentiation in about a hundred lines of Python, the best exercise for understanding backpropagation.
- Stanford CS231n, Backpropagation, Intuitions; 3Blue1Brown, the neural networks series; Dive into Deep Learning.
FAQ
- How are neural networks related to large language models?
- A large language model is one very large neural network. Its input is a sequence of integer token ids, which are looked up in an embedding table and then pass through dozens of Transformer blocks built from linear layers and nonlinear activations; a final linear layer plus softmax outputs the probability of the next token. It is trained with exactly the machinery on this page: a cross-entropy loss, backpropagation and gradient descent (in practice its improved version, AdamW).
- Why does training use backpropagation instead of computing gradients numerically?
- A numerical gradient needs two extra forward passes per parameter (central differences), so a model with N parameters needs 2N forward passes, which is 14 billion for a 7B model. Backpropagation gets the gradient of every parameter from one backward pass that costs about twice a forward pass, in line with the 6ND compute estimate. Numerical gradients are only good for checking that a backward pass is correct.
- What are vanishing and exploding gradients, and how do you fight them?
- In backpropagation the gradient is multiplied layer after layer by weight matrices and activation derivatives. With many layers this product shrinks exponentially (vanishing) or grows exponentially (exploding), so early layers stop learning or the parameters turn into NaN. Four kinds of remedies are common: a sound initialization (He or Xavier), normalization layers (LayerNorm, RMSNorm), residual connections, and gradient clipping. Transformers use all of them.
- How should I choose between ReLU, GELU and SiLU?
- In large models the differences are small and convention decides. GPT-2 and BERT use GELU, and Llama-style models use SwiGLU in the feed-forward network, whose gate branch is a SiLU. ReLU is the simplest and cheapest, but its gradient is exactly 0 for negative inputs; GELU and SiLU are smooth versions of it. Initialization and normalization usually matter more for whether training works than the choice of activation.