Sub topic 3
Neural network basics: layers, weights, and learning
A large language model is a neural network with billions of adjustable numbers. Later chapters cover its specific parts: embeddings, attention, and the transformer block. This chapter covers the general machinery those parts are built from. That machinery is layers, weights, nonlinearities, a loss, and gradient descent.
This chapter assumes you can read basic Python and NumPy. It also assumes you are comfortable with vectors and matrix multiplication, and know what a derivative is.
A layer is a matrix multiply plus a bias
The basic building block is the linear layer. It takes an input vector x and returns
y = x @ W + bW is a matrix of weights and b is a vector of biases. Together they are the layer's parameters: numbers that training adjusts. If x has 2 entries and W has shape (2, 8), the output has 8 entries. Each output entry is a weighted sum of all the inputs, plus a bias.
In practice you process many examples at once. Stack them into a matrix X of shape (batch, features) and compute X @ W + b. NumPy broadcasting adds b to every row. Transformers work the same way, except the "batch" rows are the token positions in a sequence.
Why nonlinearity is required
Stacking linear layers alone gains nothing. Two linear layers collapse into one:
import numpy as np
rng = np.random.default_rng(1)
x = rng.normal(size=(5, 3))
W1 = rng.normal(size=(3, 4))
W2 = rng.normal(size=(4, 2))
two_layers = (x @ W1) @ W2
one_layer = x @ (W1 @ W2)
print(np.allclose(two_layers, one_layer))This prints True. The product W1 @ W2 is itself a single matrix, so the two-layer model can only represent what one layer could.
To get more expressive power, put a nonlinear activation function between layers. Common choices:
| Activation | Formula | Typical use |
|---|---|---|
| ReLU | `max(0, z)` | Simple and fast, common in older and smaller networks |
| tanh | `(e^z - e^-z) / (e^z + e^-z)` | Squashes values into (-1, 1) |
| sigmoid | `1 / (1 + e^-z)` | Squashes values into (0, 1), used for binary probabilities |
| GELU | smooth variant of ReLU | Common in transformer feed-forward layers |
A network of the form activation(x @ W1 + b1) @ W2 + b2 is a multilayer perceptron (MLP). The layers between input and output are called hidden layers. Each transformer block contains an MLP like this one, which a later chapter covers.
The forward pass, the loss, and the backward pass
Training repeats a cycle with three steps.
- Forward pass. Run the input through the layers to get a prediction.
- Loss. Compare the prediction to the target with a loss function, a single number that is small when the prediction is good.
- Backward pass. Compute the gradient of the loss with respect to every parameter, then nudge each parameter in the direction that lowers the loss.
The gradient of the loss with respect to a weight tells you how much the loss changes if you increase that weight slightly. Gradient descent updates each weight by a small step against its gradient:
w = w - learning_rate * dLoss/dwThe learning rate sets the step size. If it is too large, the loss oscillates or diverges. If it is too small, training is slow.
Backpropagation
Backpropagation computes all the gradients efficiently with the chain rule. For a chain of operations loss = f(g(h(w))), the derivative with respect to w is the product of each step's local derivative. The backward pass walks the chain in reverse and reuses the intermediate values saved during the forward pass. This costs about as much as one more forward pass, however many parameters there are. That efficiency is why networks with billions of parameters are trainable at all.
In practice, you do not write backpropagation by hand. Frameworks such as PyTorch and JAX do it automatically, a technique called automatic differentiation. Writing it once for a tiny network is still the best way to see what the framework does.
A complete example: learning XOR
XOR outputs 1 when exactly one of its two inputs is 1. No single linear layer can compute it, but a network with one hidden layer can. The script below trains one with plain NumPy.
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)
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
lr = 0.5
for step in range(5001):
# Forward pass
h = np.tanh(X @ W1 + b1)
p = sigmoid(h @ W2 + b2)
loss = -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))
# Backward pass
dz2 = (p - y) / len(X) # gradient of the loss w.r.t. the output logit
dW2 = h.T @ dz2
db2 = dz2.sum(axis=0)
dh = dz2 @ W2.T
dz1 = dh * (1 - h ** 2) # derivative of tanh
dW1 = X.T @ dz1
db1 = dz1.sum(axis=0)
# Gradient descent update
W1 -= lr * dW1
b1 -= lr * db1
W2 -= lr * dW2
b2 -= lr * db2
if step % 1000 == 0:
print(step, round(float(loss), 4))
print(np.round(p.ravel(), 2))The loss falls steadily over the run, and the final predictions come out close to [0, 1, 1, 0]. Exact digits depend on the random initialization.
A few points in the code matter beyond XOR:
dz2 = (p - y) / len(X)is a neat result. When a sigmoid output is paired with binary cross-entropy loss, the gradient with respect to the pre-sigmoid value is just prediction minus target. The softmax output layer of a language model has the same property, which is why cross-entropy and softmax are paired.- Each gradient has the same shape as its parameter, so
dW1matchesW1. A shape mismatch is the most common sign of a backpropagation bug. - The division by
len(X)comes from averaging the loss over the batch.
Initialization, depth, and common failure modes
Several practical issues come up as soon as networks get deeper.
- Initialization scale matters. If initial weights are too large, activations and gradients grow as they pass through layers. If they are too small, they shrink toward zero. Schemes such as Xavier and He initialization choose the scale from the layer's input and output sizes. The
rng.normal(size=...)call above is fine for a tiny network but is not what large models use. - Vanishing and exploding gradients. In the backward pass, the chain rule multiplies many numbers together. If they are mostly below 1, the gradient reaching early layers shrinks to nothing. If they are mostly above 1, it blows up. Saturating activations such as sigmoid and tanh make vanishing worse, because their derivatives are near 0 for large inputs.
- Learning rate too high. The loss jumps around or becomes
nan. Lower the rate, or clip gradients to a maximum norm, which large-model training does routinely. - Overfitting. The network memorizes the training examples and does worse on new data. You detect it by tracking loss on held-out data. More data, regularization such as dropout, and early stopping all reduce it.
- Local minima and plateaus. The loss surface of a large network is not convex. In practice, gradient descent still finds good solutions, and flat regions slow training more than true dead ends do.
Two techniques address depth directly, and both reappear in the transformer block. Residual connections add a layer's input to its output (x + layer(x)), giving gradients a direct path backward. Normalization layers rescale activations to keep them in a stable range.
How this connects to language models
Everything above carries over to LLMs with a change of scale and some structure.
- Parameters. A model described as "7B" has about seven billion weights and biases. Most sit in matrices like
W1andW2above, plus embedding and attention matrices. - Loss. Binary cross-entropy becomes cross-entropy over the whole vocabulary. The prediction is a probability for each possible next token, and the target is the token that actually came next.
- Training loop. It is the same cycle: forward pass, loss, backpropagation, and an Adam update. It runs on batches of text across many accelerators.
- Feed-forward layers. Each transformer block applies an MLP to every token position independently. It uses the same structure as the XOR network, with much wider hidden layers.
- What is learned. Nobody programs any rule into the weights. Gradient descent adjusts them until predictions improve, and whatever structure helps prediction ends up encoded there.
The next chapter looks at the first part specific to language: how token IDs become vectors that this machinery can process.
Exercise
In the XOR script, suppose you remove the np.tanh call so that h = X @ W1 + b1. The sigmoid at the output stays. Can the network still learn XOR? Explain why or why not.
Show answer
No. Without the tanh, the hidden layer and output layer are both linear, so together they compute X @ (W1 @ W2) + (b1 @ W2 + b2), which is a single linear function of the input. The sigmoid is monotonic, so the decision boundary is still a straight line. No straight line separates the XOR points (0,1) and (1,0) from (0,0) and (1,1), so the loss would stall around 0.69 (the cross-entropy of predicting 0.5 everywhere) and the predictions would not match the targets.
Exercise
A network's training loss reaches 0.02, but its loss on held-out data is 1.4. Name the likely problem, and give two changes that could help.
Show answer
The network is overfitting: it has memorized the training examples instead of learning patterns that generalize. Helpful changes include adding more training data, adding regularization such as dropout or weight decay, reducing the model size, and stopping training earlier based on the held-out loss.