Braj Kishore
JourneyVaultML FoundationsAI PM GuideAgenticNewsWork With MeMentorshipPulseNow
Say hi

Hiring · Building · Investing

Have a system — or a team —that needs to scale?

info@avyxon.ai

Usually replies within a day · track record here

JourneyVaultML FoundationsAI PM GuideAgenticNewsWork With MeMentorshipPulseNow
LinkedInXYouTubeSubstackInstagramThreadsFacebookDiscordGitHubTopmate
© 2026 Braj Kishore · Bengaluru, INThink Big · Start Small · Scale Fast
ML Foundations
12Track 3 · Architectures & the walls they broke

Transformers & self-attention

Query, key, value; why the √dₖ is there; multi-head, positional encoding and the O(n²) bill — the architecture every modern model is built from.

70 min1 interactive8 sources

"The animal didn't cross the street because it was too tired." What does "it" refer to? Change one word — "too wide" — and the answer flips from the animal to the street. Self-attention is the mechanism that lets a model resolve that in a single operation, by letting every word look directly at every other word and decide what it needs.

The intuition

A room full of people, each holding a question (query), a name badge describing what they know (key), and the actual knowledge (value). Everyone compares their question against everyone's badge, decides who's worth listening to, and takes a weighted blend of what those people say. One round, everyone at once, no queueing.

Unlearn this

That attention is a search that retrieves the single most relevant token. It's a soft weighted average over all tokens — the softmax produces a distribution, and every value contributes something. That softness is exactly what makes it differentiable and therefore trainable; a hard argmax retrieval would have no gradient.

01The reframe: stop carrying state, start looking around

Recurrence's assumption is that context must be compressed into a state and carried forward. The transformer drops it entirely. Every position holds its own representation, and at each layer every position looks at every other position and pulls in whatever it needs.

Two consequences follow immediately. Path length between any two positions is 1 rather than O(n), so long-range dependencies are as easy to learn as short-range ones. And every position's computation is independent given the layer's input, so the whole sequence can be processed in parallel on a GPU during training. Those two together are the entire reason this architecture took over.

02Query, key, value — and the √dₖ everyone asks about

Each token's embedding is projected three ways by learned matrices into a query, a key and a value. The query is 'what am I looking for'; the key is 'what do I offer'; the value is 'what I'll actually contribute if you pick me'.

Score every query against every key by dot product, giving an n×n matrix of raw relevance. Scale it, softmax each row into a distribution, and use those weights to average the values. That's it: Attention(Q,K,V) = softmax(QKᵀ/√dₖ)V. Three matrix multiplies and a softmax.

The √dₖ is the most reliably asked detail in the whole architecture, so know the mechanism rather than the fact. The dot product of two random vectors of dimension dₖ has variance proportional to dₖ, so as dimension grows the scores spread out. Feed large-magnitude scores into a softmax and it saturates — nearly all the mass lands on one token and the gradients everywhere else go to approximately zero. Dividing by √dₖ normalises the variance back to roughly 1, keeping the softmax in a regime where gradients flow. It is a vanishing-gradient fix, which is why it belongs in a fundamentals course and not a footnote.

Attention(Q,K,V) = softmax(QKᵀ/√dₖ)·V

Score, scale, normalise, blend. The one formula to be able to write from memory.

Var(q·k) ∝ dₖ

Why the scaling exists: unscaled scores grow with dimension, saturating the softmax and killing gradients.

Attention Is All You NeedVaswani et al., NeurIPS · 2017The Illustrated TransformerJay AlammarAttention in transformers, step-by-step (Chapter 6)3Blue1Brown

Try it

Every token looks at every token

Change the last word from 'tired' to 'wide' and watch the pronoun resolve to a different noun.

03Multi-head: several kinds of relationship at once

One attention operation produces one weighting per position — one notion of relevance. Language needs several simultaneously: syntactic agreement, coreference, topical association, positional adjacency.

Multi-head attention runs h attention operations in parallel on lower-dimensional projections (dₖ = d_model/h, so the total cost is roughly unchanged), then concatenates and projects the results. Each head is free to specialise, and when people probe trained models they do find heads that track syntactic dependencies, heads that resolve coreference, and heads that mostly attend to the previous token.

The caution worth voicing: those interpretations are post-hoc and partial. Attention weights are a useful diagnostic, not a faithful explanation of the model's reasoning — there's a substantial literature on precisely that point, and claiming otherwise in an interview is a small red flag.

Transformer ExplainerPolo Club, Georgia Tech

04Positional encoding: attention has no idea about order

Self-attention is permutation-equivariant. Shuffle the input tokens and the output set is the same, just shuffled — nothing in QKᵀ knows which token came first. For language that is catastrophic: 'dog bites man' and 'man bites dog' would be identical.

So position is injected explicitly. The original paper added fixed sinusoidal encodings of varying frequency to the input embeddings — chosen partly so relative offsets are expressible as linear functions, and so it extrapolates to lengths unseen in training. Learned absolute embeddings were the common alternative.

Modern models mostly use rotary position embeddings (RoPE), which rotate the query and key vectors by an angle proportional to position. Because attention depends on the dot product, the relative rotation between two positions falls out naturally — so relative position is encoded directly, and it extends to longer contexts more gracefully. Naming RoPE and saying why (relative position, better length extrapolation) is a strong, current answer.

In an interview

"Why do transformers need positional encodings when RNNs don't?" — Because recurrence gets order for free from the order of processing, while attention sees an unordered set. Without positional information the model literally cannot distinguish two permutations of the same words.

05The block: attention, residual, norm, feed-forward

A transformer layer is: multi-head self-attention → add the residual → layer-norm → a position-wise feed-forward network → add the residual → layer-norm. Modern implementations mostly apply the norm before each sub-layer (pre-norm), which trains much more stably at depth than the original post-norm arrangement.

Two details people underweight. First, the feed-forward block is where most of the parameters live — it expands to roughly 4× the model dimension and back, and it accounts for around two-thirds of a standard block's parameters. Attention gets the attention; the MLP does a lot of the storing.

Second, the residual connections are doing exactly the job they did in ResNet: giving gradients an additive path through a very deep stack. Everything in Lesson 6 applies unchanged — a transformer is a deep network with all the same optimisation problems, solved with the same tools.

Transformers, the tech behind LLMs (Chapter 5)3Blue1BrownThe Annotated TransformerHarvard NLP

06Encoder, decoder, and causal masking

Encoder-only (BERT-style) sees the whole sequence bidirectionally and is trained by masking tokens and predicting them. Good for understanding tasks — classification, extraction, embeddings for retrieval.

Decoder-only (GPT-style) is what every modern LLM uses. A causal mask sets attention scores to −∞ for all future positions before the softmax, so each position attends only to itself and the past. That mask is what makes next-token prediction a valid training objective: every position in the sequence becomes a training example simultaneously, without leaking the answer.

Encoder-decoder (T5, the original 2017 model) keeps both, with cross-attention from the decoder into the encoder. Standard for translation and sequence-to-sequence tasks with clearly separate input and output.

Attention? Attention!Lilian Weng

07The bill: O(n²), and what's been done about it

The attention matrix is n×n. Doubling the sequence length quadruples both the compute and the memory for that matrix. This is the transformer's defining weakness and the reason context windows were small for years.

The mitigations worth naming. FlashAttention restructures the computation to avoid materialising the full matrix in high-bandwidth memory — exact attention, dramatically less memory traffic, and it's the reason long contexts became affordable rather than any change to the maths. Sparse and sliding-window patterns restrict which positions attend to which. Multi-query and grouped-query attention share keys and values across heads to shrink the KV cache. Linear-attention and state-space models change the asymptotics outright.

And one point that closes the loop with recurrence: training is parallel, but generation is not. Producing token t requires token t−1 to exist, so inference is inherently sequential — which is why a KV cache exists (reuse the keys and values of every previous token rather than recomputing them) and why memory bandwidth, not arithmetic, is usually what limits LLM serving.

The point

The transformer traded a sequential training bottleneck for a quadratic memory one, and kept the sequential bottleneck at inference. Almost every serving optimisation you'll read about — KV caching, GQA, FlashAttention, speculative decoding — is a consequence of that one trade.

Let's build GPT: from scratch, in code, spelled outAndrej Karpathy
The vocabulary, defined once
Self-attention
Every position attends to every position in one operation. Path length 1 between any two tokens.
Query / key / value
What I'm looking for / what I offer / what I contribute. Three learned projections of the same input.
Scaled dot-product
Divide scores by √dₖ so the softmax doesn't saturate as dimension grows — a gradient-flow fix.
Multi-head attention
Several attention operations in parallel on lower-dimensional projections, so different heads capture different relationships.
Positional encoding / RoPE
Order injected explicitly, since attention sees an unordered set. RoPE rotates Q and K so relative position falls out of the dot product.
Causal mask
Future positions set to −∞ before the softmax. Makes next-token prediction trainable on every position at once.
KV cache
Stored keys and values for previous tokens so generation doesn't recompute them. The main memory cost of LLM serving.
FlashAttention
Exact attention computed without materialising the n×n matrix in slow memory. Why long contexts became affordable.

The lab

Everything above, with the dials exposed. Break it deliberately — the failure modes are where the understanding is.

Try it

Every token looks at every token

Change the last word from 'tired' to 'wide' and watch the pronoun resolve to a different noun.

What they actually ask

Transformers & self-attention — the interview questions

QExplain self-attention.Answer it out loud first, then open this

Project each token into a query, key and value. Score every query against every key by dot product to get an n×n relevance matrix, scale by √dₖ so the softmax doesn't saturate, softmax each row into weights, and take the weighted average of the values. Every position ends up as a blend of the whole sequence, weighted by learned relevance. Because all positions compute independently, it parallelises — that's the advantage over recurrence.

QTraining is parallel — why is generation still slow?Answer it out loud first, then open this

Because generation is autoregressive: token t is an input to producing token t+1, so you can't compute them simultaneously. Each step attends over everything before it, which is why the KV cache exists — you store previous keys and values rather than recomputing them. That makes serving memory-bandwidth-bound rather than compute-bound, and it's what grouped-query attention and speculative decoding are attacking.

What they're listening for
This question separates people who've served a model from people who've read about one.

QCan you use attention weights to explain a model's output?Answer it out loud first, then open this

As a diagnostic, cautiously; as a faithful explanation, no. Attention weights show where information was gathered from, but the value vectors, the feed-forward blocks and the residual stream all shape the output, and there's published work showing you can alter attention distributions substantially without changing the prediction. I'd use them for debugging and reach for attribution methods if I needed an explanation I could defend.

QWhat does the feed-forward block in a transformer layer do?Answer it out loud first, then open this

Attention mixes information across positions; the feed-forward network processes each position independently, expanding to about 4× the model dimension and projecting back. It's where most of the block's parameters live, and there's good evidence it functions as key-value memory storing a lot of the model's factual knowledge. Attention moves information around; the MLP is where much of it is stored.

Before you move on

Recall beats re-reading, every time. Answer before you flip.

Transformers & self-attention · self-test1 / 3

Why divide by √dₖ?

Go to the primary sources

Where each claim above comes from. Open them alongside the lesson rather than after it — the papers are shorter than you think, and the figures usually carry the whole argument.

Paper
  • Attention Is All You Need(2017)Vaswani et al., NeurIPSThe paper. Eleven pages, and section 3.2.1 contains the √dₖ justification in two sentences — read it in the original at least once.
Watch
  • Attention in transformers, step-by-step (Chapter 6)3Blue1BrownQuery, key and value made geometric. The 'it' → 'animal' resolution is worked through explicitly.
  • Transformers, the tech behind LLMs (Chapter 5)3Blue1BrownThe whole block — embeddings, attention, the feed-forward layer, the unembedding — animated end to end.
  • Let's build GPT: from scratch, in code, spelled outAndrej KarpathyTwo hours building a working decoder-only transformer from nothing, including the causal mask and the KV intuition. The practical capstone for this track.
Read
  • The Illustrated TransformerJay AlammarThe visual walkthrough that taught most practitioners this architecture. Follow the vectors through every step with actual shapes.
  • The Annotated TransformerHarvard NLPThe entire paper reimplemented line by line in PyTorch, with the prose interleaved. The bridge from reading it to building it.
  • Attention? Attention!Lilian WengThe rigorous survey: attention from Bahdanau through self-attention and the transformer family, with the maths kept intact.
Play with it
  • Transformer ExplainerPolo Club, Georgia TechA live GPT-2 in your browser. Type a sentence, watch the attention matrices form per head, and change the temperature on the output distribution.

External links open in a new tab. Every URL was reachable when this page was written; links rot, so treat the list as a map rather than a guarantee.

Connects to

LLMs, tokens & context, for PMs

Got it? Tick it off — progress saves on this device.

← PreviousRecurrent networks (RNN, LSTM, GRU)Next →How a transformer becomes an LLM
Every token looks at every token, at once11×11 per layer
Last word
Layer

Layer 2 · attention from "it"

top: animal 96% · tired 1% · it 1%

Theanimaldidn'tcrossthestreetbecauseitwastootiredTheanimaldidn'tcrossthestreetbecauseitwastootiredThe → The: 8.1%The → animal: 15.3%The → didn't: 8.1%The → cross: 9.0%The → the: 8.1%The → street: 9.1%The → because: 8.1%The → it: 8.9%The → was: 8.1%The → too: 8.1%The → tired: 9.2%animal → The: 8.1%animal → animal: 15.3%animal → didn't: 8.1%animal → cross: 9.0%animal → the: 8.1%animal → street: 9.1%animal → because: 8.1%animal → it: 8.9%animal → was: 8.1%animal → too: 8.1%animal → tired: 9.2%didn't → The: 8.1%didn't → animal: 15.3%didn't → didn't: 8.1%didn't → cross: 9.0%didn't → the: 8.1%didn't → street: 9.1%didn't → because: 8.1%didn't → it: 8.9%didn't → was: 8.1%didn't → too: 8.1%didn't → tired: 9.2%cross → The: 8.1%cross → animal: 15.3%cross → didn't: 8.1%cross → cross: 9.0%cross → the: 8.1%cross → street: 9.1%cross → because: 8.1%cross → it: 8.9%cross → was: 8.1%cross → too: 8.1%cross → tired: 9.2%the → The: 8.1%the → animal: 15.3%the → didn't: 8.1%the → cross: 9.0%the → the: 8.1%the → street: 9.1%the → because: 8.1%the → it: 8.9%the → was: 8.1%the → too: 8.1%the → tired: 9.2%street → The: 8.1%street → animal: 15.3%street → didn't: 8.1%street → cross: 9.0%street → the: 8.1%street → street: 9.1%street → because: 8.1%street → it: 8.9%street → was: 8.1%street → too: 8.1%street → tired: 9.2%because → The: 8.1%because → animal: 15.3%because → didn't: 8.1%because → cross: 9.0%because → the: 8.1%because → street: 9.1%because → because: 8.1%because → it: 8.9%because → was: 8.1%because → too: 8.1%because → tired: 9.2%it → The: 0.3%it → animal: 95.5%it → didn't: 0.3%it → cross: 0.7%it → the: 0.3%it → street: 0.4%it → because: 0.3%it → it: 0.7%it → was: 0.3%it → too: 0.3%it → tired: 0.9%was → The: 8.1%was → animal: 15.3%was → didn't: 8.1%was → cross: 9.0%was → the: 8.1%was → street: 9.1%was → because: 8.1%was → it: 8.9%was → was: 8.1%was → too: 8.1%was → tired: 9.2%too → The: 5.5%too → animal: 29.2%too → didn't: 5.5%too → cross: 8.0%too → the: 5.5%too → street: 15.8%too → because: 5.5%too → it: 6.8%too → was: 5.5%too → too: 5.5%too → tired: 7.4%tired → The: 0.1%tired → animal: 97.8%tired → didn't: 0.1%tired → cross: 0.3%tired → the: 0.1%tired → street: 0.2%tired → because: 0.1%tired → it: 0.4%tired → was: 0.1%tired → too: 0.1%tired → tired: 0.5%rows = queries · columns = keys

Why √dₖ is in the formula

Theanimadidn'crossthestreebecauitwastootiredraw scores span 0.8 → 6.6

Scaled. The distribution stays soft as dₖ grows, so gradients keep flowing to every position.

What "it" is carrying after layer 1

animate0.30
extent0.10
pronoun1.00
pred·animate0.97
pred·extent0.00

It arrived as a bare pronoun. After one layer it is carrying predicate-of-animate — picked up from "tired". That is what layer 2's query is built from.

The pronoun test. With "too tired", layer 2 resolves "it" to animal at 96%. Flip the last word and the answer flips — not because anything was hard-coded, but because "it" absorbed a different predicate at layer 1, which changed its layer-2 query, which changed which key it scores highest against. Look at layer 1 on its own and you will see it resolves nothing: this needs both layers, which is a compact argument for why transformers are deep and not wide.

And the bill. That matrix is 11×11 = 121 entries for eleven tokens, per head, per layer. At 10,000 tokens it is 100 million — the O(n²) cost that FlashAttention, sliding-window attention and the linear-attention family all exist to pay down.

Click a word to see what it attends to. Each row is a probability distribution over the whole sentence — attention is a soft weighted average, not a lookup of a single winner.

Every token looks at every token, at once11×11 per layer
Last word
Layer

Layer 2 · attention from "it"

top: animal 96% · tired 1% · it 1%

Theanimaldidn'tcrossthestreetbecauseitwastootiredTheanimaldidn'tcrossthestreetbecauseitwastootiredThe → The: 8.1%The → animal: 15.3%The → didn't: 8.1%The → cross: 9.0%The → the: 8.1%The → street: 9.1%The → because: 8.1%The → it: 8.9%The → was: 8.1%The → too: 8.1%The → tired: 9.2%animal → The: 8.1%animal → animal: 15.3%animal → didn't: 8.1%animal → cross: 9.0%animal → the: 8.1%animal → street: 9.1%animal → because: 8.1%animal → it: 8.9%animal → was: 8.1%animal → too: 8.1%animal → tired: 9.2%didn't → The: 8.1%didn't → animal: 15.3%didn't → didn't: 8.1%didn't → cross: 9.0%didn't → the: 8.1%didn't → street: 9.1%didn't → because: 8.1%didn't → it: 8.9%didn't → was: 8.1%didn't → too: 8.1%didn't → tired: 9.2%cross → The: 8.1%cross → animal: 15.3%cross → didn't: 8.1%cross → cross: 9.0%cross → the: 8.1%cross → street: 9.1%cross → because: 8.1%cross → it: 8.9%cross → was: 8.1%cross → too: 8.1%cross → tired: 9.2%the → The: 8.1%the → animal: 15.3%the → didn't: 8.1%the → cross: 9.0%the → the: 8.1%the → street: 9.1%the → because: 8.1%the → it: 8.9%the → was: 8.1%the → too: 8.1%the → tired: 9.2%street → The: 8.1%street → animal: 15.3%street → didn't: 8.1%street → cross: 9.0%street → the: 8.1%street → street: 9.1%street → because: 8.1%street → it: 8.9%street → was: 8.1%street → too: 8.1%street → tired: 9.2%because → The: 8.1%because → animal: 15.3%because → didn't: 8.1%because → cross: 9.0%because → the: 8.1%because → street: 9.1%because → because: 8.1%because → it: 8.9%because → was: 8.1%because → too: 8.1%because → tired: 9.2%it → The: 0.3%it → animal: 95.5%it → didn't: 0.3%it → cross: 0.7%it → the: 0.3%it → street: 0.4%it → because: 0.3%it → it: 0.7%it → was: 0.3%it → too: 0.3%it → tired: 0.9%was → The: 8.1%was → animal: 15.3%was → didn't: 8.1%was → cross: 9.0%was → the: 8.1%was → street: 9.1%was → because: 8.1%was → it: 8.9%was → was: 8.1%was → too: 8.1%was → tired: 9.2%too → The: 5.5%too → animal: 29.2%too → didn't: 5.5%too → cross: 8.0%too → the: 5.5%too → street: 15.8%too → because: 5.5%too → it: 6.8%too → was: 5.5%too → too: 5.5%too → tired: 7.4%tired → The: 0.1%tired → animal: 97.8%tired → didn't: 0.1%tired → cross: 0.3%tired → the: 0.1%tired → street: 0.2%tired → because: 0.1%tired → it: 0.4%tired → was: 0.1%tired → too: 0.1%tired → tired: 0.5%rows = queries · columns = keys

Why √dₖ is in the formula

Theanimadidn'crossthestreebecauitwastootiredraw scores span 0.8 → 6.6

Scaled. The distribution stays soft as dₖ grows, so gradients keep flowing to every position.

What "it" is carrying after layer 1

animate0.30
extent0.10
pronoun1.00
pred·animate0.97
pred·extent0.00

It arrived as a bare pronoun. After one layer it is carrying predicate-of-animate — picked up from "tired". That is what layer 2's query is built from.

The pronoun test. With "too tired", layer 2 resolves "it" to animal at 96%. Flip the last word and the answer flips — not because anything was hard-coded, but because "it" absorbed a different predicate at layer 1, which changed its layer-2 query, which changed which key it scores highest against. Look at layer 1 on its own and you will see it resolves nothing: this needs both layers, which is a compact argument for why transformers are deep and not wide.

And the bill. That matrix is 11×11 = 121 entries for eleven tokens, per head, per layer. At 10,000 tokens it is 100 million — the O(n²) cost that FlashAttention, sliding-window attention and the linear-attention family all exist to pay down.

Click a word to see what it attends to. Each row is a probability distribution over the whole sentence — attention is a soft weighted average, not a lookup of a single winner.