Linear algebra for LLMsPart 3: Matrices as transformations

Composition

6 min

One map after another

B(Ax)=(BA) x\displaystyle B(Ax) = (BA)\,x

Apply AA, then apply BB to the result. The product BABA does both in one step. Read it right to left: the matrix nearest xx acts first.

Write

B(Ax)=(BA)xB(Ax) = (BA)x: AA first, then BB.

Two maps to combine

turn 90°stretch the width ×2

RR is the quarter turn from the last deck. SS doubles every first coordinate.

Turn, then stretch: SRSR

SR=SR =
Me₁Me₂

e1e_1 turns to [0,1][0, 1], and the stretch leaves it alone (its first coordinate is 0). e2e_2 turns to [−1,0][-1, 0], then stretches to [−2,0][-2, 0].

Stretch, then turn: RSRS

RS=RS =
Me₁Me₂

Now e1e_1 stretches to [2,0][2, 0] first, then turns to [0,2][0, 2]. A different map: SR≠RSSR \ne RS. The same matrices in a different order do different things.

Write

SR≠RSSR \ne RS: the order of maps matters.

✏️ Your turn

Compose

P=[1101]P = \begin{bmatrix} 1 & 1 \\ 0 & 1 \end{bmatrix}R=[0−110]R = \begin{bmatrix} 0 & -1 \\ 1 & 0 \end{bmatrix}

Write the matrix for “shear with PP, then turn with RR”. Which order do you multiply in?

Work it out on paper, then go to the next card to check.

Answer: RPRP

RP=RP =

PP acts first, so it sits on the right: RPRP. Check a column: PP sends e2e_2 to [1,1][1, 1], and RR turns that to [−1,1][-1, 1], which is column 2 of RPRP.

Stacked linear layers collapse

W2(W1x)=(W2W1) x\displaystyle W_2(W_1 x) = (W_2 W_1)\,x

In a transformer

Two linear layers in a row are one linear layer: the product W2W1W_2 W_1 is a single matrix. A transformer’s MLP has a nonlinearity (GELU or SiLU) between its two matrices for exactly this reason. Without it, the extra matrix would add parameters but no new kinds of function.

Write

No nonlinearity between them: two layers = one matrix W2W1W_2 W_1.

In code, read left to right

y = x @ W1 @ W2        # row-vector layout: W1 acts first
y = x @ (W1 @ W2)      # the same map, one matrix

With row vectors the order flips: xW1W2xW_1W_2 applies W1W_1 first. It’s the same composition, transposed: (W2⊤W1⊤x⊤)⊤(W_2^\top W_1^\top x^\top)^\top.

📌 Recap

Composition in one card

  • B(Ax)=(BA)xB(Ax) = (BA)x: column layout reads right to left.
  • Order matters: SR≠RSSR \ne RS.
  • Linear layers with nothing between them collapse into one matrix; activations prevent that.
  • Code layout xW1W2xW_1W_2 reads left to right.

Write

The four lines above.