Lesson 1: Scaled dot-product attention, derived and built by hand
Module 2 · Lesson 1 · About 50 minutes · Needs: Module 1, Lessons 1 and 2 (tensors, dot products, softmax, the copy race)
The situation
Sol 404 at Aurora Station. In Module 1 your transformer beat the GRU, but its attention came from PyTorch's ready-made nn.TransformerEncoderLayer. Kofi Mensah will not sign off a part nobody in the lab has opened. "Write attention yourself," he says, "and show me it gives the same numbers."
This lesson starts tinyformer/attention.py. If you met attention in the ai-engineering course (Module 6, Lesson 1), skim sections 1 and 3; the checks, shapes and head survey are new.
A real case, first
On 8 March 2022 Catherine Olsson, Nelson Elhage, Neel Nanda and colleagues at Anthropic published "In-context Learning and Induction Heads" (transformer-circuits.pub). They describe a circuit of "a pair of attention heads in different layers". The first is a "previous token head" that copies information from each token into the next. The second, the induction head, makes "…[A][B]…[A] … more likely to be completed with [B]".
They report that these heads form in "a phase change that occurs early in training for language models of every size" (with more than one layer), and may account for most in-context learning. They call their evidence "a circumstantial case", stronger for small models than large. The point for this lesson: a head's job can be read off its attention weights. By the end you will find an induction head in GPT-2 with your own code.
What you will be able to do
- Derive attention from a dictionary lookup, checking each step in code.
- Write
naive_attentionand match PyTorch's built-in. - Trace the five steps, naming every shape.
- Read an attention matrix's rows, columns and axes, and catch the wrong-axis bug.
- Read one GPT-2 head and sort all 144 by pattern.
1. Deriving scaled dot-product attention (Essential)
Every transformer runs one formula many times. Derive it once and every later variant (masks, heads, caches) is a small edit. Paste the torch setup cell and shared block 1 first.
import torch
DEVICE = "cuda" if torch.cuda.is_available() else "cpu" # every lesson runs on "cpu"; a GPU is optional
torch.manual_seed(11) # the course seed (see course-guide/06)
print("torch", torch.__version__, "| device", DEVICE, "| CPU threads", torch.get_num_threads())Code walkthrough
- The course's torch setup cell: PyTorch, the CPU, seed 11. It printed
torch 2.14.1 | device cpu | CPU threads 5on the author's Mac.
import random
import torch
COURSE_DATE = "2026-10-09" # versions, model names and prices checked on this day
SEED = 11 # every generator in the course starts from this seed
SNAPSHOT_SOL = 400 # the corpus is the station record up to sol 399
def set_seed(seed=SEED):
"""Seed Python and PyTorch so a cell gives the same numbers every run."""
random.seed(seed)
torch.manual_seed(seed)
set_seed()
print("torch", torch.__version__, "| threads", torch.get_num_threads())Code walkthrough
- Shared block 1, as written:
SEED = 11andset_seed().
Start with a Python dictionary. Ask for "Maya" and you get Maya's value; every other row is ignored. The copy task needs exactly this. Its flaw for learning: a query is an exact match or nothing, so nothing says "you were close".
Now make keys and query vectors. Score the query against each key, turn the scores into weights with a softmax, and return the weighted blend of the values: a soft lookup. Our query is mostly Maya, a little Kofi.
import torch.nn.functional as F
set_seed()
keys = torch.randn(3, 4) * 0.5 # one key per crew member: Maya, Kofi, Hana
values = torch.eye(3) # what each hands over: Maya [1,0,0], Kofi [0,1,0] ...
query = (0.7 * keys[0] + 0.3 * keys[1]).requires_grad_() # mostly "Maya", a little "Kofi"
scores = keys @ query # one similarity per key
hard = F.one_hot(scores.argmax(), 3).float() # a dictionary: the best key wins outright
soft = scores.softmax(dim=-1) # attention: every key wins a share
print("scores", [round(s, 3) for s in scores.tolist()])
print("hard ", hard.tolist(), "| can learn from it:", (hard @ values).requires_grad)
print("soft ", [round(w, 3) for w in soft.tolist()])
(soft @ values)[0].backward() # how should the query move to read more of Maya?
print("gradient on the query", [round(g, 3) for g in query.grad.tolist()])
for sharpen in [1, 4, 16]:
print(f"scores x{sharpen:2d}", [round(w, 3) for w in (sharpen * scores.detach()).softmax(-1).tolist()])Code walkthrough
values = torch.eye(3)makes each value a label, so the output says how much of each person was read.queryis 0.7 of Maya's key plus 0.3 of Kofi's;requires_grad_()tracks its gradient.keys @ queryis three dot products.argmaxthenone_hotis the dictionary;softmaxthe soft version.argmaxreturns an index, so the hard output has no gradient.backward()on Maya's share fillsquery.grad. The loop multiplies the scores by 1, 4 and 16 before the softmax.
Scores 1.012, -0.251 and -0.362 give weights 0.651, 0.184 and 0.165. Multiply the scores by 4 and Maya's share is 0.990; by 16, 1.000. The dictionary is the extreme case of the soft lookup, so attention can learn to act like one.
The difference that matters is the gradient. The hard lookup printed False. The soft lookup gave the query a gradient, a direction to move to read more of Maya. Training can only shape what it can differentiate.
Which similarity? The dot product: multiply slot by slot and add. It is large when two vectors point the same way. Bahdanau's attention (Module 1, Lesson 3) used a small network per pair; the dot product wins because all pairs are one matrix product.
set_seed()
T, d = 4, 4 # 4 positions, 4 numbers per query, key and value
Q, K, V = torch.randn(T, d), torch.randn(T, d), torch.randn(T, d)
out_loops = torch.zeros(T, d)
for i in range(T): # one query at a time
s = torch.stack([sum(Q[i, c] * K[j, c] for c in range(d)) for j in range(T)]) / d ** 0.5
a = s.exp() / s.exp().sum() # softmax over the keys, by hand
out_loops[i] = sum(a[j] * V[j] for j in range(T))
out_matrix = torch.softmax(Q @ K.T / d ** 0.5, dim=-1) @ V # the same thing as two matrix products
print("largest difference:", (out_loops - out_matrix).abs().max().item())
print("multiply-adds for scores and sum:", 2 * T * T * d)Code walkthrough
- In self-attention every position makes a query, a key and a value, so
Q,KandVhave one row per position. - The loop is the derivation written literally: a sum over slots
c, divided by the square root ofd, a hand-written softmax, a weighted sum of value rows. Q @ K.Tmakes all 16 scores at once;softmax(dim=-1)normalises each row;@ Vmixes. The last line counts the multiply-adds.
The versions differ by 1.2e-07, float32 rounding. Both do 128 multiply-adds (arithmetic: 2 x 4 x 4 x 4), a count that grows with the square of the length (Module 10).
Assembled, this is the formula from Section 3.2.1 of "Attention Is All You Need" (Vaswani et al., 2017): scaled dot-product attention. The division by the square root of d keeps scores moderate as vectors get wider; Lesson 2 derives that factor and breaks it.
2. Naive attention, line by line (Essential)
The lab keeps two versions of attention: a plain one you can read and print, and the fast built-in later modules use. Kofi's test is that they agree.
The five steps: project tokens into queries, keys and values; score every pair; scale; normalise each row with a softmax, after masking forbidden pairs; mix the values. Projection needs learned weights, so it lives in the layer (Lesson 3).
import math
def naive_attention(q, k, v, mask=None, return_weights=False):
"""Scaled dot-product attention, one step per line.
q: (..., T_q, d_head); k and v: (..., T_k, d_head); mask: True where a query may look."""
scores = q @ k.transpose(-2, -1) # step 2: every query against every key
scores = scores / math.sqrt(q.shape[-1]) # step 3: divide by sqrt(d_head)
if mask is not None:
scores = scores.masked_fill(~mask, float("-inf")) # step 4a: forbidden pairs score -inf
weights = scores.softmax(dim=-1) # step 4b: each row sums to 1 over the keys
out = weights @ v # step 5: weighted sum of value rows
return (out, weights) if return_weights else out
set_seed()
q, k, v = (torch.randn(32, 4, 128, 32) for _ in range(3)) # base sizes: batch 32, 4 heads, 128 tokens, 32 wide
causal = torch.ones(128, 128, dtype=torch.bool).tril()
for name, mine, theirs in [
("no mask", naive_attention(q, k, v), F.scaled_dot_product_attention(q, k, v)),
("causal ", naive_attention(q, k, v, causal), F.scaled_dot_product_attention(q, k, v, is_causal=True))]:
print(name, tuple(mine.shape), "largest difference from PyTorch:", f"{(mine - theirs).abs().max().item():.1e}")Code walkthrough
k.transpose(-2, -1)swaps the keys' last two axes, soq @ k^Tscores every pair for every batch item and head at once; any leading axes work.math.sqrt(q.shape[-1])reads the head width from the tensor.masked_fill(~mask, float("-inf"))sets forbidden scores to minus infinity, which the softmax turns into exactly 0. Lesson 4 builds every mask; here only the causal mask (each token sees itself and earlier ones) appears, made bytorch.ones(...).tril().softmax(dim=-1)normalises over the last axis, the keys.return_weightsreturns the weights for inspection.- The test uses the
basemodel's sizes (course-guide/06): batch 32, 4 heads, 128 tokens, head width 32.
The largest differences were 9.5e-07 and 8.3e-07: float32 rounding from adding in a different order. A real bug shows up as 1e-2 or worse.
3. Tracing the five steps on Maya (Essential)
Shapes are where attention code breaks. Tracing a tiny example, printing everything, shows what each line does.
The running example is the name Maya: ids 32, 45, 68, 45 in the shared character tokeniser (course-guide/06, block 7 printed encode("Maya")), typed in so this lesson needs no corpus. One head, width 8, head width 4.
ids = torch.tensor([[32, 45, 68, 45]]) # "Maya" in the shared character tokeniser (block 7)
set_seed()
embed = torch.nn.Embedding(69, 8) # 69 tokens in the vocabulary, 8 numbers each
W_q, W_k, W_v = (torch.randn(8, 4) / 8 ** 0.5 for _ in range(3)) # one head: 8 in, 4 out
with torch.no_grad():
x = embed(ids) # (1, 4, 8): batch, tokens, width
q, k, v = x @ W_q, x @ W_k, x @ W_v # step 1: project -> (1, 4, 4) each
scores = q @ k.transpose(-2, -1) # step 2: score -> (1, 4, 4)
scaled = scores / math.sqrt(4) # step 3: scale
mask = torch.ones(4, 4, dtype=torch.bool).tril()
weights = scaled.masked_fill(~mask, float("-inf")).softmax(-1) # step 4: mask and normalise
out = weights @ v # step 5: mix the values -> (1, 4, 4)
for name, t in [("x", x), ("q", q), ("scores", scores), ("weights", weights), ("out", out)]:
print(f"{name:8}{tuple(t.shape)}")
print("scaled scores, row 3 (the second 'a'):", [round(s, 2) for s in scaled[0, 3].tolist()])
print(weights[0].numpy().round(2))
print("same as naive_attention:", torch.allclose(out, naive_attention(q, k, v, mask)))Code walkthrough
nn.Embedding(69, 8)is a random table, one row per token in the shared vocabulary;embed(ids)picks four rows.- The projections are random, divided by the square root of the input width to keep values moderate; a trained model learns them.
torch.no_grad()skips gradient tracking. - Each step is one line, its shape in the comment. The last line checks the trace against
naive_attention.
Row 3, the second a, is [0.97, 0.15, -0.35, 0.15]. Row 1, the first a, is identical: same character, same query. Upper-triangle cells are minus infinity: no reading ahead.
After the softmax, row 0 is [1, 0, 0, 0] whatever its score of -1.19: a first token can only read itself. Row 3 is [0.46, 0.21, 0.12, 0.21], and the trace matches naive_attention.
Step 5 for row 3 mixes 0.46 of M's value, 0.21 of each a's and 0.12 of y's. Weights are positive and sum to 1, so each output is an average: a head blends what it sees and cannot go outside that range.
4. Attention matrix shape and meaning (Essential)
The weight matrix is the one object you can print, plot and test. Knowing its rows, columns and axes turns a silent bug into a failed check.
A row answers "where does this query read from?" and sums to 1. A column answers "how much is this key read?" and sums to anything. The rows and columns of an attention matrix are not interchangeable, and the next block proves it.
A = weights[0] # (4, 4): rows are queries, columns are keys
print("row sums ", A.sum(-1).tolist())
print("column sums", [round(c, 2) for c in A.sum(0).tolist()])
print("row 0 ", A[0].tolist())
print("'a' at 1 and 3, same key:", torch.equal(k[0, 1], k[0, 3]),
"| row 3 weights on them:", round(A[3, 1].item(), 3), round(A[3, 3].item(), 3))
order = torch.tensor([2, 0, 3, 1]) # shuffle the four tokens: "yMaa"
with torch.no_grad():
out_plain = naive_attention(q, k, v) # no mask, no positions
out_shuffled = naive_attention(q[:, order], k[:, order], v[:, order])
print("shuffle in, same shuffle out:", torch.allclose(out_shuffled, out_plain[:, order], atol=1e-6))
print("the two 'a' outputs are identical:", torch.allclose(out_plain[0, 1], out_plain[0, 3]))Code walkthrough
A.sum(-1)adds across rows;A.sum(0)down columns.torch.equalconfirms the two a's share a key.orderrearranges the positions. Comparing attention on shuffled tokens (no mask) with the shuffled original output tests whether attention notices order.
Rows sum to 1 (one prints 0.99999994, rounding). Columns sum to 2.64, 0.86, 0.30 and 0.21: M is read most, partly because every row sees it. Row 3 gives each a exactly 0.206.
A real model adds two axes: (batch, heads, queries, keys). One base layer on a training batch holds 32 x 4 x 128 x 128 = 2,097,152 weights (arithmetic). Queries and keys can differ in length (see the exercise).
The shuffle printed True twice. Without a mask or positions, attention is permutation equivariant: reorder the inputs and the outputs reorder the same way, and the two a's get identical outputs. Module 4 adds positions.
Break it: softmax down the wrong axis
Normalise over queries instead of keys. It is one character, -2 for -1, and nothing crashes.
def wrong_axis_attention(q, k, v, mask):
scores = (q @ k.transpose(-2, -1) / math.sqrt(q.shape[-1])).masked_fill(~mask, float("-inf"))
return scores.softmax(dim=-2) @ v, scores.softmax(dim=-2) # the bug: normalise down the columns
with torch.no_grad():
bad_out, bad_w = wrong_axis_attention(q, k, v, mask)
print("shape still fine:", tuple(bad_out.shape))
print("row sums ", [round(r, 2) for r in bad_w[0].sum(-1).tolist()])
print("column sums", [round(c, 2) for c in bad_w[0].sum(-2).tolist()])
print("row 0 now reads", round(bad_w[0, 0, 0].item(), 2), "of its own value")
assert torch.allclose(weights.sum(-1), torch.ones(1, 4)), "rows must sum to 1"
print("the row-sum test catches it:", not torch.allclose(bad_w.sum(-1), torch.ones(1, 4)))Code walkthrough
wrong_axis_attentionisnaive_attentionwithsoftmax(dim=-2): each column now sums to 1 instead of each row.- The
assertis the test that goes into the lab: correct weights pass it, and the last line shows the broken ones fail it.
The output keeps its (1, 4, 4) shape, so a shape check passes. But rows sum to 0.04, 0.69, 1.04 and 2.22. A model with this bug still trains, just badly. The one-line row-sum test goes into tests/test_m02_attention.py.
5. Reading one real attention head (Recommended)
Random weights show the arithmetic; a trained model shows its purpose. GPT-2 small, the course's reference model, has 12 layers of 12 heads.
%pip install -q transformers==5.19.0from transformers import AutoModelForCausalLM, AutoTokenizer
REF = "openai-community/gpt2" # the course's reference model: GPT-2 small, MIT licence
tok = AutoTokenizer.from_pretrained(REF)
ref = AutoModelForCausalLM.from_pretrained(REF, attn_implementation="eager").eval()
text = "Log 4821, sol 212. Maya Lindqvist repaired the oxygen recycler. Maya Lindqvist"
ids = tok(text, return_tensors="pt")["input_ids"]
pieces = [tok.decode([i]) for i in ids[0]]
with torch.no_grad():
run = ref(ids, output_attentions=True)
ATT = torch.stack(run.attentions)[:, 0] # (layers, heads, T, T) for our one sentence
print(len(pieces), "tokens:", pieces)
print("one layer:", tuple(run.attentions[0].shape), "| all layers:", tuple(ATT.shape))Code walkthrough
- The loading lines are the course standard (course-guide/02, section 6).
attn_implementation="eager"selects the plain path, the only one that returns weights. textis a corpus-style log line with Maya's name twice: the [A][B] ... [A] pattern.output_attentions=Truereturns one (1, 12, T, T) tensor per layer;torch.stack(...)[:, 0]makes one (12, 12, 21, 21) tensor.
The line is 21 tokens: ' Maya' at positions 7 and 17, then Lindqvist split into ' Lind', 'qv', 'ist'.
first, second = [i for i, p in enumerate(pieces) if p == " Maya"]
w = ATT[:, :, second, first + 1] # every head: weight from the 2nd " Maya" to the token after the 1st
layer, head = divmod(int(w.argmax()), 12)
row = ATT[layer, head, second, : second + 1]
print(f"layer {layer} head {head}, query {pieces[second]!r} at position {second}")
for j in row.topk(3).indices.tolist():
print(f" key {j:2d} {pieces[j]!r:12} weight {row[j].item():.3f}")
print("GPT-2's next-token guess after the 2nd ' Maya':", repr(tok.decode(run.logits[0, second].argmax())))
diag = ATT[layer, head].diagonal(offset=-(second - first - 1)) # the stripe "the token after my earlier copy"
print("weights on that stripe for the repeated name:", [round(x, 2) for x in diag[-4:].tolist()])Code walkthrough
wis a (12, 12) table: for every head, the weight from the second' Maya'to' Lind'(key 8).divmod(..., 12)turns its largest entry's position into a layer and head.row.topk(3)lists that head's three largest weights;run.logits[0, second].argmax()is GPT-2's next-token guess.diagonal(offset=-9)reads cells nine below the diagonal: each repeated token looking at the token after its earlier copy.
Layer 5, head 5 puts 0.942 of the second Maya's attention on ' Lind', the token after the first Maya, and GPT-2's guess is ' Lind'. That is the induction pattern Olsson and colleagues describe, found in a published model with your own code.
Along the repeated name the stripe reads 0.94, 1.00, 0.88 and 0.95. Still, one sentence is an anecdote; section 6 tests every head properly.
6. Every head at a glance (Recommended)
You cannot read 144 heads one by one; you can read one summary number per head. Clark and colleagues did this for BERT ("What Does BERT Look At?", 2019, arXiv:1906.04341) and found heads attending to delimiter tokens, fixed offsets, or broadly.
Three heads, one line: 4.11 reads the token just before, 5.5 is the induction stripe, 5.7 puts nearly everything on the first token. Each pattern becomes a score: weight on the previous position, on the token after an earlier copy, on position 0.
g = torch.Generator().manual_seed(SEED)
R = 50 # 50 random tokens, then the same 50 again
rnd = torch.randint(1000, 10000, (4, R), generator=g)
seq = torch.cat([torch.full((4, 1), tok.bos_token_id), rnd, rnd], dim=1) # (4, 101)
with torch.no_grad():
A = torch.stack(ref(seq, output_attentions=True).attentions) # (12, 4, 12, 101, 101)
pos = torch.arange(R + 1, 2 * R + 1) # positions in the repeat
score = {"induction": A[..., pos, pos - R + 1].mean((1, 3)), # the token after my earlier copy
"previous": A[..., torch.arange(1, 2 * R + 1), torch.arange(0, 2 * R)].mean((1, 3)),
"first": A[..., 1:, 0].mean((1, 3))} # parked on position 0
kind = torch.full((12, 12), 3) # 3 = mixed
kind[score["first"] > 0.5] = 2
kind[score["previous"] > 0.4] = 1
kind[score["induction"] > 0.4] = 0
for name, n in zip(["induction", "previous", "first", "mixed"], torch.bincount(kind.flatten(), minlength=4)):
print(f"{name:10}{n.item():4d} heads")
print(f"head {layer}.{head} induction score {score['induction'][layer, head]:.3f}")
print("first-token share by layer", [round(x, 2) for x in score["first"].mean(1).tolist()])Code walkthrough
- As in Olsson and colleagues' test, the input is random tokens repeated: four rows of 50 random ids, written twice after GPT-2's
<|endoftext|>token (bos_token_id). Only copying can predict the repeat. A[..., pos, pos - R + 1]picks each repeated position's weight on the token after its earlier copy;.mean((1, 3))averages over rows and positions, leaving a (12, 12) score.- The previous-token score takes cells one below the diagonal; the first-token score takes column 0.
kindlabels each head by the tests it passes (thresholds 0.4 and 0.5, chosen here, not standard);bincountcounts labels.
Head 5.5 scored 0.922, so the anecdote holds on data built for the test. The induction heads begin in layer 5; previous-token heads appear from layer 2. That order fits the two-layer circuit, though it does not prove it.
The labels rest on two thresholds chosen here, so treat them as a map, not a census. Module 14 measures what heads do by switching them off.
The biggest group is the surprise: weight parked on position 0 rises from 0.08 in layer 0 to 0.63 in layer 8. One common reading: rows must sum to 1, so a head needs somewhere to put weight when nothing matches, and the first token is always visible.
In production
Nobody serves naive_attention. PyTorch's documentation for scaled_dot_product_attention (version 2.14, checked October 2026) lists three implementations it may pick (FlashAttention-2, a memory-efficient kernel, a C++ version of the formula) and says it returns the attention output only. Fused kernels never store the (B, H, T, T) matrix; Module 10 measures why. So transformers 5, fused by default, needs attn_implementation="eager" to return weights. The lab keeps both paths and a test that they agree.
What you added to tinyformer-lab
naive_attentionfortinyformer/attention.py: steps 2 to 5, any leading axes, optional mask and weights.- A check against
F.scaled_dot_product_attentionand a row-sum test, fortests/test_m02_attention.py. - A head survey of GPT-2 small: three scores for all 144 heads.
- The module lab saves all three into the package.
Check yourself
- Why can a dictionary lookup not be trained, and what replaces it?
- Why is row 0 of a causal attention matrix always [1, 0, 0, 0]?
- A column of the weight matrix sums to 2.64. Is that a bug?
- Why did the two a's in Maya get identical outputs without a mask?
- Head 5.5 put 0.942 on
' Lind'. Why is one sentence not enough to call it an induction head?
argmaxreturns an index, which has no gradient. The softmax gives every key a share that changes smoothly, so the query gets a gradient.- The mask leaves one allowed key, and the softmax of a single number is 1.
- No. Rows are distributions and must sum to 1; columns count how much a key is read and can sum to anything.
- Same character, so same query, key and value; nothing marks position.
- One sentence is an anecdote. On repeated random tokens (200 positions, no meaning to lean on) it scored 0.922.
Exercise
Queries and keys need not match in number: a new token reading a cache has one query and many keys. Predict the weight and output shapes when 2 queries read 4 keys, then run the check.
def cross_attention_check(n_queries=2, n_keys=4, d_head=8):
set_seed()
q = torch.randn(1, n_queries, d_head) # 2 queries ...
k, v = torch.randn(1, n_keys, d_head), torch.randn(1, n_keys, d_head) # ... reading 4 keys
out, w = naive_attention(q, k, v, return_weights=True)
assert w.shape == (1, n_queries, n_keys), "weights are (queries, keys)"
assert out.shape == (1, n_queries, d_head), "one output per query"
assert torch.allclose(w.sum(-1), torch.ones(1, n_queries)), "each query's row sums to 1"
assert torch.allclose(out, F.scaled_dot_product_attention(q, k, v), atol=1e-6)
return tuple(w.shape), tuple(out.shape)
print(cross_attention_check(), "check passed")Code walkthrough
qhas 2 rows;kandvhave 4. The asserts check both shapes, the row sums and agreement with PyTorch.- It printed
((1, 2, 4), (1, 2, 8)) check passed. Then setn_keysto 7 and predict before rerunning.
Key terms
| Term | Meaning |
|---|---|
| Soft lookup | Score every key, weight every value by its softmax share, return the blend |
| Scaled dot-product attention | softmax(QK^T / sqrt(d)) V |
| Causal mask | Each token may read itself and earlier tokens only |
| Attention matrix | (queries, keys) weights; each row sums to 1 |
| Permutation equivariant | Shuffle the inputs and the outputs shuffle the same way |
| Previous-token head | A head whose weight sits on the token just before |
| Induction head | A head that reads the token after an earlier copy of the current one |
Sources
- Catherine Olsson, Nelson Elhage, Neel Nanda et al. (Anthropic), "In-context Learning and Induction Heads", 2022. https://transformer-circuits.pub/2022/in-context-learning-and-induction-heads/index.html
- Ashish Vaswani et al., "Attention Is All You Need", 2017, Section 3.2.1. https://arxiv.org/abs/1706.03762
- Kevin Clark, Urvashi Khandelwal, Omer Levy, Christopher D. Manning, "What Does BERT Look At? An Analysis of BERT's Attention", 2019. https://arxiv.org/abs/1906.04341
- PyTorch,
torch.nn.functional.scaled_dot_product_attention, documentation for version 2.14, checked October 2026. https://docs.pytorch.org/docs/2.14/generated/torch.nn.functional.scaled_dot_product_attention.html