6.1.13 · D1 · HinglishScaling & Efficient Architectures

FoundationsKV-cache optimization

3,244 words15 min read↑ Read in English

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

Isse pehle ki tum samjho kyun hum K aur V cache karte hain (aur Q nahi), tumhe yeh jaanna zaroori hai ki parent note mein har letter aur picture ka matlab kya hai. Yeh page unhe order mein build karta hai, har cheez pichli cheez pe depend karti hai. Kuch bhi assume nahi kiya gaya.

Related maps: 6.1.13 KV-cache optimization (Hinglish) · parent KV-cache optimization · prerequisites 6.1.1-transformer-architecture, 6.1.4-multi-head-attention.


1. Ek token aur uski embedding — sab kuch ka atom

Picture: ek row of boxes imagine karo, ek per word: "The cat sat". Har box ko numbers ka ek arrow se replace kiya jaata hai jo "meaning space" mein point karta hai. Position hai "The", hai "cat", aur aise hi aage.

Topic ko yeh kyun chahiye: poori cost story yeh hai ki "kya hota hai per token". Agar tum yeh nahi jaante ki har token ek vector ban jaata hai, toh tum count nahi kar sakte ki uske liye kya compute hota hai.

Figure — KV-cache optimization
Figure 1 — teen word-boxes "The", "cat", "sat" positions par, har ek ke saath ek neecha arrow numbers ki ek bracketed list mein: length ka embedding vector .

Ek embedding arrow mein components ki sankhya model dimension hai. Bade models (GPT-2 small) se lekar hazaron tak use karte hain. Woh akela number cost formulas mein har jagah aata hai, isliye use abhi pin kar lo.

Notation
position par token ka embedding vector hai; batata hai ki usme kitne numbers hain.

2. Q, K, V — har token se puchhe gaye teen sawaal

Attention (6.1.4-multi-head-attention mein built) har token ki embedding ko teen naye vectors mein badalta hai, use teen fixed number-grids (matrices) se multiply karke jinhe , , kehte hain.

Picture — ek library: har past book ki ek spine label (uski Key) aur contents (uski Value) hoti hai. Naya token ek search slip (uski Query) lekar andar aata hai. Woh apni slip ko har spine label se compare karta hai, phir un books se contents uthata hai jo best match karti hain.

Figure — KV-cache optimization
Figure 2 — do past-token "books" har ek mein ek green Key label aur ek blue Value content dikha rahi hain, plus ek orange new-token "search slip" jisme dashed red arrows har Key se compare kar rahe hain.

Topic ko yeh kyun chahiye — aur yeh caching ka dil hai: ek past token ka label aur contents kabhi nahi badalte ek baar likhne ke baad. Lekin har naya token ek fresh search slip laata hai. Yahi asymmetry exactly woh reason hai kyun hum K aur V cache karte hain lekin Q recompute karte hain.

Recall Hum Q cache kyun nahi kar sakte?

Kyunki Q naye token ka sawaal hai, jo har step par alag hota hai. K aur V purane tokens ke fixed jawab hain. ::: Bilkul sahi.

kya hai?
Shape ki ek fixed matrix (training mein seekhi gayi, generation ke dauran frozen) jo ek embedding ko uske Key vector mein map karti hai.

3. Books ko rank karne wala multiply — aur dot product

Yeh measure karne ke liye ki search slip spine label se kitna match karti hai, attention dot product use karta hai: matching components ko multiply karo aur jod lo. Bada dot product = strong match.

Shapes ko pin down karna (yahan beginners confuse ho jaate hain): generation step par ek naya query hai, ek row vector aur cached keys hain jo ek matrix mein stack hain, ek key per row:

Query ko har key ke saath ek saath dot karne ke liye, hume har key ek column ke roop mein chahiye. Transpose exactly wahi karta hai — woh rows ka stack ko columns ka block mein badal deta hai:

Ab shapes matrix multiply ke liye line up hoti hain: har past token ke liye ek score. Inner dimensions match karke cancel ho jaate hain — transpose karne ki poori wajah yehi hai.

Picture: query arrow ki shadow jo har key arrow par padti hai — jitni lambi shadow, utna zyada score.

Figure — KV-cache optimization
Figure 3 — origin se ek orange query vector aur teen key vectors ; dotted projection lines dikhate hain (green) ke saath sabse zyada align karta hai, sabse zyada dot-product score deta hai.

Parent note ke single-layer worked example mein (3rd token generate karna, 4 heads, ), exactly 3 scores produce karta hai — ek per past position — jo upar derive ki gayi length ki row se match karta hai.

se divide kyun karte hain?
Scores ko bahut bada hone se rokne ke liye jab badhta hai, jo agla step (softmax) bahut spiky bana deta. Yeh ek stabiliser hai.

4. Softmax — scores ko ek choice mein badalna

Picture — attention ka ek pie chart: bada raw score → bada slice, aur saare slices ek poori pie mein sum hote hain. Exponential leader ko exaggerate karta hai taaki strongest match dominate kare lekin kuch fully ignore na ho.

Figure — KV-cache optimization
Figure 4 — left: teen raw scores ka ek bar chart; right: wahi scores softmax ke baad ek pie ke roop mein dikhaye gaye jinke teen slices 1 mein sum hote hain, sabse bada score sabse bada slice le raha hai.

Topic ko yeh kyun chahiye — aur yahan V ki shape enter karti hai: yeh weights cached Values ko blend karke ek output banane ke liye multiply karte hain. Value vectors ko waise hi stack karo jaise humne Keys stack ki thi: Softmax output weights ki ek row hai, shape . Shapes multiply karna: Inner cancel ho jaata hai, toh ek weight row times Value stack ek ek length- output vector deta hai — saari Values ka weighted blend. Toh poora attention formula

left-to-right padhta hai: labels ko score karo → pie mein badlocontents mix karo.


5. Heads, , aur — kaam ko split karna

Ek attention kaafi nahi hai, toh model kaafi heads parallel mein run karta hai — har ek ek head hai.

Ek "layer" kya count hota hai? Ek transformer identical blocks ko ek ke upar stack karta hai; har block ek layer hai (6.1.1-transformer-architecture inhe build karta hai). Ek layer mein apna attention (apne ke saath) plus ek feed-forward network hota hai. GPT-2 small mein aisi layers hain; GPT-3-style model mein hain. = layers ki sankhya. Har layer apna alag KV-cache rakhti hai, isliye full-model memory se multiply hoti hai.

Topic ko yeh kyun chahiye: cache memory per head, per layer, per token count ki jaati hai. Ab ki , aur sab define ho gaye hain, memory formula padhta hai:

isliye kyunki hum do cheezein store karte hain: Key stack aur Value stack.


6. Multi-Query Attention — jahaan -fold saving aati hai

Memory derivation, explicitly:

heads ke saath, MQA kam KV-cache store karta hai, kyunki K aur V dono ek baar (length par) store hote hain times ki jagah. Quality typically sirf 1–2% drop hoti hai.


7. Autoregressive generation aur causal mask

Picture — ek lower-triangular grid: row (attending token) columns (khud aur past) fill kar sakta hai lekin upper-right triangle (future) blacked out hai.

Figure 5 — ek grid attending position (rows) aur key position (columns) se indexed; green cells mein (allowed), red upper-right cells mein (future blocked).

Topic ko yeh kyun chahiye: kyunki mask guarantee karta hai ki ek token sirf positions attend karta hai, aur woh past K,V frozen hain — yahi exactly unhe cache karne ka license hai. Cache ke hote hue bhi tumhe mask add karna hi hoga, warna model illegally future positions read kar lega.


8. Big-O, , aur woh cost jisse hum lad rahe hain

Topic ko yeh kyun chahiye: poora motivation ek cost comparison hai. Per token projection cost per layer hai ( matrix times length- vector, heads mein sum karne par milta hai). Big-O constant factors (layers) aur per-head split chhupaata hai, toh neeche clean formulas per-layer projection costs hain; full model ke liye layers se multiply karo:

100-token sequence ke liye, yeh roughly kam projection work hai. Parent note ka GPT-2-small worked example (jisme dono sides par layer factor include hai, toh woh cancel ho jaata hai) ke liye real speedup measure karta hai — ideal se thoda kam kyunki attention khud abhi bhi har step par thoda cost karta hai, lekin same order of magnitude hai.

vs ka matlab?
Per-layer projection cost: pehla length mein quadratic hai (naive), doosra linear (cached). Unka ratio hai, speedup. Pure model ke liye kisi bhi ko layers se multiply karo.

Do classic mistakes (ek line mein kyun galat hain)


Prerequisite map

Token and embedding x_t

Q K V projections

Model dimension d

Dot product Q times K transpose

Softmax weights

Attention output

Heads h and head dim d_k

Autoregressive generation

Causal mask

Cost in Big-O with length L

KV-cache optimization

Har foundation agla feed karta hai; saath mein woh justify karte hain kyun K aur V cache karna (Q nahi) safe aur sasta hai. Deeper follow-ups: 6.2.3-inference-optimization, 6.1.11-sparse-attention, 6.3.1-model-quantization, 7.2.1-llm-deployment, 5.4.2-beam-search.


Equipment checklist

Khud test karo — right side cover karo.

kya hai?
Position par token ke liye embedding (numbers ka vector).
ka matlab kya hai?
Model dimension — ek embedding mein kitne numbers hain.
Q, K, V ek-ek word mein?
Query = main kya dhoondh raha hoon; Key = mera label; Value = mera content.
Har projection matrix ki shape kya hai?
— yeh length- embedding ko length- vector mein map karta hai.
Q, K, V mein se kaunse cache hote hain, aur kyun?
K aur V — woh past tokens ke hain aur kabhi nahi badalte; Q har step par fresh hota hai.
Step par mein shapes kya hain?
hai, hai, toh hai aur scores hain.
Kyun softmax() length- output deta hai?
weight row times Value stack inner cancel karta hai, chodta hai.
Softmax kya karta hai?
Raw scores ko positive weights mein badalta hai jo 1 mein sum hote hain (attention ki ek pie).
, , ka relationship?
.
Memory formula mein precision kya hai?
Stored number per bytes — fp16 mein , fp32 mein .
Total KV-cache footprint formula?
(K+V, saari layers, saare tokens).
Cache memory formula mein 2 ka factor kyun hai?
Do stacks store hoti hain: K aur V.
Ek "layer" kya hota hai aur cache ke liye yeh kyun matter karta hai?
Ek transformer block (attention + feed-forward); layers mein se har ek apna KV-cache rakhti hai, toh memory se scale hoti hai.
MQA structurally kya change karta hai, aur cache kitna shrink hota hai?
Saare heads ek K aur ek V share karte hain ( size par stored, nahi), cache factor se shrink hota hai.
Causal mask ki dimensions kya hain, aur yeh kaise apply hota hai?
Ek matrix jo softmax se pehle raw scores mein add hoti hai; for aur for .
Naive vs cached per-layer generation cost, aur speedup?
vs ; speedup (full model ke liye se multiply karo).