AI Systems: Transformers & Attention

With the long-form video: how LLMs work inside. Tokens, embeddings, attention, and why Transformers changed AI.

Advanced9 min read
Language
Theme

Long-form: Transformers Explained (Hindi), 14 min deep dive

TheanimalwastiredembeddingsSelf-attention: tokens see each otherThen: predict the next token, one at a time
Key idea at a glance

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.

Key takeaways

Interview pointer

The full deep dive is the long-form video on the channel. Watch it and you will be able to whiteboard attention from memory.