P7 — Tensor Shapes for Transformers
About 55 min
Read before L5.7 — Self-Attention. P2 covered two-dimensional arrays. Here we track batch, time and channels in the actual L5.7 notebook. If you get every question below right, you can move to the next lesson. This is a non-numbered optional guide: its checks and Labs do not record course progress.
Quick Check
Goal
Trace (B,T,C) through head splitting, transpose, matmul, causal mask, softmax and merge. Locate these transformations in the L5.7 notebook and verify zero future attention mass.
Name each axis before reading a formula
(B,T,C) means B batches/examples, T token positions, C feature channels per token. In L5.7's real notebook, q = torch.eye(4).unsqueeze(0) makes (1,4,4): unsqueeze(0) adds a batch axis. k=q.clone() and v=q.clone() keep that shape. causal_attention(q,k,v) returns out (1,4,4) and attention weights (1,4,4). The middle row of weights is one query position's legal key distribution; future attention mass must be zero.
The opening example sets k=q.clone() and v=q.clone() only to simplify shape and mask tracing. Actual attention layers use separately learned Q, K and V projections.
In cell 5, TinyConfig(n_embd=32, n_head=4) and x=torch.randn(2,5,32) produce x (B,T,C)=(2,5,32). attention(x) keeps output shape (2,5,32) despite temporary head dimensions. That distinction is the key invariant.
Reshape/view and transpose
B, T, C = x.shape
H = 4
D = C // H # 8 channels per head
heads = x.reshape(B, T, H, D).transpose(1, 2)
# (2,5,32) -> (2,5,4,8) -> (2,4,5,8)
reshape changes the dimension grouping without changing number of elements; view may only reinterpret compatible memory layout. transpose(1,2) swaps axis 1 and 2, not arbitrary values; contiguous().view(...) is common on the reverse path after transpose. C % H == 0 is mandatory to split channels evenly.
Matrix multiplication creates scores for every query and key
scores = q @ k.transpose(-2, -1) / math.sqrt(D)
# (2,4,5,8) @ (2,4,8,5) -> (2,4,5,5)
torch.matmul or @ multiplies over the last two dimensions and broadcasts the leading dimensions. The two 5 axes are query time and key time. Scaling by sqrt(D) stabilizes scores; it does not change shape.
Mask before softmax
future = torch.triu(torch.ones(T, T, dtype=torch.bool), diagonal=1)
masked = scores.masked_fill(future, float("-inf"))
weights = torch.softmax(masked, dim=-1)
# both (2,4,5,5)
The upper triangle blocks future key positions. Boolean shape (T,T) broadcasts across B and H. softmax(dim=-1) normalizes over allowed key positions: valid rows approximately sum to 1 and masked future cells have probability zero. The sample ensures at least the diagonal is legal so rows do not become all -inf. Padding masks are another constraint; a wrong broadcast shape can mask the wrong positions.
Combine weighted values and recover (B,T,C)
mixed = weights @ v # (2,4,5,8)
result = mixed.transpose(1, 2).contiguous().view(B, T, C)
# (2,5,4,8) -> (2,5,32)
The L5.7 implementation hides some splitting inside CausalSelfAttention; the P7 companion notebook exposes each tensor so you can print it directly. Use the Open notebook in Google Colab Lab launcher below. If the public materials have not yet been synchronized, download the P7 notebook file and select File → Upload notebook in Colab. Run CPU cells in order, change T=5 to T=3, and restore it. No new PyTorch function writing is required.
Loading lab…
Predict
Browser practice: read before editing
The browser Lab uses plain Python tuples, not torch, to check the three intermediate shapes. Complete the three return statements for head splitting, attention scores and merged output. Use the progressive hints and full answer. Then open the P7 CPU notebook to confirm the tuple answers with actual tensors.
Loading lab…
A quick L5.7 notebook reading checklist
Follow the real l05-07-causal-self-attention.ipynb: (1) eye(4).unsqueeze(0) → (1,4,4); (2) weights → (1,4,4) with no future mass; (3) TinyConfig(n_embd=32,n_head=4); (4) x and y both (2,5,32). Its setup cell may fetch tiny_llm.py from the public materials repository; that dependency is separate from this self-contained P7 companion notebook.
Quick Check
Key Takeaways
- (B,T,C) describes input and output even when an attention implementation temporarily splits heads.
- A transpose swaps dimensions; matmul contracts D and produces (T,T) scores.
- Causal masking must happen before softmax, and future probabilities must be zero.