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
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.
One [T, d] matrix, refined L times
One block and the two ends, with shapes
LLaMA-7B sizes on "The cat sat"
A one-block forward pass in numpy
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
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.
Bytewise
All courses