Module 5. Modern Attention Mechanisms
Try each exercise first. Expand worked answers or project guidance when needed; their open state is shared between RU/EN.
Download course files (.zip) 2588.1 KBThe archive preserves the source folder structure, both languages, and supporting files.
E1. Hybrid cache arithmetic
For 36 layers, , , , bf16, and context 131,072, compute the all-full cache and then replace 18 layers with a window of 128. Count one sequence and K/V payload only, assuming local caches are window-capped.
Show answer and solution
Solution. Each retained token needs both a key and a value on every layer:
Thus all-full cache is GiB. The 18 full layers use GiB, while 18 local layers retain only their window and use MiB. Total: 4.5043945 GiB. Query-head count does not enter because K/V are stored per KV head.
E2. Online softmax
Process logits [2,1] and [3,0.5] as two tiles with values [1,2] and [3,4]. Reproduce , , the rescaling factor , and output 2.502297.
Show answer and solution
Solution. The first tile has maximum :
For the second tile, , so and . The global maximum is ; move tile 1 into this scale with :
Therefore . This rescaling is what lets tiled attention combine blocks without retaining all logits.
E3. Learned sink
Prove equivalence to an extra score column of constant and a zero value. Explain why an ordinary fixed key cannot create the same constant score for every query.
Show answer and solution
Solution. Append a logit to the ordinary scores and pair it with . The output becomes
The extra column can absorb probability mass without adding content. A fixed key instead produces , which changes with the query. Setting gives only the constant 0; an arbitrary learned constant for every query must be represented as a separate scalar/bias, not as an ordinary key.
E4. GQA grouping
With and , show that consecutive repeat matches the grouped formula while whole-array tiling changes head assignments.
Show answer and solution
Solution. The group size is , so query head uses KV head : heads 0–3 map to KV0 and 4–7 to KV1. Label the KV heads [10, 20]. Correct expansion is
repeat_interleave(4): [10, 10, 10, 10, 20, 20, 20, 20]which matches the grouped formula. tile(4) produces [10, 20, 10, 20, 10, 20, 10, 20]; the shape is valid but the head mapping is wrong. A shape check alone therefore cannot detect the bug.
E5 [project]
On a GPU, compare naive PyTorch attention with the available SDPA/Flash backend for . Record time, peak memory, and error against a float64 reference.
Project demos and guidance
Demo for this project exercise: English project-demo notebook for Module 5, sections “Demo 1” and “Demo 2” as starting points for this module’s projects. It shows a compact reproducible example on small inputs, not a completed solution to the full-scale project.
E6. Mask after a prefix
For query position 5 and keys 0–5, write the full and window masks. Compare them with tril(ones(1, 6)).
Show answer and solution
Solution. Causality compares absolute positions: a key is visible when . The full mask row is therefore [1,1,1,1,1,1]. A window of width 3 also requires , retaining keys 3, 4, and 5: [0,0,0,1,1,1].
The only row of tril(ones(1,6)) has local index 0, so it yields [1,0,0,0,0,0]. The operation has no knowledge of the five preceding positions. Construct the mask from absolute indices or supply the appropriate offset. Extend the notebook experiment to a chunk of new queries, assigning each row its own absolute position.
E7. MLA absorption
Use , , seven four-dimensional latents, and three six-dimensional queries. Compare scores and outputs before and after moving projections, then add the positional branch. Explain why absorbing rotation into the query depends on the key position.
Show answer and solution
Solution. Stack the queries as rows of and the latents as rows of . The direct path constructs of shape and of shape . Its content scores satisfy
The rearranged path first computes , a array, then the score matrix. Add the same positional scores and use identical scaling, masks, and softmax on both paths to obtain the same weights . The value computation satisfies
The direct path reconstructs seven width-5 values before mixing them. The rearranged path mixes four-dimensional latents first, producing of shape , then expands the result to . With an output matrix , the product can be formed in advance.
Rotating reconstructed keys changes the effective query to , which depends on key position . It cannot be computed once and reused for every key. A separate positional branch avoids this particular dependency. Notebook §8 checks scores, values, and output projection at tolerance ; a changed-key-position counterexample tests the limit of the rearrangement.
For the GPU project, establish accuracy on a short sequence with one head and an FP64 reference first. Benchmark larger shapes with matched inputs, masks and precision, warm-up, no_grad, CUDA synchronization around timing, and reset peak counters. State whether projections, mask construction and cache allocation are included; record the selected kernel and distinguish allocated from reserved memory. Reduce shapes on memory exhaustion; do not construct a large FP64 reference merely to measure speed.