from_scratch.llm
Foundation
00

A neural network

forward pass + backprop, learning XOR
steps/01_foundation/00_neural_network.py ► Open as notebook (with output)

Every LLM is, at bottom, a neural network trained by gradient descent. So we start at the true atom: a two-layer net that learns XOR — the classic problem a single linear layer cannot solve.

It contains the three ideas that never leave: a forward pass (predict), a loss (measure wrongness), and backpropagation (nudge every weight downhill). Written in pure NumPy so nothing hides.

a = σ(W·x + b) · σ′(z) = σ(z)(1 − σ(z)) · w ← w − η ∂L/∂wa neuron: weighted sum → nonlinearity; trained by gradient descent on the loss.
The theory

A neuron computes a weighted sum of its inputs and passes it through a nonlinear activation. Stacking a hidden layer of these between input and output makes the network a universal function approximator — with enough hidden units it can represent any continuous function. The nonlinearity is essential: without it, stacked linear layers collapse into a single linear map.

Learning means minimizing a loss (here, mean-squared error) by gradient descent. Backpropagation is just the chain rule applied in reverse: compute how the loss depends on each weight, layer by layer from output back to input, then nudge every weight a small step against its gradient. XOR is the canonical test because it is not linearly separable — a single layer cannot solve it, but a hidden layer learns the intermediate features that can.

Animation
Visual walkthrough
Four glowing XOR corner points with crossed class structure.
XOR cornersThe matching labels sit on opposite corners, so one straight split cannot solve the task.
Small neural network bending input signals through a hidden layer.
Hidden featuresA hidden layer bends the input space into features a final neuron can separate.
Output neuron receiving weighted hidden signals and resolving binary predictions.
Output predictionForward pass, loss, and backprop nudge the weights until the XOR outputs are correct.
The notebook · steps/01_foundation/00_neural_network.ipynb — code cells & their output. Open & run on GitHub →
In [1]
import numpy as np


def sigmoid(x):
    """Squashes any number into the range (0, 1) — our activation function."""
    return 1 / (1 + np.exp(-x))


def sigmoid_derivative(out):
    """Gradient of sigmoid, expressed in terms of its OUTPUT (out = sigmoid(x))."""
    return out * (1 - out)


class NeuralNetwork:
    """A 2-layer feedforward net: input -> hidden -> output."""

    def __init__(self, n_inputs, n_hidden, n_outputs, seed=42):
        rng = np.random.default_rng(seed)
        # Weights are small random values; biases start at zero.
        # W1 connects inputs -> hidden, W2 connects hidden -> output.
        self.W1 = rng.normal(size=(n_inputs, n_hidden))
        self.b1 = np.zeros((1, n_hidden))
        self.W2 = rng.normal(size=(n_hidden, n_outputs))
        self.b2 = np.zeros((1, n_outputs))

    def forward(self, X):
        """Push inputs through the network to get a prediction."""
        self.z1 = X @ self.W1 + self.b1     # weighted sum into hidden layer
        self.a1 = sigmoid(self.z1)          # hidden layer activations
        self.z2 = self.a1 @ self.W2 + self.b2  # weighted sum into output
        self.a2 = sigmoid(self.z2)          # final prediction
        return self.a2

    def train(self, X, y, epochs=10000, lr=0.5):
        """Learn the weights via gradient descent + backpropagation."""
        for epoch in range(epochs):
            # --- Forward pass: compute predictions ---
            pred = self.forward(X)

            # --- Loss: mean squared error (how wrong we are) ---
            loss = np.mean((y - pred) ** 2)

            # --- Backward pass: how should each weight change? ---
            # Chain rule from the loss back to every parameter.
            d_pred = (pred - y) * sigmoid_derivative(self.a2)   # error at output
            d_W2 = self.a1.T @ d_pred
            d_b2 = np.sum(d_pred, axis=0, keepdims=True)

            d_hidden = (d_pred @ self.W2.T) * sigmoid_derivative(self.a1)  # error at hidden
            d_W1 = X.T @ d_hidden
            d_b1 = np.sum(d_hidden, axis=0, keepdims=True)

            # --- Gradient descent: nudge weights opposite the gradient ---
            self.W2 -= lr * d_W2
            self.b2 -= lr * d_b2
            self.W1 -= lr * d_W1
            self.b1 -= lr * d_b1

            if epoch % 1000 == 0:
                print(f"epoch {epoch:5d}  loss {loss:.4f}")
In [2]
# The 4 XOR examples: output is 1 only when inputs differ.
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([[0], [1], [1], [0]])

net = NeuralNetwork(n_inputs=2, n_hidden=4, n_outputs=1)
net.train(X, y)

print("\nFinal predictions:")
for inputs, prediction in zip(X, net.forward(X)):
    print(f"  {inputs} -> {prediction[0]:.3f}  (rounded: {round(prediction[0])})")
Output
epoch     0  loss 0.2775
epoch  1000  loss 0.0149
epoch  2000  loss 0.0025
epoch  3000  loss 0.0012
epoch  4000  loss 0.0008
epoch  5000  loss 0.0006
epoch  6000  loss 0.0004
epoch  7000  loss 0.0004
epoch  8000  loss 0.0003
epoch  9000  loss 0.0003

Final predictions:
  [0 0] -> 0.009  (rounded: 0)
  [0 1] -> 0.984  (rounded: 1)
  [1 0] -> 0.986  (rounded: 1)
  [1 1] -> 0.019  (rounded: 0)