Sub topic 3
Neural network basics: layers, weights, and learning
This chapter assumes you can read basic Python and NumPy, multiply matrices, and know what a probability distribution is. It covers the parts of neural networks that the rest of the tutorial reuses: layers, weights, nonlinearities, loss, and gradient descent.
A layer is a matrix multiply plus a bend
A neural network is a function built from simple steps. Each step is a layer. A linear layer takes a vector x and computes:
z = x @ W + b
W is a weight matrix and b is a bias vector. Together they are the layer's parameters. Parameters are the numbers the model learns. A language model with 7 billion parameters has 7 billion such numbers spread across its matrices.
Stacking only linear layers gains nothing. Two matrix multiplies in a row equal one bigger matrix multiply. A nonlinearity between layers fixes this. It is a function applied to each element, such as tanh or ReLU (max(0, z)). With nonlinearities, a stack of layers can represent curved, complicated functions.
Transformers use this pattern inside every block. The feed-forward part of a block is a linear layer, a nonlinearity, and another linear layer.
Learning: loss and gradients
Learning means adjusting parameters so the network's outputs match the data. Three pieces make that work:
- Forward pass. Run the input through the layers to get a prediction.
- Loss. A single number that says how wrong the prediction is. Lower is better.
- Gradient. For each parameter, the direction in which the loss increases. Backpropagation computes all gradients by applying the chain rule backward through the layers.
Gradient descent then moves each parameter a small step against its gradient: w = w - lr * grad. The learning rate lr sets the step size.
A complete example
This network learns XOR, a function that a single linear layer cannot represent. The gradients are written by hand so each step is visible.
import numpy as np
rng = np.random.default_rng(0)
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=float)
y = np.array([[0], [1], [1], [0]], dtype=float)
W1 = rng.normal(size=(2, 8))
b1 = np.zeros(8)
W2 = rng.normal(size=(8, 1))
b2 = np.zeros(1)
lr = 0.2
def forward(X):
h = np.tanh(X @ W1 + b1)
return h, h @ W2 + b2
for step in range(3001):
h, pred = forward(X)
loss = ((pred - y) ** 2).mean()
if step % 1000 == 0:
print(step, round(float(loss), 4))
dpred = 2 * (pred - y) / len(X) # d loss / d pred
dW2 = h.T @ dpred
db2 = dpred.sum(axis=0)
dz = (dpred @ W2.T) * (1 - h ** 2) # tanh' = 1 - tanh^2
dW1 = X.T @ dz
db1 = dz.sum(axis=0)
W1 -= lr * dW1
b1 -= lr * db1
W2 -= lr * dW2
b2 -= lr * db2
print(np.round(forward(X)[1], 2))The printed loss should drop across the checkpoints. The final predictions should land near 0, 1, 1, 0. Exact values depend on the random seed.
Notice that every gradient has the same shape as its parameter. dW1 is (2, 8), like W1. If a shape does not match, the backward pass has a bug.
Common errors
| Symptom | Likely cause |
|---|---|
| Loss becomes `nan` or grows without bound | Learning rate too high |
| Loss barely moves | Learning rate too low, or no nonlinearity |
| Loss falls on training data but not on new data | Overfitting: the model memorized examples |
| Shape errors in the backward pass | Gradient does not match its parameter's shape |
Why this matters for language models
An LLM is a very large version of this loop. The input is token vectors. The loss is a measure of how badly the model predicted the next token (later chapters cover it). The update rule is gradient descent, usually in a refined form, applied to billions of parameters.
Exercise
In the XOR example, what would change if you removed the np.tanh call so that h = X @ W1 + b1? Could the network still learn XOR?
Show answer
The two layers would collapse into one linear map, because (X @ W1) @ W2 equals X @ (W1 @ W2). A single linear function cannot represent XOR, so the loss would stall at a high value. The nonlinearity is what lets the hidden layer bend the input space.