Neural Network Layers as Matrices
A dense neural network layer is a matrix-vector product plus a bias, followed by a simple function applied entry by entry. Training it is mostly more matrix products, with transposes. Once you see this, deep learning code (and its shape errors) becomes much easier to read.
One layer:
A dense (fully connected, linear) layer with inputs and outputs stores a weight matrix () and a bias vector (). For an input ,
Row of holds the weights of output neuron , so is a dot product: each neuron measures how well the input lines up with its weight vector. The map is affine, and without the nonlinear , stacking layers would be pointless: is again a single layer (Matrix Multiplication).
The number of parameters is . A layer from 784 inputs to 128 outputs has 100,480.
Batches: many inputs at once
Frameworks process a batch of inputs together, stored as the rows of (). Stacking the column equation row-wise gives
PyTorch's nn.Linear stores as (out, in) and computes exactly X @ W.T + b. One big matrix multiplication is far faster on a GPU than separate ones, which is the whole reason batches exist.
import numpy as np
rng = np.random.default_rng(0)
B, n_in, n_hidden, n_out = 4, 3, 5, 2
X = rng.normal(size=(B, n_in))
W1, b1 = rng.normal(size=(n_hidden, n_in)) * 0.5, np.zeros(n_hidden)
W2, b2 = rng.normal(size=(n_out, n_hidden)) * 0.5, np.zeros(n_out)
Z1 = X @ W1.T + b1 # (4, 5)
A1 = np.maximum(Z1, 0) # ReLU
Y = A1 @ W2.T + b2 # (4, 2)
print("shapes:", X.shape, "->", Z1.shape, "->", Y.shape)
print("parameters:", W1.size + b1.size + W2.size + b2.size)
y0 = W2 @ np.maximum(W1 @ X[0] + b1, 0) + b2 # one sample, column-vector style
print("row 0 of batch:", np.round(Y[0], 4), " single sample:", np.round(y0, 4))
print("ReLU zeroed", int((Z1 <= 0).sum()), "of", Z1.size, "hidden values")shapes: (4, 3) -> (4, 5) -> (4, 2)
parameters: 32
row 0 of batch: [-0.1224 0.0431] single sample: [-0.1224 0.0431]
ReLU zeroed 12 of 20 hidden values
The backward pass is transposes
Training needs the gradient of a scalar loss with respect to every weight. Write for the matrix of gradients arriving at the layer's output (from the layer above). The chain rule for gives three formulas:
For an activation the backward step is entrywise: (for ReLU, zero where ). So the backward pass runs the same matrices in reverse, transposed. Where does come from? , so and , the entry of . A useful rule: the gradient always has the shape of the thing it is the gradient of, and there is usually exactly one way to multiply the available matrices to get that shape.
Checking against finite differences is the standard way to trust hand-written gradients:
import numpy as np
rng = np.random.default_rng(1)
X = rng.normal(size=(6, 3)); T = rng.normal(size=(6, 2)) # inputs and targets
W1, b1 = rng.normal(size=(4, 3)), rng.normal(size=4)
W2, b2 = rng.normal(size=(2, 4)), rng.normal(size=2)
def loss(W1):
A1 = np.maximum(X @ W1.T + b1, 0)
return 0.5 * np.sum((A1 @ W2.T + b2 - T) ** 2) / len(X)
# forward, keeping what the backward pass needs
Z1 = X @ W1.T + b1; A1 = np.maximum(Z1, 0); Y = A1 @ W2.T + b2
G2 = (Y - T) / len(X) # dL/dY
dW2 = G2.T @ A1 # (2,4)
dA1 = G2 @ W2 # (6,4)
G1 = dA1 * (Z1 > 0) # through ReLU
dW1 = G1.T @ X # (4,3)
num = np.zeros_like(W1); h = 1e-6
for i in range(4):
for j in range(3):
E = np.zeros_like(W1); E[i, j] = h
num[i, j] = (loss(W1 + E) - loss(W1 - E)) / (2 * h)
print("dW1 shape:", dW1.shape, " dW2 shape:", dW2.shape)
print("max |analytic - numeric| =", f"{np.max(np.abs(dW1 - num)):.1e}")dW1 shape: (4, 3) dW2 shape: (2, 4)
max |analytic - numeric| = 2.6e-10
Training with these gradients
Gradient descent (Gradient Descent) updates . Here is a whole training loop for a tiny regression network, nothing but matrix products:
import numpy as np
rng = np.random.default_rng(3)
X = np.linspace(-2, 2, 40).reshape(-1, 1)
T = np.sin(1.5 * X) # target function
W1, b1 = rng.normal(size=(16, 1)), np.zeros(16)
W2, b2 = rng.normal(size=(1, 16)) * 0.1, np.zeros(1)
lr = 0.05
for step in range(3001):
Z1 = X @ W1.T + b1; A1 = np.tanh(Z1); Y = A1 @ W2.T + b2
G2 = (Y - T) / len(X)
G1 = (G2 @ W2) * (1 - A1 ** 2) # tanh' = 1 - tanh^2
W2 -= lr * G2.T @ A1; b2 -= lr * G2.sum(0)
W1 -= lr * G1.T @ X; b1 -= lr * G1.sum(0)
if step % 1000 == 0:
print(f"step {step:4d} mse = {np.mean((Y - T) ** 2):.5f}")step 0 mse = 0.30412
step 1000 mse = 0.02565
step 2000 mse = 0.01847
step 3000 mse = 0.01310
Tip: When a deep learning framework reports "mat1 and mat2 shapes cannot be multiplied (32x100 and 128x10)", it is telling you the inner dimensions of do not match: the previous layer produced 100 features but this layer expects 128.
In software
- Every framework.
torch.nn.Linear, KerasDenseand JAXDenseare , and one matmul; automatic differentiation generates the transposed products for you (Backpropagation, Automatic Differentiation). - LLMs. The feed-forward block of a transformer is two dense layers () applied to every token, i.e. to the rows of a () matrix; attention is more matrix products.
- Hardware. GPUs and TPUs are built around fast matrix multiplication (tensor cores); "FLOPs" of a model are mostly per layer per token.
- Fine-tuning. LoRA replaces the update by a low-rank product .
See also Neural Networks and the AI view.
Exercises
Exercise 1: Count parameters
A network has layers 784 → 256 → 64 → 10 (dense, with biases). How many parameters?
Answer
218,058.
Solution
784·256 + 256 = 200,960
256·64 + 64 = 16,448
64·10 + 10 = 650
total 218,058Exercise 2: Shapes
is and a layer maps 100 → 50. What are the shapes of , , and ?
Answer
: , : , : , : .
Solution
Gradients have the shapes of their variables. With (): is and is .
Exercise 3: Collapse two linear layers
Without activations, the layers , and , are applied in sequence. Find the single equivalent layer.
Answer
, .
Solution
; .
Exercise 4: One gradient by hand (code)
For a single linear layer with , and loss , compute .
Answer
with .
Solution
, and with a batch of one, (an outer product).
import numpy as np
x = np.array([1.0, 2.0]); W = np.array([[1.0, 0], [0, 1], [1, 1]])
z = W @ x
print(z, np.outer(z, x).tolist())[1. 2. 3.] [[1.0, 2.0], [2.0, 4.0], [3.0, 6.0]]
Test yourself
For a batch () and nn.Linear weight (), the output is…
If for , the gradient passed to the previous layer is…
Why do neural networks need nonlinear activations between dense layers?
- To save memory
- Without them, stacked layers collapse into a single affine map
- To make the gradients exact
- Because matrices cannot be multiplied twice