AI from scratch

Module 04 · Transformers & LLMs

Attention is how language models look around

Tokens, embeddings, self-attention, the transformer stack, and the training path from next-token prediction to a helpful assistant — without the jargon wall.

From deep nets to language models

Module 3 ended here: a neural net is weights + activations + loss + backprop. An LLM is that same loop on text, with a special layer called attention so every token can look at every other token.

The training objective sounds almost silly: predict the next token. Do that well enough, at scale, and grammar, facts, and reasoning-ish behaviour emerge as side effects — not because anyone wrote rules for them.

Interview one-liner: “A GPT-style model is a deep transformer trained with cross-entropy to predict the next token; fine-tuning and preference tuning reshape its behaviour on top.”

Tokens & embeddings

Models don’t read characters or words directly. A tokenizer chops text into tokens — often subwords (BPE / SentencePiece). Common words may be one token; rare words split into pieces.

Why this matters in production: cost and latency scale with tokens, not characters. Numbers, code, and non-English text often tokenize awkwardly — budget for it.

Self-attention (Q, K, V)

For each token, the model builds three vectors:

Q  query   — “what am I looking for?”
K  key     — “what do I contain?”
V  value   — “what should I pass along if selected?”

The query of token A is dotted with keys of other tokens → scores → softmax → mix of values. High score = “pay attention here.” That’s it: soft, learned lookup across the sequence.

Multi-head attention runs several of these lookups in parallel so different heads can specialise (syntax, coreference, punctuation…).

Causal (masked) attention in GPT-style models: a token may only look at itself and the past — never the future — so next-token training isn’t cheating.

Tiny mental demo: in “The keys to the cabinet … it was locked,” attention helps “it” land on “cabinet.” RNNs struggled to carry that signal across long distances; attention jumps there in one step.

The transformer block

input tokens
  → embeddings (+ positional info)
  → N × [ multi-head attention → feed-forward MLP ]
       (with residual connections + layer norm)
  → linear + softmax over vocab
  → next-token probabilities

Positional encoding / RoPE — without it, attention is a bag of tokens; order would be invisible. Modern LLMs bake position into the attention math.

Encoder vs decoder:

ChatGPT-class models are mostly decoder-only transformers scaled up.

How an LLM is trained

1. Pretraining

Massive text corpora. Loss = cross-entropy on next token. This builds general language competence. Expensive; done by labs, not by most product teams.

2. Supervised fine-tuning (SFT)

Show high-quality (instruction, response) pairs. Same next-token loss, sharper data. Turns a base model into something that follows instructions.

3. Preference tuning (RLHF / DPO)

Humans (or proxies) rank answers; the model is nudged toward preferred ones. RLHF uses a reward model + RL. DPO skips explicit RL with a clever preference loss. Goal: helpful, harmless, honest behaviour — imperfectly.

Product decision framework: prompt / tools / RAG first for changing facts; fine-tune for style, format, or reliable tool-calling patterns. Many systems combine all three.

Decoding: temperature, top-p, context

Always version prompts the way you’d version code. A one-line prompt change can move product metrics more than a model swap.

Interview questions

Also in the interview bank.

Explain self-attention in plain English.

Each token builds a query, key, and value. Queries score against keys to decide how much to read from each value — a soft, learned lookup across the sequence.

What is a token, and why does tokenization matter?

A subword unit the model consumes. It drives cost (context length), multilingual behaviour, and weird edge cases with numbers and code.

Pretraining vs SFT vs RLHF?

Pretrain = next-token on huge corpora. SFT = imitate instruction/response pairs. RLHF/DPO = prefer answers humans like. Different data, different failure modes.

Why causal masking in GPT models?

So a token never sees the future during training — otherwise next-token prediction would cheat and wouldn’t match generation time.

What do temperature and top-p control?

They reshape the next-token distribution. Higher → more diverse/less reliable. Keep low for factual tasks; raise carefully for brainstorming.