Transformers and Attention, Intuitively

The architecture behind every modern LLM, explained at the level needed to reason about behaviour, cost and limits.

Beginner · about 6 hours · difficulty 3/5

Learn first: Tokens and Context Windows

You do not need to implement a transformer to be an AI engineer, but a working intuition explains why models behave the way they do.

The pipeline in one pass

  1. Tokens become embedding vectors, plus information about their position.
  2. The vectors pass through many stacked transformer layers.
  3. Each layer has self-attention, where every token looks at earlier tokens and decides which ones are relevant to it, and a feed-forward block that transforms each token's representation.
  4. The final layer produces a probability distribution over the next token.
  5. The model picks a token, appends it, and repeats. This is autoregressive generation.

Consequences you will notice

  • Attention cost grows with context length, which is why long prompts are slower and pricier, and why providers invest in caching.
  • The KV cache stores intermediate attention results for tokens already processed, which makes generation fast and is the basis of prompt caching.
  • Models are next-token predictors, so they produce plausible continuations. Without grounding they can confidently produce false statements (hallucinations).
  • Decoder-only models (GPT, Claude, Gemini, Llama families) generate text; encoder models (BERT-style) are often used for embeddings and classification.

Good enough to move on

You can explain in plain words what attention does, why generation happens one token at a time, and why the KV cache matters for latency.

Key concepts

  • Embeddings and positional information
  • Self-attention
  • Autoregressive generation
  • KV cache
  • Decoder-only vs encoder models
  • Mixture-of-experts models
  • Build a tiny GPT from scratch: Great for depth, not required

Mini project

Load a small open model with Hugging Face Transformers, print the top 10 next-token probabilities for a few prompts, and write a short note on what you observe.

Check yourself

Why does doubling the prompt length make a request slower even when the answer stays the same length?

Free resources