BACKPROP LAB
01TITLE

Scaled Dot-Product Attention

DIFFICULTY 2/312 MIN06 · Attention Mechanisms
PREREQUISITES:Cross-Entropy Loss
UNSEEN
02EQUATION
CRISP KATEX // NO DISTORTION

Attention(Q,K,V)=softmax ⁣(QK⊤dk)V\text{Attention}(Q, K, V) = \text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right)V

where Q∈RT×dkQ \in \mathbb{R}^{T \times d_k}, K∈RT×dkK \in \mathbb{R}^{T \times d_k}, and V∈RT×dvV \in \mathbb{R}^{T \times d_v}.

03WHAT IT MEANS

Each query token scores its similarity against every key token via a dot product, divides by dk\sqrt{d_k} so large head dimensions do not push softmax into tiny-gradient saturation, normalizes scores into weights summing to 11, and takes a weighted average of the value vectors VV.

04WHERE A MODEL USES IT

Every Transformer self-attention and cross-attention head executes this equation to route context between tokens.

05WORKED EXAMPLE

Let T=2T = 2, dk=4d_k = 4 (so dk=2\sqrt{d_k} = 2), with:

Q=[10100200],K=[20200101]Q = \begin{bmatrix} 1 & 0 & 1 & 0 \\ 0 & 2 & 0 & 0 \end{bmatrix}, \quad K = \begin{bmatrix} 2 & 0 & 2 & 0 \\ 0 & 1 & 0 & 1 \end{bmatrix}

Row 11 raw dot products are [4,0][4, 0]. Dividing by 4=2\sqrt{4} = 2 yields [2,0][2, 0], and softmax([2,0])≈[0.8808,0.1192]\text{softmax}([2, 0]) \approx [0.8808, 0.1192].

06RUN IT
PYTHON 3 + NUMPY // LAZY WEBASSEMBLY WORKER

CODE RUNS ONLY IN YOUR BROWSER VIA PYODIDE WEBASSEMBLY — NOTHING IS SENT TO ANY SERVER.

07SOURCES
08CHECK YOURSELF

QUESTION 1 / 3

0 / 3 ANSWERED

Q1 · MCQ

Why are query-key dot products divided by sqrt(d_k) before applying softmax?

09NEXT UP

NO DOWNSTREAM FORMULAS YET

Nothing downstream lists Scaled Dot-Product Attention as a prerequisite yet. Open all 20 curriculum sections to pick what to prove next.

BROWSE ALL 20 SECTIONS →