43 / 90

Day 43: Scaled Dot-Product Attention and Query-Key-Value Projections

Formulate attention as routing queries against keys to weight values. Derive the variance of dot products in R^{d_k}, prove why the 1/sqrt(d_k) scaling factor prevents vanishing gradients in softmax, and trace explicit (T, d_k) score matrices by hand and in code.

Models & Training 480 active minutes (8 hours focused study)
01 120 min

Query, Key, and Value: Vector Roles and Attention Formulation

Agent-Assisted Engineering Check

Prerequisites

Day 41-42 forward pass, matrix multiplication, and row-wise softmax mechanics.

Learning Objective

Deconstruct attention into query routing against keys to retrieve values, derive matrix dimensions, and compute raw dot-product score matrices.

Instructions

Study source: within this activity's existing reading/practice time, use Stanford CS224N: Natural Language Processing with Deep Learning, Winter 2026 Lecture 05 Transformers (2026-01-20); attention and self-attention slides, then explain one connection to the local task in your own words. Keep the local exercise and acceptance checks; use its original explanation if the external source is unavailable. Required work: formulate scaled dot-product attention Attention(Q, K, V) = softmax(Q K^T / sqrt(d_k)) V. Given sequence length T=3, key dimension d_k=4, and value dimension d_v=2, define Q with rows q_0=[2.0, 0.0, 2.0, 0.0], q_1=[0.0, 2.0, 0.0, 2.0], q_2=[1.0, 1.0, 1.0, 1.0]; K with rows k_0=[1.0, 0.0, 1.0, 0.0], k_1=[0.0, 2.0, 0.0, 1.0], k_2=[2.0, 1.0, 0.0, 1.0]; and V with rows v_0=[1.0, 0.0], v_1=[0.0, 2.0], v_2=[1.0, 1.0]. Compute the raw dot-product matrix S_raw = Q K^T step by step. Explain the conceptual role of Query (what position seeks), Key (what position offers), and Value (content transmitted).

Practice & Prediction Log

1. Compute the 3x3 entries of S_raw = Q K^T for the matrices above.
2. State the tensor shapes of Q, K, V, Q K^T, and the final output.
3. Why is attention an associative retrieval mechanism rather than a fixed linear layer?

Independent Mastery Criterion

Accurate step-by-step matrix multiplication yielding the exact 3x3 S_raw matrix and correct shape annotations.

Authoritative Source Resources & Provenance

linking Stanford University copyright; no course-wide open reuse license verified linking only; no reproduction

Stanford CS224N: Natural Language Processing with Deep Learning

Author: Stanford University CS224N staff | Original Source Link ↗

Relevant Section / Range: Winter 2026 Lecture 05 Transformers (2026-01-20); attention and self-attention slides

Verified Version & Date: Public edition checked 2026-11-01; moving pages may change

Selection Rationale:

Selected attention/Transformer lecture slides provide a coherent teaching check on Q/K/V and architecture; original papers remain definition references and local code exercises remain required.

Source Prerequisites:

Linear algebra, gradients, basic neural language models and PyTorch.

Safe Fallback (Offline Resilience):

Use the original localized explanations, exercises and checks already present in this activity; no external account or purchase is required for that fallback.

Compared Candidate Sources & Selection Analysis (2)
The Annotated Transformer ↗ compared_alternative [MIT]

Runnable code commentary remains the implementation spine; its sublayer convention must not be mistaken for the original paper.

The Illustrated Transformer ↗ compared_alternative [Copyright Jay Alammar; edition-specific reuse terms unverified]

Concise diagrams are useful, but provide neither the wider lecture sequence nor checked implementation exercises.

linking arXiv.org perpetual non-exclusive license / Open Access

Attention Is All You Need

Author: Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin | Original Source Link ↗

Relevant Section / Range: Section 3.2.1: Scaled Dot-Product Attention equation and query/key/value matrix definitions

Verified Version & Date: NeurIPS 2017 / arXiv:1706.03762v7 (Verified: 2026-10-30)

Selection Rationale:

The foundational primary literature establishing scaled dot-product attention, multi-head projection mechanisms, and autoregressive causal masking.

Source Prerequisites:

Linear algebra, matrix multiplication, softmax probability distributions

Safe Fallback (Offline Resilience):

Complete original algebraic derivations, matrix examples, variance proofs, and tensor diagrams are self-contained in the curriculum text without external document dependency.

Compared Candidate Sources & Selection Analysis (3)

Pioneered additive attention in RNNs, but Vaswani scaled dot-product attention replaced additive alignment in modern LLM architectures due to parallel matrix multiplication speed.

Introduces relative positional biases into attention; deferred to subsequent positional embedding modules after absolute scaled attention is thoroughly mastered.

Karpathy nanoGPT (causal self-attention module) ↗ compared_selected_co_primary [MIT]

Selected jointly as the primary code reference: translates Section 3.2 of the Vaswani paper into minimal, idiomatic PyTorch tensor operations.

linking MIT

nanoGPT: Simplest, Fastest Repository for Training and Finetuning Medium GPTs

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: model.py: CausalSelfAttention forward pass query/key/value projection extraction

Verified Version & Date: GitHub master commit (Verified: 2026-10-30)

Selection Rationale:

Detailed modern reference implementation of clean, idiomatic batched causal self-attention in fewer than 60 lines of code.

Source Prerequisites:

Python, NumPy/PyTorch tensor fundamentals, and feed-forward network basics

Safe Fallback (Offline Resilience):

Self-contained step-by-step tensor derivations, numeric matrix traces, and pure Python/NumPy implementations are directly provided in curriculum exercises.

Compared Candidate Sources & Selection Analysis (3)
Hugging Face transformers (GPT2Attention) ↗ compared_rejected_for_foundations [Apache-2.0]

Includes extensive production abstraction layers, configuration polymorphism, and cache tracking that obscure direct mathematical tensor operations for beginner learners.

Harvard NLP: The Annotated Transformer ↗ compared_selected_co_primary [MIT]

Selected jointly: provides line-by-line literary commentary mapping equations directly to PyTorch tensors.

Expanded video walkthrough; software is MIT-licensed while video audio/subtitles remain linking-only without transcript import.

02 120 min

The Scaling Factor sqrt(d_k) and Attention Score Matrices

Independent Mastery Check

Prerequisites

Complete Day 43 Activity 1.

Learning Objective

Apply the 1/sqrt(d_k) scale factor to score matrices, calculate row-wise stable softmax distributions, and compute weighted value outputs.

Instructions

Required work: with d_k = 4, the scaling factor is sqrt(4) = 2.0. Scale S_raw by dividing each entry by 2.0 to obtain S = S_raw / 2.0. Then compute the row-wise softmax using max-shift: row 0 scaled is [2.0, 0.0, 2.0]; row 1 is [0.0, 3.0, 2.0]; row 2 is [1.0, 1.5, 2.0]. Compute softmax weights A = softmax(S) and the final output Out = A V. Verify that every row of A sums strictly to 1.0.

Practice & Prediction Log

1. Write the scaled score matrix S = S_raw / 2.0.
2. Compute the exact softmax attention matrix A to 6 decimal places.
3. Compute the output representation Out = A V for all 3 positions.

Independent Mastery Criterion

Learner derives S, computes the normalized attention probabilities matching to 4+ decimal places, and produces correct value mixtures Out.

Authoritative Source Resources & Provenance

linking arXiv.org perpetual non-exclusive license / Open Access

Attention Is All You Need

Author: Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin | Original Source Link ↗

Relevant Section / Range: Section 3.2.1: Mathematical justification for scaling factor 1/sqrt(d_k) to prevent vanishing softmax gradients

Verified Version & Date: NeurIPS 2017 / arXiv:1706.03762v7 (Verified: 2026-10-30)

Selection Rationale:

The foundational primary literature establishing scaled dot-product attention, multi-head projection mechanisms, and autoregressive causal masking.

Source Prerequisites:

Linear algebra, matrix multiplication, softmax probability distributions

Safe Fallback (Offline Resilience):

Complete original algebraic derivations, matrix examples, variance proofs, and tensor diagrams are self-contained in the curriculum text without external document dependency.

Compared Candidate Sources & Selection Analysis (3)

Pioneered additive attention in RNNs, but Vaswani scaled dot-product attention replaced additive alignment in modern LLM architectures due to parallel matrix multiplication speed.

Introduces relative positional biases into attention; deferred to subsequent positional embedding modules after absolute scaled attention is thoroughly mastered.

Karpathy nanoGPT (causal self-attention module) ↗ compared_selected_co_primary [MIT]

Selected jointly as the primary code reference: translates Section 3.2 of the Vaswani paper into minimal, idiomatic PyTorch tensor operations.

linking MIT

The Annotated Transformer

Author: v2022: Austin Huang, Suraj Subramanian, Jonathan Sum, Khalid Almubarak, Stella Biderman; original: Sasha Rush (Harvard NLP) | Original Source Link ↗

Relevant Section / Range: Scaled Dot Product Attention code cell and attention matrix visualization

Verified Version & Date: Updated 2022 edition (Verified: 2026-10-30)

Selection Rationale:

Widely used pedagogical commentary that pairs every paragraph of the original Vaswani paper with an executable, testable code cell.

Source Prerequisites:

Intermediate Python, PyTorch broadcasting and tensor slicing semantics

Safe Fallback (Offline Resilience):

The curriculum provides standalone hand-worked numerical tables, explicit causal mask verification scripts, and offline analytical proofs.

Compared Candidate Sources & Selection Analysis (3)
Jay Alammar: The Illustrated Transformer ↗ compared_alternative [CC BY-NC 4.0]

Spectacular visual diagrams and intuitive color-coding, but lacks executable tensor code and formal numerical shape validation.

Stanford CS224N: Natural Language Processing with Deep Learning (Lecture 10) ↗ compared_alternative [Stanford University Copyright]

Rigorous academic slides and video lectures, but access to assignment grading is restricted to Stanford enrolled students.

Vaswani et al.: Attention Is All You Need ↗ compared_selected_co_primary [arXiv Open Access]

The original primary paper; Annotated Transformer annotates it directly.

03 120 min

Variance Scaling Derivation and Gradient Saturation Analysis

Agent-Assisted Engineering Check

Prerequisites

Complete Day 43 Activity 2; basic probability and calculus.

Learning Objective

Mathematically prove that the variance of the dot product of two d_k-dimensional random vectors is d_k, and demonstrate softmax gradient vanishing without scaling.

Instructions

Required work: let q and k have independent components q_i, k_i with E[q_i] = E[k_i] = 0 and Var(q_i) = Var(k_i) = 1. Prove E[q . k] = 0 and Var(q . k) = d_k. Show that Var((q . k) / sqrt(d_k)) = 1. Then analyze the counterexample with d_k = 64 (sqrt(d_k) = 8): suppose unscaled scores reach +16 and -16. Calculate softmax on logits [16, 0, -16] and show that softmax derivative dp_i / dz_j = p_i (delta_ij - p_j) saturates to near-zero.

Practice & Prediction Log

1. Write out the variance proof step by step using Var(X Y) = E[X^2] E[Y^2] - (E[X]E[Y])^2 for independent zero-mean variables.
2. Compute softmax([16, 0, -16]) and its local gradient magnitude.
3. In two sentences, why does unscaled dot-product attention cause training to stall in deep transformers?

Independent Mastery Criterion

Complete algebraic proof of variance scaling plus concrete numerical demonstration of gradient saturation on extreme logits.

Authoritative Source Resources & Provenance

linking arXiv.org perpetual non-exclusive license / Open Access

Attention Is All You Need

Author: Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin | Original Source Link ↗

Relevant Section / Range: Section 3.2.1 footnote and variance derivation for inner products of unit-variance components

Verified Version & Date: NeurIPS 2017 / arXiv:1706.03762v7 (Verified: 2026-10-30)

Selection Rationale:

The foundational primary literature establishing scaled dot-product attention, multi-head projection mechanisms, and autoregressive causal masking.

Source Prerequisites:

Linear algebra, matrix multiplication, softmax probability distributions

Safe Fallback (Offline Resilience):

Complete original algebraic derivations, matrix examples, variance proofs, and tensor diagrams are self-contained in the curriculum text without external document dependency.

Compared Candidate Sources & Selection Analysis (3)

Pioneered additive attention in RNNs, but Vaswani scaled dot-product attention replaced additive alignment in modern LLM architectures due to parallel matrix multiplication speed.

Introduces relative positional biases into attention; deferred to subsequent positional embedding modules after absolute scaled attention is thoroughly mastered.

Karpathy nanoGPT (causal self-attention module) ↗ compared_selected_co_primary [MIT]

Selected jointly as the primary code reference: translates Section 3.2 of the Vaswani paper into minimal, idiomatic PyTorch tensor operations.

linking MIT

nanoGPT: Simplest, Fastest Repository for Training and Finetuning Medium GPTs

Author: Andrej Karpathy | Original Source Link ↗

Relevant Section / Range: model.py: scaling by 1.0 / math.sqrt(k.size(-1)) in attention calculation

Verified Version & Date: GitHub master commit (Verified: 2026-10-30)

Selection Rationale:

Detailed modern reference implementation of clean, idiomatic batched causal self-attention in fewer than 60 lines of code.

Source Prerequisites:

Python, NumPy/PyTorch tensor fundamentals, and feed-forward network basics

Safe Fallback (Offline Resilience):

Self-contained step-by-step tensor derivations, numeric matrix traces, and pure Python/NumPy implementations are directly provided in curriculum exercises.

Compared Candidate Sources & Selection Analysis (3)
Hugging Face transformers (GPT2Attention) ↗ compared_rejected_for_foundations [Apache-2.0]

Includes extensive production abstraction layers, configuration polymorphism, and cache tracking that obscure direct mathematical tensor operations for beginner learners.

Harvard NLP: The Annotated Transformer ↗ compared_selected_co_primary [MIT]

Selected jointly: provides line-by-line literary commentary mapping equations directly to PyTorch tensors.

Expanded video walkthrough; software is MIT-licensed while video audio/subtitles remain linking-only without transcript import.

04 120 min

Independent Mastery Check: Dot-Product Attention and Tensor Shapes

Independent Mastery Check

Prerequisites

Activities 43-01 through 43-03.

Learning Objective

Verify unassisted mastery of scaled dot-product attention calculation, variance scaling proof, and multi-dimensional tensor shape contracts under declared AI-free conditions.

Instructions

Required work: work independently without AI assistants or external calculators. For a new setup with T=2, d_k=4, d_v=2: Q has rows [0.0, 2.0, 0.0, 2.0], [2.0, 0.0, 2.0, 0.0]; K has rows [0.0, 2.0, 0.0, 2.0], [1.0, 0.0, 1.0, 0.0]; V has rows [2.0, 1.0], [0.0, 3.0]. Compute S_raw, scale by sqrt(4)=2, calculate exact softmax weights, and find the output representations. Complete the knowledge check quiz.

Practice & Prediction Log

1. Compute S_raw and scaled S = S_raw / 2.0.
2. Compute the exact 2x2 softmax matrix A.
3. Compute the 2x2 output matrix Out = A V.
4. Complete the 3-question objective quiz.

Objective Knowledge Check: Scaled Dot-Product Attention

Answer the following diagnostic questions to verify your understanding. Select your declared assistance condition before submitting.

Declared Assistance Condition

Note: AI-free work is an honest declared condition, not claimed surveillance.

1.

What is the primary mathematical reason for dividing the dot product Q K^T by sqrt(d_k)?

2.

For an input sequence of length T=3, key dimension d_k=4, and value dimension d_v=2, what is the shape of the attention score matrix S = (Q K^T) / sqrt(d_k)?

3.

If vectors q, k in R^{d_k} have independent components with zero mean and unit variance, what is the variance of their unscaled dot product q . k?

Attempt History & Evidence

    Independent Mastery Criterion

    Independent derivation of exact matrices S, A, Out and 100% score on the objective diagnostic quiz.

    Authoritative Source Resources & Provenance

    linking arXiv.org perpetual non-exclusive license / Open Access

    Attention Is All You Need

    Author: Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Łukasz Kaiser, Illia Polosukhin | Original Source Link ↗

    Relevant Section / Range: Section 3.2.1: Attention equation verification and tensor shape dimensions

    Verified Version & Date: NeurIPS 2017 / arXiv:1706.03762v7 (Verified: 2026-10-30)

    Selection Rationale:

    The foundational primary literature establishing scaled dot-product attention, multi-head projection mechanisms, and autoregressive causal masking.

    Source Prerequisites:

    Linear algebra, matrix multiplication, softmax probability distributions

    Safe Fallback (Offline Resilience):

    Complete original algebraic derivations, matrix examples, variance proofs, and tensor diagrams are self-contained in the curriculum text without external document dependency.

    Compared Candidate Sources & Selection Analysis (3)

    Pioneered additive attention in RNNs, but Vaswani scaled dot-product attention replaced additive alignment in modern LLM architectures due to parallel matrix multiplication speed.

    Introduces relative positional biases into attention; deferred to subsequent positional embedding modules after absolute scaled attention is thoroughly mastered.

    Karpathy nanoGPT (causal self-attention module) ↗ compared_selected_co_primary [MIT]

    Selected jointly as the primary code reference: translates Section 3.2 of the Vaswani paper into minimal, idiomatic PyTorch tensor operations.

    linking MIT

    The Annotated Transformer

    Author: v2022: Austin Huang, Suraj Subramanian, Jonathan Sum, Khalid Almubarak, Stella Biderman; original: Sasha Rush (Harvard NLP) | Original Source Link ↗

    Relevant Section / Range: Attention function test assertions and shape contracts

    Verified Version & Date: Updated 2022 edition (Verified: 2026-10-30)

    Selection Rationale:

    Widely used pedagogical commentary that pairs every paragraph of the original Vaswani paper with an executable, testable code cell.

    Source Prerequisites:

    Intermediate Python, PyTorch broadcasting and tensor slicing semantics

    Safe Fallback (Offline Resilience):

    The curriculum provides standalone hand-worked numerical tables, explicit causal mask verification scripts, and offline analytical proofs.

    Compared Candidate Sources & Selection Analysis (3)
    Jay Alammar: The Illustrated Transformer ↗ compared_alternative [CC BY-NC 4.0]

    Spectacular visual diagrams and intuitive color-coding, but lacks executable tensor code and formal numerical shape validation.

    Stanford CS224N: Natural Language Processing with Deep Learning (Lecture 10) ↗ compared_alternative [Stanford University Copyright]

    Rigorous academic slides and video lectures, but access to assignment grading is restricted to Stanford enrolled students.

    Vaswani et al.: Attention Is All You Need ↗ compared_selected_co_primary [arXiv Open Access]

    The original primary paper; Annotated Transformer annotates it directly.