Inside Transformer Attention
Extend the AI Transformer foundation with positions, attention heads, and masks.
generative ai, transformers, attention, positionExtend the foundation
The AI Transformer lesson introduces queries, keys and values. Here we add architecture detail. Position can be encoded using fixed or learned representations, or incorporated through relative-position methods. This matters because changing word order can change meaning.
One attention head
- A token's query is compared with eligible keys to form scores.
- Scale the scores and apply a mask where required; softmax converts eligible scores to weights summing to one.
- Use those weights to combine value vectors. For scalar values 2 and 6 with weights 0.25 and 0.75, the result is 5.
See the reasoning
Follow the example one step at a time
Follow one simplified attention calculation. This is a prepared teaching demonstration, not live code execution.
Score
query · eligible keys → scores
Compare a query with permitted keys; masks can block positions.
Heads and blocks
Multiple heads use different learned projections; their outputs are combined and projected. A Transformer block also uses feedforward layers, residual connections and normalisation. A causal decoder masks future positions; an encoder may allow bidirectional attention, while cross-attention can read a separate encoded input.
Attention weights do not alone explain an entire model decision. Long contexts have compute and memory costs that depend on the implementation. Architectures and positional methods differ; check the model rather than assuming every Transformer has identical components.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
