Query, key, value matrices
4.1.3· AI-ML › Transformer Architecture
Q, K, V Matrices Kya Hain?
- Query matrix jahan
- Key matrix jahan
- Value matrix jahan
Ye learned linear transformations hain jo har token ko teen alag subspaces mein project karti hain, jo attention mechanism mein alag-alag purposes ke liye optimize hote hain.
Teen Alag Matrices Kyun?
Alag transformations kyun?
-
Roles ko decouple karna: Ek hi token embedding alag-alag purposes serve karti hai. Jab token A, token B ko attend karta hai, toh humein chahiye:
- A ki query: "Main kya dhundh raha hoon?"
- B ki key: "Main matching ke liye kya represent karta hoon?"
- B ki value: "Main kaunsi information contribute karunga?"
-
Asymmetric relationships: "cat" aur "sat" ke beech ki similarity alag tarike se compute honi chahiye, na ki waisi jaise "cat" information provide karta hai. Keys matching geometry handle karte hain, values information geometry handle karti hain.
-
Optimization flexibility: Alag weight matrices network ko ye seekhne deti hain ki "cat" verbs ke liye query kar sakta hai (Q-K space mein "sat" ke saath high similarity) lekin noun information provide karta hai (V space mein).

First Principles Se Derivation
Starting Point: Hum Kaunsi Problem Solve Kar Rahe Hain?
Hum chahte hain ki har token relevant context ko attend kare. Raw embeddings mein saari semantic information mixed hoti hai. Humein ye karna hai:
Step 1: "Relevance" ko similarity score ke roop mein define karo
Token ke liye token ki relevance determine karne ke liye hum compute karte hain:
Lekin raw dot product bahut rigid hai—ye similarity ke liye wahi dimensions use karta hai jo position, syntax, semantics, etc. encode karti hain.
Ye kyun fail hota hai: Jo dimensions "word meaning" ke liye optimize hain, wo zaruri nahi ki "is pe attend karna chahiye" ke liye bhi optimize hon.
Step 2: Ek specialized "matching space" mein project karo
Iske bajaye, ko ek query vector mein transform karo jo "main kya dhundh raha hoon" represent kare:
jahan "search intent" extract karne ke liye seekha jaata hai.
Kyun: Ab ek -dimensional space mein rehta hai jo specifically relevance compute karne ke liye optimize hai (typically efficiency aur overfitting rokne ke liye).
Step 3: Comparison targets ko ek "key space" mein project karo
ko ek key vector mein transform karo jo "main kya offer karta hoon" represent kare:
Ab relevance aise compute hoti hai:
Alag aur kyun: Attention directional hai. "The cat sat" → "cat" ka "sat" ko query karna, "sat" ke "cat" ko query karne se alag hai. Asymmetric matrices asymmetric relationships encode karti hain.
Step 4: Information retrieval ko alag karo
Jab hum relevance jaante hain, toh humein information extract karni hoti hai. Lekin token se jo information chahiye wo shayad alag ho us cheez se jisne use relevant banaya!
ko ek value vector mein transform karo:
jahan "information content" ke liye optimize hai, "matching" ke liye nahi.
Kyun: "The cat sat on the mat" mein, jab "sat" "cat" ko attend karta hai, toh key decide karne mein help karti hai ki "cat" relevant hai (subject-verb relationship), lekin value determine karti hai ki "cat" kya information provide karta hai (semantic features: animal, subject, etc.).
Full Matrix Form
Ek sequence ke liye:
Jahan:
- ki har row ek token ka query vector hai
- ki har row ek token ka key vector hai
- ki har row ek token ka value vector hai
- learned parameters hain jo backpropagation se update hote hain
Attention mein inhe HOW use kiya jaata hai:
Worked Examples
Maan lo hai, aur humne ye seekha hai:
Query compute karo:
Ye step kyun? 4D semantic space se 2D "search" space mein project karna.
Step-by-step multiplication:
- First dimension:
- Second dimension:
Key compute karo:
- First dimension:
- Second dimension:
Query se alag kyun? Usi token ke alag roles hain: "main kya dhundhta hoon" vs. "main kya offer karta hoon jab koi mujhe dhundhe."
Dot product kyun? Attention space mein alignment measure karta hai. High dot product = high relevance.
Interpretation: Token 1 ki apne aap ke saath thodi si positive relevance hai. Practice mein, ise se scale kiya jaata aur softmax se pehle doosre tokens ke scores ke saath combine kiya jaata.
Scaling kyun? Jaise badhta hai, dot products magnitude mein badhte hain, softmax ko saturation regions mein push karte hain. Scaling gradient flow maintain karta hai.
- First:
- Second:
- Third:
Alag dimension kyun? Values information content encode karti hain, jiske liye matching space se alag dimensionality ki zaroorat ho sakti hai. Simplicity ke liye often rakha jaata hai, lekin ye zaroori nahi.
HOW use hota hai: Relevance scores ke softmax se attention weights compute karne ke baad, token ka output hai:
Common Mistakes
Kyun sahi lagta hai: Hum architecturally unke dimensions aur roles define karte hain.
Kyun galat hai: learned parameters hain. Ye random start hote hain aur gradient descent se optimize hote hain taaki ye specific task mein attention ke liye relevant features seekh sakein.
Fix: Inhe "learnable lenses" ki tarah socho jo model task-relevant patterns pe focus karne ke liye tune karta hai. Ek translation model mein ye alag patterns seekhte hain, aur ek summarization model mein alag.
Kyun sahi lagta hai: Kabhi kabhi implementation code mein "QKV" ek single matrix ke roop mein dikhta hai.
Kyun galat hai: Q, K, V usi input ke teen alag linear projections hain. Ye ko parts mein nahi kaatate; ye poore ko teen alag tareekon se transform karte hain.
Fix:
- Nahi: (galat: ye concatenation hai)
- Balki: , , (sahi: teen alag transformations)
Kabhi kabhi implementations compute karke ek matrix multiply karti hain, phir result split karti hain, lekin conceptually ye alag transformations hain.
Kyun sahi lagta hai: Zyada dimensions = zyada information preserved.
Kyun galat hai:
- Computational cost: Attention hai. reduce karna compute bachata hai.
- Regularization: Lower-dimensional projections model ko attention ke liye compressed, essential features seekhne par majboor karte hain.
- Multi-head attention: heads ke saath, har ek dimension ka, total dimension hoti hai, jo heads ke across expressiveness maintain karta hai.
Fix: ko "attention query language" ki dimension socho—ek compressed, task-optimized space. Typical: jahan heads ki sankhya hai.
Q, K, V Multi-Head Attention Ko Kaise Enable Karte Hain
Multi-head attention mein, hum ke liye sets of banate hain. Har head:
- , , compute karta hai
- Attention run karta hai:
- Heads concatenate aur project hote hain:
Multiple heads kyun? Alag heads alag attention patterns seekh sakte hain:
- Head 1: syntactic relationships (subject-verb)
- Head 2: semantic similarity (synonyms)
- Head 3: positional patterns (nearby words)
Har head ke Q, K, V matrices alag aspects mein specialize ho jaate hain.
Recall Ek 12-Saal Ke Bacche Ko Samjhao
Socho tum class mein ho, aur teacher ek sawaal poochhti hai.
Query (Q): Ye waisa hai jaise tumne haath uthaya ho aur tumhare specific question likha card ho—"Mujhe fractions mein help chahiye!"
Key (K): Ye waisa hai jaise class mein baaki sab cards utha ke dikhaa rahe hon ki wo kisme acche hain—"Main fractions jaanta hoon!" ya "Main spelling mein great hoon!" ya "Main science jaanta hoon!"
Value (V): Ye actual helpful information hai jo log de sakte hain. Sarah ki KEY kehti hai "Main fractions jaanta hoon," lekin uski VALUE actual explanation hai jo wo provide kar sakti hai ki 1/2 aur 1/3 kaise add karte hain.
Teacher (attention mechanism) tumhara QUERY card dekhti hai, usse sabke KEY cards se compare karti hai best matches dhundhne ke liye, phir unse VALUE information collect karti hai aur tumhe combined answer deti hai.
Magical part? Transformer seekhta hai ki ye cards kaise likhne hain! Pehle, wo Q, K, V cards pe random cheezein likhta hai, lekin hazaaron examples dekhne ke baad, wo seekhta hai:
- QUERY cards kaise likhein jo sahi sawaal poochhein
- KEY cards kaise likhein jo relevant help advertise karein
- VALUE cards kaise likhein jo sabse useful information de
Aur sabse cool part ye hai: Usi student (word token) ke paas teeno tarah ke cards hote hain. Jab TUM sawaal poochho, tum apna QUERY card use karte ho. Lekin jab KOI AUR poochhe, wo tumhara KEY card dekhta hai ye jaanne ke liye ki tum help kar sakte ho ya nahi, aur tumhare VALUE card se information leta hai.
Ya: "Query the library, spine pe Keys match karo, andar ki Values padho."
Connections
- Attention Mechanism: Q, K, V matrices attention function ke inputs hain
- Scaled Dot-Product Attention: Attention scores compute karne ke liye use karta hai
- Multi-Head Attention: Q, K, V projections ke multiple sets banata hai
- Linear Layers: Q, K, V transformations linear layers hain (matrix multiplications)
- Embedding Layer: Input embedding layer se aata hai
- Positional Encoding: Q, K, V projection se pehle mein add hota hai
- Self-Attention: Q, K, V sab usi sequence se derive hote hain
- Cross-Attention: Q ek sequence se, K aur V doosre se (encoder-decoder)
- Backpropagation: Jisse seekhe jaate hain
- Gradient Descent: Weight matrices update karne wala optimization algorithm
#flashcards/ai-ml
Attention mein teen matrices kaunsi hain aur conceptually har ek kya represent karti hai? :: Query (Q) = "main kya search kar raha hoon", Key (K) = "main matching ke liye kya offer karta hoon", Value (V) = "main kaunsi information provide karta hoon". Ye input embeddings ke learned linear projections hain.
Input diya gaya, Q, K, V matrices ke formulas likho :: , , jahan aur learned weight matrices hain.