Skip to the content

fatehi.devx2Learning

Deep learning

Linear layers

One weight matrix and one bias: y = x WT + b. The block every network is built from, written here by hand, forward, backward and the update, as the base of the site’s own nn package.

The linear layer is the simplest block that learns, and the place to fix what every line and box in a network diagram means: signals flow, parameters stay, gradients flow back, and only the optimiser changes a parameter.

One matrix and one bias

A linear layer multiplies its input by a matrix of weights and adds a vector of biases. It is the block every neural network is built from, under several names: linear, dense or fully connected, and nn.Linear in PyTorch. Strictly the map is affine, because of the bias, but the name has stuck.

Written for a whole batch at once, one example (or one token) per row of X:

Y=XWT+b

X has n rows of din numbers, W is dout × din, b has dout numbers, and Y has n rows of dout. Each output number is a weighted sum of all the input numbers plus its own bias. W is stored as PyTorch stores it, one row per output, which is why it appears transposed (T).

Signals, parameters and neurons

Diagrams of networks are easy to misread, because two very different kinds of number sit in them side by side. This site draws and codes every block by one rule.

  • A signal is what flows forward along the wires: X and Y, drawn as rows of coloured tiles (copper positive, blue negative). An embedding is a signal too, once it has been looked up. In code it is the array passed to forward.
  • A parameter stays inside its block and never travels: W and b, drawn as the chip’s weight memory and as a thin vector. In code it is a Parameter, its numbers in .data.
  • A gradient flows backward along the same wires, drawn in violet; a block at work on the way forward is edged in gold, on the way back in violet, and while the optimiser writes it in green. Each parameter keeps its own gradient beside it, in .grad.
  • The optimiser is the only thing that ever changes a parameter, the weights and the biases alike; its writes are drawn in green.

The signal line reads like the formula: the input, × where it meets W, + where the bias comes in, = before the result. And a neuron is neither a block nor a wire. Neuron j is row j of W with entry j of b, and its output is number j of Y: a slice of the parameters and of the signal. The classic picture of a neuron “firing” a signal mixes the two: what it calls the neuron’s weights are parameters, and what it calls its output is one number of the next signal.

One neuron at a time. The input row flows in from the left, is multiplied by W, gets the bias added, and leaves as Y. Neuron j is lit where it lives: row j of W, its entry of b, and number j of the output. The weights do not move; only the signals do.

Forward and backward

The forward pass is the formula, and the layer keeps its input X for later. The backward pass receives the gradient of the loss with respect to the layer’s output, dY, and from it computes by the chain rule the gradients of its parameters and the gradient with respect to its input, which it hands back to the block before it.

dW=dYTX,db=∑rowsdY,dX=dYW

dW has the shape of W: its entry (j, i) is the gradient arriving at output j times the input number i, summed over the rows. db is the arriving gradient summed over the rows. dX has the shape of X: the arriving gradient sent back through the same weights.

Every result has the shape of the thing it belongs to, which is the quickest test of a backward pass; the slower, certain one compares it with finite differences, nudging every number a little and watching the loss, which the module’s gradcheck does.

One step of learning

With the gradients in place, an optimiser changes the parameters. The simplest, plain gradient descent, moves every parameter a small step against its gradient, W ← W − η dW and b ← b − η db, with η the learning rate; better optimisers differ only in how they turn the gradient into the step.

One training step. Forward: the signal runs through the layer, edged in gold while it works. Backward: the gradient (violet) runs back the same way, the layer edged in violet, and fills dW and db. Update: the optimiser rewrites W and b (green), the only moment a parameter changes.

Why an activation comes next

Two linear layers in a row are still one: (X W1T) W2T = X (W2W1)T, a single matrix. A network gains its power from an activation function between them, a fixed curve applied to every number on its own. There are many; the package treats them all alike, as an Activation with a function and its slope, and the pages that use one say which. The Transformer’s FFN is the first: linear, activation, linear.

Try it

The first two cells are the package itself, nn/core.py and nn/linear.py: every page can import them, as the third cell does. Running one of them defines its classes on this page; editing it changes this page only, while imports always get the published version. The third cell checks the gradients against finite differences, then lets a linear layer find the matrix and bias that made its data.

Python starts loading once the page is ready.

KEYMAP
How the code on this page runs

nn/core.py: Parameter, Module, Activation, Sequential, gradcheck

Cell 1: nn/core.py: Parameter, Module, Activation, Sequential, gradcheck

nn/linear.py: Linear

Cell 2: nn/linear.py: Linear

Check the gradients, then learn A and c

Cell 3: Check the gradients, then learn A and c

Test yourself

  1. Where is a neuron in the code of Linear?

    Neuron j is row j of W.data together with b.data[j]; its output is column j of the layer’s output, one number per row of the input. There is no neuron object: the weights are parameters inside the block, the output is part of the signal.

  2. Why does Linear.backward add into W.grad with += instead of setting it?

    So that a weight used more than once collects the sum of its gradients: a recurrent cell uses the same weights at every step, and the total gradient is the sum over the steps. The price is that the gradients must be set to zero before each backward pass, which zero_grad does.

  3. Why does a network need an activation between two linear layers?

    Without it the two layers multiply into a single matrix, so the pair can compute nothing a single linear layer could not. The activation bends every number, and the stack becomes able to represent curved functions.

Where it leads

Kept in this browser only, never sent.