Compute a mixture, apply a causal mask, trace gradients and combine heads.
Preparation: Weighted averages; matrix multiplication for college.
Plan 20–35 minutes with the activities; this is a study estimate, not a timed requirement. Both paths have complete narration. Your notes and progress are kept separately for each level.
FULL LOCAL NARRATION
Follow the complete explanation.
Narration includes worked solutions. Pause at each practice prompt before continuing. Formula notation has a spoken explanation; all teaching text remains readable.
College path. Compute a mixture, apply a causal mask, trace gradients and combine heads.
Preparation: Weighted averages; matrix multiplication for college. Work through one section at a time. Predict the experiment result before changing its controls, then explain what the example leaves out.
For one head, Q has shape n×d_k, K has shape m×d_k, and V has shape m×d_v. QK transpose produces n×m scores. Row-wise softmax produces weights of the same shape, and multiplying by V produces n×d_v outputs. Query length determines output length. Self-attention commonly uses n=m; cross-attention need not. Batch and head axes surround this core calculation without changing the contracted dimensions.
Worked step 1. One query compares with three keys.
Worked step 2. Its three scores produce three weights.
Worked step 3. Those weights mix three values into one output.
Queries times transposed keys produce one score per query and key. Multiplying weights by values produces one output per query.
Try it yourself. Four queries attend to seven source positions. How many output positions result?
Pause the recording and write your reasoning before continuing. The worked solution follows.
Reveal worked solution
Worked solution. Four. Every query makes one mixture. The seven sources determine what can be mixed.
Section 02 / 07
Calculate the mixture
For logits [2,1,0], A≈[0.665241,0.244728,0.090031]. With scalar values [10,20,30], O≈14.2479. A standard softmax row is a convex combination before output projection and residual addition. Values may be vectors with negative coordinates; convexity concerns the coefficients. Subsequent learned transformations need not preserve the scalar bounds of the original values, so state which stage your interpretation describes.
Worked step 1. First contribution: 0.665241×10 ≈ 6.6524.
Worked step 2. Second: 0.244728×20 ≈ 4.8946.
Worked step 3. Third: 0.090031×30 ≈ 2.7009; total ≈ 14.2479.
O = Σⱼ aⱼvⱼ
Add each attention weight multiplied by its value.
Try it yourself. Can this mixture exceed thirty before any later transformation?
Pause the recording and write your reasoning before continuing. The worked solution follows.
Reveal worked solution
Worked solution. No. Nonnegative weights summing to one keep this scalar weighted average between ten and thirty.
Section 03 / 07
Exclude forbidden information
Use an additive mask with zero on allowed logits and negative infinity on forbidden logits. Finite substitutes depend on dtype and implementation. Entirely masked rows have no valid normalized distribution and can produce undefined values. Padding and causal masks encode distinct constraints. Check the boolean convention of the actual attention API rather than assuming true always means blocked or always means allowed.
Worked step 1. Block the third entry in scores [2,1,0].
Worked step 2. The remaining probabilities become [0.7311,0.2689,0].
Worked step 3. The values [10,20,30] now mix to about 12.6894.
A = softmax(QKᵀ/√dₖ + M)
Add the mask before softmax. Allowed entries add zero; forbidden entries add negative infinity.
Try it yourself. Why is replacing the forbidden score with zero wrong?
Pause the recording and write your reasoning before continuing. The worked solution follows.
Reveal worked solution
Worked solution. Zero is still a valid score. In the original example it receives about nine percent of the weight.
Section 04 / 07
Scale scores and protect arithmetic
If independent zero-mean query and key coordinates have unit variance, the dot product has variance d_k. Dividing by √d_k restores unit variance under that model. Learned representations need not satisfy those assumptions exactly; this is a motivation, not an unconditional theorem about trained scores. Max-subtracted row softmax handles overflow separately. Optimized attention kernels can change memory traffic while preserving this mathematical definition within numerical tolerance.
Worked step 1. A key width of 64 has square root eight.
Worked step 2. A raw dot product of sixteen becomes a scaled score of two.
Worked step 3. Subtracting a common row maximum afterward leaves the intended probabilities unchanged.
S = QKᵀ / √dₖ
Divide the query-key dot product by the square root of key width.
Try it yourself. Does scaling guarantee variance one for every trained attention head?
Pause the recording and write your reasoning before continuing. The worked solution follows.
Reveal worked solution
Worked solution. No. The argument assumes particular independence and variance conditions that learned features may not satisfy.
Section 05 / 07
Trace the backward path
With upstream G=dL/dO, the value gradient is A transpose G and the weight gradient is G V transpose. For each row, the score gradient is A elementwise multiplied by the weight gradient minus its A-weighted row sum. Then dQ=dS K/√d_k and dK=dS transpose Q/√d_k. Hold the mask fixed. Omitting the softmax Jacobian loses the coupling between weights.
Worked step 1. For unit output sensitivity, the first score derivative is 0.665241×(10−14.2479)≈−2.8259.
Worked step 2. All three score derivatives sum to zero.
Worked step 3. A common score shift therefore cannot change the output.
∂O/∂sⱼ = aⱼ(vⱼ−O)
For a scalar mixture, the score derivative is the weight times the difference between its value and the output.
Try it yourself. Why can the three weights not be differentiated as independent quantities?
Pause the recording and write your reasoning before continuing. The worked solution follows.
Reveal worked solution
Worked solution. They share one normalization denominator. Changing one score changes every normalized weight.
Section 06 / 07
Combine heads and verify
Concatenate h heads along features, producing n×(h d_v), then apply W_O of shape (h d_v)×d_model. Do not concatenate sequence positions. Verify shapes, row sums, exact mask zeros, a small reference output and finite differences. Compare optimized implementations using documented floating-point tolerances. Attention maps reveal one intermediate routing operation; they do not alone identify the causal importance of input tokens to the complete network.
Worked step 1. Four heads with eight features each give 32 features per position.
Worked step 2. A 32×24 output matrix returns 24 features.
Worked step 3. Ten input query positions remain ten output positions.
Try it yourself. What is wrong with turning four heads over ten queries into forty output positions?
Pause the recording and write your reasoning before continuing. The worked solution follows.
Reveal worked solution
Worked solution. That concatenates the sequence axis instead of the feature axis. Standard multihead attention preserves query length.
Section 07 / 07
Mastery and transfer
Bring the pieces together. First answer the checkpoint without the worked solutions. Then explain the mechanism in your own words, using one numerical example from this lesson.
Pause here and choose an answer before continuing. The checkpoint explanation follows.
Reveal worked solution
The correct choice is option 3: 4×3. Scores are 4×7; multiplying by 7×3 values gives 4×3.
Transfer task. Change one assumption in the worked example. State your prediction, calculate or test it in Workbench, then explain whether the result supports your prediction.
Reveal worked solution
Self-check rubric. Name the changed assumption, keep the other inputs fixed, show at least one intermediate calculation, and distinguish what the toy example guarantees from what would require a trained model or a real measurement.
WORKBENCH / PREDICT → TEST → EXPLAIN
Inspect exact numerical data
These are computed teaching fixtures. No remote AI model or GPU is called by the experiment.
CHECK YOUR UNDERSTANDING
Commit to an explanation.
Keep your learning record.
LONGER TRANSFORMER SYSTEMS LESSONS
Follow the mechanism in depth
Worked examples, local narration and connected learning modes at your level.
Original worked examples and teaching text, grounded in these primary references. Numerical fixtures explain mechanisms; model quality and hardware performance require separate measurements. Both levels share key examples, with different explanations and checkpoints.