Linear algebra for LLMsPart 6: The rest of the transformer

Linear layers in code

5 min

What nn.Linear computes

y=xW⊤+b\displaystyle y = xW^\top + b

nn.Linear(in, out) stores WW as (out×in)(\text{out} \times \text{in}) and a bias of length out\text{out}. Input (…,in)(\dots, \text{in}), output (…,out)(\dots, \text{out}): any leading axes (batch, tokens) come along for free.

Write

y=xW⊤+by = xW^\top + b, W ⁣:(out,in)W\!: (\text{out}, \text{in}), b ⁣:(out,)b\!: (\text{out},).

A small one by hand

+=

In 2, out 3. xW⊤=[1,2,3]xW^\top = [1, 2, 3], plus the bias [0,0,1][0, 0, 1].

Each output is a dot product with a row of W

y3=x⋅W3,:+b3=[1,2]⋅[1,1]+1=4\quad y_3 = x \cdot W_{3,:} + b_3 = [1, 2] \cdot [1, 1] + 1 = 4

Row jj of the stored weight belongs to output feature jj. That’s why PyTorch stores (out,in)(\text{out}, \text{in}): each row is one output’s “detector”, contiguous in memory.

Write

yj=x⋅Wj,:+bjy_j = x \cdot W_{j,:} + b_j: one row of WW per output.

Count the parameters

params=in×out+out\displaystyle \text{params} = \text{in} \times \text{out} + \text{out}
4096×14336=58,720,256(no bias)\displaystyle 4096 \times 14336 = 58{,}720{,}256 \quad (\text{no bias})

Llama’s linear layers have no biases, so a 4096→143364096 \to 14336 projection is just its weight: almost 59 million numbers, one of three in each MLP.

✏️ Your turn

GPT-2's MLP input

nn.Linear(768, 3072)\displaystyle \texttt{nn.Linear(768, 3072)}

How many parameters, bias included?

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

Answer

768×3072+3072=2,362,368\displaystyle 768 \times 3072 + 3072 = 2{,}362{,}368

In code

lin = nn.Linear(4096, 14336, bias=False)
lin.weight.shape          # torch.Size([14336, 4096])
y = lin(x)                # x: (B, T, 4096) → y: (B, T, 14336)

In a transformer

When you load a checkpoint, mlp.up_proj.weight with shape [14336, 4096] reads as (out, in): this layer maps 4,096 features to 14,336.

📌 Recap

Linear layers in one card

  • y=xW⊤+by = xW^\top + b, with WW stored (out,in)(\text{out}, \text{in}).
  • Output jj is x⋅Wj,:+bjx \cdot W_{j,:} + b_j.
  • Parameters: in⋅out+out\text{in} \cdot \text{out} + \text{out} (Llama: no bias).

Write

The three lines above.