concept / generative-ai--self-attention
Next task →
University/Generative AI/Transformer/Self-attention
Representation · Transformer · Attention

Self-attention

Self-attention in Representation → Transformer → Attention. Transformers have no recurrence: they must represent order and route information between positions using only attention and position information, while keeping memory tractable at long context.

39 template sectionsfoundational75 mingenerated template · not reviewed
Generated template — not a reviewed lesson. This page shares boilerplate with other generated pages, so its prose may not be specific to Self-attention. The structural heuristic reports 20/100, but that number is not an accuracy score and should not be read as one.Generated template: prose is not specific to this concept · No prerequisites declared · Prerequisite chain incomplete · No interactive visualStudy a hand-authored reference lesson instead →
Mastery requires: derivation reproduced, from-scratch implementation committed, failure case explained, and assessment score ≥ 80%. Current state: not_started.

1. Concept overview

Self-attention is a concept in Representation → Transformer → Attention. Transformers have no recurrence: they must represent order and route information between positions using only attention and position information, while keeping memory tractable at long context. The central question of this page is not what is it called but what problem forces it to exist, which assumptions make it valid, and how it fails. The compact statement is:

Q=XWQ,  K=XWK,  V=XWV,A=softmax⁡ ⁣(QK⊤dk+M),Y=AV.Q=XW_Q,\;K=XW_K,\;V=XW_V,\qquad A=\operatorname{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}+M\right),\qquad Y=AV . RoPE rotates query and key by an angle proportional to position: Rm⊤Rn=Rn−mR_m^\top R_n=R_{n-m}, so dot products depend only on relative offset.

Everything below derives that statement, implements it, measures it and identifies the cases where it breaks.

2. Why this concept exists

Recurrent networks compressed history into a hidden state, losing parallelizability; CNNs needed many layers to connect distant tokens; absolute positional indices did not generalize to longer sequences.

Before self-attention, practitioners either solved a restricted version by hand or accepted an unjustified heuristic. self-attention appears because it buys a real guarantee — a bound, an invariance, a tighter approximation or a tractable computation — under assumptions you can state and test. In generative ai the pressure is usually scale: larger data, higher dimensions, longer contexts or larger models.

3. Historical background

Attention was introduced for machine translation in 2014–2015 and became the core of the Transformer in 2017; RoPE (2021) and FlashAttention (2022) solved position and efficiency issues.

The idea did not appear fully formed. Earlier work supplied the notation and the motivating failure; later work supplied the derivation and the implementation. When reading the original literature, separate the theorem from the author's heuristic justification — the two are often presented together but have different status.

4. Fundamental problem

Transformers have no recurrence: they must represent order and route information between positions using only attention and position information, while keeping memory tractable at long context.

Formally, the difficulty is that the object of interest is defined by a global property (an optimum, a distribution, an invariant, a limit) while we can only compute local quantities. Assumptions bridge that gap: Fixed vocabulary, finite context length, learned projections, and (for causal LM) a lower-triangular mask M with −∞ above the diagonal. If any of them fails, the result may still be useful empirically, but the guarantee no longer applies.

5. First-principles explanation

Embed each token with a position-dependent vector, compute content-based similarity between queries and keys, normalize with softmax, and mix values. Causal masking enforces autoregression.

Derivation starts from the simplest possible model rather than from a definition. Project X into Q,K,V; scaling by sqrt(d_k) keeps scores O(1) at initialization. Apply causal mask so position i cannot read j>i. Only after the local model is justified do we add the machinery specific to self-attention.

6. Prerequisite concepts

You should be comfortable with: the preceding modules of this domain. In particular, you must be able to manipulate the notation in section 8 and understand why each assumption in section 7 is needed. If a prerequisite is still listed as outlined in the curriculum, use the linked papers and the 11-step practical chain on its task page first.

7. Complete mathematical formulation

Q=XWQ,  K=XWK,  V=XWV,A=softmax⁡ ⁣(QK⊤dk+M),Y=AV.Q=XW_Q,\;K=XW_K,\;V=XW_V,\qquad A=\operatorname{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}+M\right),\qquad Y=AV . RoPE rotates query and key by an angle proportional to position: Rm⊤Rn=Rn−mR_m^\top R_n=R_{n-m}, so dot products depend only on relative offset.

Assumptions. Fixed vocabulary, finite context length, learned projections, and (for causal LM) a lower-triangular mask M with −∞ above the diagonal.

Domain of validity. The statement is made for the setting described above. Extending it to generative ai / Transformer requires new assumptions and a new proof; do not assume the formula transfers automatically.

8. Notation dictionary

| Symbol | Meaning | Type | |---|---|---| | xx | input / state / observation | vector | | θ\theta | parameters being learned or solved for | vector | | ff | objective, map or density under study | function | | ∇,∂\nabla,\partial | gradient / partial derivative | differential operator | | E\mathbb{E} | expectation under an implied distribution | operator | | ε,δ\varepsilon,\delta | tolerance and the radius it forces | positive scalar | | α,η,γ\alpha,\eta,\gamma | step size, learning rate, discount | scalar | | X\mathcal{X} | domain / feasible set | set | | TT | number of steps, samples or trials | integer |

Every symbol above is used with the same meaning throughout this page. The concept-specific symbols appear in section 7.

9. Step-by-step derivation

Steps

  1. Project X into Q,K,V; scaling by sqrt(d_k) keeps scores O(1) at initialization.
  2. Apply causal mask so position i cannot read j>i.
  3. Softmax rows give a convex combination of values.
  4. Add positional information either absolutely or by rotating Q,K (RoPE).
  5. Cache K,V for past positions to avoid recomputation during generation.

At each step, pause and check which assumption is doing the work. A step that seems obvious is usually hiding one: for self-attention the hidden assumption is typically about regularity, independence or finite precision.

10. Proofs and proof intuition

Proof / proof intuition. Permutation equivariance without positions follows because (ΠX)W = Π(XW) and attention commutes with Π; adding positional encodings breaks it intentionally. RoPE's relative property follows from the rotation group identity.

The standard proof is constructive: it exhibits the quantity that must shrink and shows it does. If you remove an assumption, locate the exact line of the proof that fails — that line is the boundary of the result.

11. Geometric interpretation

Each query defines a direction in embedding space; keys form a set of landmarks; attention weights are a soft nearest-landmark lookup over the value vectors.

Draw the objects before trusting the algebra. In two dimensions the statement usually reduces to angles, distances, projections or contour shapes; the same geometry survives in high dimensions even when you cannot plot it.

12. Visual explanation

Use the interactive visualizers in Practical Labs to see self-attention change as its controlling parameters move. For this topic, plot the governing expression from section 7 against one variable at a time. Label axes with units, overlay the assumption boundary, and annotate the point where the conclusion stops holding. A visual that does not let you predict the outcome before changing a parameter is decorative, not explanatory.

13. Numerical worked example

Worked numerical example. For d_k=4 and q·k=8, the scaled score is 8/2=4. With competitor scores 1 and 0, softmax gives about (0.952,0.047,0.002) — the largest score dominates but others still contribute.

Redo this calculation by hand, then reproduce it in code. If your computed numbers disagree with the text, either the arithmetic or the implementation is wrong — find out which.

14. Real-world analogy

At every word, the model consults all previous words with a relevance score and summarizes what it finds.

Analogies are scaffolding: they make the first step intuitive, but they break where the formal assumptions are stronger than the analogy. Always return to the equation after using one.

15. Algorithm pseudocode

algorithm Attention(X, mask):
    Q,K,V = XWq, XWk, XWv
    S = Q K^T / sqrt(d_k) + mask
    A = row_softmax(S)
    return A V

The pseudocode intentionally omits engineering details. Add input validation, numerical guards and logging in the real implementation.

16. Implementation from scratch

import numpy as np

def attention(x, wq, wk, wv, causal=False, temperature=1.0):
    q, k, v = x @ wq, x @ wk, x @ wv
    s = (q @ k.T) / (np.sqrt(q.shape[-1]) * temperature)
    if causal:
        s = np.where(np.triu(np.ones(s.shape, bool), 1), -1e9, s)
    e = np.exp(s - s.max(axis=-1, keepdims=True))
    a = e / e.sum(axis=-1, keepdims=True)
    return a @ v, a

rng = np.random.default_rng(1)
x = rng.standard_normal((4, 8))
w = [rng.standard_normal((8, 8)) * 0.1 for _ in range(3)]
y, a = attention(x, *w, causal=True)
assert np.allclose(a.sum(axis=1), 1.0)
assert np.allclose(a[np.triu_indices(4, 1)], 0.0)
print(y.shape, a.shape)

This implementation is deliberately small and dependency-light. Run it, then extend it to the concrete dataset named in the experimental section.

17. Professional library implementation

import torch, torch.nn.functional as F
# q,k,v: (batch, heads, seq, d_k)
out = F.scaled_dot_product_attention(q, k, v, is_causal=True)  # fused, flash path when available

The library version uses a battle-tested kernel. Compare it to your from-scratch version on a tiny input before trusting either on real data.

18. Code walkthrough

Scratch code. The function first validates its inputs, then performs the core computation and asserts a known answer. The assertion is the point: without a hand-computed reference, a wrong implementation looks identical to a right one.

Library code. The library call hides numerical safeguards (stable softmax, fused kernels, dtype handling). Know which safeguards it provides so you can reproduce them when writing your own self-attention kernel.

19. Tensor and memory analysis

For a batch of shape (b,d)(b,d) in fp32, the input occupies 4bd4bd bytes and each same-sized buffer another 4bd4bd. A quantity of shape (b,n,n)(b,n,n) costs 4bn24bn^2 bytes, which becomes the dominant term once nn grows. O(n·d) for Q,K,V plus O(n²) naive attention weights or O(n·d) with streaming softmax; KV cache is O(n·layers·d). On a GPU, also budget for allocator fragmentation, CUDA context and communication buffers; a theoretical fit is not the same as a successful allocation.

20. Time complexity

O(n²d) score computation and O(n²) memory for the weights; flash attention avoids materializing the n×n matrix. Express the bound in terms of the problem dimensions you actually measured — sample count n, feature dimension d, sequence length L or vocabulary size V — and state whether it is per update or over the full training run. Report both asymptotic growth and measured wall-clock time, because constants and memory movement decide real performance.

21. Space complexity

O(n·d) for Q,K,V plus O(n²) naive attention weights or O(n·d) with streaming softmax; KV cache is O(n·layers·d). Separate persistent state (parameters, buffers, caches) from transient working memory (activations, temporaries, communication buffers). The peak allocation, not the average, determines whether a job fits on the device. When you change batch size or precision, recompute this estimate rather than extrapolating from a small run.

22. Experimental demonstration

Vary sequence length and plot attention time and memory with and without a fused kernel; verify causal zeros.

Pre-register the hypothesis, fix the seed before running, and keep a record of every failed attempt. Report at least three seeds so a reader can tell signal from noise.

23. Benchmark results

Compare naive softmax, PyTorch SDPA and FlashAttention at equal dtype and shape; report tokens/s and peak memory, not just one latency number.

There is no legitimate universal benchmark number for this concept. Any claim of state of the art must name the dataset, hardware, precision, implementation and metric. Qualitative claims in this page are theory; numbers you obtain by running the experiment are evidence.

24. Limitations

  • Quadratic cost in context length
  • Attention weights alone are not a complete explanation of model behaviour
  • Position extrapolation is imperfect

Limitations are part of the result, not an appendix. A method whose assumptions you cannot check is a method whose conclusions you cannot trust when using self-attention.

25. Failure scenarios

  • Missing causal mask leaks future tokens
  • KV cache dtype mismatch
  • Score overflow at large magnitudes without max subtraction

For each scenario, write down which assumption is violated, the earliest observable symptom and an automatic detector. A failure you cannot detect is a failure you will eventually ship.

26. Common misconceptions

  • Attention is the whole transformer (FFN and residuals matter equally)
  • High attention weight proves causal importance

Misconceptions survive because the wrong story is often simpler than the correct one. Replace each with the precise statement from section 7.

27. Alternative approaches

  • Linear attention
  • State-space models
  • Sparse and sliding-window attention
  • Cross-attention for conditioning

Choose among alternatives by stating which assumption you are willing to drop and what you get in exchange. Compare them with the same budget and the same metric.

29. Research applications

  • Language modeling
  • Vision
  • Retrieval
  • Multimodal fusion

For each application, write one sentence about what self-attention contributes and one about what it cannot contribute. Research uses a tool well when it knows its boundary.

30. Important research papers

  • Attention Is All You Need — 2017, NeurIPS (library id: transformer2017)
  • Language Models are Few-Shot Learners — 2020, NeurIPS (library id: gpt3)
  • Direct Preference Optimization: Your Language Model is Secretly a Reward Model — 2023, NeurIPS (library id: dpo2023)
  • LoRA: Low-Rank Adaptation of Large Language Models — 2021, ICLR (2022) (library id: lora2021)
  • FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness — 2022, NeurIPS (library id: flashattention2022)

31. Further reading

Vaswani et al. (2017) Attention Is All You Need; Su et al. (2021) RoFormer; Dao et al. (2022) FlashAttention.

Prefer primary sources and official documentation over blog summaries. When a source states a result without proof, mark it as a claim until you can derive it.

32. Practical exercises

  1. Implement attention with and without causal mask and verify the zeros.
  2. Add RoPE and check relative-position invariance numerically.
  3. Measure KV-cache memory for n=4096.
  4. Complete the 11-step practical chain for Self-attention in My Tasks, starting with the from-scratch implementation.
  5. Record a plot and a numerical table, not just a sentence saying it worked.

33. Debugging challenges

  • NaNs in softmax: subtract the row max.
  • Wrong shape: check head reshape order.
  • Causal leakage: inspect the mask diagonal.

For each bug, add a regression test that fails before the fix and passes after it.

34. Advanced exercises

  1. Implement FlashAttention-style tiled softmax in Triton.
  2. Derive attention's Jacobian and analyze gradient flow.
  3. Write a one-page critique of a paper that uses self-attention: identify which assumptions it relies on and whether it checks them.

35. Interview questions

  • Why scale by sqrt(d_k)?
  • Why is attention permutation equivariant before positional encoding?

Also be ready to: state the assumptions out loud before deriving anything; give a concrete counterexample where self-attention fails; explain the difference between a theorem and an empirical observation about it; and describe how you would verify your implementation in a code review.

36. Research questions

  • Can attention be replaced entirely by state spaces for long context?
  • Which attention heads implement reusable circuits?

A research question is useful only if an experiment could answer it. For each one above, state what observation would falsify your preferred answer.

37. Mastery assessment

No mastery rubric is shown for this page. It is a generated template, and its rubric was boilerplate that did not match the topic. Use the core path or a hand-authored lesson for assessed material.

38. Implementation submission

No mastery rubric is shown for this page. It is a generated template, and its rubric was boilerplate that did not match the topic. Use the core path or a hand-authored lesson for assessed material.

39. Completion criteria

All of: derivation reproduced on paper; code executed with passing tests; numerical example matched; one failure mode reproduced and detected; assessment passed; primary source cited; results written up with hardware, seed and metric. Only then may the task be marked mastered.

Research papers linked to this concept