Reading preferences
Concept

Inside Transformer Attention

Extend the AI Transformer foundation with positions, attention heads, and masks.

generative ai, transformers, attention, position

Extend 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

  1. A token's query is compared with eligible keys to form scores.
  2. Scale the scores and apply a mask where required; softmax converts eligible scores to weights summing to one.
  3. 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.

1. Why supply position information to a Transformer?
2. What are attention weights computed from?
3. What can multiple attention heads provide?
4. What does a causal mask block?

References and further reading