6.1.13 · D5 · HinglishScaling & Efficient Architectures

Question bankKV-cache optimization

2,371 words11 min read↑ Read in English

6.1.13 · D5 · AI-ML › Scaling & Efficient Architectures › KV-cache optimization

Figure — KV-cache optimization

Upar figure 1 dekho: baayein taraf ke fixed grey blocks cached hain past tokens ke; daayein taraf ka bright block bilkul naya token hai, jise ek fresh query chahiye lekin sirf ek key aur ek value append karta hai.

True or false — justify

T/F jawab do, phir reason bhi do. Sirf "True" likhne se zero milega — reasoning hi point hai.

KV-cache, no-cache ki tulna mein generation ka mathematical output change kar deta hai.
False. Cache ek pure memoisation trick hai — ye wahi numbers store karta hai unhe recompute karne ki jagah. Output bit-identical hota hai (floating-point non-determinism tak); sirf speed aur memory differ karti hai.
KV-caching inference ke dauran model ki total memory use ko reduce karta hai.
False. Ye memory badhata hai: ab aap har past token ke liye store kar rahe ho. Ye extra memory ko saved compute ke badle trade karta hai — memory saving ka ulta.
KV-caching training ke saath-saath generation mein bhi speedup deta hai.
False. Training teacher forcing use karti hai — saare tokens ek saath present hote hain, isliye har exactly ek baar compute hota haiैसे भी. Steps ke across kuch reuse karne ke liye nahi hai, isliye cache sirf autoregressive generation mein help karta hai.
Token 5 ki keys aur values constant rehti hain jab hum tokens 6, 7, 8, … generate karte hain.
True. Weight matrices training ke baad frozen hain aur token 5 ki embedding fixed hai, isliye aur kabhi nahi badlte. Yahi fixedness exactly kyun hai ki wo cacheable hain.
Multi-Query Attention cache size utna hi reduce karta hai jitna model parameters reduce karta hai.
False. MQA cache ko (heads ki sankhya) ke factor se shrink karta hai, lekin parameter saving bahut choti hai — sirf projection matrices shrink hoti hain, aur wo poore model ka ek chota slice hain. Fayda inference par memory-bandwidth ka hai, parameter count ka nahi.
KV-cache ke saath, per-token generation cost pehle kitne tokens aaye usse independent ho jaati hai.
Mostly false. Projection cost per token ab constant hai (, jahan model dimension hai), lekin attention score step abhi bhi cost karta hai kyunki naya query ko saare cached keys ke saath dot karna padta hai. Latency context length ke saath abhi bhi badhti hai, bas overall quadratic ki jagah linearly.
Size ka sliding-window cache memory ko sequence length se independent constant banata hai.
True. Aap sirf last keys/values rakhte ho, isliye cache memory par cap ho jaati hai. Cost ye hai ki steps se pehle ke tokens literally invisible hain — long-range dependencies drop ho jaati hain.
Grouped-Query Attention ek special case hai jisme MQA aur standard attention dono endpoints ke roop mein hain.
True. GQA query heads ko KV-groups mein group karta hai. set karne se standard multi-head attention wapas aata hai; set karne se MQA wapas aata hai. GQA inke beech interpolate karta hai.

Spot the error

Har line ek plausible-sounding claim hai jisme ek hidden flaw hai. Flaw batao.

" ko bhi cache karein — isme bhi matrix multiply chahiye, toh aur bhi compute bachega."
Flaw ye hai: har naya token ek fresh query generate karta hai jo kabhi reuse nahi hoti, kyunki query encode karti hai "yeh naya token kya dhundh raha hai". Sirf (jo past tokens offer karte hain) reuse hote hain. ko cache karna kuch nahi bachata.
"Kyunki cache mein pehle se har key hai, token unhe freely attend kar sakta hai."
Causal mask missing hai. Token ko sirf positions dekhne chahiye. Agar future keys kabhi cache mein baith jaayein (jaise kuch batched/padded setups mein), unhe attend karna woh information leak kar deta hai jo model ko nahi honi chahiye.
"Heads ki sankhya double karne se compute double hoti hai lekin cache size same rehti hai."
Standard attention ke liye galat: cache size precision hai (jahan = heads, = head dimension), isliye ye ke saath linearly scale karta hai। Heads double karne se cache bhi double ho jaata hai. (Yahi exactly kyun MQA/GQA exist karte hain.)
"MQA aur GQA lossless hain — ye sirf same numbers ko reorganise karte hain."
False. Query heads ke across share karne se representational capacity hat jaati hai, isliye model ko iske liye train ya fine-tune karna padta hai aur typically thodi quality loss hoti hai (MQA ke liye ≈1–2% perplexity). Ye ek approximation hai, rewrite nahi.
"FlashAttention aur KV-caching same bottleneck solve karte hain, isliye dono use karna redundant hai."
Ye alag bottlenecks attack karte hain. KV-cache steps ke across redundant projection recompute hatata hai; FlashAttention ek step ke andar score matrix ko materialize karne ki memory cost hatata hai. Ye compose karte hain.
"Memory bachane ke liye hum cache ko bina kisi downside ke int8 mein store kar sakte hain."
Flaw "bina kisi downside ke" hai. Cache quantization memory bahut shrink karta hai, lekin low-precision har attention score mein rounding error inject karte hain — usually acceptable, lekin free nahi. Ye ek tradeoff hai, freebie nahi.
" beams ke saath beam search ko greedy decoding jaisa hi cache chahiye."
Galat: beams mein se har ek ek alag hypothesis hai apne past tokens ke saath, isliye aapko alag KV-caches chahiye (ya ek shared-prefix cache per-beam tails ke saath). Memory beam width ke saath scale karta hai.

Why questions

Yahan reasoning hi poora jawab hai.

Naive (no-cache) projection cost ki jagah kyun badhti hai?
Step par naive model sequence ko fresh treat karta hai aur saare tokens ke projections recompute karta hai, cost karta hai. sum karne se quadratic milta hai. Cache har step ki cost ko constant banata hai, isliye sum linear ho jaata hai.
aur cache hote hain, attention output kyun nahi?
sirf past tokens par depend karte hain aur fixed hain, isliye ye reusable inputs hain. Attention output current par depend karta hai, jo har step naya hota hai — isliye output recompute karna hi padta hai aur cache karne ke liye kuch stable nahi hai.
KV-cache size layers ki sankhya ke saath kyun scale karta hai?
Har transformer layer ka apna independent attention hai apne projections ke saath. Caching per layer hoti hai, isliye total cache = per-layer cache . Isliye ek per-token cache ~48 KB (ek layer) se ~4.7 MB (saari layers) tak jump karta hai GPT-3-scale model mein.
MQA inference latency mein raw FLOP count se zyada help kyun karta hai?
Autoregressive generation memory-bandwidth bound hai, compute bound nahi — bottleneck cache ko har step memory se load karna hai. MQA cache ko shrink karta hai, isliye per token memory bus ke across bahut kam data jaata hai, jo FLOP savings se bhi bada real-world speedup deta hai.
Hum generation cost amortise karne ke liye batch size indefinitely kyun nahi badha sakte?
Kyunki batch mein har sequence ko apna poora KV-cache chahiye, aur cache memory (batch × length × layers × heads) ke saath badhti hai. Aap jaldi GPU memory ceiling hit karte ho — weights nahi, cache large batches ke liye limiting resource ban jaata hai. deployment considerations dekho.
Caching ke baad bhi causal mask kyun matter karta hai, jab cache sirf past tokens hold karta hai?
Practice mein caches aksar batched aur padded hote hain, aur kuch pipelines temporarily placeholder ya future entries hold karti hain. Mask guarantee hai ki token mathematically sirf ko attend karta hai, generation ko causal rakhta hai chahe buffer mein physically kuch bhi baitha ho.

Edge cases

Boundary conditions jo log bhool jaate hain. Har case ko uski extreme tak push karo.

Bilkul pehle token par (), KV-cache mein kya hai aur kya caching abhi help karta hai?
Token 1 se pehle cache empty hai; aap compute karte ho aur store karte ho. Pehle se reuse karne ke liye kuch nahi hai, isliye caching step 1 par kuch nahi bachata — fayda step 2 se shuru hota hai.
Length (single-token generation) ki sequence ke liye cache speedup kya hai?
Exactly — koi speedup nahi. Speedup factor hai, isliye ke liye amortise karne ke liye kuch nahi. Caching tabhi payoff karta hai jab sequence badhti hai.
Jab model ko window se purani dependency chahiye toh sliding-window cache ka kya hota hai?
Woh information simply gone hai — key/value evict ho chuki hai. Model ab usse attend nahi kar sakta, isliye us far-back context ki zarurat wala koi bhi jawab degrade ho jaata hai. Ye bounded-memory caching ki fundamental accuracy cost hai.
MQA cache-ratio mein, limit physically kya matlab hai?
ke saath sirf ek head hai, isliye standard attention pehle se hi single-KV attention hai aur MQA koi reduction nahi deta (). MQA ka fayda sirf tab badhta hai jab head count badhta hai.
GQA mein, group count kya correspond karta hai, aur kya correspond karta hai?
matlab har query head apna KV rakhta hai — ye ordinary multi-head attention hai bina kisi cache saving ke. matlab saare heads ek single KV share karte hain — ye full MQA hai maximum saving ke saath. GQA strictly inke beech rehta hai.
Context length bahut zyada badne par (jaise 1M tokens) KV-caching ka fayda kyun limit hota hai?
Do limits collide karte hain: cache memory linearly badhti hai aur GPU ko exhaust kar sakti hai, aur attention-score step abhi bhi per token cost karta hai, isliye per-token latency badhti rehti hai. Isliye very-long-context systems caching ke upar sparse attention ya windowing ki taraf jaate hain.
Ek prompt jo generation se pehle ek saath process hota hai ("prefill" phase), kya caching us step ko change karta hai?
Prefill saare prompt tokens ke ek parallel pass mein compute karta hai — training ki tarah, prefill ke andar koi reuse exploit karne ke liye nahi hai. Wahan caching ka role simply un ko store karna hai taaki subsequent one-token-at-a-time decode phase unhe reuse kar sake.
Recall Quick self-test

, , mein se kaunsa har generation step par recompute hota hai? ::: Sirf — ye encode karta hai naya token kya dhundh raha hai; aur cache hote hain kyunki wo fixed past tokens se belong karte hain. Kya cache output numbers change karta hai? ::: Nahi — ye sirf identical values ko recompute karna avoid karta hai, isliye results (bit-)identical hote hain. MQA/GQA kaunsa resource bachata hai, aur kya cost aata hai? ::: KV-cache memory aur memory bandwidth tak ke factor se bachata hai; thodi model quality ki cost hoti hai.

Related vault topics for definitions used above: 6.1.1-transformer-architecture, 6.1.4-multi-head-attention, 6.1.11-sparse-attention, 6.3.1-model-quantization, 5.4.2-beam-search, 6.2.3-inference-optimization, 7.2.1-llm-deployment, aur parent KV-cache optimization.