SeeingML
Modern AI & LLMs Guide 3 of 7 · tap to switch
✦ Interactive Visual Guide 9 min · 4 hands-on labs · Beginner friendly

Transformer Architecture & KV Cache

Step inside the complete blueprint powering GPT, Claude, and Gemini: Pre-Norm blocks, RoPE positional encoding, Encoder vs. Decoder families, and KV Caching.

When you open the famous 2017 paper “Attention Is All You Need”, the architecture diagram can look like a spaceship wiring schematic. Yet peel away the jargon, and a modern Transformer (powering ChatGPT, Claude, Gemini, and Llama) is just one clean Lego block stacked 32 to 96 times tall.

Think of each block as a two-desk assembly line that every word in your sentence passes through:

  1. Desk 1, the Group Meeting: Words compare notes with each other across the sentence so an ambiguous word like “bank” picks up clues from neighbors like “river” or “flooded”. The official name for this desk is Self-Attention, and it is the only place in the block where different words talk to each other.
  2. Desk 2, the Private Thinking Booth: Each word steps away alone into a mini neural network to digest those clues and pull up factual knowledge stored in the model’s learned weights. The official name is the Feed-Forward Network, or MLP (modern models often use a gated style called SwiGLU).

To stack dozens of these blocks without losing the plot, every block adds two simple safety rails:

  • Steady Signal Volume (Pre-Norm / RMSNorm): Before entering either desk, the model gently levels each word’s numbers so signals never blow up or fade away. Doing this before each desk is called Pre-Norm, commonly implemented with RMSNorm.
  • Keep Your Original Notes (+ Skip Highway): Instead of erasing a word’s old meaning and rewriting it from scratch, each desk simply adds its new insight onto a clean copy of the original notes. That bypass lane is called a Residual Skip Connection.

Step through all 4 stages inside one modern Transformer block below and watch what happens to the word "bank" as it moves through the assembly line.

Interactive Lab 1: Inside One Transformer Block
Follow the word "bank" in "The river bank flooded" across all 4 stages.Stacked 32 to 96x deep
+ Skip Highway (keep original notes)+ Skip Highway (keep updated notes)WordsInNormLevel vol.Self-AttentionTalk to othersDesk 1 (group)+NormLevel vol.Private MLPThink aloneDesk 2 (1x->4x->1x)+SmarterOutVolume Check:->Wild spikes smoothed before Desk 1 and Desk 2
Step 1: Keep Signal Volume SteadyPre-Norm (RMSNorm)
Before entering either desk, the model gently rescales each word's numbers so signals never spike too loud or fade to zero. Doing this before each desk keeps 32 to 96 stacked blocks calm and stable.
Before this step ("bank")Raw bumpy signal: [0.1, 9.4, -6.2]
After this step ("bank")Steady balanced signal: [0.2, 1.3, -0.9]
Takeaway: Step 1 (Pre-Norm): Leveling each word's signal volume before both desks keeps deep Transformers stable from layer 1 to layer 96.

Solving Attention’s blind spot: Positional Encoding & RoPE

Pop quiz: "Dog bites man" and "Man bites dog" contain the exact same three words, yet tell opposite news stories!

Because Self-Attention compares every word against every other word all at once without reading left to right, it has a surprising blind spot: it sees an unordered bag of words. Pouring the words {bites, dog, man} onto a table loses who came first and who came last.

The fix is simple: before words compare notes, stamp every seat in the sentence with a unique position signal (like giving each word its own clock-hand angle or rhythmic wave signature). Early Transformers added smooth wave patterns directly onto each word’s numbers, called Positional Encoding. Modern models like Llama, Gemma, and Mistral instead rotate each word’s matching vectors like hands on a clock, called RoPE (Rotary Position Embedding), so the angle gap between any two words immediately tells the model how far apart they sit.

Start with Position Info: OFF below and click Swap Words to catch the bag-of-words bug in action, then turn Position Info: ON to watch position stamps fix it!

Interactive Lab 2: Position Info & RoPE Clock Stamps
Step 1: Click Swap Words while OFFStep 2: Turn Position Info ON & Swap again
Human sentence: "Dog bites man"
Model's Unordered Word Bag (No Slot Numbers!)bitesdogmanBag set: { bites, dog, man } (alphabetical soup, zero order!)Who bit whom? Model cannot tell! Click "Swap Words" above to prove it.
Takeaway: Position Info is OFF right now. Click "Swap Words" above and watch what happens inside the Model's Word Bag below.

One blueprint, three famous families: BERT vs. T5 vs. GPT/Gemini

Since 2017, engineers split this single Transformer blueprint into three famous families based on one simple choice: which words is each word allowed to look at?

  • The Reader (Encoder-Only, e.g., BERT): Every word looks both left and right across the whole sentence at once, making it ideal for understanding meaning in semantic search, review classification, and tagging key facts.
  • The Translator (Encoder-Decoder, e.g., T5, Whisper): First reads the entire input in both directions (like an English sentence or an audio clip), then uses a second stack to write out the converted answer word by word (like French text or a transcript).
  • The Writer (Decoder-Only, e.g., GPT, Claude, Gemini, Llama): Each word can only look backward at earlier words (never peeking ahead), predicting the next word one at a time. Turning almost any task into next-word prediction let this clean, uniform stack win general-purpose AI!

Click each family below to see how its attention arrows flow across words.

Interactive Lab 3: Three Transformer Families (How Attention Arrows Flow)
Click each family to compare which words can look at which other words.
ThemoviewasgreatPositiveReview (98%)All-to-all arrows: every word reads BOTH left and right neighbors at once
Reader (Encoder)BERT, RoBERTa, ModernBERT, Search Embedders
How it looks at words: Bidirectional: every word looks freely at both left and right neighbors.
Best used for: Semantic search, sorting reviews by mood, spotting names and dates in documents, and ranking search results.
Why it shines: Seeing the full sentence from both sides builds deep understanding of meaning, though it is built to score and summarize rather than write long open-ended replies.
Takeaway: Choose a Reader (Encoder) when you want to understand, search, or classify existing text as fast and accurately as possible.

What Is KV Cache? Fixing O(N²) Transformer Memory

Imagine writing a report on a 500-page book. If you threw away all your notes after writing every single word and had to re-read all 500 pages from page 1 just to write the next word, finishing one paragraph would take hours!

That is the exact trap a naive Transformer falls into. When a model reads N words and compares every word with every other word, the number of word pairs grows like N × N (O(N²)). On a 32,000-word prompt, that is over 1 billion comparisons!

Here is the clever shortcut: in a Writer (Decoder-Only) model, earlier words never peek ahead at future words. That means the summary notes for page 1 through page 500 never change once you read them! Instead of re-reading the entire conversation for every new word, the model keeps sticky-note summaries of every past word on its desk. Writing a new word then only takes 1 × N work (O(N)): compare your 1 brand-new word against the N saved sticky notes.

In ML terms, this two-phase trick has three names:

  1. Prefill (O(N²)): Reading your entire pasted prompt once up front to build those first sticky notes (this is why a huge prompt pauses briefly before the first word appears).
  2. KV Cache: The memory shelf in GPU RAM that stores each past word’s saved Key (K) and Value (V) sticky-note vectors.
  3. Decode (O(N) per word): Streaming the reply one new word at a time by computing just 1 new Query vector and looking up the saved KV Cache. On long conversations, this speeds up typing by over 100×, trading a few gigabytes of GPU memory for silky-smooth real-time speed.

Start with KV Cache: OFF below to see the re-reading bottleneck across short chats and full books, then flip KV Cache: ON to watch sticky notes slash per-word wait time!

Interactive Lab 4: Sticky Notes vs. Re-Reading (KV Cache)
Step 1: Watch the re-reading work with KV Cache OFF -> Step 2: Turn KV Cache ON and test longer chats!
Re-reading ALL 32,000 past words from scratch just to write 1 new word!N x N pairs (O(N²))
Word 1Re-read!
Word 2Re-read!
Word 3Re-read!
... 31,996 more ...Re-read!
Word 32,000Re-read!
New WordWaiting...
Wait Time to Write 1 New Word (32,000 words conversation)
Without KV Cache (Re-read all)Active2.1 sec / word! (1.02 Billion pairs)
With KV Cache (Sticky Notes)18 ms / word (32,000 lookups)
Work per New Word1.02 Billion pairs
Streaming Speed2.1 sec / word!
Sticky-Note Shelf (GPU RAM)0 GB (re-reading)
Takeaway: Without sticky notes, writing just ONE new word forces the model to re-read all 32,000 earlier words from scratch (1.02 Billion word pairs, 2.1 sec / word!). Flip KV Cache ON above to see sticky notes slash that wait!
See Pre-Norm Residual Blocks, Sinusoidal Waves & Rotary Position Embeddings (RoPE)Thesis / Reference

1. Modern Pre-Norm Decoder Block (Xiong et al., 2020; Touvron et al., 2023): Given hidden state matrix X(ℓ)∈RN×d\mathbf{X}^{(\ell)} \in \mathbb{R}^{N \times d}, each layer updates the clean residual stream via:

U(ℓ)=X(ℓ)+MHA⁡ ⁣(RMSNorm⁡(X(ℓ))),X(ℓ+1)=U(ℓ)+SwiGLU⁡ ⁣(RMSNorm⁡(U(ℓ)))\mathbf{U}^{(\ell)} = \mathbf{X}^{(\ell)} + \operatorname{MHA}\!\big(\operatorname{RMSNorm}(\mathbf{X}^{(\ell)})\big), \qquad \mathbf{X}^{(\ell+1)} = \mathbf{U}^{(\ell)} + \operatorname{SwiGLU}\!\big(\operatorname{RMSNorm}(\mathbf{U}^{(\ell)})\big)

After LL blocks, a final normalization and unembedding projection Wlm∈Rd×∣V∣\mathbf{W}_{\text{lm}} \in \mathbb{R}^{d \times |V|} produces next-token logits across the full vocabulary.

2. Sinusoidal Positional Encoding (Vaswani et al., 2017) vs. RoPE (Su et al., 2021): Vaswani et al. added multi-frequency waves PE(p,2i)=sin⁡(p/100002i/d)\text{PE}_{(p, 2i)} = \sin(p / 10000^{2i/d}) and PE(p,2i+1)=cos⁡(p/100002i/d)\text{PE}_{(p, 2i+1)} = \cos(p / 10000^{2i/d}) to input embeddings. Modern frontier LLMs instead apply Rotary Position Embeddings (RoPE), rotating each 2D pair of Query/Key coordinates by angle mθim\theta_i so their inner product depends exclusively on relative token distance m−nm - n:

(Rmq)⊤(Rnk)=q⊤Rn−m k\big(\mathbf{R}_m \mathbf{q}\big)^\top \big(\mathbf{R}_n \mathbf{k}\big) = \mathbf{q}^\top \mathbf{R}_{n - m}\,\mathbf{k}

3. Scaling Laws & MoE (Kaplan et al., 2020; Hoffmann et al., 2022): Chinchilla scaling laws showed compute-optimal pretraining balances model parameters NN and training tokens DD roughly at D≈20ND \approx 20N. Frontier models further scale total knowledge capacity without inflating per-token FLOPs using Mixture-of-Experts (MoE), routing each token through only 2 to 8 active MLP experts out of 64 to 128 total experts!

See a Complete Pre-Norm Transformer Block in 15 Lines of PyTorchOptional Code
python
import torch.nn as nn
import torch.nn.functional as F

class TransformerBlock(nn.Module):
  def __init__(self, d_model=512, n_heads=8):
      super().__init__()
      self.norm1 = nn.RMSNorm(d_model)
      self.attn = nn.MultiheadAttention(d_model, n_heads, batch_first=True)
      self.norm2 = nn.RMSNorm(d_model)
      self.mlp = nn.Sequential(
          nn.Linear(d_model, 4 * d_model),
          nn.GELU(),
          nn.Linear(4 * d_model, d_model),
      )

  def forward(self, x, causal_mask):
      h = self.norm1(x)
      x = x + self.attn(h, h, h, attn_mask=causal_mask, is_causal=True)[0]
      x = x + self.mlp(self.norm2(x))
      return x

So the final Transformer layer spits out 100,000 scores: now what?

You now understand the entire internal engine, from raw text all the way to the final next-word probability scores! Yet ask the exact same prompt twice and an LLM writes two subtly different replies. How do Temperature, Top-K, and Top-P turn those final scores into creative writing, crisp code, or accidental hallucinations?

Next up: How LLMs Generate Text (Temperature, Top-K & Top-P).

✓ Self-Check

Quick Intuition Check

Four quick real-world scenarios. No scores, just test your intuition.

1

Inside a single Transformer block, how do Self-Attention and the Feed-Forward MLP divide the work?

Pick an option first, or peek anytime
2

What happens if you remove Positional Encoding (and RoPE) from a bare Self-Attention layer and feed it 'Dog bites man' vs. 'Man bites dog'?

Pick an option first, or peek anytime
3

Why does turning on the KV Cache speed up word-by-word LLM generation by over 100x on long conversations?

Pick an option first, or peek anytime
4

A Reader (Encoder-Only) Transformer like BERT lets every word look both left and right at the same time, making it ideal for semantic search and classification rather than streaming open-ended chat replies.

Pick an option first, or peek anytime
Quick Reference

Common Questions

What is KV Cache in an LLM and how does it work?
During autoregressive generation, every new token attends back to all previous tokens' Key (K) and Value (V) vectors. Instead of recomputing K and V for the whole prompt on every generated word (O(N^2) redundant work), KV Caching stores past K and V tensors in GPU memory so each new token only computes one fresh K/V row.
What is KV cache quantization and why does it matter?
Long prompts and large batch sizes can push the KV Cache into tens of gigabytes of GPU VRAM. Quantizing cached K/V values from 16-bit floats down to 8-bit or 4-bit numbers (alongside Grouped-Query Attention) shrinks VRAM usage dramatically with minimal loss in answer quality.
How does a Transformer block work in simple terms?
Every Transformer block alternates two complementary steps wrapped in Residual Skip Connections and Layer/RMS Normalization: (1) Multi-Head Self-Attention mixes context across different tokens, and (2) a Feed-Forward MLP processes each token individually to transform features and retrieve stored factual knowledge.
Why do Transformers need Positional Encoding or RoPE?
Unlike older sequential RNNs, Self-Attention compares all tokens simultaneously like an unordered set, so 'Dog bites man' and 'Man bites dog' produce identical scores unless position information is injected via Sinusoidal waves or Rotary Position Embeddings (RoPE).
What is the difference between BERT, T5, and GPT/Claude/Gemini?
BERT is Encoder-Only (bidirectional attention, great for search embeddings and classification). T5 and Whisper are Encoder-Decoder (read a full source input then generate a target output). GPT, Claude, Gemini, and Llama are Decoder-Only (causal left-to-right attention that scales cleanly into general-purpose assistants).
What is a KV Cache in LLM inference?
When generating an answer word by word, earlier tokens' Key and Value vectors never change in a causal Transformer. Saving those K and V tensors in GPU RAM (the KV Cache) avoids recomputing the entire conversation history on every single new output token.
Why are long context windows (like 128K or 1M tokens) expensive?
Full Self-Attention compares every token against every prior token (O(N^2) compute during prompt prefill), and the KV Cache grows linearly with context length N, consuming gigabytes of GPU memory per active user.

Written & illustrated by Muhammad Aashir Irshad · Updated December 2026 · Free open-access reference

https://seeingml.com/learn/transformers/ Open GitHub issue Suggest an edit
Cite this guide in a paper, thesis, or course (BibTeX & APA)
BibTeX
@misc{irshad2026transformers,
  author       = {Irshad, Muhammad Aashir},
  title        = {Transformer Architecture & KV Cache: Interactive Visual Guide},
  howpublished = {SeeingML},
  year         = {2026},
  month        = {dec},
  url          = {https://seeingml.com/learn/transformers/},
  note         = {Interactive visual guide}
}
APA

Irshad, M. A. (2026). Transformer Architecture & KV Cache: Interactive Visual Guide. SeeingML. https://seeingml.com/learn/transformers/