Level 7 · BuilderLesson 7.1 38 min read 10 question quiz 12 marks of written practice

Neural Networks: Layers, Matrices and the Forward Pass

From one neuron to a network

A neural network connects neurons in layers. Every neuron in one layer feeds every neuron in the next, which is called a fully connected or dense layer.

A multi-layer perceptronA neural network drawn left to right on four tinted, slightly tilted slabs. The input layer has 4 neurons for 4 features, two hidden layers have 6 neurons each using ReLU, and the output layer has 3 neurons with softmax, giving probabilities cat 0.71, dog 0.21 and fox 0.08 as bars. Every neuron connects to every neuron in the next layer; lines are pink for positive weights and blue for negative weights, thicker for larger weights.A multi-layer perceptron: every neuron feeds every neuron in the next layerinput layer4 featureshidden layer 16 neurons, ReLUhidden layer 26 neurons, ReLUoutput layer3 classes, softmaxcat 0.71dog 0.21fox 0.08+ weight− weight
4 × 6 + 6 × 6 + 6 × 3 = 78 weights and 15 biases: 93 parameters.
LayerWhat it holds
Input layerThe features, such as 784 pixel brightnesses. It does no computing
Hidden layersNeurons whose outputs are passed on, never seen directly. They learn useful intermediate features
Output layerOne neuron per thing to predict: one number for regression, one probability per class for classification

A network with at least one hidden layer is often called a multi-layer perceptron (MLP). "Deep" learning simply means many hidden layers. The values computed by the hidden neurons for an input are called its activations.

A layer is a matrix multiplication

Each neuron in a layer computes a weighted sum of the same inputs, with its own weights. Stack each neuron's weights as a row of a weight matrix W, and the whole layer is one calculation:

A dense layer

output = f(W x + b), where W has one row per neuron and one column per input

A layer as a matrix multiplicationA 4 by 3 weight matrix W, each cell coloured blue for negative and pink for positive, multiplied by an input vector x of 1, 2 and 0.5, plus a bias vector b of 0.1, 0, minus 0.2 and 0.3, gives z: -0.20, -0.50, 1.15, 1.05. ReLU turns the negatives to zero, giving the output 0.00, 0.00, 1.15, 1.05. The third row is highlighted: neuron 3 computes minus 0.3 times 1 plus 0.8 times 2 plus 0.1 times 0.5 minus 0.2, which is 1.15, and ReLU keeps it.A whole layer at once: f(W x + b)0.2−0.510.5−12−0.30.80.110−0.5W (4 neurons × 3 inputs)×120.5x+0.10−0.20.3b=−0.2−0.51.151.05zReLU001.151.05outputneuron 3: z = (−0.3)(1) + (0.8)(2) + (0.1)(0.5) + (−0.2) = 1.15, ReLU keeps it: 1.15
Each row of W is one neuron. One multiplication computes them all.

To multiply a matrix by a vector, take the dot product of each row with the vector. Each row gives one neuron's weighted sum. A layer with 3 inputs and 4 neurons has a 4 × 3 weight matrix and a bias vector of 4 numbers.

Why this matters for hardware

Writing a layer as one matrix multiplication is not just tidy notation. Graphics processors (GPUs) and specialised AI chips are built to multiply huge matrices quickly, thousands of multiplications at the same time. That is why the same chips that render video games train neural networks.

Batches

Feed a batch of examples at once by stacking them as the rows of a matrix X. The layer becomes X Wᵀ + b, and one matrix multiplication handles every example in the batch together.

The forward pass, worked through

The forward pass carries an input through the network, layer by layer, to the output. Here is a tiny network that solves XOR with ReLU hidden neurons:

NeuronCalculation
Hidden h₁ReLU(x₁ + x₂)
Hidden h₂ReLU(x₁ + x₂ − 1)
Outputh₁ − 2h₂
x₁x₂h₁h₂OutputXOR
00000 − 0 = 00
01101 − 0 = 11
10101 − 0 = 11
11212 − 2 = 00

Four inputs, four correct answers: what a single neuron could never do.

What hidden layers really do

The hidden layer transforms the space. It moves each input point to a new position, given by the hidden neurons' outputs, where the problem becomes easy.

How a hidden layer solves XOROn the left, the four XOR inputs in the input space: 01 and 10, the pink 1s, on one diagonal and 00 and 11, the hollow 0s, on the other, which no line separates. In the middle, the hidden layer: h1 equals ReLU of x1 plus x2 and h2 equals ReLU of x1 plus x2 minus 1. On the right, the same points in the hidden space: 00 goes to (0, 0), 01 and 10 both land on (1, 0), and 11 goes to (2, 1). Now a single green line, h1 minus 2 h2 equals 0.5, separates the pink point from the hollow ones.The hidden layer moves the points; then one line is enoughinput space (x₁, x₂)hidden space (h₁, h₂)h₁ − 2h₂ = 0.50001101101 and 10 land together1100hidden layerh₁ = ReLU(x₁ + x₂)h₂ = ReLU(x₁ + x₂ − 1)output = h₁ − 2h₂: positive on one side of the green line, zero on the other
Each layer re-represents the data so the next layer's job is easier.

In the input space the XOR classes sit on opposite diagonals and no line separates them. In the hidden space (h₁, h₂), the points (0, 1) and (1, 0) land on the same spot, and a single straight line now divides the classes. The output neuron only has to draw that line.

This is the deep idea of deep learning. Each layer re-represents the data so that the next layer's job is simpler. In an image network, early layers turn pixels into edges, later layers turn edges into textures and shapes, and the last layers turn shapes into "cat" or "aeroplane". Nobody programs these features: training discovers them.

Width and depth

The universal approximation theorem (Level 6) says one wide hidden layer is enough in principle. In practice, depth is far more efficient: each layer can fold and reuse what the previous one built, so a deep network can represent with thousands of neurons what a shallow one would need millions for.

Counting parameters

A dense layer from n inputs to m neurons has:

Parameters in a dense layer

n × m weights + m biases

A classic network for handwritten digits, with 784 inputs, hidden layers of 128 and 64 neurons and 10 outputs:

LayerWeightsBiasesTotal
784 → 128100,352128100,480
128 → 648,192648,256
64 → 1064010650
Whole network109,386
Model sizes, from 3 to 175 billionHorizontal bars on a logarithmic scale, where each grid line is ten times the one before, from 1 to 1 trillion parameters: a perceptron for AND, 3; LeNet-5 from 1998, which read handwritten cheques, about 60 thousand; the digit network from this lesson, 109,386; AlexNet from 2012, about 60 million; BERT-large from 2018, 340 million; GPT-2 from 2019, 1.5 billion; and GPT-3 from 2020, 175 billion.How many parameters? Every grid line is ten times the last110010 thousand1 million100 million10 billion1 trillionPerceptron for AND2 weights + 1 bias3LeNet-5 (1998)read handwritten cheques60,000Digit MLP, 784-128-64-10this lesson109,386AlexNet (2012)the ImageNet breakthrough60 millionBERT-large (2018)language understanding340 millionGPT-2 (2019)fluent paragraphs1.5 billionGPT-3 (2020)few-shot learning175 billion
Modern frontier models are larger still, though most of their makers no longer publish the numbers.

Stored as 32-bit floating point numbers (4 bytes each), that network takes about 0.44 MB. A model with 70 billion parameters takes 280 GB in that format, which is why large models are stored in 16-bit or smaller formats (Level 14).

Hands-on: a network from lists

A dense layer as matrix times vector

Python
def matvec(W, x):
    return [sum(w * xi for w, xi in zip(row, x)) for row in W]

def dense(W, b, x, activation):
    return [activation(z + bias) for z, bias in zip(matvec(W, x), b)]

def relu(z): return max(0.0, z)
def identity(z): return z

# the XOR network from the lesson
W1, b1 = [[1, 1], [1, 1]], [0, -1]
W2, b2 = [[1, -2]], [0]

for x in [(0, 0), (0, 1), (1, 0), (1, 1)]:
    h = dense(W1, b1, x, relu)
    out = dense(W2, b2, h, identity)
    print(f"x = {x} -> hidden {h} -> output {out[0]}")

Counting parameters

Python
def count_parameters(sizes):
    total = 0
    for n_in, n_out in zip(sizes, sizes[1:]):
        layer = n_in * n_out + n_out
        print(f"  {n_in:>5} -> {n_out:<5}: {layer:>11,} parameters")
        total += layer
    return total

for sizes in [[784, 128, 64, 10], [784, 512, 512, 10], [2, 3, 1]]:
    total = count_parameters(sizes)
    print(f"{sizes}: {total:,} parameters, {total * 4 / 1e6:.2f} MB as 32-bit numbers\n")

A forward pass on a batch

Python
def matmul(A, B):
    # (rows of A) x (columns of B)
    return [[sum(a * b for a, b in zip(row, col)) for col in zip(*B)] for row in A]

X = [[0, 0], [0, 1], [1, 0], [1, 1]]          # a batch of four examples
W1_T = [[1, 1], [1, 1]]                       # weights, one column per hidden neuron
hidden = [[max(0, z + b) for z, b in zip(row, [0, -1])] for row in matmul(X, W1_T)]
print("hidden activations for the whole batch:", hidden)

Try this

  1. Change the output weights in the XOR network from [1, −2] to [1, −1]. Which input now gets the wrong answer?
  2. How many parameters does a network with sizes [3, 4, 4, 1] have? Check with the code.

Level check

  • Describe input, hidden and output layers, and what makes a layer dense
  • Write a dense layer as output = f(Wx + b) and give the shape of W
  • Carry out a forward pass through a small network by hand
  • Explain how a hidden layer makes XOR linearly separable
  • Explain why depth helps, with the idea of features built from features
  • Count the weights and biases in a network from its layer sizes

Key terms you must be able to define

Neural network
Layers of artificial neurons, each layer feeding the next.
Dense layer
A layer in which every neuron receives every output of the previous layer; also called fully connected.
Hidden layer
A layer between input and output whose values are internal to the network.
Multi-layer perceptron (MLP)
A network of dense layers with at least one hidden layer.
Weight matrix
The weights of a whole layer, one row per neuron and one column per input.
Forward pass
Computing a network's output from an input, layer by layer.
Activations
The outputs of a layer's neurons for a particular input.
Representation
The way data is encoded at some layer; each layer re-represents the data for the next.
Parameter count
The total number of weights and biases, which sets a model's size and memory.
Deep learning
Machine learning with neural networks that have many hidden layers.

Flashcards

DefineNeural network
AnswerLayers of artificial neurons, each layer feeding the next.
DefineDense layer
AnswerA layer in which every neuron receives every output of the previous layer; also called fully connected.
DefineHidden layer
AnswerA layer between input and output whose values are internal to the network.
DefineMulti-layer perceptron (MLP)
AnswerA network of dense layers with at least one hidden layer.
DefineWeight matrix
AnswerThe weights of a whole layer, one row per neuron and one column per input.
DefineForward pass
AnswerComputing a network's output from an input, layer by layer.
DefineActivations
AnswerThe outputs of a layer's neurons for a particular input.
DefineRepresentation
AnswerThe way data is encoded at some layer; each layer re-represents the data for the next.

Go further: notes for future AI engineers

Tensors, shapes and broadcasting

Real frameworks work with whole tensors. A batch of 32 examples with 784 features is a (32, 784) tensor; multiplying by a (784, 128) weight matrix gives (32, 128); adding a bias of shape (128,) is broadcast across all 32 rows automatically. Most bugs in deep learning code are shape mistakes, so engineers write the expected shape beside every line, and check it.

The cost of a forward pass

Multiplying an (n × k) matrix by a (k × m) one takes about n × k × m multiplications and as many additions, so roughly 2 × parameters floating point operations (FLOPs) per example for a dense network. A training step costs about three times a forward pass, because the backward pass needs about twice as much work. Level 11 uses exactly this rule of thumb to estimate what it costs to train a large language model.

Misconceptions to avoid

Avoid these
  • Counting the input layer as a layer of neurons. It holds the features and does no computation.
  • Forgetting the biases when counting parameters: each neuron has one.
  • Getting the weight matrix the wrong way round. W has one row per neuron (output) and one column per input.
  • Thinking hidden layers are programmed with features by people. Training discovers them.
  • Believing bigger is always better. More parameters need more data and compute, and overfit more easily.
Fun fact

When a phone unlocks with your face, a neural network runs a forward pass of many millions of multiplications in a few hundredths of a second, using a chip built into the phone for exactly that job.

Knowledge check

0 of 10 answered
1What is a dense layer?
2A layer has 5 inputs and 3 neurons. What shape is its weight matrix?
3How is a matrix multiplied by a vector?
4In the XOR network, h₁ = ReLU(x₁ + x₂) and h₂ = ReLU(x₁ + x₂ − 1). What are h₁ and h₂ for input (1, 1)?
5How does a hidden layer let a network solve XOR?
6How many parameters does a dense layer from 10 inputs to 4 neurons have?
7Why are GPUs good at running neural networks?
8What do the early layers of an image network typically learn?
9What does 'deep' mean in deep learning?
10A model has 1 million parameters stored as 32-bit numbers. Roughly how much memory is that?
Score 0 / 10

Check you could explain this

12 marks
1Explain why a layer of a neural network can be written as a single matrix multiplication.4 marks
Explain

Mark scheme0 / 4
  • LEach neuron computes a weighted sum of the same inputs
  • LEach neuron's weights form a row of a matrix
  • LMultiplying the matrix by the input vector gives every weighted sum at once
  • LThen the bias is added and the activation applied, f(Wx + b)
Model answer

Every neuron in a layer computes a weighted sum of the same inputs, each with its own weights. If each neuron's weights are written as one row of a matrix W, then multiplying W by the input vector x takes the dot product of every row with x, giving all of the neurons' weighted sums in one operation. Adding the bias vector and applying the activation function gives the whole layer's output, f(Wx + b).

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.

Think this answer or mark scheme is wrong? Report it

2A network has 4 inputs, one hidden layer of 5 neurons and 2 outputs. Calculate its total number of parameters, showing your working.4 marks
Calculate

Mark scheme0 / 4
  • L4 × 5 = 20 weights into the hidden layer
  • L5 hidden biases, so 25 for the first layer
  • L5 × 2 = 10 weights and 2 biases, so 12 for the second layer
  • LTotal 37
Model answer

The first layer has 4 × 5 = 20 weights and 5 biases, which is 25 parameters. The second layer has 5 × 2 = 10 weights and 2 biases, which is 12 parameters. The total is 25 + 12 = 37 parameters.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.

Think this answer or mark scheme is wrong? Report it

3Explain how the hidden layers of a deep image classifier build up an understanding of an image.4 marks
Explain

Mark scheme0 / 4
  • LEarly layers detect simple features such as edges or colours
  • LLater layers combine these into textures, parts or shapes
  • LThe final layers represent whole objects or classes
  • LThese features are learned in training, not programmed
Model answer

Each layer re-represents the image for the next. The early layers learn to detect simple features such as edges, lines and patches of colour. Later layers combine those into more complex features such as textures, corners and parts of objects, like an eye or a wheel. The final layers combine parts into whole objects, so the output layer can decide between classes such as cat or aeroplane. None of these features is programmed by a person: they are learned automatically during training.

The marker looks for key phrases. If you said it another way and it is still right, give yourself the mark.

Think this answer or mark scheme is wrong? Report it

Machine mark 0 / 12