Exercises — KV-cache optimization
6.1.13 · D4· AI-ML › Scaling & Efficient Architectures › KV-cache optimization
Shuru karne se pehle, do duniyaon ki ek shared picture — "sab kuch recompute karo" vs "yaad rakho aur append karo":

Figure padhna. Top row step 4 par cache ke bina generation hai: saare chaar key boxes black mein draw kiye gaye hain kyunki model unhe scratch se recompute karta hai. Bottom row cache ke saath generation hai: black hain (already stored, bas reuse ho rahe hain — "reuse" arrow follow karo) aur sirf red mein draw kiya gaya hai, kyunki yeh uss step mein cache ko compute karni wali ek nayi projection hai. Yahi contrast — teen reused vs ek nayi — cache ka poora idea hai, aur neeche ke har memory/FLOP problem mein bas inhi boxes ko count kiya ja raha hai.
Level 1 — Recognition
Exercise 1.1 (L1)
Batao ki neeche diye gaye mein se kaun sa autoregressive generation ke dauran KV-cache mein store hota hai, aur kaun sa har step par recompute hota hai: (a) key projections , (b) value projections , (c) query projections , (d) final softmax attention weights.
Recall Solution
- (a) — cached. Ek past token ki key ek baar compute hone ke baad kabhi nahi badalti, isliye hum ise store karte hain (Figure s01 mein black boxes).
- (b) — cached, usi wajah se.
- (c) — recomputed har step par. Query yeh hoti hai ki "current token kya dhundh raha hai," aur har step par ek brand-new current token hota hai, isliye reuse karne ko kuch nahi hai (red box har step par nayi hoti hai).
- (d) softmax weights — recomputed. Yeh nayi par depend karte hain, isliye har step par change hote hain.
Cache exactly wahi cheezein store karta hai jo past positions ke liye fixed hain: aur . Isliye naam hai KV-cache.
Exercise 1.2 (L1)
Shape ki recognition. Ek single layer mein heads aur head dimension hai. 5 tokens generate karne ke baad, ki shape kya hai (tokens × heads × head-dim ke roop mein)?
Recall Solution
Har token ek head per ek key contribute karta hai: token per shape hai. 5 tokens stack karne par milta hai ki shape identical hai. Pehla axis (yahan ) hi ek hai jo generate karte waqt badhta hai.
Level 2 — Application
Exercise 2.1 (L2)
Per-token cache memory. Ek layer mein heads, hai, fp16 mein store hai (2 bytes each). Ek token uss ek layer ke liye KV-cache mein kitne bytes add karta hai?
Recall Solution
Formula kahan se aata hai (short derivation). Ek token ke liye humein uski keys aur values store karni hoti hain. Ek single token ka key set ek -vector per head hota hai, isliye usmein numbers hote hain; same value set ke liye bhi. Yeh do tensors hain numbers ke, aur har number "precision" bytes occupy karta hai. Multiply karo: Yahi reason hai har factor ka — kuch blindly cite nahi kiya gaya. Plug in karo: (Unit convention yaad karo: bytes exactly.)
Exercise 2.2 (L2)
Ek poori sequence ke liye full-model cache. Same layer specs (, , fp16), ab aur tokens ki sequence. Total cache size gigabytes mein?
Recall Solution
Ek token ek layer mein Ex 2.1 se cost karta hai. Ab hamare paas tokens hain (pehla cache axis badhta hai) aur independent layers hain (har ek apna cache rakhti hai), isliye dono se multiply karte hain: Plug in karo: Step karo: ; ; ; ; bytes. Convert karo (binary GB): GB. Answer: GB ( MB, kyunki ).
Exercise 2.3 (L2)
Speedup factor. Recall karo ki model width hai, aur har ek token ke -vector ko -vector mein project karta hai, har token ke liye multiply-adds lete hue. Caching ke bina, step par model saare tokens ko re-project karta hai, aur poori generation par sum karne se projection work scale karti hai; caching ke saath har step par sirf ek nayi token project hoti hai, jo deta hai. Pehle derive karo ki no-cache total kyun hai, phir ke liye projection speedup compute karo.
Recall Solution
No-cache cost kyun hai (missing "why"). Ek token ki teen projections mein se har ek cost karti hai — kyunki ek -vector ko matrix se multiply karna multiply-adds hai — isliye per token. Cache ke bina, generation step par model sequence ko fresh maanta hai aur ab tak dekhe gaye saare tokens ko re-project karta hai, us step mein cost karke. Har step par sum karo: mein quadratic purely triangular sum se aata hai. Cache ke saath, har step par sirf ek nayi token project hoti hai: . Speedup: cancel ho jata hai — speedup purely sequence-length factor hai. Lambi generations zyada benefit karti hain.
Level 3 — Analysis
Exercise 3.1 (L3)
MQA vs standard. Ek model query heads, use karta hai. Standard multi-head attention ke KV-cache size ko Multi-Query Attention (MQA) se compare karo, jo ek single K/V head share karta hai. Ratio do aur interpret karo.
Recall Solution
Standard cache (per token, per layer, constant factor ignore karke): MQA ek K aur ek V head rakhta hai: Ratio: MQA kam KV-cache use karta hai. Interpretation: query heads ab bhi specialize karte hain (har ek ka apna hai), lekin sab same keys aur values se padhte hain, isliye hum sirf ek set store karte hain. Cost: thodi si quality drop (~1–2% perplexity).
Exercise 3.2 (L3)
GQA middle ground. Llama-2 70B query heads use karta hai jo K/V groups mein grouped hain. (a) Standard attention ke versus cache reduction kya hai? (b) GQA standard aur MQA ke beech kahan hai?

Figure padhna. Teen head-sharing schemes side by side draw ki gayi hain. Top boxes query heads hain; bottom boxes stored KV heads hain; har line dikhati hai ki kaun si queries kaun sa KV padhti hain. Left ("standard "): har query ka apna private KV hai — koi sharing nahi, maximal cache. Right ("MQA "): saari queries ek shared KV mein funnel hoti hain — minimal cache. Middle ("GQA ", red mein drawn): queries groups mein bundle hoti hain, har group ek KV share karta hai — tunable middle ground. Jaise aap ko se tak slide karte ho, cache "standard" se "MQA" tak slide hota hai; red middle exactly woh case hai jo part (b) ke baare mein poochhta hai.
Recall Solution
(a) GQA ki jagah K/V heads store karta hai: Toh 8× reduction. (b) Figure ko left-to-right padho: standard mein har query head ke liye ek K/V head hota hai (, koi reduction nahi); MQA ek single shared K/V head mein collapse ho jaata hai (, maximal reduction); GQA (beech mein red grouping) ke saath beech mein hai. Yeh MQA ki zyaadatar memory savings recover karta hai jabki standard attention ki zyaada quality rakhta hai har group of queries ko apni keys/values dekar.
Exercise 3.3 (L3)
Sliding-window memory. Ek 100K-token context ke liye, full-cache memory ko width ke sliding-window cache se compare karo. Assume karo , , , fp16. Dono sizes aur ratio do.
Recall Solution
Per-token-per-layer bytes: B KB. Full cache (): (Binary conversion: GB.) Sliding-window (): Ratio: chhota. Trade-off: window memory ko context length se regardless constant par rakhta hai, lekin model literally tokens se purani kisi bhi cheez ko attend nahi kar sakta — window ke paar ki long-range dependencies lost ho jaati hain.
Level 4 — Synthesis
Exercise 4.1 (L4)
FLOP accounting, cache vs no-cache. GPT-2 small ke liye (, model width ), caching ke saath aur bina tokens generate karne ke liye projection FLOPs estimate karo. Dono aur speedup report karo.
Recall Solution
Per-step cost kahan se aata hai. Jaise Ex 2.3 mein establish hua, ek token ko matrix se project karna multiply-adds cost karta hai; hum teen projections ko maante hain aur small constant factor drop karte hain ("3" aur koi bhi terms) kyunki hum sirf aur ratio ke saath scaling chahte hain — constants ratio mein cancel ho jaate hain. Toh:
- No-cache, step , per layer: saare tokens re-project karo .
- Cache, step , per layer: sirf 1 nayi token project karo .
Without cache — saare steps par triangular series sum karo, times layers: (Use kiya — Ex 2.3 jaisi hi triangular sum.) With cache — har step par ek nayi K/V/Q, toh per step: Speedup: Yeh expected factor se match karta hai: sum-of-integers vs deta hai, yaani . Dropped constant factor kabhi matter nahi kiya kyunki woh numerator aur denominator dono mein identically appear hota hai.
Exercise 4.2 (L4)
Memory budget ke under design karo. Tumhare paas 24 GB GPU hai. Model weights 14 GB lete hain, 10 GB KV-cache ke liye bachte hain. Layer specs: , , , fp16. (a) Standard attention ke saath maximum context length kya hai jo aap cache kar sakte ho? (b) par GQA ke saath?
Recall Solution
Per-token, all-layers, standard: Budget GB B (binary GB). (a) tokens. (b) GQA with head count ko K/V mein se replace karta hai → per-token size KB/token: Design conclusion: GQA() par switch karna same memory budget ke under affordable context length ko quadruple kar deta hai.
Level 5 — Mastery
Exercise 5.1 (L5)
Crossover analysis. MQA memory save karta hai lekin aap quality ke baare mein worried ho. Maano standard attention perplexity deta hai aur MQA deta hai (1.5% increase). Meanwhile MQA tumhe zyada tokens cache karne deta hai. Agar lambi context perplexity ko roughly reduce karti hai jab context grow hoti hai (empirical), toh kya context kharidne ke liye standard→MQA trade karna perplexity ko net help karta hai ya hurt karta hai?
Recall Solution
Do effects perplexity par multiplicatively compose karte hain:
- MQA head-sharing penalty: factor (worse).
- lambi usable context: factor (better). Net factor: Kyunki hai, net perplexity ~0.53% drop hoti hai — context gain sharing penalty se outweigh karta hai. Mastery point: memory optimizations "free lunch vs pure cost" nahi hain; yeh longer context enable karte hain, jo khud quality improve karta hai. Tumhe direct penalty ko uske dwara unlock ki gayi capability ke against weigh karna hoga.
Exercise 5.2 (L5)
Full stack estimate. Sab kuch combine karo: , , , fp16, aur aap GQA() sliding window ke saath deploy karte ho ek nominal 200K-token context ke liye. (a) 200K tokens par full standard cache kya cost karti? (b) GQA + sliding-window cache actually kya cost karta hai? (c) Combined reduction factor?
Recall Solution
Standard per-token-all-layers: (Binary: MB.) (a) Full standard at : (b) GQA K/V heads cut karta hai, factor → per-token KB. Sliding window tokens ko par cap karta hai: (c) Reduction: Interpretation: do orthogonal levers multiply karte hain — GQA deta hai (head sharing) aur window deta hai (bounded length), aur . Isliye production long-context serving (7.2.1-llm-deployment, 6.2.3-inference-optimization) multiple cache tricks stack karta hai ek par rely karne ki jagah.
Recall Quick self-check summary
Cache sirf K aur V rakhta hai ::: queries har step fresh hoti hain Memory formula ka leading constant ::: 2, K aur V ke liye Heads ke terms mein model width ::: Standard→MQA cache ratio ::: GQA() cache ratio ::: Caching se projection speedup ::: factor Sliding window memory order ::: , mein constant Combining independent cache savings ::: factors ko multiply karo
Related: 6.1.11-sparse-attention, 6.3.1-model-quantization, 5.4.2-beam-search, 6.1.13 KV-cache optimization (Hinglish).