VKVlad KulikovPublic / lectures
Modern LLMs5 / 20

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 KB

The archive preserves the source folder structure, both languages, and supporting files.

E1. Hybrid cache arithmetic

For 36 layers, Hq=64H_q=64, Hkv=8H_{kv}=8, dh=64d_h=64, 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:

2Hkvdh⋅2 bytes=2⋅8⋅64⋅2=2048 B/token.2H_{kv}d_h\cdot2\ \text{bytes}=2\cdot8\cdot64\cdot2=2048\ \text{B/token}.

Thus all-full cache is 36⋅131072⋅2048=936\cdot131072\cdot2048=9 GiB. The 18 full layers use 18⋅131072⋅2048=4.518\cdot131072\cdot2048=4.5 GiB, while 18 local layers retain only their window and use 18⋅128⋅2048=4.518\cdot128\cdot2048=4.5 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 ℓ1=1.367879\ell_1=1.367879, n1=1.735759n_1=1.735759, the rescaling factor e−1e^{-1}, and output 2.502297.

Show answer and solution

Solution. The first tile has maximum m1=2m_1=2:

ℓ1=e2−2+e1−2=1+e−1=1.367879,\ell_1=e^{2-2}+e^{1-2}=1+e^{-1}=1.367879, n1=1e0+2e−1=1.735759.n_1=1e^0+2e^{-1}=1.735759.

For the second tile, m2=3m_2=3, so ℓ2=1+e−2.5=1.082085\ell_2=1+e^{-2.5}=1.082085 and n2=3+4e−2.5=3.328340n_2=3+4e^{-2.5}=3.328340. The global maximum is M=3M=3; move tile 1 into this scale with em1−M=e−1e^{m_1-M}=e^{-1}:

ℓ=e−1ℓ1+ℓ2=1.585300,n=e−1n1+n2=3.966890.\ell=e^{-1}\ell_1+\ell_2=1.585300,\qquad n=e^{-1}n_1+n_2=3.966890.

Therefore O=n/ℓ=2.502297O=n/\ell=\mathbf{2.502297}. 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 ss 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 ss to the ordinary scores zi=q⊤ki/dhz_i=q^\top k_i/\sqrt{d_h} and pair it with vs=0v_s=0. The output becomes

O=es0+∑iezivies+∑iezi=∑iezivies+∑iezi.O=\frac{e^s0+\sum_i e^{z_i}v_i}{e^s+\sum_i e^{z_i}} =\frac{\sum_i e^{z_i}v_i}{e^s+\sum_i e^{z_i}}.

The extra column can absorb probability mass without adding content. A fixed key instead produces q⊤ks/dhq^\top k_s/\sqrt{d_h}, which changes with the query. Setting ks=0k_s=0 gives only the constant 0; an arbitrary learned constant ss for every query must be represented as a separate scalar/bias, not as an ordinary key.

E4. GQA grouping

With Hq=8H_q=8 and Hkv=2H_{kv}=2, show that consecutive repeat matches the grouped formula while whole-array tiling changes head assignments.

Show answer and solution

Solution. The group size is g=Hq/Hkv=4g=H_q/H_{kv}=4, so query head hh uses KV head ⌊h/4⌋\lfloor h/4\rfloor: heads 0–3 map to KV0 and 4–7 to KV1. Label the KV heads [10, 20]. Correct expansion is

text
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 N=1K,2K,4K,8KN=1K,2K,4K,8K. 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 W=3W=3 window masks. Compare them with tril(ones(1, 6)).

Show answer and solution

Solution. Causality compares absolute positions: a key is visible when k≤5k\le5. The full mask row is therefore [1,1,1,1,1,1]. A window of width 3 also requires 5−3+1≤k5-3+1\le k, 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 A∈R6×4A\in\mathbb R^{6\times4}, B∈R5×4B\in\mathbb R^{5\times4}, 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 Q∈R3×6Q\in\mathbb R^{3\times6} and the latents as rows of C∈R7×4C\in\mathbb R^{7\times4}. The direct path constructs K=CA⊤K=CA^\top of shape 7×67\times6 and V=CB⊤V=CB^\top of shape 7×57\times5. Its content scores satisfy

QK⊤=QAC⊤.QK^\top=QAC^\top.

The rearranged path first computes QAQA, a 3×43\times4 array, then the 3×73\times7 score matrix. Add the same positional scores and use identical scaling, masks, and softmax on both paths to obtain the same weights P∈R3×7P\in\mathbb R^{3\times7}. The value computation satisfies

PV=P(CB⊤)=(PC)B⊤.PV=P(CB^\top)=(PC)B^\top.

The direct path reconstructs seven width-5 values before mixing them. The rearranged path mixes four-dimensional latents first, producing PCPC of shape 3×43\times4, then expands the result to 3×53\times5. With an output matrix O∈R5×doutO\in\mathbb R^{5\times d_{out}}, the product B⊤OB^\top O can be formed in advance.

Rotating reconstructed keys changes the effective query to A⊤Rn−m⊤qA^\top R_{n-m}^\top q, which depends on key position nn. 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 10−1210^{-12}; 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.