All courses

Trace a modern LLM's forward pass with shapes

Given a prompt, trace a LLaMA-style model step by step (tokenize, embed, RoPE attention with causal mask, SwiGLU FFN, residual adds, norm, unembed, softmax) with the tensor shape at every step. Explain what each component contributes.

Builds on: The modern LLaMA-style architecture

▶ Watch this lesson Start the whole course

What the animation says

One matrix, refined 32 times

You type 'The cat sat'. The tokenizer turns it into three ids. Each id picks one row of the embedding table. Now we hold a matrix: three rows, 4096 columns. One row per token. Think of each row as that token's running vector. This matrix passes through thirty-two blocks. Each block reads it and adds something back. After all thirty-two blocks, what shape comes out?

Attention compares positions

Same shape out of every block. Now open one block. Normalize a copy. One head projects it into queries, keys and values, each three by 128. RoPE rotates each query and key by an angle set by its position. So scores depend on distance. Queries times keys gives a three by three grid: query positions down, key positions across. Then the mask hides the future. No token may look at a later token. Of these nine scores, how many survive the mask?

Weights, values, heads

Six survive: the diagonal and everything below it. Row one, 'The', weights only itself. Row three, 'sat', weights all three tokens. Softmax turns each row into weights summing to one. The pattern's size comes from the number of tokens, not from the model's width. These weights times the values give three by 128 again. Thirty-two heads do this side by side. Joined, they make three by 4096. An output matrix mixes them, and the result is added back to the running rows.

SwiGLU: per token, wider

Next, normalize again and run the feed-forward part. Two matrices widen each row, from 4096 to 11008. One branch passes through SiLU and gates the other, entry by entry. A third matrix shrinks it back to 4096, and we add it to the rows. Each row is processed alone. No row sees another. Tap the sublayer that lets 'sat' read from 'cat'.

The two ends

That was one block. Thirty-two run in a row, and the shape never changes. At the end, normalize, then multiply by the unembedding matrix. It is separate from the embedding table. Now we have three rows of 32000 scores: one per vocabulary token. Softmax the last row. That is the next-token distribution after 'The cat sat'. Ids, embed, thirty-two blocks, unembed, softmax. Any model reads as this list of shapes.

What happens to a prompt, tensor by tensor?

You type "The cat sat" and get a probability for every possible next token. In between, a LLaMA-style model runs a fixed chain of matrix operations. Which tensors appear, what shape is each, and what does each step add? Once you can trace this, any model's code reads as a list of shapes. You can then point to the step that mixes positions, the step that encodes order, and the step that computes per token.

One [T, d] matrix, refined L times

Tokenize into T ids. Look up rows of $W_E$ to get a [T, d] matrix: one running vector per token. Each of the L blocks keeps that shape. First it normalizes a copy and lets attention move information between positions, then adds the result back. RoPE makes the scores depend on relative position, and the mask hides the future. Then it normalizes again, applies SwiGLU to each position alone, and adds back. Finally: normalize, multiply by $W_U$, and softmax the last row.

One block and the two ends, with shapes

**In:** $r^{(0)}=W_E[x_1..x_T]$ → [T, d]. **Attention**, per head: $X=\text{RMSNorm}(r)$; $Q,K,V=XW_Q,XW_K,XW_V$ → [T, $d_{\text{head}}$]. RoPE rotates each row of $Q$ and $K$ by angles set by that row's position. $A=\text{softmax}(QK^\top/\sqrt{d_{head}}+M)$ → [T, T]; $AV$ → [T, $d_{\text{head}}$]. Concatenating the h heads gives [T, h·$d_{\text{head}}$]; $W_O$ maps it to [T, d], which is added to $r$. **FFN:** $X=\text{RMSNorm}(r)$; $(\text{SiLU}(XW_1)\odot XW_3)W_2$. The hidden layer is [T, $d_{\text{ff}}$] and the output is [T, d], which is added to $r$. Here $W_1,W_3\in\mathbb{R}^{d\times d_{ff}}$ and $W_2\in\mathbb{R}^{d_{ff}\times d}$. **Out:** $z=\text{RMSNorm}(r^{(L)})W_U$ → [T, V], with $W_U$ untied from $W_E$.

LLaMA-7B sizes on "The cat sat"

Sizes: V=32000, d=4096, L=32, h=32, $d_{\text{head}}$=128, $d_{\text{ff}}$=11008, and B=1. Say the prompt tokenizes to 3 ids. 1. ids, shape [1, 3] → embeddings [1, 3, 4096] 2. Per head: Q, K, V are [1, 3, 128]. A is [1, 3, 3]: row 1 weights only position 1; row 3 weights all three. 3. 32 heads × 128 = [1, 3, 4096], then $W_O$ → [1, 3, 4096] 4. FFN: [1, 3, 11008] → [1, 3, 4096] 5. After 32 blocks: [1, 3, 4096] 6. Logits [1, 3, 32000]. The softmax of row 3 is $p_\theta(x_4\mid x_{\le 3})$.

A one-block forward pass in numpy

Tiny sizes, random weights, one block. RMSNorm has no learned gain here. Heads are a leading axis h. The mask is `np.triu(-inf, 1)`: −∞ wherever key position > query position. SiLU(g) is written as g·σ(g).
import numpy as np; r=np.random.randn
T,d,h,dh,dff,V=3,8,2,4,16,50; ids=np.array([5,17,42])   # [T]
x=r(V,d)[ids]                                           # embed lookup: [T,d]
rms=lambda u:u/np.sqrt((u**2).mean(-1,keepdims=True)+1e-6)
def rope(q):  # rotate each (even,odd) pair of q [h,T,dh] by angle t*theta_i
    a,b=q[...,0::2],q[...,1::2]; ang=np.arange(1,T+1)[:,None]*10000.0**(-np.arange(dh//2)/(dh//2))
    return np.stack([a*np.cos(ang)-b*np.sin(ang),a*np.sin(ang)+b*np.cos(ang)],-1).reshape(q.shape)
X=rms(x); Q,K,Vh=[np.einsum('td,hde->hte',X,r(h,d,dh)) for _ in range(3)]  # [h,T,dh]
s=rope(Q)@rope(K).transpose(0,2,1)/np.sqrt(dh)+np.triu(np.full((T,T),-np.inf),1)
A=np.exp(s-s.max(-1,keepdims=True)); A/=A.sum(-1,keepdims=True)           # [h,T,T]
x=x+(A@Vh).transpose(1,0,2).reshape(T,h*dh)@r(h*dh,d); X=rms(x); g=X@r(d,dff)  # x:[T,d] g:[T,dff]
x=x+(g/(1+np.exp(-g))*(X@r(d,dff)))@r(dff,d); print((rms(x)@r(d,V)).shape)  # (3, 50)

The shape story to remember

Ids [T] → lookup [T, d] → L blocks, each [T, d] in and [T, d] out → unembed [T, V] → softmax of the last row gives the next-token distribution. Inside a block, only attention mixes positions: RoPE rotates Q and K, and the mask blocks the future. SwiGLU computes per token in a wider $d_{\text{ff}}$ space. Every sublayer reads a normalized copy and adds its output back.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.