Transformers · Intermediate

Transformer Self-Attention

Trace Q, K, V and token-to-token attention without pretending to train an LLM.

This focused lab teaches the self-attention mechanism with small deterministic vectors so every matrix remains inspectable.

Step by step

  1. Represent tokens as vectors.
  2. Project into Q, K and V.
  3. Calculate scaled query-key scores.
  4. Apply stable softmax.
  5. Use attention weights to mix value vectors.

Core formulas

Scaled attention

A = softmax(QKᵀ / √dₖ)

Each query gets a normalized distribution over keys.

Output

O = A·V

Values are mixed with the calculated weights.

When to use Transformer Self-Attention

  • Understanding the core self-attention operation.

Official documentation

Attention Is All You Need