Scaled dot-product self-attention by hand
Attention is a masked, normalized lookup: queries score keys, softmax allocates influence, and values carry the information.
Domain autocomplete needs a model whose every component the team can explain.
This chapter moves from check the score geometry to read one attention row. We will make the idea concrete in a small code example before placing it back inside a production system with one-device educational build.
Confirm its allowed weights sum to one, then calculate the same weighted sum of value rows by hand and compare with the tensor result.
Verify the behavior illustrated in attention_by_hand.py, then measure decision utility, slice reliability, and system latency.
Without the causal mask, each position sees its target and validation loss becomes impossibly good. An unsafe release must degrade to a named baseline or the last known-good version.
Build the idea one layer at a time.
Self-attention lets every token ask a question, compare it with the keys of allowed tokens, and blend their values into a context-aware answer.
Learned projections create queries, keys, and values. A query-key dot product measures compatibility, and dividing by the square root of head width keeps score variance from growing until softmax saturates. Softmax turns each allowed score row into nonnegative weights that sum to one; multiplying by values forms a weighted context vector.
Masks change which relationships exist. A padding mask removes storage-only positions, while a causal mask removes keys to the right of each query. Apply the mask before softmax by replacing forbidden logits with a very negative value. Masking the output afterward is too late because forbidden positions already consumed probability mass.
- embeddings
- RoPE
- QKV projections
- causal masks
Follow the reasoning before touching the code.
- 01
Check the score geometry
For Q and K shaped `[batch, time, head_width]`, compute `QKᵀ` to obtain one `[time, time]` relation matrix per batch and head.
- 02
Remove forbidden edges
Set future and padded key logits to negative infinity before normalization. Visualize the mask for a four-token example.
- 03
Read one attention row
Confirm its allowed weights sum to one, then calculate the same weighted sum of value rows by hand and compare with the tensor result.
import math
import torch
torch.manual_seed(2)
q = torch.randn(1, 4, 3)
k = torch.randn(1, 4, 3)
v = torch.randn(1, 4, 2)
scores = q @ k.transpose(-2, -1) / math.sqrt(q.shape[-1])
future = torch.triu(torch.ones(4, 4, dtype=torch.bool), diagonal=1)
scores = scores.masked_fill(future, float('-inf'))
weights = torch.softmax(scores, dim=-1)
context = weights @ v
assert torch.allclose(weights.sum(-1), torch.ones(1, 4))
assert context.shape == (1, 4, 2)
print(weights[0])Compute one causal attention head with explicit shapes and masking.
What to notice
- Row zero can attend only to key zero, so its single allowed weight is one.
- Later rows distribute one unit of probability over progressively longer prefixes, never over a future column.
YOUR TURN Pause and predict before revealing the answer.
Remove the division by √3 and multiply both Q and K by 10. What happens to most softmax rows?
Need a hint?
Large differences between logits make exponentials concentrate on the maximum.
Check your reasoning
The distributions become nearly one-hot and gradients through softmax shrink for most entries. Scaling the dot product controls this saturation as head width or vector magnitude grows.
Lessons 1 in this course.
Connect the chapter to the course’s quantitative spine.
Attention is a masked, normalized lookup: queries score keys, softmax allocates influence, and values carry the information. The scaled dot-product attention below is the shared course-level lens that helps quantify the surrounding system. Name each symbol, check its units or shape, and use only values that were available at the production cutoff.
Scaled dot-product attention
| Symbol | Meaning / shape / unit |
|---|---|
Q, K, V | query, key, value matrices |
d_k | head width |
M | causal or padding mask |
Open derivation and numerical substitution
Start from the production quantity being optimized, substitute the observed values with their declared units, then isolate the model-controlled term. Preserve shape annotations at each step so broadcasting or aggregation cannot silently change the result.
- Write the named inputs: Q, K, V, d_k, M.
- Substitute one small, hand-checkable batch before vectorizing.
- Calculate an independent reference value and compare within a declared tolerance.
# equation → code contract
inputs = validate_shapes_and_units(batch)
value = compute_c14(inputs)
assert is_finite(value)Change one assumption and make the tradeoff visible.
Use the worked chapter as your prediction, then change one input in the lab and explain why the output moves. The lab runs predefined TypeScript and never executes learner code, so the focus stays on the concept rather than setup.
Attention temperature lab
Change score temperature and inspect the exact softmax distribution.
Assumption: Fixed scores [1.2, 0.3, −0.4, 1.8].
Open nonvisual data table
| Item | Computed state | Interpretation |
|---|---|---|
| token 1 | 1.2 | 0.2915 |
| token 2 | 0.3 | 0.1185 |
| token 3 | -0.4 | 0.0589 |
| token 4 | 1.8 | 0.5311 |
Trace the complete operating path.
Carry the chapter’s central idea into the system: Attention is a masked, normalized lookup: queries score keys, softmax allocates influence, and values carry the information. The path below shows where that reasoning needs an artifact, a test, an owner, or a fallback.
- 01
Turn “Check the score geometry” into a written invariant and a failing test.
- 02
Promote attention_by_hand.py from illustration to a versioned implementation with representative fixtures.
- 03
Use “Read one attention row” as the release checkpoint: Confirm its allowed weights sum to one, then calculate the same weighted sum of value rows by hand and compare with the tensor result.
- 04
Serve or materialize behind explicit one-device educational build.
- 05
Join telemetry to mature outcomes and retain a rollback path.
Observability
Join service health, input quality, prediction distributions, slice behavior, and mature outcomes by exact version.
Cost
Measure storage, preprocessing, compute, queueing, and human review under a representative arrival pattern.
Failure modes
Without the causal mask, each position sees its target and validation loss becomes impossibly good. Add a detector, owner, mitigation, and stop condition for this class of failure.
Alternatives
Compare a rule, a simpler statistical baseline, and a different system boundary before adding model complexity.
Explain the contract, not just the vocabulary.
Decoder-only transformer from scratch
Specify tokenizer, attention blocks, causal training, unit tests, sampling, and KV-cache parity without a transformer module.
- Shape/mask tests
- Tiny-batch overfit
- Held-out evaluation
- Cached/uncached parity
Read primary material with a purpose.
Return to the opening failure.
Version tokenizer, vocabulary, special tokens, architecture, weights, prompt template, and generation policy together.
For this lesson, the release evidence is the worked code example, a hand-checked formal result, deterministic simulation output, a ≥80% checkpoint, the production rubric, and a named fallback. The course resolves when the system can produce tokenizer, attention, rope, residual stack, training loop, generation, and kv cache.