By the end
- Explain query, key, and value roles with one example.
- Calculate and normalize attention scores.
- Trace batch × sequence × embedding shapes.
- Identify the attention, feedforward, residual, and positional parts of an encoder block.
Week 12 · Hands-on foundations
How can each position gather information directly from other positions?
The current Transformer materials range from long video playlists and a complete machine-translation build to newer 2025 notebooks that implement self-attention and encoder blocks from scratch. The durable core is smaller: queries, keys, values, scaled dot-product attention, positional information, and a residual feedforward block.
This chapter condenses materials taught in the 2023–2025 Advanced Data Science course into a smaller core path. Optional depth remains available in the companion notebook.
Use the explorer and three short Python examples before changing a longer model.
Add a causal upper-triangular mask and verify that each position receives zero weight from later positions.
Core ideas
A query represents what the current position seeks; keys represent what each position offers for matching. Their dot products form relevance scores.
Softmax-normalized scores weight the value vectors. The output is a context-dependent mixture rather than a fixed window or one recurrent state.
Multi-head self-attention is combined with residual paths, normalization, and a position-wise feedforward network. Positional information is added because attention alone does not encode order.
Mathematical intuition
Scaling by √d_k prevents dot products from growing too large as key dimension increases. Softmax converts each query's scores into weights over positions.
Identify the input, learned quantity, output, and aggregation. Re-create the relationship with a tiny hand-checkable example before using a library layer.
Interactive explorer
Predict the direction of change before moving a control.
Change a control to inspect the relationship.
Hands-on path
Minimal Python
Each example is independent. Explain its output before copying it into a larger workflow.
import torch
scores=torch.tensor([2.,1.,0.])
weights=torch.softmax(scores,dim=0)
print([round(float(v),3) for v in weights])Predict the result, then click Run.
weights=[0.6,0.3,0.1]
values=[10.,2.,-1.]
print(round(sum(w*v for w,v in zip(weights,values)),1))Predict the result, then click Run.
queries, keys, dimension = 5, 7, 4
print((queries, keys), 'from', (queries,dimension), 'x', (dimension,keys))Predict the result, then click Run.
Failure checks
What goes wrong: Large dot products make softmax extremely sharp.
Check: Divide by the square root of key dimension.
What goes wrong: A causal model can attend to future tokens.
Check: Visualize the allowed attention matrix.
What goes wrong: A high weight is treated as proof of why a model decided.
Check: Use controlled tests and alternative explanation evidence.
Check your understanding
Answer in your own words before opening each panel.
Standard answer: A strong answer connects the central idea to a visible computation and a held-out or shape-based check. The durable core is smaller: queries, keys, values, scaled dot-product attention, positional information, and a residual feedforward block.
Standard answer: A query represents what the current position seeks; keys represent what each position offers for matching. Their dot products form relevance scores.
Standard answer: Softmax-normalized scores weight the value vectors. The output is a context-dependent mixture rather than a fixed window or one recurrent state.
Standard answer: Multi-head self-attention is combined with residual paths, normalization, and a position-wise feedforward network. Positional information is added because attention alone does not encode order.
Standard answer: Scaling by √d_k prevents dot products from growing too large as key dimension increases. Softmax converts each query's scores into weights over positions. It does not by itself prove useful behavior on unseen intended-use cases.
Standard answer: The visible calculation and interpretation should change together. Predict the direction first, then use the result to correct your mental model.
Standard answer: Start with three small token vectors and one query.
Standard answer: Divide by the square root of key dimension.
Standard answer: Record data and split assumptions, input/output shapes, settings, the baseline, held-out metrics, representative failures, and the decision supported by that evidence.
Standard answer: Week 13 turns the learned representation into a transferable backbone and compares frozen features with fine-tuning.
Terminology
Go further
Next: Week 13 turns the learned representation into a transferable backbone and compares frozen features with fine-tuning.