Embedding layers and tied weights
4.2.5· AI-ML › Tokenization & Language Modeling
Overview
Embedding layers discrete token IDs ko continuous vector representations mein convert karte hain, jabki weight tying input embedding aur output projection layers ke beech parameters share karta hai, jisse model size kam hoti hai aur generalization improve hoti hai.
[!intuition] Core Idea
Embeddings ko ek lookup table ki tarah socho jahan har token ID ek row number hai, aur tum us row ka vector retrieve karte ho. Token "cat" (ID=42) hamesha usi ek learned vector se map hota hai.
Weights tie kyun karein? Input embedding poochta hai "is token ka matlab kya hai?" aur output projection poochta hai "agla token kaunsa hona chahiye?" Ye inverse operations hain—isliye same weight matrix (transposed) use karna model ko ek consistent representation space seekhne par majboor karta hai.
Analogy: Agar English→French aur French→English translation seekh rahe ho, toh dono directions ke liye same dictionary use karna consistency ensure karta hai.
[!definition] Embedding Layer
Ek embedding layer ek learned matrix hai jahan:
- = vocabulary size
- = embedding dimension
- Har row token ka embedding vector hai
Operation: Input token ID ke liye, embedding yeh hai:
Yeh ek matrix multiplication nahi hai—yeh ek indexing operation (retrieval) hai.
[!formula] Embedding Operation Derive Karna
Goal: Token ID ko vector mein convert karo.
Step 1: One-Hot Encoding (Conceptual)
Token ko one-hot vector ke roop mein represent karo jahan:
Step 2: Matrix Multiplication Interpretation
Agar hum compute karein:
Yeh step kyun? Yeh dikhata hai ki embeddings mathematically equivalent hain one-hot vectors ke saath matrix multiplication ke, lekin hum one-hot actually kabhi banate nahi (memory inefficient hota hai).
Step 3: Efficient Implementation
Practice mein:
# Conceptual: e_x = one_hot(x) @ E # O(V*d) - slow!
e_x = E[x] # O(1) indexing - fast!Yeh kyun important hai: , ke liye, one-hot multiplication multiplications waste karta (zyaadatar zeros ke against). Direct indexing instant hai.
[!formula] Weight Tying: Poori Derivation
Standard Architecture (No Tying)
Forward pass:
- Input embedding: jahan
- Transformer layers:
- Output projection: jahan
- Softmax:
Total parameters: (input) (output)
Weight Tying Constraint
(transpose) set karo. Ab:
Component-wise: Token ka logit hai:
Interpretation: Token ka score = context representation aur token embedding ke beech similarity.
Yeh step kyun? Dot product measure karta hai ki context token ke meaning ke saath kitna "aligned" hai—high similarity → high probability.
Parameter reduction: Ab sirf parameters hain (embeddings + bias), parameters ki saving hoti hai.
Gradient Flow with Tying
Backpropagation ke dauran:
Yeh step kyun? Kyunki do jagah use hota hai (input aur output), dono paths se gradients accumulate hote hain. Yeh richer supervision deta hai—embeddings dono se seekhte hain: "tokens context mein kya mean karte hain" aur "agla kaunsa token likely hai."
[!example] Example 1: Small Vocabulary Embedding
Setup: tokens ["cat", "dog", "the", "ran"], dimensions.
Embedding matrix:
Query: "dog" (ID=1) embed karo.
Solution:
Yeh step kyun? Hum bas row 1 index karte hain. Koi computation nahi chahiye.
[!example] Example 2: Output Projection with Weight Tying
Context: Transformer ke baad, hamare paas hai.
Logits compute karo (tied weights use karke, ):
Har logit calculate karo:
Probabilities (softmax ke baad):
Interpretation: "ran" (ID=3) ki highest probability hai kyunki uska embedding ke saath sabse zyaada aligned hai.
Yeh step kyun? Weight tying model se yeh poochhta hai: "Meri hidden state ke sabse close kaunsa token embedding hai?" Agar embeddings achhe se seekhe gaye hain, toh yeh exactly wahi hai jo hum chahte hain.
[!example] Example 3: Parameter Count Comparison
Scenario: GPT-2 small with , .
Weight tying ke bina:
- Input embeddings:
- Output projection:
- Total: parameters
Weight tying ke saath:
- Shared embeddings:
- Output bias:
- Total: parameters
Savings: parameters (~50% reduction embedding/projection mein).
Yeh step kyun? Bade vocabularies ke liye, embeddings parameter count mein dominate karte hain. Tying ise almost aadha kar deti hai bina performance hurt kiye (aksar improve karke!).
[!mistake] Common Mistake 1: "Embeddings sirf random vectors hote hain"
Galat intuition: Embeddings arbitrary hote hain—koi bhi random initialization kaam karta hai.
Kyun sahi lagta hai: Initially, embeddings hote hain random. Aur random embeddings bhi kuch signal dete hain.
Fix: Embeddings learned representations hain. Gradient descent ke through:
- Similar tokens (cat/dog) similar vectors paate hain
- Embeddings semantic aur syntactic relationships capture karte hain
- Model ek aise geometry seekhta hai jahan "king - man + woman ≈ queen"
Evidence: Pre-trained embeddings (Word2Vec, GloVe) tasks ke across transfer hote hain kyunki yeh real linguistic structure capture karte hain.
[!mistake] Common Mistake 2: "Weight tying force karta hai input=output exactly"
Galat intuition: Weight tying ke saath, , toh input aur output identical hain.
Kyun sahi lagta hai: Hum same matrix use karte hain, toh woh same hone chahiye.
Fix: Hum (transpose!) tie karte hain. Operations hain:
- Input: (row select karo)
- Output: (saare dot products compute karo)
Yeh geometrically inverse operations hain:
- Input: "Is token ko kaunsa vector represent karta hai?"
- Output: "Kaunse token vectors is context ke sabse close hain?"
Yeh kyun kaam karta hai: Output layer pooch raha hai "meri hidden state ke saath kaunsa embedding most similar hai?" Agar embeddings achhe se seekhe gaye hain, toh yeh exactly wahi hai jo hum chahte hain.
[!mistake] Common Mistake 3: "Embeddings per-position hote hain"
Galat intuition: Position 5 par token "cat" ko position 10 par "cat" se alag embedding milta hai.
Kyun sahi lagta hai: Transformers positional encodings use karte hain, toh position matter karta hai.
Fix: Token embedding position-independent hota hai: "cat" hamesha paata hai. Position alag se add hoti hai:
Yeh step kyun? Token aur position information ko alag karna cleaner hai—embedding capture karta hai ki token kya hai, positional encoding capture karta hai ki woh kahan hai.
[!recall]- Kisi 12-Saal-Ke Bachhe Ko Samjhao
Imagine karo tumhare paas ek magic dictionary hai. Har word ka ek secret code hai (numbers ki ek list). Jab tum "dog" dekhte ho, tumhe hamesha wahi code milta hai, jaise [5, -2, 8].
Ab, tum ek story likh rahe ho. Tumne "The dog ran" likha hai, aur tum agla word predict karna chahte ho. Tumhara brain (transformer) story ke baare mein sochta hai aur apna khud ka code produce karta hai, jaise [6, -1, 7].
Agla word choose karne ke liye, tum apne brain ke code ko dictionary mein har word ke code se compare karte ho. Jis word ka code sabse close hoga woh jeet jaata hai! Shayad "fast" ka code [6, -1.5, 7.2] hai—bahut close—toh tum "fast" predict karte ho.
Weight tying ka matlab hai same dictionary use karna words ko shuru mein lookup karne ke liye AUR end mein compare karne ke liye. Kyun? Kyunki agar "dog" aur "puppy" ke dictionary mein similar codes hain, toh tum chahte ho ki tumhara brain predict karte waqt bhi unhe similarly treat kare. Yeh ek jagah jaane aur wapas aane ke liye ek hi map use karne jaisa hai—zyaada efficient aur consistent!
[!mnemonic] Weight Tying Yaad Karo
"Shared Shoes": Input aur output ek hi shoes (weight matrix) pehnte hain, lekin ek aage chalta hai (tokens embed karna), doosra peeche chalta hai (tokens predict karna). Same shoes, opposite directions. Paison ki bachat (parameters), phir bhi destination tak pahunch jaate ho!
Key Formulas
Embedding Lookup
Output Logits (Weight Tying)
Probability Distribution
Connections
- 4.2.01-Tokenization-fundamentals — Tokens IDs mein convert hote hain, phir embed hote hain
- 4.2.04-Subword-tokenization-BPE-WordPiece — Vocabulary size embedding matrix size determine karta hai
- 4.3.02-Positional-encoding — Token embeddings mein add hota hai position info inject karne ke liye
- 4.4.03-Self-attention-mechanism — Embedded token vectors par operate karta hai
- 5.1.03-Cross-entropy-loss — Loss function jo embeddings ke through backprop karta hai
- 6.2.04-Parameter-efficient-fine-tuning — Adapter methods aksar embeddings freeze karte hain
Practical Notes
Weight tying kab use karein:
- ✅ Standard language models (GPT, BERT)
- ✅ Chhote se medium models jahan parameter count matter karta hai
- ✅ Jab vocabulary badi ho ()
Kab use NA karein:
- ❌ Encoder-decoder models jahan alag source/target vocabularies hon
- ❌ Models jahan input/output dimensions differ karein ()
- ❌ Kuch multimodal models (vision+language) jahan output token prediction nahi hai
Implementation tip: Zyaadatar frameworks (PyTorch, TensorFlow) weight tying ko trivial banate hain:
self.output_proj.weight = self.embedding.weight # Share reference#flashcards/ai-ml
Embedding layer kya hoti hai?
Embedding layer kaunsa operation perform karta hai?
E[token_id] corresponding row vector retrieve karta hai. Yeh practice mein matrix multiplication NAHI hai (halanki one-hot vector se multiply karne ke equivalent hai).