The problem, stated properly
Before 2017, sequence models (RNNs, LSTMs) read text one token at a time, carrying a compressed memory forward. Two fatal flaws: the memory bottlenecked on long texts (the 50th word barely influenced the understanding of the 1st), and the sequential loop could not be parallelized, so training crawled. The Transformer ("Attention Is All You Need", 2017) threw the loop away entirely: every token looks directly at every other token, all at once, in parallel. That single idea, attention, is why modern LLMs exist, and understanding its mechanics is understanding why they cost what they cost and fail where they fail.
Attention, mechanically
Each token starts as an embedding vector (say 4,096 numbers representing the word in context-free space). Three learned matrices project it into three roles:
- Query (Q): "what am I looking for?"
- Key (K): "what do I contain?"
- Value (V): "what do I pass on if you attend to me?"
For every pair of tokens, the score is the dot product of one token's query with the other's key, scaled by sqrt(d) to keep gradients stable. A row of scores goes through softmax, producing weights that sum to 1: a probability distribution over which tokens matter to this one. The token's new representation is the weighted sum of everyone's values. "The animal didn't cross the street because it was too tired": the token "it" gets high attention weight on "animal", and its representation absorbs that meaning. Ambiguity resolution is now arithmetic.
Multi-head: why one attention is not enough
A single softmax forces tokens to split attention across all relationship types at once. Multi-head attention runs h parallel copies (typically 32-96 heads), each with its own smaller Q/K/V projections, so different heads specialize: some track syntax (subject-verb agreement), some coreference (pronouns), some position, some semantics. Their outputs concatenate and project back. In an interview, the answer to "why multi-head?" is: different heads learn different relationship types, the way different filters in a CNN learn different visual features.
The cost that shapes everything: O(n^2)
Every token attends to every token: n tokens means n^2 score computations. This quadratic wall is the Transformer's defining constraint:
- Memory: at 100K context with typical dimensions, the raw attention matrix is 10^10 entries: tens of GB per layer per head. Techniques like FlashAttention (tiling the computation to stay in fast SRAM, never materializing the full matrix) made long contexts practical; it is an IO-optimization, not an approximation, and it is why 100K-1M token contexts exist at all.
- Inference and the KV cache: generating text one token at a time would recompute attention over the whole prefix per token. Instead, every token's K and V are cached, so each new token only computes its own Q against the cache: generation becomes O(n) per token. The KV cache is why long conversations eat GPU memory linearly, and why context length is a pricing lever, not a free parameter.
- Why "long context" is genuinely hard: doubling context quadruples prefill compute and doubles KV cache. Every sparse/linear-attention variant (sliding windows, sparse patterns, linear approximations) is an attempt to soften this wall, each trading some recall of distant context.
The rest of the block, briefly but correctly
- Positional encoding: attention is order-blind (it sees a bag of tokens), so position must be injected: original sinusoidal encodings, now mostly rotary embeddings (RoPE), which rotate Q/K vectors by position-dependent angles so relative position shows up naturally in dot products. RoPE's behavior at extrapolation (contexts longer than training) is a live engineering problem.
- Feed-forward network: after attention mixes information across tokens, a per-token MLP (expand 4x, activate, project back) does the "thinking." Most parameters live here, not in attention.
- Residual connections + layer norm: each sublayer adds its output to its input (residuals) and normalizes. Without residuals, 100-layer networks would not train; gradients die.
- Stacking: a modern LLM is this block repeated 30-120 times. Early layers handle syntax, middle layers facts and relations, late layers task-level reasoning. Depth is where capability comes from; width and data decide the rest.
Training and inference, numbers attached
- Training FLOPs: roughly 6 x N x D (parameters x tokens). A 70B model on 15T tokens is about 6 x 7e10 x 1.5e13 which is on the order of 10^24 FLOPs: months on thousands of GPUs, millions of dollars. Chinchilla scaling laws say model size and data should grow together; most early models were under-trained, not too small.
- Inference economics: a forward pass touches every parameter, so generating a token from a 70B model in fp16 moves ~140 GB of weights from memory: inference is memory-bandwidth-bound, which is why batching many requests is the whole serving game (amortize weight reads across the batch) and why quantization to 4-8 bits (cutting bytes per weight 2-4x) gives near-linear speedups.
Failure modes worth naming
- Hallucination: next-token prediction optimizes plausibility, not truth. The model generates what text should come next, with no internal flag for "I don't actually know." Grounding (RAG) and training mitigations reduce it; nothing eliminates it.
- Context degradation: attention is exact in principle, but models measurably under-use the middle of long contexts ("lost in the middle").
- Position extrapolation: models trained at 8K context fed 128K tokens degrade unpredictably without specific extensions.
- Adversarial prompts: the model cannot distinguish instructions from data at the architecture level. This is the root of prompt injection, and no amount of fine-tuning fully fixes it.
Common interview traps
- Explaining attention as "the model focuses on important words" without Q/K/V, softmax, or the weighted sum. That is a blog-post answer.
- Not knowing why it is O(n^2) or what the KV cache is. Both are standard follow-ups.
- Claiming attention "solved" long-range dependencies, full stop. It made them addressable in parallel; quadratic cost and lost-in-the-middle are the fine print.
- Saying positional encodings tell the model word order "so it is not permutation-invariant" without being able to say how RoPE differs from absolute encodings.
Interview Q&A
Q: Why does the Transformer scale so much better than an LSTM?
A: Parallelism and path length. An LSTM processes token n only after token n-1: training is a serial loop that cannot fill a GPU, and information from token 1 travels through n-1 sequential steps (each a chance to forget) to influence token n. The Transformer computes all tokens simultaneously (matrix multiplies saturate thousands of GPU cores), and any two tokens interact in one attention hop: path length O(1) instead of O(n). Short paths mean stronger gradients for long-range dependencies, and parallelism means you can throw hardware at the problem. Scale came from both.
Q: Your 8K-context model must now handle 100K-token documents. What are your options?
A: In order of effort: (1) rope scaling (NTK-aware or position interpolation) often stretches RoPE 4-8x with light fine-tuning; (2) fine-tune on long documents so attention learns to use the new range; (3) architectural: sliding-window or sparse attention to cap the quadratic; (4) systemic: chunk + RAG, so no single context ever needs to hold 100K tokens. In production, (4) plus a modest context extension beats a heroic 1M-context deployment on cost per query, because prefill is quadratic and the KV cache bill arrives on every single request.
Problem ko sahi se samjho
2017 se pehle, sequence models (RNNs, LSTMs) text ko ek-ek token karke padhte the, compressed memory aage le jaate hue. Do fatal flaws: lambi texts pe memory bottleneck ho jaati thi (50vein word ka 1st word pe asar na ke barabar), aur sequential loop parallelize nahi ho sakta tha, to training rangti thi. Transformer ("Attention Is All You Need", 2017) ne loop ko hi fek diya: har token har doosre token ko directly dekhta hai, sab ek saath, parallel mein. Ye ek idea, attention, hi wajah hai ki modern LLMs exist karte hain, aur iske mechanics samajhna matlab samajhna ki ye cost itni kyun karte hain aur kahan fail karte hain.
Attention, mechanically
Har token ek embedding vector se shuru hota hai (maan lo 4,096 numbers, context-free space mein word ko represent karte hue). Teen learned matrices use teen roles mein project karti hain:
- Query (Q): "main kya dhoondh raha hu?"
- Key (K): "mere paas kya hai?"
- Value (V): "agar tum mujhe attend karo to main kya aage doon?"
Tokens ke har pair ke liye, score ek token ke query ka doosre ke key ke saath dot product hai, sqrt(d) se scaled taaki gradients stable rahein. Scores ki ek row softmax se guzarti hai, producing weights jo 1 tak sum karte hain: is token ke liye kaunse tokens matter karte hain, ek probability distribution. Token ka naya representation sabke values ka weighted sum hai. "The animal didn't cross the street because it was too tired": "it" token ko "animal" pe high attention weight milta hai, aur uska representation wo meaning absorb kar leta hai. Ambiguity resolution ab arithmetic hai.
Multi-head: ek attention kaafi kyun nahi
Ek softmax tokens ko saare relationship types ke across attention split karne pe majboor karta hai. Multi-head attention h parallel copies chalata hai (typically 32-96 heads), har ek ke apne chhote Q/K/V projections, taaki alag heads specialize karein: kuch syntax track karte hain (subject-verb agreement), kuch coreference (pronouns), kuch position, kuch semantics. Unke outputs concatenate ho ke wapas project hote hain. Interview mein "multi-head kyun?" ka jawab: alag heads alag relationship types seekhte hain, jaise CNN mein alag filters alag visual features seekhte hain.
Wo cost jo sab kuch shape karti hai: O(n^2)
Har token har token ko attend karta hai: n tokens matlab n^2 score computations. Ye quadratic wall Transformer ki defining constraint hai:
- Memory: 100K context pe typical dimensions ke saath, raw attention matrix 10^10 entries: per layer per head tens of GB. FlashAttention jaise techniques (computation ko tile karke fast SRAM mein rakhna, poori matrix kabhi materialize na karna) ne long contexts practical banaye; ye IO-optimization hai, approximation nahi, aur isi wajah se 100K-1M token contexts exist karte hain.
- Inference aur KV cache: text ek-ek token generate karte waqt har token pe poori prefix ka attention dobara compute karna padega. Iske bajaye har token ke K aur V cache ho jaate hain, to naya token sirf apna Q cache ke against compute karta hai: generation per token O(n). KV cache hi wajah hai ki lambi conversations GPU memory linearly khaati hain, aur context length pricing lever hai, free parameter nahi.
- "Long context" genuinely mushkil kyun hai: context double karna prefill compute ko quadruple aur KV cache ko double karta hai. Har sparse/linear-attention variant (sliding windows, sparse patterns, linear approximations) is wall ko naram karne ki koshish hai, har ek distant context ki thodi recall trade karta hua.
Baaki block, briefly par correctly
- Positional encoding: attention order-blind hai (tokens ka bag dekhta hai), to position inject karni padti hai: original sinusoidal encodings, ab mostly rotary embeddings (RoPE), jo Q/K vectors ko position-dependent angles se rotate karte hain taaki relative position dot products mein naturally dikhe. Extrapolation pe RoPE ka behavior (training se lambe contexts) ek live engineering problem hai.
- Feed-forward network: attention ke tokens ke across information mix karne ke baad, ek per-token MLP (4x expand, activate, project back) "thinking" karta hai. Zyadatar parameters yahin rehte hain, attention mein nahi.
- Residual connections + layer norm: har sublayer apna output apne input mein jodta hai (residuals) aur normalize karta hai. Bina residuals ke 100-layer networks train nahi hote; gradients mar jaate hain.
- Stacking: modern LLM ye block 30-120 baar repeat hai. Early layers syntax, middle layers facts aur relations, late layers task-level reasoning. Depth se capability aati hai; width aur data baaki decide karte hain.
Training aur inference, numbers ke saath
- Training FLOPs: roughly 6 x N x D (parameters x tokens). 70B model 15T tokens pe about 6 x 7e10 x 1.5e13, matlab 10^24 FLOPs ke order pe: hazaron GPUs pe mahine, millions of dollars. Chinchilla scaling laws kehte hain model size aur data saath badhne chahiye; zyadatar early models under-trained the, too small nahi.
- Inference economics: ek forward pass har parameter ko chhoota hai, to 70B model se fp16 mein ek token generate karna ~140 GB weights memory se move karta hai: inference memory-bandwidth-bound hai, isliye kai requests batch karna poora serving game hai (weight reads ko batch ke across amortize karo) aur 4-8 bits tak quantization (bytes per weight 2-4x kam) near-linear speedups deta hai.
Failure modes jo naam dene layak hain
- Hallucination: next-token prediction plausibility optimize karta hai, truth nahi. Model wo generate karta hai jo agla text hona chahiye, bina kisi internal flag ke ki "mujhe asal mein nahi pata." Grounding (RAG) aur training mitigations kam karte hain; kuch eliminate nahi karta.
- Context degradation: attention principle mein exact hai, par models lambi contexts ke beech ka measurably kam use karte hain ("lost in the middle").
- Position extrapolation: 8K context pe trained models ko 128K tokens do to specific extensions ke bina unpredictably degrade hote hain.
- Adversarial prompts: model architecture level pe instructions aur data mein farak nahi kar sakta. Ye prompt injection ki jad hai, aur koi fine-tuning ise poori tarah fix nahi karta.
Common interview traps
- Attention ko "model important words pe focus karta hai" bolke explain karna, bina Q/K/V, softmax ya weighted sum ke. Ye blog-post jawab hai.
- Ye na jaanna ki O(n^2) kyun hai ya KV cache kya hai. Dono standard follow-ups hain.
- Kehna ki attention ne long-range dependencies "solve" kar di, bas. Unhe parallel mein addressable banaya; quadratic cost aur lost-in-the-middle fine print hai.
- Kehna ki positional encodings word order batate hain "to ye permutation-invariant nahi hai", bina ye bata sake ki RoPE absolute encodings se kaise alag hai.
Interview Q&A
Q: Transformer LSTM se itna better scale kyun karta hai?
A: Parallelism aur path length. LSTM token n ko token n-1 ke baad process karta hai: training ek serial loop hai jo GPU bhar nahi sakta, aur token 1 ki information token n tak n-1 sequential steps se guzarti hai (har ek bhoolne ka chance). Transformer saare tokens simultaneously compute karta hai (matrix multiplies hazaron GPU cores saturate karte hain), aur koi bhi do tokens ek attention hop mein interact karte hain: path length O(n) ke bajaye O(1). Chhote paths matlab long-range dependencies ke liye stronger gradients, aur parallelism matlab problem pe hardware phenk sakte ho. Scale dono se aaya.
Q: Tumhare 8K-context model ko ab 100K-token documents handle karne hain. Options kya hain?
A: Effort ke order mein: (1) rope scaling (NTK-aware ya position interpolation) aksar RoPE ko light fine-tuning ke saath 4-8x stretch kar deta hai; (2) lambe documents pe fine-tune karo taaki attention nayi range use karna seekhe; (3) architectural: sliding-window ya sparse attention, quadratic cap karne ke liye; (4) systemic: chunk + RAG, taaki kisi ek context ko kabhi 100K tokens rakhne ki zaroorat hi na ho. Production mein (4) plus modest context extension heroic 1M-context deployment ko cost per query pe harata hai, kyunki prefill quadratic hai aur KV cache ka bill har request pe aata hai.