TExcelTAD
Home › Linear Algebra & Matrix Theory › Neural Network Layers as Matrices

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: y=Wx+b\mathbf{y} = W\mathbf{x} + \mathbf{b}

A dense (fully connected, linear) layer with nn inputs and mm outputs stores a weight matrix WW (m×nm \times n) and a bias vector b\mathbf{b} (mm). For an input x∈Rn\mathbf{x} \in \mathbb{R}^n,

z=Wx+b(pre-activation, m numbers)a=φ(z)(activation, applied to each entry: ReLU⁡(t)=max⁡(0,t), tanh⁡, …)\begin{aligned} \mathbf{z} &= W\mathbf{x} + \mathbf{b} && \text{(pre-activation, } m \text{ numbers)} \\ \mathbf{a} &= \varphi(\mathbf{z}) && \text{(activation, applied to each entry: } \operatorname{ReLU}(t) = \max(0, t),\ \tanh,\ \ldots\text{)} \end{aligned}

Row ii of WW holds the weights of output neuron ii, so zi=(row i)⋅x+biz_i = (\text{row } i) \cdot \mathbf{x} + b_i is a dot product: each neuron measures how well the input lines up with its weight vector. The map x↦Wx+b\mathbf{x} \mapsto W\mathbf{x} + \mathbf{b} is affine, and without the nonlinear φ\varphi, stacking layers would be pointless: W2(W1x+b1)+b2=(W2W1)x+(W2b1+b2)W_2(W_1\mathbf{x} + \mathbf{b}_1) + \mathbf{b}_2 = (W_2 W_1)\mathbf{x} + (W_2\mathbf{b}_1 + \mathbf{b}_2) is again a single layer (Matrix Multiplication).

The number of parameters is m⋅n+mm \cdot n + m. A layer from 784 inputs to 128 outputs has 100,480.

Batches: many inputs at once

Frameworks process a batch of BB inputs together, stored as the rows of XX (B×nB \times n). Stacking the column equation z=Wx+b\mathbf{z} = W\mathbf{x} + \mathbf{b} row-wise gives

Z=XWT+b(B×n)(n×m)=B×m, and b is broadcast to every rowZ = XW^T + \mathbf{b} \qquad (B \times n)(n \times m) = B \times m, \text{ and } \mathbf{b} \text{ is broadcast to every row}

PyTorch's nn.Linear stores WW as (out, in) and computes exactly X @ W.T + b. One big matrix multiplication is far faster on a GPU than BB separate ones, which is the whole reason batches exist.

python · try it yourself
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 LL with respect to every weight. Write G=∂L/∂ZG = \partial L/\partial Z for the B×mB \times m matrix of gradients arriving at the layer's output (from the layer above). The chain rule for Z=XWT+bZ = XW^T + \mathbf{b} gives three formulas:

∂L∂W=GTX(m×B)(B×n)=m×n, same shape as W∂L∂b=sum of the rows of G(m)∂L∂X=GW(B×m)(m×n)=B×n, passed on to the layer below\begin{aligned} \frac{\partial L}{\partial W} &= G^T X && (m \times B)(B \times n) = m \times n, \text{ same shape as } W \\ \frac{\partial L}{\partial \mathbf{b}} &= \text{sum of the rows of } G && (m) \\ \frac{\partial L}{\partial X} &= G W && (B \times m)(m \times n) = B \times n, \text{ passed on to the layer below} \end{aligned}

For an activation a=φ(z)\mathbf{a} = \varphi(\mathbf{z}) the backward step is entrywise: ∂L/∂Z=∂L/∂A⊙φ′(Z)\partial L/\partial Z = \partial L/\partial A \odot \varphi'(Z) (for ReLU, zero where z≤0z \le 0). So the backward pass runs the same matrices in reverse, transposed. Where does GTXG^T X come from? zβi=∑jwijxβj+biz_{\beta i} = \sum_j w_{ij} x_{\beta j} + b_i, so ∂zβi/∂wij=xβj\partial z_{\beta i}/\partial w_{ij} = x_{\beta j} and ∂L/∂wij=∑βgβixβj\partial L/\partial w_{ij} = \sum_\beta g_{\beta i} x_{\beta j}, the (i,j)(i, j) entry of GTXG^T X. 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:

python · try it yourself
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 W←W−η⋅∂L/∂WW \leftarrow W - \eta \cdot \partial L/\partial W. Here is a whole training loop for a tiny regression network, nothing but matrix products:

python · try it yourself
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 XWTXW^T do not match: the previous layer produced 100 features but this layer expects 128.

In software

  • Every framework. torch.nn.Linear, Keras Dense and JAX Dense are WW, b\mathbf{b} 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 (d→4d→dd \to 4d \to d) applied to every token, i.e. to the rows of a (tokens×d\text{tokens} \times d) matrix; attention is more matrix products.
  • Hardware. GPUs and TPUs are built around fast matrix multiplication (tensor cores); "FLOPs" of a model are mostly 2⋅m⋅n2 \cdot m \cdot n per layer per token.
  • Fine-tuning. LoRA replaces the update ΔW\Delta W by a low-rank product BABA.

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
text
784·256 + 256 = 200,960
256·64  + 64  =  16,448
64·10   + 10  =     650
total           218,058

Exercise 2: Shapes

XX is 32×10032 \times 100 and a layer maps 100 → 50. What are the shapes of WW, Z=XWT+bZ = XW^T + \mathbf{b}, ∂L/∂W\partial L/\partial W and ∂L/∂X\partial L/\partial X?

Answer

WW: 50×10050 \times 100, ZZ: 32×5032 \times 50, ∂L/∂W\partial L/\partial W: 50×10050 \times 100, ∂L/∂X\partial L/\partial X: 32×10032 \times 100.

Solution

Gradients have the shapes of their variables. With G=∂L/∂ZG = \partial L/\partial Z (32×5032 \times 50): GTXG^T X is (50×32)(32×100)=50×100(50 \times 32)(32 \times 100) = 50 \times 100 and GWGW is (32×50)(50×100)=32×100(32 \times 50)(50 \times 100) = 32 \times 100.

Exercise 3: Collapse two linear layers

Without activations, the layers W1=[1201]W_1 = \begin{bmatrix} 1 & 2 \\ 0 & 1 \end{bmatrix}, b1=(1,0)\mathbf{b}_1 = (1, 0) and W2=[1−1]W_2 = \begin{bmatrix} 1 & -1 \end{bmatrix}, b2=(3)\mathbf{b}_2 = (3) are applied in sequence. Find the single equivalent layer.

Answer

W=[11]W = \begin{bmatrix} 1 & 1 \end{bmatrix}, b=(4)\mathbf{b} = (4).

Solution

W=W2W1=[1⋅1+(−1)⋅01⋅2+(−1)⋅1]=[11]W = W_2 W_1 = \begin{bmatrix} 1 \cdot 1 + (-1) \cdot 0 & 1 \cdot 2 + (-1) \cdot 1 \end{bmatrix} = \begin{bmatrix} 1 & 1 \end{bmatrix}; b=W2b1+b2=1⋅1+(−1)⋅0+3=4\mathbf{b} = W_2\mathbf{b}_1 + \mathbf{b}_2 = 1 \cdot 1 + (-1) \cdot 0 + 3 = 4.

Exercise 4: One gradient by hand (code)

For a single linear layer z=Wx\mathbf{z} = W\mathbf{x} with x=(1,2)\mathbf{x} = (1, 2), W=[100111]W = \begin{bmatrix} 1 & 0 \\ 0 & 1 \\ 1 & 1 \end{bmatrix} and loss L=12∥z∥2L = \frac{1}{2}\lVert \mathbf{z} \rVert^2, compute ∂L/∂W\partial L/\partial W.

Answer

∂L/∂W=zxT=[122436]\partial L/\partial W = \mathbf{z}\mathbf{x}^T = \begin{bmatrix} 1 & 2 \\ 2 & 4 \\ 3 & 6 \end{bmatrix} with z=(1,2,3)\mathbf{z} = (1, 2, 3).

Solution

∂L/∂z=z\partial L/\partial \mathbf{z} = \mathbf{z}, and with a batch of one, GTX=zxTG^T X = \mathbf{z}\mathbf{x}^T (an outer product).

python · try it yourself
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 XX (B×nB \times n) and nn.Linear weight WW (m×nm \times n), the output is…

  1. WXWX
  2. XWXW
  3. XWT+bXW^T + \mathbf{b}
  4. WTX+bW^T X + \mathbf{b}

If G=∂L/∂ZG = \partial L/\partial Z for Z=XWT+bZ = XW^T + \mathbf{b}, the gradient passed to the previous layer is…

  1. GTXG^T X
  2. GWGW
  3. XGXG
  4. WGWG

Why do neural networks need nonlinear activations between dense layers?

  1. To save memory
  2. Without them, stacked layers collapse into a single affine map
  3. To make the gradients exact
  4. Because matrices cannot be multiplied twice