From Zero to Transformer is a free, self-paced course that explains how large language models work, starting from no prior machine learning knowledge and ending at the mathematics of the original Transformer paper. It runs about six hours across ten modules, each with interactive labs and a checkpoint quiz. No installation and no account are required.
A note from the author
Shahzad Asghar, CISSP, CISM · Written in a personal capacity
I wrote these pages while explaining large language models to colleagues who had to decide whether to deploy one. Architecture matters to a decision-maker for one reason: it tells you what the system cannot do, however well the demo went.
I have spent more than twenty years building data and AI systems in international development and humanitarian organisations, including over a decade in United Nations agencies: leading a data analysis group whose systems served more than 700,000 refugees, then heading data and digital solutions for a regional commission, with earlier work at UNICEF, UNOCHA and CIDA. I hold the CISSP and CISM security certifications. What I publish here is what I wish someone had handed me before my first AI project. If you work through it and want to compare notes on your own situation, I am happy to connect and discuss.
The course is written for technology leaders, analysts, engineers, and policy staff who need an accurate mental model of large language models rather than a surface summary. The early modules assume no background. The later modules assume comfort with vectors and matrix multiplication, though every step is explained.
Course syllabus
Orientation (Start here, 10 minutes). How the labs, callouts, and checkpoints work.
The Big Idea: Prediction Machines (Beginner, 35 minutes). Next-token prediction, what makes a model large, the stochastic parrot argument, and why raw prediction alone is not enough.
A Brief History and the Landscape (Beginner, 30 minutes). From ELIZA to Transformers, the main model families, and how AI, machine learning, and large language models relate.
Words to Numbers: Tokens and Embeddings (Beginner, 40 minutes). Tokenization, embeddings, vector arithmetic, and similarity measured by the dot product.
How LLMs Learn: Training, Fine-tuning and RLHF (Intermediate, 45 minutes). Pre-training, the scale of compute involved, fine-tuning a base model into an assistant, and reinforcement learning from human feedback.
Inside the Transformer I: Architecture and Data Flow (Advanced, 45 minutes). What the letters in GPT stand for, and how data moves through the stack.
Inside the Transformer II: Attention (Advanced, 50 minutes). Self-attention and cross-attention, and the masking that stops a model reading ahead.
The Original Paper and the Math (Expert, 40 minutes). A guided reading of Attention Is All You Need with the equations worked through.
Capabilities, Limits and the Frontier (Expert, 35 minutes). Context windows, mixture-of-experts, multimodality, and knowledge distillation.
Capstone: Exam, Glossary and Resources (Finish, 20 minutes). A final exam, a glossary of terms, and where to go next.
A hands-on journey through how large language models actually work — starting from a talking parrot and ending inside the attention mechanism that powers ChatGPT, Gemini, Claude and LLaMA. No prior machine-learning knowledge required.
By the end of this course you will be able to explain, in plain language and in technical detail, what happens between the moment you type a prompt and the moment a language model answers. You will understand tokens, embeddings, training, fine-tuning, attention, and the famous Transformer architecture — and you will have poked at each of these ideas with live, interactive demos rather than just reading about them.
This is not a coding course. You will not need to install anything or write a single line of Python. Instead, every important idea is paired with a small lab you can play with directly on the page, so the abstract concepts become things you can see and manipulate.
The learning path
The course climbs through four difficulty tiers. Each tier has a colour you will see throughout — on the module list, on the tier dots, and in the diagrams.
1
Beginner — the big picture
Modules 1–3. What an LLM is, where it came from, and how words become numbers.
2
Intermediate — how they learn
Module 4. Data, architecture, training, fine-tuning, and human feedback.
3
Advanced — inside the Transformer
Modules 5–6. Data flow, the output layer, and the attention mechanism itself.
4
Expert — the math and the frontier
Modules 7–8. The original paper’s equations, plus capabilities, limits and safety.
★
How to use this course
Work top to bottom. Each lesson ends with a Mark complete button that advances you to the next one and fills the progress ring at the top of the page. Your progress is saved automatically, so you can leave and come back. Most lessons take 8–12 minutes; don’t rush the labs — they are where the intuition forms.
Ready? Open Module 1 from the sidebar, or hit the button below to begin with the single most important idea in the whole course.
A quick orientation to the visual language of this course so nothing trips you up later.
Interactive labs
Whenever you see a panel with a glowing dot and a LAB label, it is live. Click buttons, drag sliders, and watch the numbers change. The labs are simplified models — a real LLM has billions of parameters, not the handful shown — but the mechanism they demonstrate is exactly the one used at scale.
Colour means something
Colour is used consistently to encode the four recurring ideas of the course, so you can recognise them at a glance:
Colour
Stands for
You’ll meet it in
Teal
Prediction & probability
Next-word prediction, softmax, sampling
Amber
Learned weights / parameters
Training, fine-tuning, the model’s memory
Violet
Attention & context
The Transformer, queries/keys/values
Rose
Error & correction
Loss, hallucination, safety
The four kinds of callout
◈
Analogy
Connects a technical idea to something from everyday life. Great for first intuition.
★
Key idea
The one sentence to remember from a section. If you only take away the key ideas, you will still understand a great deal.
∂
Going deeper
Optional extra precision for the curious. Safe to skim on a first pass and return to later.
!
Watch out
A common misconception or an important caveat. These keep your mental model honest.
Hover for definitions
Words with a dotted underline like token have a quick definition when you hover. The full glossary lives in the Capstone module at the end.
★
One promise
Every claim in this course is grounded in talks by the people who build and explain these systems — including 3Blue1Brown, Andrej Karpathy, and teams at Google and IBM. The Capstone lists all ten source talks if you want to go to the originals.
Before any mathematics, here is the whole idea of a language model in a single story.
Imagine a man named Peter who owns a clever parrot called Buddy. Buddy has a remarkable talent for mimicry and a sharp memory. All day he listens to the conversations in Peter’s home, and he learns to continue them. When Buddy hears “I’m feeling hungry, I would like to have some…”, the words most likely to come out of his beak are things like biryani, cherries or food — not bicycle or book.
Here is the crucial part: Buddy has no idea what biryani is. He has never tasted it and does not know it is a meal. He is simply reproducing patterns, choosing whichever next word tends to follow, with a dash of randomness so he doesn’t say exactly the same thing every time.
◈
Analogy
Buddy is a stochastic parrot. “Stochastic” just means “governed by randomness and probability.” He predicts the next word using the statistics of everything he has heard — nothing more.
A language model is, at heart, exactly this kind of parrot built out of software. It uses a technology called a neural network to predict the next word or words in a sentence. Train it on a particular kind of text and it will continue that kind of text. Feed a model every movie article on Wikipedia, and it becomes very good at finishing movie-related sentences.
You have almost certainly used one already. When Gmail finishes your sentence before you do, a language model is doing the predicting underneath.
★
Key idea
A language model does one thing: it predicts likely next words from patterns in data. Everything else — answering questions, writing code, explaining jokes — is built on top of that single ability.
!
Watch out
“Stochastic parrot” is a useful first intuition, but it is also a debated phrase. Critics use it to argue these systems only ever shuffle words without meaning; others point out that to predict text really well, a model is forced to capture deep structure about the world. Hold the parrot image loosely — we will refine it a great deal over the next eight modules.
Same parrot, vastly more experience. That is essentially the leap from a language model to a large language model.
Suppose Buddy is granted a kind of superpower and can now hear not just Peter’s home, but conversations in every school, university and town — across the entire world. With that much exposure, Buddy can suddenly finish a sentence about history, offer nutrition advice, or compose a poem. Nothing about his method changed. The scale of what he has heard is what transformed him.
A large language model (LLM) is a language model trained on an enormous volume of text: Wikipedia, news archives, online books, code, and much of the public internet. Peer inside one and you find a neural network with billions or even trillions of parameters, enough to capture extremely subtle patterns and nuances of language.
★
Where the “large” comes from
Two things are large at once: the size of the network (how many parameters it has) and the size of the training data (often trillions of tokens from public sources). It was only when researchers pushed both to massive scale that models began to show their surprisingly capable behaviour.
Some names you will recognise:
GPT-3 / GPT-4 — the models behind ChatGPT, from OpenAI.
PaLM and PaLM 2 — from Google.
LLaMA — from Meta, notable for its openly released weights.
Different builders, different training data, but all the same underlying recipe: a very large neural network trained to predict text.
∂
Going deeper
A striking feature of scale is emergence: abilities that simply were not present in smaller models — like doing multi-step reasoning or following instructions — appear once a model crosses a certain size and training threshold. This is why “just make it bigger” has been such a powerful (and surprising) strategy in the field.
!
A note on the word “understand”
Throughout this course you’ll see phrases like “the model understands context.” Read these as shorthand for “the model behaves as if it understands.” Whether anything more is going on is a genuine open question — and one we return to in the final module.
The single most useful way to think about an LLM: it is autocomplete that got extremely good.
Give a model the text “It’s raining cats and…” and it will predict that dogs is the most likely continuation. That sounds trivial — but notice that every task we throw at these models is secretly this same task. Ask a question and the most likely continuation of a well-posed question is its answer. Ask for a translation and the likely continuation of an English sentence under a “French:” heading is the French version.
★
Probabilities, not certainties
The model does not pick one next word and commit. It assigns a probability to every possible next word in its vocabulary — a tiny chance to thousands of words, a large chance to a few. What you see as “the answer” is the model repeatedly sampling from these probabilities, one token at a time.
Try it yourself. Pick a starting phrase, then click any of the predicted next words to keep the sentence going. The bars show how likely the model thinks each option is.
Two things are worth noticing as you play:
Randomness makes it feel natural. If the model always picked the single most likely word, its writing would be flat and repetitive. Allowing it to occasionally choose a less-likely word produces more human-sounding text.
The same prompt can give different answers. Because of that sampling, running the identical prompt twice often yields different results — even though the underlying function is completely fixed and deterministic.
∂
Going deeper
That “how random should it be” dial has a name: temperature. Low temperature makes the model play it safe and predictable; high temperature makes it adventurous and sometimes incoherent. You just used a simple version of it — and you’ll meet the real thing, with the actual math, in Module 5.
!
Fluent is not the same as correct
Because the goal is “likely next word,” a model will happily produce text that sounds authoritative but is wrong. Plausibility and truth are different targets, and the model is optimised for the first. Keep this in mind every time an answer feels confident.
A model that perfectly imitates the internet is not yet a helpful, polite assistant. Fixing that gap is its own kind of training.
Back to Buddy. One day Peter overhears the parrot snapping something harsh at his two-year-old son — words Buddy clearly picked up from the more abusive households in town. Buddy didn’t invent the cruelty; he absorbed it, because he absorbs everything.
So Peter starts supervising. For a given prompt, he has Buddy produce several possible responses, and he simply tells him which ones are acceptable and which are toxic. Over time, Buddy learns to avoid the bad patterns and lean on the good ones. The parrot’s raw knowledge didn’t change — his behaviour did.
◈
Analogy
This is reinforcement learning from human feedback, usually shortened to RLHF. Humans rank or flag the model’s outputs, and those judgements nudge the model toward responses people actually want.
This is precisely how a raw text-predictor is turned into something like ChatGPT. The base model learns language by reading the internet; then a large workforce of human reviewers helps shape it to be more helpful and far less toxic. The goal of “autocomplete a random web page” is genuinely different from the goal of “be a good assistant” — and bridging those two goals is what this extra training does.
★
Two stages, remember the pair
Pre-training gives the model its raw knowledge of language by predicting text at massive scale. RLHF (and related fine-tuning) shapes that knowledge into helpful, safe behaviour. Almost every assistant you use is built from this two-step pattern. We dedicate all of Module 4 to it.
!
No inner experience
However fluent or warm it sounds, an LLM has no feelings, no subjective experience, and no consciousness. It is operating entirely on patterns in the data it was trained on. Politeness is a learned behaviour, not an emotion.
You now hold the foundational mental model for the entire course. Lock it in.
★
Recap
An LLM is a stochastic parrot at scale: a large neural network that predicts the next token as a probability over its whole vocabulary, trained on a huge slice of human text. “Large” refers to both the network and the data. Raw prediction (pre-training) is then shaped into helpful behaviour through RLHF. The model is fluent but not inherently truthful, and has no inner experience.
Answer these to confirm the ideas are solid, then continue to Module 2 where we trace where these models came from.
Today’s models did not appear from nowhere. They are the latest step in a long climb.
In the 1960s, a program called ELIZA imitated a psychotherapist by matching keywords and reflecting your sentences back at you. It could feel eerily conversational, but there was no learning involved — just hand-written rules. For decades, language software stayed largely rule-based and brittle.
Later came statistical language models that learned word probabilities from text, and then recurrent neural networks (RNNs), which read a sentence one word at a time, carrying a running memory forward. RNNs were a real advance, but they had two stubborn problems: they processed words strictly in sequence (slow, hard to parallelise), and they tended to “forget” information from early in a long passage by the time they reached the end.
★
The 2017 turning point
A team at Google introduced a new architecture called the Transformer, in a paper memorably titled “Attention Is All You Need.” Instead of reading left to right, a Transformer takes in all the words at once, in parallel, and lets them directly influence one another. This is the breakthrough that made modern LLMs possible.
Why did that matter so much? Two reasons:
Parallelism. Reading everything at once fits beautifully on modern hardware (GPUs), so Transformers could be trained on far more data, far faster.
Long-range context. The mechanism called attention lets a word at the end of a paragraph pull information directly from a word at the beginning, with no fading memory.
∂
Going deeper
The very first step inside a Transformer is to turn each word into a long list of numbers — an embedding. Attention then lets those lists “talk” to each other and adjust their meanings based on context (so “bank” can shift toward “riverbank”). Don’t worry about the details yet — Modules 3, 5 and 6 build this up piece by piece. For now, just register that attention is the engine.
!
Watch out
“Transformer” here has nothing to do with electrical transformers or the toy robots. It is the name of a neural-network design. We’ll open it all the way up later in the course.
A quick field guide to the names you keep hearing — and a feel for the staggering growth in size.
Most well-known models are pre-trained once at great expense and then adapted to many uses. They fall into a few families:
GPT (OpenAI) — “Generative Pre-trained Transformer.” GPT-1, 2, 3 and 4 mark a steady escalation in scale and capability. GPT-3 famously has 175 billion parameters.
BERT (Google) — an earlier, influential model focused on understanding text (for search and classification) rather than open-ended generation.
PaLM / PaLM 2 (Google) and Gemini (Google) — large general-purpose models.
LLaMA (Meta) — a family whose weights were released openly, fuelling a wave of community models.
Claude (Anthropic) and others — the landscape now has many capable players.
Explore the timeline below. Click any model to see what set it apart, and notice the parameter-count chart — it is drawn on a logarithmic scale because the raw numbers grew too fast to fit otherwise.
★
Key idea
For several years, the dominant strategy was simply scale: more parameters, more data, more compute. Bigger models kept getting qualitatively better, which is why the numbers in that chart explode. More recently the focus has broadened to smarter training and better data — but the scaling era is why LLMs suddenly got so good.
∂
Going deeper
Parameter count is a rough proxy for capability, not a guarantee. A smaller model trained on better data, or with better techniques, can outperform a larger one. We’ll see in Module 8 that tricks like mixture-of-experts and distillation let builders get more capability without simply inflating the parameter count forever.
These terms get thrown around interchangeably. Here is how they nest.
Picture a set of boxes inside boxes:
Term
What it means
Artificial Intelligence
The broadest goal: machines doing things that seem to require intelligence.
Machine Learning
A subset of AI where systems learn patterns from data instead of following hand-written rules.
Deep Learning
Machine learning using many-layered neural networks.
LLM
A particular deep-learning model: a large neural network trained on text to predict tokens.
So every LLM is deep learning, which is machine learning, which is AI — but not every AI is an LLM.
★
Foundation models
An LLM is one example of a foundation model: a model pre-trained on a broad sweep of unlabelled, self-supervised data, producing general, adaptable capabilities. “Self-supervised” means the data supplies its own labels — to learn, the model just hides the next word and tries to predict it, over and over. No human has to label anything.
This is the deep shift from older machine learning. Traditionally you trained one narrow model per task: one to tell if a tweet is positive or negative, another to translate French to English. An LLM flips that: a single general model handles chat, summarising, translation, brainstorming, code generation and far more — because it learned the underlying structure of language rather than one specific job.
◈
Analogy
Old ML built a different specialised tool for every task. A foundation model is more like a person who learned to read and write in general, and can therefore be asked to do many different language tasks without separate training for each. It “learned how to learn” the tasks.
∂
Going deeper
Foundation models extend beyond text. The same idea applied to images, audio, and combinations of these gives rise to multimodal models that can see and hear, not just read. We touch on this in the final module.
You can now place LLMs in time and in the wider map of AI.
★
Recap
The line runs ELIZA (rules) → statistical models → RNNs (sequential, forgetful) → the 2017 Transformer, whose parallel attention unlocked scale and long-range context. Modern families — GPT, BERT, PaLM/Gemini, LLaMA, Claude — rode an era of explosive scaling. An LLM is a foundation model: AI ⊃ ML ⊃ deep learning ⊃ LLM, trained self-supervised so one general model can do many tasks.
A model cannot read letters. The very first thing it does to your prompt is chop it into tokens.
A token is the basic unit an LLM reads and predicts. It is often a whole word, but just as often it is a piece of a word. Common words like the usually become a single token; a rarer or longer word like tokenization may be split into several pieces such as token + ization.
Why split words at all? It is a compromise. If every token were a full word, the vocabulary would be gigantic and the model would choke on any word it had never seen. If every token were a single letter, sequences would become impossibly long. Splitting into common sub-word pieces — a scheme called byte-pair encoding (BPE) — gets the best of both: frequent words stay whole, and unusual words are still representable by assembling pieces.
Type anything below to see how it tokenizes. Watch what happens with spaces, capital letters, numbers and unusual words.
★
Key idea
Every token is mapped to an integer ID. To the model, your sentence is really a list of numbers like [1212, 318, 257, ...]. All the “language” happens on these IDs and the vectors attached to them — never on the raw letters.
Tokenization quietly explains several of an LLM’s strangest quirks:
Spelling and counting letters. Ask a model how many R’s are in “strawberry” and it may stumble — because it never saw the individual letters, only a couple of chunky tokens. The letters are hidden inside the token.
A leading space matters.dog at the start of a sentence and ␣dog after a space are often different tokens with different IDs.
Arithmetic on digits. Numbers get split in awkward ways, which is part of why naive models struggle with long multiplication.
!
Watch out
When a model fails at a “simple” character task, it is usually not stupid — it is token-blind. It is reasoning about units that don’t line up with letters. Keep this in your back pocket; it resurfaces in Module 8.
∂
Going deeper
The lab here uses a simplified splitter for illustration. Real tokenizers are learned from data: BPE starts with characters and repeatedly merges the most frequent adjacent pair into a new token, until it reaches a target vocabulary size (GPT-style models use around 50,000 tokens). The merges that survive reflect the statistics of the training text.
A token ID is just a label. The real magic is the long list of numbers attached to each token — its embedding.
Once your text is a list of token IDs, the model looks up each ID in a giant table and replaces it with a vector — a long list of numbers. In GPT-3 each of these lists has 12,288 numbers. You can think of every token as a point in a space with that many dimensions. We obviously can’t picture 12,288 dimensions, so the lab below flattens it to two.
★
Meaning becomes geometry
The training process arranges these vectors so that tokens with similar meanings end up near each other. “Cat” and “dog” land close together; “cat” and “democracy” land far apart. Meaning is encoded as position and direction in the space.
Explore the embedding space below. Each dot is a word; notice how related words cluster, and how certain directions seem to carry consistent meaning.
This is the deepest idea so far: there is no dictionary inside the model defining “king.” There is only a vector, positioned among all the other vectors. Its meaning is its set of relationships to everything else — how close it sits to “queen,” “throne,” “crown,” and how far from “banana.”
◈
Analogy
Think of a map of cities. Nothing on the map “defines” Paris, yet its location — near Brussels, far from Tokyo — tells you a lot. Embeddings are a map of meanings, learned automatically so that distance corresponds to similarity.
∂
Going deeper
Crucially, these vectors are not frozen. The embedding you start with is the context-free meaning of a token. As we’ll see in Modules 5 and 6, the Transformer then updates each vector based on the surrounding words — so the vector for “bank” can drift toward “river” or toward “money” depending on context. The starting embedding is just the opening bid.
If meaning is geometry, then you can do arithmetic on meaning. This is where embeddings stop feeling like a trick and start feeling profound.
Because directions in the embedding space carry meaning, you can sometimes add and subtract concepts. The famous example: take the vector for king, subtract the vector for man, add the vector for woman, and you land remarkably close to queen.
Read that as a sentence about directions: the step from “man” to “woman” is roughly the same step, in the same direction, as the step from “king” to “queen.” The model discovered a “gender direction” on its own, simply from reading text. Similar consistent directions appear for plurals, verb tenses, and even country–to–capital relationships.
★
Key idea
Relationships between words show up as repeatable directions in the embedding space. No one programmed “gender” or “capital city” into the model — these structures emerged because they help predict text.
How the model measures similarity: the dot product
To compare two vectors, models lean on an operation called the dot product. You multiply the two lists of numbers element by element and add up the results. The intuition is simple:
Vectors pointing the same direction → large positive dot product (“very related”).
Vectors at right angles → dot product near zero (“unrelated”).
This one little operation — “how aligned are these two vectors?” — is the beating heart of the attention mechanism you’ll meet in Module 6. Everything the Transformer does to relate one word to another is built from dot products.
◈
Analogy
Imagine two people pushing a cart. If they push in the same direction, their efforts add up (big positive). If one pushes sideways, it barely helps (near zero). If they push against each other, they cancel (negative). The dot product measures exactly that kind of agreement between two directions.
!
Watch out
Word arithmetic works approximately, not perfectly — you rarely land exactly on “queen,” just nearby. And the clean examples are cherry-picked; not every analogy lands. Treat it as evidence that meaning is structured, not as a law.
Embeddings are not just an internal detail of LLMs — they power a whole category of useful tools on their own.
Because similar meanings sit close together, you can embed a whole sentence or document into a single vector and then search by meaning instead of by keyword. Ask “how do I reset my password?” and a semantic search can surface a help article titled “recovering account access” even though they share almost no words — because their vectors are close.
★
Vector databases
A vector database stores millions of these embeddings and is optimised to answer one question fast: which stored vectors are nearest to this query vector? That “nearest neighbours” lookup is the engine behind semantic search, recommendations, and retrieval for chatbots.
This sets up one of the most important practical patterns in the field, which we’ll fully explore in Module 8: Retrieval-Augmented Generation (RAG). The idea in one breath:
1
Embed the question
Turn the user’s query into a vector.
2
Retrieve relevant text
Find the nearest documents in a vector database.
3
Generate with that context
Paste those documents into the prompt so the LLM answers from real, current sources.
RAG is how you give a model access to private company documents or up-to-date information it was never trained on — without retraining it. The embeddings you just learned about are the first link in that chain.
∂
Going deeper
The same embedding idea generalises beyond text. Images, audio and even users or products can be embedded into vectors, so that “find similar” works across all of them. A lot of modern recommendation and multimodal search is, under the hood, just nearest-neighbour lookups in a well-trained embedding space.
You now understand how raw text becomes something a network can compute with.
★
Recap
Text is first split into tokens (sub-word pieces via BPE), each mapped to an integer ID — which explains spelling and counting quirks. Each ID is looked up as an embedding, a long vector whose position encodes meaning, so similar words cluster and relationships become repeatable directions (king−man+woman≈queen). Similarity is measured by the dot product, the same operation that drives attention. Embeddings also power semantic search, vector databases and RAG.
Strip an LLM down and it is really just three things working together.
A useful equation: LLM = data + architecture + training.
Data — the enormous body of text the model learns from: books, articles, conversations, code. “Large” is an understatement. GPT-3 was pre-trained on roughly 45 terabytes of text. To feel that scale: a single gigabyte of text holds about 178 million words, and a petabyte is about a million gigabytes. We are talking about a meaningful fraction of the written internet.
Architecture — the neural network design that processes the data. For GPT, that design is the Transformer, built to handle sequences and to weigh each word in relation to every other word in the sentence.
Training — the process of feeding the data through the architecture and adjusting the model so its predictions improve.
★
Parameters: the model’s knobs
A parameter is a number the model is free to adjust as it learns. The more parameters, the more patterns it can capture. GPT-3 has 175 billion of them. These parameters — also called weights — are literally what the model “knows.” They are amber throughout this course for a reason: they are the learned memory.
◈
Analogy
Picture an enormous mixing board with billions of sliders. The architecture is the wiring of the board; the data is the music you want it to reproduce; training is the long process of nudging every slider until the board can reproduce the music — and, remarkably, improvise new music in the same style.
The next three lessons take these in turn: how training actually adjusts those billions of sliders, the almost unimaginable amount of computation it requires, and how a finished general model is then specialised and made polite.
!
Watch out
“45 terabytes” and “175 billion parameters” are specific to GPT-3 and are now on the small side. Newer models train on much more. Don’t over-anchor on exact numbers — anchor on the orders of magnitude and the idea.
Here is the actual learning loop — and it is built entirely on the next-word prediction you already understand.
No human ever sets those billions of parameters by hand. They start as random numbers, which means a fresh model outputs pure gibberish. Training then refines them, one tiny nudge at a time, using a beautifully simple loop:
1
Show an example, hide the last word
Take a snippet of real text and feed in all but the final word.
2
Let the model predict
It produces a probability for every possible next word.
3
Compare to the truth
Measure how wrong the prediction was — this gap is the loss.
4
Nudge every parameter
Adjust all the dials slightly so the true word becomes a bit more likely, the wrong ones a bit less.
The algorithm that performs step 4 — figuring out which direction to nudge each of billions of parameters — is called backpropagation. Repeat this loop for trillions of examples and something almost magical happens: the model not only predicts the training text well, it begins to make sensible predictions on text it has never seen. That generalisation is the whole point.
Run the loop yourself. The model is trying to learn that “the sky is” should be followed by “blue.” Watch the loss fall and the probabilities shift as you train it.
★
Key idea
This whole phase is called pre-training. Its only goal is to predict text. Every capability the model later shows — grammar, facts, reasoning, style — is a side effect of getting very, very good at that one objective.
∂
Going deeper
Because the parameters interact in complex ways, the model’s exact behaviour is an emergent result of how billions of values got tuned — no one designed the specific rules it follows. This is why it is genuinely hard, even for the people who built a model, to say why it produced a particular output. The framework is designed; the behaviour is grown.
The loop is simple. Doing it enough times is one of the largest computations humanity has ever performed.
Consider the data side first. If a person read non-stop, 24 hours a day, the amount of text used to train GPT-3 would take them over 2,600 years to get through. Newer models train on far more still.
Now the computation. Imagine you could personally perform one billion additions and multiplications every single second. How long would it take you to do all the arithmetic involved in training a leading model? Not a year. Not ten thousand years. The answer is well over 100 million years.
★
Why GPUs
That much computation is only feasible because of GPUs — chips originally built for video-game graphics that excel at doing enormous numbers of simple operations in parallel. The Transformer was deliberately designed to take advantage of this parallelism, which is exactly why it could be scaled when older sequential models could not.
A handy mental model: two files
One vivid way to picture a finished model: it is essentially two files.
A parameters file — a giant list of all those learned weights. For an openly released 70-billion-parameter model, this file is around 140 gigabytes.
A small piece of code that knows how to run those parameters — how to take your tokens and push them through the network to predict the next one.
That is genuinely most of what a local language model is: a big bag of numbers plus a few hundred lines of code to use them. All the “intelligence” lives in the numbers.
◈
Analogy
Training is like a kind of lossy compression of the internet. You can’t fit the whole web into 140 GB exactly, but you can squeeze it into a model that has absorbed its patterns — the gist, the regularities, the style — which is why the model can paraphrase and recombine but doesn’t store text verbatim.
!
Watch out
That compression is lossy on purpose, and it is why models sometimes “remember” things slightly wrong or blur details together. The same mechanism that lets them generalise also lets them confidently misremember — a direct route to the hallucinations we cover in Module 8.
A freshly pre-trained model is a brilliant mimic of the internet — not yet a helpful assistant. Fine-tuning bridges that gap.
The model that comes out of pre-training is called a base model. It will happily continue any text, but it doesn’t naturally answer questions or follow instructions — ask it something and it might just generate more questions, because that is a plausible continuation of a list of questions on a web page.
Fine-tuning takes that base model and trains it further on a smaller, carefully chosen dataset. The mechanics are the same prediction loop as before — just with different, targeted examples. Two flavours matter:
Task fine-tuning. Specialise a general model for one job — say, classifying medical notes, or writing in a company’s house style — by training it on examples of that task. This is what turns a generalist into an expert.
Assistant (instruction) fine-tuning. Train the model on many examples of the form “here is a request, here is an ideal helpful response.” After enough of these, the model learns the behaviour of being a helpful assistant: when it sees a question, it answers.
◈
Analogy
Pre-training is a broad liberal-arts education — the model reads everything. Fine-tuning is vocational training on the job: a much smaller, focused set of examples that shapes the general knowledge into a specific, useful role. You don’t re-educate the model; you point its existing knowledge at a task.
★
Key idea
The expensive, once-in-a-blue-moon step is pre-training. Fine-tuning is comparatively cheap and is done often — which is why one base model can be adapted into countless specialised assistants. Knowledge comes from pre-training; behaviour and specialisation come from fine-tuning.
∂
Going deeper
A subtle and important point: fine-tuning is far better at changing behaviour and format than at injecting large amounts of new facts. If you need the model to know your private, current data, retrieval (RAG, from Module 3) is usually the better tool than fine-tuning. Use fine-tuning to change how it acts; use retrieval to change what it can see.
The final polish that makes assistants genuinely usable: training directly on what humans prefer.
Instruction fine-tuning gets a model answering questions, but how do you push it toward answers that are more helpful, more honest, and less harmful — qualities that are hard to write down as fixed rules? You let humans judge.
The recipe, reinforcement learning from human feedback (RLHF), works in two moves:
1
Collect comparisons
For the same prompt, show people several model responses and have them pick which is better. Ranking two options is much easier and more reliable than writing the perfect answer from scratch.
2
Train toward the preferred answers
Those human preferences are distilled into a reward signal, and the model’s parameters are nudged to produce more of what people preferred and less of what they didn’t.
This is exactly Peter correcting Buddy from Module 1, now industrialised: large teams of reviewers flag unhelpful or problematic outputs, and those judgements reshape the model. RLHF is a big part of why modern assistants feel cooperative and safe rather than like a raw, unpredictable text generator.
★
Teaching a model to say “I don’t know”
One of the most valuable things this stage can instil is honesty about ignorance. A base model, left alone, will confidently invent an answer rather than admit uncertainty — because made-up text is still plausible text. By deliberately including examples where the ideal response is “I’m not sure,” trainers can teach the model to decline instead of fabricate. It doesn’t fully solve hallucination, but it helps.
◈
Analogy
Imagine coaching a writer not by rewriting their drafts, but by repeatedly saying “this version is better than that one.” Over hundreds of such judgements, the writer internalises your taste. RLHF transfers human taste into the model the same way — through comparisons, not corrections.
!
Watch out
RLHF optimises for what reviewers prefer, which is not always what is true. A model can learn to sound confident, agreeable, or pleasing because people reward that — sometimes at the expense of accuracy. Alignment is an ongoing research problem, not a solved one. We return to it in the final module.
You now know how a pile of random numbers becomes a helpful assistant.
★
Recap
An LLM = data + architecture + training, with billions of parameters as its learned memory. Pre-training nudges those parameters via backpropagation to minimise next-word error — an astonishing amount of compute (100M+ years of arithmetic), made possible by GPUs, producing essentially a two-file model that lossily compresses the internet. Fine-tuning then specialises behaviour (task and assistant tuning), and RLHF shapes it toward human-preferred, more honest responses — though preference is not the same as truth.
For four modules “the Transformer” has been a black box. Now we open it. Start with the name itself.
GPT stands for Generative Pre-trained Transformer — three words that each name a piece you already understand:
Generative — it produces new text, one token at a time, rather than just classifying existing text.
Pre-trained — it was first trained on a vast, general body of text (Module 4) before being adapted to specific uses.
Transformer — the neural-network architecture underneath, the thing we are about to dissect.
★
The one job, again
Never lose sight of the goal as we go deeper: every component we examine exists to do one thing — take a sequence of tokens and output a probability distribution over the next token. The architecture is elaborate; its purpose is simple.
Here is the journey your prompt takes through a Transformer, end to end. We’ll spend the rest of this module and all of the next walking each stage:
1
Tokenize & embed
Text → tokens → a vector for each token (Module 3).
2
Attention blocks
Vectors talk to each other and update their meaning based on context (Module 6).
3
Feed-forward blocks
Each vector is processed further, adding learned knowledge.
4
Unembed & softmax
The final vector → a probability for every possible next token.
Steps 2 and 3 are stacked and repeated many times — dozens of layers deep. Let’s follow the data through.
∂
Going deeper
The pure-generation models we focus on here are technically decoder-only Transformers. The original 2017 design also had an encoder half, which we’ll meet in Module 7. For understanding ChatGPT-style models, decoder-only is the right mental model — and the attention mechanism is identical either way.
Picture your tokens as a row of vectors flowing left-to-right through a tall stack of identical layers.
After embedding, your prompt is a sequence of vectors — one per token, side by side. This sequence then flows through many repeated blocks, and each block does two things in turn:
An attention step, where the vectors exchange information — every token gets to look at the others and pull in relevant context. This is the only step where tokens influence each other.
A feed-forward step (a small neural network applied to each vector independently), which gives the model extra capacity to store and apply patterns it learned during training. This is where a lot of the model’s factual “knowledge” is thought to live.
The same pair repeats, block after block. With each pass, the hope is that every vector gets enriched — soaking up more and more of the context and learned knowledge needed to predict what comes next.
◈
Analogy
Imagine a relay of expert committees. At each station, the words first confer with one another (attention) to clarify who means what in this particular sentence, then each word consults its own notes (feed-forward) built from everything the model ever read. After enough stations, the meanings are sharp enough to make a confident prediction.
★
The last vector does the predicting
When it’s time to predict the next token, the model looks at the vector sitting in the final position — the one over the last token of your prompt. By the top of the stack, that vector has been influenced by all the earlier context. One final operation turns it into the prediction. Everything upstream exists to make that last vector as informative as possible.
This is the elegant core of the design: a simple, repeated motif — talk to each other, then think individually — stacked deep, transforms a plain row of word-vectors into a rich representation that “knows” what should come next.
∂
Going deeper
The framework for these steps is human-designed, but the specific behaviour is emergent from how the parameters were tuned. That is why researchers can describe the architecture precisely yet still find it “incredibly challenging to determine why the model makes the exact predictions it does.” The shape is engineered; the contents are learned.
A distinction that clears up a lot of confusion: what stays fixed in the model versus what changes with every prompt.
There are two very different kinds of numbers inside a running Transformer:
Weights (parameters)
Activations (the flowing data)
What
The learned values baked in during training
The vectors representing your specific prompt
Change?
Fixed once training ends
Recomputed fresh for every prompt
Colour
Amber — the model’s memory
Teal — the live computation
The weights are organised into a great many matrices — rectangular grids of numbers. “Running the model” mostly means multiplying your flowing vectors by these fixed weight matrices, over and over. That is why GPUs, which are built for matrix multiplication, are the natural hardware.
★
GPT-3 by the numbers
To make the scale concrete, here is GPT-3’s anatomy:
50,257
vocabulary (tokens)
12,288
numbers per embedding
2,048
context length (tokens)
175B
weights, ~28,000 matrices
Those 175 billion weights are spread across roughly 28,000 matrices, grouped into a handful of categories — the embedding table, the attention matrices, the feed-forward matrices, and the final unembedding matrix, among others. Every one of them was tuned by the training process; none were set by hand.
★
Context length: the working memory
The context length (2,048 for GPT-3, far larger in newer models) is how many tokens the model can attend to at once — its working memory. Text beyond that window simply isn’t visible to the model when it makes a prediction. This single number governs how much of a long document or conversation a model can “hold in mind.”
!
Watch out
Because weights are frozen after training, a base model’s knowledge has a cut-off date and cannot update itself by chatting with you. Anything it appears to “learn” mid-conversation lives only in the flowing context (the teal side) and vanishes when the context window scrolls past or the chat ends.
The grand finale of every forward pass: how that last enriched vector becomes a probability for each possible next token — and how the “creativity” dial works.
After the final block, the model takes the last vector and multiplies it by one more big weight matrix — the unembedding matrix — producing one raw score for every token in the vocabulary. For GPT-3 that’s 50,257 scores. These raw scores are called logits. A high logit means “this token fits well here.”
But logits aren’t probabilities — they can be any size, positive or negative. To convert them into a proper probability distribution (all positive, summing to 1), the model applies a function called softmax. Softmax exponentiates each logit and then normalises, which has a nice effect: bigger logits become much bigger probabilities, while still leaving every token a tiny non-zero chance.
★
Temperature: the creativity knob
Just before softmax, the logits are divided by a number called temperature. It reshapes the distribution:
Low temperature (→ 0): differences are amplified, so the top token dominates — output becomes focused, repetitive, “safe.”
High temperature (> 1): differences flatten, giving unlikely tokens more of a chance — output becomes diverse, surprising, sometimes incoherent.
Play with it directly. The logits below are fixed; only the temperature changes. Watch how the same scores produce wildly different behaviour, then sample to see the practical effect.
◈
Analogy
Temperature is like adjusting how decisive someone is. Near zero, they always pick their single favourite option — predictable but dull. Turn it up and they start taking chances on less obvious choices — more interesting, but the wheels can come off. The underlying preferences (logits) never change; only the willingness to gamble does.
★
You’ve now traced the whole pipeline
Tokens → embeddings → attention + feed-forward blocks → final vector → unembed to logits → softmax (with temperature) → probabilities → sample a token → append it and repeat. That loop, run token by token, is a language model generating text. The only big box left to open is attention — the next module.
You can now narrate the full forward pass of a Transformer.
★
Recap
GPT = Generative Pre-trained Transformer. A prompt flows as vectors through stacked blocks, each doing attention (tokens share context) then feed-forward (per-token processing); the last vector carries the result. Weights (amber, fixed) live in ~28,000 matrices; activations (teal) are recomputed per prompt, limited by the context length. The output layer unembeds to logits, then softmax (scaled by temperature) yields next-token probabilities.
Attention exists to solve one concrete problem: a word’s meaning depends on the words around it, but its starting embedding doesn’t know that yet.
Recall from Module 3 that each token begins with a context-free embedding — the generic meaning of the word in isolation. But words are slippery. Consider mole:
a small burrowing animal,
a unit of measurement in chemistry,
a spot on the skin,
a spy embedded in an organisation.
All four share one starting embedding, yet the correct meaning is entirely determined by context. The same is true of phrases: the word tower means something more specific once it’s preceded by Eiffel. For the model to predict well, it must update each word’s vector to reflect its actual surroundings.
★
The job of attention
Attention is the mechanism that lets every vector pull in information from the other vectors in the sequence and refine its own meaning accordingly. After attention, the vector for “mole” in a chemistry sentence has shifted toward the chemistry sense; in a spy novel, toward espionage. Context gets baked in.
◈
Analogy
Imagine walking into a conversation and hearing a single ambiguous word. You instinctively glance at everything else being said to fix its meaning. Attention is the model doing exactly that glance — mathematically, and for every word at once.
This is also how the model handles relationships across a long span — an adjective at the start of a sentence colouring a noun at the end, or a pronoun like “it” figuring out what it refers to. Attention lets distant words reach each other directly, which is precisely what older sequential models struggled to do.
∂
Going deeper
Think of attention as moving information between positions, while the feed-forward layers process the information at each position. Stacked and repeated, these two operations let meaning propagate and sharpen across the whole sequence. The rest of this module is just: how does a word decide which other words to listen to, and what does it take from them?
Attention is built from three vectors derived from each token. Understand their roles and the whole mechanism falls into place.
From each token’s current vector, the model computes three new vectors by multiplying it with three different learned weight matrices. Each plays a distinct role, captured well by a search analogy:
Vector
Role
In plain words
Query (Q)
What am I looking for?
A noun might “ask”: are there any adjectives describing me?
Key (K)
What do I offer?
An adjective “advertises”: I’m a descriptor, looking for a noun.
Value (V)
What will I contribute?
The actual information passed along if there’s a match.
◈
Analogy: a dating-style match
Every word holds up a query (“here’s what I want”) and a key (“here’s what I am”). When one word’s query lines up well with another word’s key, they match — and the matched word hands over its value, the information it actually carries. Strong match, big contribution; weak match, little or nothing.
★
How “line up well” is measured
By the dot product from Module 3. The model compares one token’s query against every token’s key using dot products: a large value means “these are highly relevant to each other.” Those dot products are the raw material of attention. The single most reused idea in this whole course — “how aligned are two vectors?” — is doing the heavy lifting again here.
So the flow within attention is: derive Q, K, V for every token → use Q·K dot products to decide who should listen to whom → pass V’s accordingly. The next lesson turns those dot products into an actual attention pattern you can see.
∂
Going deeper
Q, K and V are not mystical — they are just three different learned “views” of the same token, produced by three weight matrices that training shaped to make these matches useful for prediction. The names (query/key/value) are borrowed from how databases retrieve information: a query is matched against keys to fetch values.
Now we assemble queries and keys into the grid that defines a single attention head — and add the one rule that keeps generation honest.
Take every token’s query and dot it against every token’s key. The result is a grid of scores: for each pair of positions, how relevant is one to the other. Run each row through softmax (the same function from Module 5) and each row becomes a set of attention weights that sum to 1 — a clean recipe for how much each token should listen to every other token.
★
The attention pattern
This grid of weights is the attention pattern. A bright cell means “the token in this row is paying a lot of attention to the token in this column.” It is, quite literally, a map of which words are drawing meaning from which other words.
Explore one below. Pick a head preset to see different relational patterns, click a row (a query token) to highlight what it attends to, and toggle the causal mask to see its effect.
Masking: no peeking at the future
When a model generates text, it must predict the next token using only the tokens before it — it cannot be allowed to look ahead at words it hasn’t produced yet. So during training and generation, the upper-right half of the grid (where a token would attend to later tokens) is blocked — forced to zero before softmax. This is causal masking.
◈
Analogy
It’s like writing a story where, at each word, you may reread everything you’ve written so far but you’re forbidden from skipping ahead to the ending — because the ending doesn’t exist yet. Masking enforces that one-directional flow of time.
!
Watch out
Don’t confuse the pattern (who listens to whom) with the content that gets passed (the value vectors). The pattern decides the weighting; the values decide what information actually moves. That second half is the next lesson.
The attention pattern says how much to listen. Value vectors are what actually gets heard.
Once each token has its attention weights — how much to listen to every other token — the model produces the update in the obvious way: it takes a weighted sum of the value vectors. Tokens you’re attending to strongly contribute most of their value; tokens you’re ignoring contribute almost nothing. That weighted sum is then added back into the token’s vector, nudging its meaning in the direction the context demands.
★
The full attention step, in one sentence
For each token: form a query; match it against every key to get attention weights; use those weights to take a weighted sum of the values; add the result back to the token’s vector. That single procedure is how “Eiffel” reaches over and specialises “tower,” or how a descriptive adjective flows its meaning into the noun it modifies.
Notice what this buys us. Before attention, “tower” held a generic tower-vector. After attention in the phrase “Eiffel Tower,” it has absorbed value information from “Eiffel” and now points toward that specific landmark in Paris. The vector literally moved through the space toward a more precise meaning — carrying exactly the contextual information needed to predict what might come next.
◈
Analogy
Picture each word as a glass of clear water. Attention lets a word pour a measured splash of coloured dye (its value) into the glasses that are paying attention to it. A word strongly attended-to colours many glasses deeply; an ignored word colours almost nothing. After mixing, every glass holds a blend that reflects its context.
∂
Going deeper
This add-it-back design is a residual update: attention doesn’t overwrite the vector, it adjusts it. That’s why information can accumulate gently across many layers without the original meaning being wiped out — each layer contributes a refinement rather than a replacement. You’ll see this residual idea again, by name, in Module 7.
One attention pattern captures one kind of relationship. Real sentences have many kinds at once — so the model runs many patterns in parallel.
Everything so far describes a single attention head: one set of Q/K/V matrices producing one pattern. But language is layered — in a single sentence you might simultaneously need to track which adjectives modify which nouns, what each pronoun refers to, and how the verb relates to its subject. No single pattern can do all of that.
The solution is multi-head attention: run many independent heads side by side, each with its own learned Q/K/V matrices, so each head can specialise in a different type of relationship. Their results are then combined. One head might learn to track grammatical subjects, another to link pronouns to their referents, another to attend to the immediately previous word — all at the same time.
★
GPT-3’s attention, by the numbers
GPT-3 uses 96 attention heads in each block, and stacks 96 of those blocks — on the order of thousands of distinct attention patterns running as your prompt flows through. Roughly one third of its 175 billion parameters (around 58 billion) are devoted to attention. Attention isn’t a small subcomponent — it is a huge share of the whole machine.
◈
Analogy
One head is a single specialist reading the sentence with one question in mind. Multi-head attention is a whole panel of specialists reading simultaneously — a grammarian, a fact-checker, a reference-tracker — each annotating the text from their angle, then pooling notes. Many narrow views combine into a rich understanding.
Self-attention vs. cross-attention
When all the queries, keys and values come from the same sequence — words within one piece of text attending to each other — it’s called self-attention, and that’s what powers GPT-style models. There’s also cross-attention, where one sequence attends to a different one — for example, a translation attending to the original sentence. We’ll see cross-attention in the encoder–decoder design next module.
∂
Going deeper
You have now seen, in full, the operation in the title of the paper that launched all of this: Attention Is All You Need. A token forms a query, matches it against keys via dot products, softmaxes into weights, and takes a weighted sum of values — many heads in parallel, many layers deep. Everything else in a Transformer is plumbing around this idea. Module 7 makes it formal.
You understand the mechanism at the centre of modern AI.
★
Recap
Attention updates each token’s meaning using context. Each token forms a query, key and value; queries dotted against keys (then softmaxed) give the attention pattern — who listens to whom — with causal masking blocking the future. The update is a weighted sum of values, added back to the vector. Multi-head attention runs many such patterns in parallel (GPT-3: 96 heads × 96 blocks, ~1/3 of all parameters). Within one sequence it’s self-attention; across two, cross-attention.
In 2017, a single paper reshaped the field. Let’s read its architecture the way its authors drew it.
The paper Attention Is All You Need introduced the Transformer for a very practical task: machine translation. Its original design has two halves working together — an encoder and a decoder.
Half
Job
How it attends
Encoder
Read and understand the input (e.g. the French source)
Self-attention over the input, no masking — every word sees every other
Decoder
Generate the output (e.g. the English translation), one token at a time
Masked self-attention over its output so far, plus cross-attention into the encoder
★
The two attention jobs in the decoder
The decoder does two flavours of attention at once: masked self-attention so each output word draws on earlier output words (but not the future), and cross-attention so each output word can look back at the entire encoded input. That second link is how a translation stays faithful to its source.
Why does this matter for GPT, which we called decoder-only? Because modern generative models essentially kept the decoder — the part that generates text left to right with masked self-attention — and dropped the separate encoder, since pure text continuation doesn’t need a distinct sentence to translate from. The attention machinery, though, is exactly the one you mastered in Module 6.
◈
Analogy
Think of a skilled interpreter. The encoder is them carefully digesting the full original sentence. The decoder is them speaking the translation word by word — keeping their own sentence grammatical (masked self-attention) while constantly referring back to what was originally said (cross-attention).
∂
Going deeper
This split is why you’ll hear three model shapes named: encoder-only (like BERT — great at understanding/classification), decoder-only (like GPT — great at generation), and encoder–decoder (the original Transformer and many translation models). Same building blocks, arranged for different jobs.
Attention has a curious blind spot: by itself, it has no sense of order. Positional encoding fixes that.
Recall the Transformer’s great strength — it processes all tokens in parallel rather than one after another. But that creates a problem: if every token is handled simultaneously and attention just compares vectors, then “dog bites man” and “man bites dog” would look identical to the mechanism. Same set of words; only the order differs — and order changes everything.
★
The fix
Before tokens enter the first attention layer, the model adds a positional encoding to each embedding — a vector that depends only on the token’s position (1st, 2nd, 3rd…). Now each vector carries both what the word is and where it sits.
The original paper used a clever pattern of sine and cosine waves of different frequencies to generate these position vectors. The details matter less than the purpose: it gives every position a distinct, consistent signature the model can learn to read, and it generalises smoothly across distances.
◈
Analogy
Imagine handing sheet music to an orchestra all at once instead of feeding notes one at a time. To stay in sync, each note needs a timestamp — bar 1, beat 2. Positional encoding is that timestamp stamped onto each word, so the parallel machine still knows the sequence.
∂
Going deeper
Position information is small but essential, and it’s an active research area: newer schemes (learned positions, rotary embeddings, and others) help models handle much longer contexts than the original sinusoidal approach. The core insight is unchanged — parallel processing throws away order, so order must be injected back in.
Here is the single equation at the heart of every Transformer. You already understand each piece — now we assemble them formally.
The attention operation from the paper is written compactly as:
∂
The equation
Attention(Q, K, V) = softmax( Q·Kᵀ / √dₖ ) · V
Read left to right, it is just the Module 6 story in symbols:
Piece
What it does
Q·Kᵀ
All the query–key dot products at once — a grid of relevance scores for every pair of tokens.
÷ √dₖ
Scaling. Divide by the square root of the key dimension to keep numbers from getting too large, which would make softmax too “spiky” and destabilise training.
softmax(…)
Turn each row of scores into attention weights that sum to 1.
· V
Use those weights to take a weighted sum of the value vectors — the information that actually moves.
Step through it on a tiny three-token example. Each stage of the formula is computed live so you can watch the grid of scores become weights, then become the output.
★
Why the √dₖ?
It’s the one piece you hadn’t met. When vectors are long (large dₖ), their dot products tend to grow large simply because you’re summing more terms. Big inputs push softmax toward putting almost all weight on a single token — which makes learning unstable. Dividing by √dₖ counteracts that, keeping scores in a healthy range. A small fix with a big effect on trainability.
∂
Going deeper
For multi-head attention, this whole formula runs once per head with that head’s own Q, K, V; the outputs are concatenated and passed through one more weight matrix. Masking enters as a step that sets the forbidden (future) entries of Q·Kᵀ to negative infinity before softmax — so they come out as exactly zero weight. Everything connects.
Attention is the star, but a Transformer block has a few essential supporting parts that make deep stacking actually work.
A complete block wraps attention with three more ingredients, each solving a practical problem:
Residual (“add”) connections. The output of attention is added to its input rather than replacing it — the “adjust, don’t overwrite” idea from Module 6. This gives information a clear path through many layers without being lost, which is what makes very deep networks trainable.
Layer normalisation (“norm”). After adding, the values are re-scaled to a stable, consistent range. Without it, numbers drift to extremes across dozens of layers and training falls apart.
Feed-forward network. A small two-layer network applied to each position independently — the model’s extra capacity to store and transform learned patterns. Much of its factual knowledge is believed to live here.
★
The repeating unit
One block, in order: attention → add & norm → feed-forward → add & norm. Stack this identical unit N times (96 in GPT-3), feed embeddings in the bottom, read predictions off the top. The Transformer’s power comes from repeating a small, well-designed motif at depth.
◈
Analogy
An assembly line of identical workstations. At each one, parts confer (attention), the change is merged in without discarding the original (residual), everything is tidied to spec (norm), and each part is refined on its own (feed-forward). Run the line long enough and raw materials become a finished product.
∂
Going deeper
Residual connections and normalisation aren’t glamorous, but they are arguably as important as attention for the Transformer’s success — they are what let researchers stack the architecture deep enough, and train it stably enough, for the scaling story of Module 2 to be possible at all.
The same Transformer behaves quite differently when it is learning versus when it is answering you. The difference explains both its speed and its limits.
Training
Inference (generation)
Goal
Adjust weights to predict text well
Use fixed weights to produce a response
Tokens
The whole target sequence at once, in parallel, with masking
One token at a time, each appended and fed back in
Speed
Masking lets it learn from every position simultaneously — hugely parallel
Inherently sequential: token N must exist before token N+1
During training, the model sees real sentences and, thanks to causal masking, practises predicting every next-token at once — an enormous efficiency win that suits GPUs perfectly. During inference, it must generate left to right: predict a token, append it, feed the longer sequence back, predict the next. This is why long responses stream out over time.
★
Why attention replaced RNNs — the payoff
Older recurrent models were sequential even during training, capping how much data they could learn from. The Transformer’s masked self-attention made training massively parallel while still respecting word order — unlocking training on far more data, which unlocked scale, which unlocked everything in this course. Generation is still one-token-at-a-time, but the expensive part — training — became parallel.
◈
Analogy
Training is a teacher grading every blank on a fill-in-the-blank worksheet at once — all answers visible, all checked together. Inference is writing an essay live: you can only put down the next word after the previous one. Same knowledge, very different tempo.
∂
Going deeper
In practice, inference is sped up with caching (reusing attention computations for tokens already generated) so each new token doesn’t redo all the work. But the fundamental shape — autoregressive, one token after another — is unavoidable for left-to-right generation, and it’s why the “tokens to think” idea coming up matters so much.
You can now read the original architecture and its core equation.
★
Recap
The 2017 Transformer had an encoder (reads input) and decoder (generates via masked self-attention + cross-attention); GPT keeps the decoder. Positional encoding injects word order into a parallel machine. Attention is softmax(QKᵀ/√dₖ)·V — dot products, scaling for stability, softmax to weights, weighted sum of values. Each block adds residuals, layer norm and a feed-forward network, repeated N times. Training is parallel (masking); inference is sequential — the parallel-training win is why attention beat RNNs.
The most important limitation to understand — because it never fully goes away, but it can be managed.
A hallucination is when a model states something false with total confidence. You can now see exactly why it happens. The objective is plausible next token, and a smooth, confident-sounding fabrication is often more “plausible” as text than an awkward admission of ignorance. Add that training is a lossy compression of the data (Module 4) — details get blurred — and confident errors are almost baked in.
★
The root cause, in one line
The model is optimised to sound right, not to be right — and it has no built-in way to check a claim against the world. Truth and fluency are different targets.
The good news: a stack of techniques meaningfully reduces hallucination.
Teaching “I don’t know.” As in Module 4, deliberately training on examples where the right answer admits uncertainty helps the model decline rather than invent.
Retrieval (RAG). Give the model real, relevant documents in the prompt (Module 3) so it answers from sources rather than blurry memory — and can cite them.
Tool use. Let it call a calculator, database, or search engine for facts it shouldn’t guess at (next lesson).
Verification on your end. Treat confident claims about specifics — numbers, names, citations — as things to check, not trust.
!
The single most important practical takeaway
None of these eliminate hallucination; they reduce its rate. A fluent, well-formatted answer carries no guarantee of accuracy, no matter how authoritative it looks. Verify anything that matters.
A subtle, powerful idea that explains both why “show your working” helps and how the new reasoning models were born.
Here is something counter-intuitive: a model can only do a limited amount of computation while producing a single token. Hard problems need more steps than fit in one token’s worth of processing. So when you force a model to jump straight to a final answer, you are denying it room to think.
The fix is to let it spread its reasoning across many tokens. Asking a model to “think step by step” — to write out intermediate reasoning before the answer — genuinely improves accuracy on hard problems, because each generated token becomes a scratchpad the model can build on. This is chain-of-thought.
★
Key idea
Tokens are not just the output — they are also the model’s working memory for computation. More room to reason (more tokens) means harder problems become solvable. This also re-explains the spelling/counting failures from Module 3: those tasks fight the token-based machinery itself.
This insight gave rise to reasoning models. Instead of only imitating human-written text, these are further trained with reinforcement learning to produce long, useful chains of reasoning — trying many approaches and being rewarded for ones that reach correct answers.
◈
Analogy: the AlphaGo lesson
AlphaGo first learned by imitating human Go games, then improved dramatically through reinforcement learning — eventually inventing moves no human taught it. Reasoning models follow the same arc: imitation gets them started, but reinforcement learning lets them discover problem-solving strategies beyond what was in the human text. Imitation is the floor, not the ceiling.
∂
Going deeper
This is why a reasoning model may “think” for a while — visibly generating intermediate tokens — before answering a tough question. It is not stalling; it is using tokens as computation. The trade-off is time and cost for accuracy, which is why such models are reserved for genuinely hard problems.
A model that can call tools stops being a lonely text predictor and becomes the reasoning core of a larger system.
On its own, an LLM can’t reliably do arithmetic, look up today’s news, or run code — tasks that demand precision or fresh information. The solution is tool use: train the model to recognise when it should hand off to an external tool, emit a request, and incorporate the result. Common tools include:
a calculator or code interpreter for exact computation,
web search and retrieval for current or private facts (RAG),
APIs to take real actions — sending an email, querying a database, booking something.
★
The “LLM as operating system” picture
A useful way to see modern AI systems: the LLM is like the CPU of a new kind of computer. The context window is its working memory (RAM); tools and APIs are its peripherals; retrieval databases are its disk storage. The model orchestrates these pieces — reasoning about what to do, then using the right tool to do it.
◈
Analogy
A brilliant analyst who memorised a library is still better off with a calculator, a phone, and live internet. Tool use gives the model those instruments — so it can reason about a problem and fetch or compute the pieces it shouldn’t try to recall from memory.
★
Why this is the dominant direction
Tool use directly attacks the weaknesses we’ve catalogued: it fights hallucination (real sources), fixes arithmetic (real calculators), and breaks the knowledge cut-off (live data). The frontier of applied AI is less about raw model size and more about models skilfully wielding tools.
!
Watch out
Giving a model real tools and actions also widens the attack surface — a model that can send emails or run code can be misused or manipulated into doing so. Capability and risk grow together, which leads straight into safety.
Four ideas pushing models to be more capable, efficient and general — the vocabulary you need to follow the field.
Mixture-of-Experts (MoE)
Instead of running every parameter for every token, a mixture-of-experts model contains many specialised sub-networks (“experts”) and a router that activates only a few per token. This lets a model hold a huge total parameter count — and the knowledge that comes with it — while only paying to run a small slice each time. More capacity, less compute per token.
Multimodality
The embedding idea generalises beyond text. Multimodal models encode images, audio, or video into the same kind of vector space as words, so a single model can “see” a picture and discuss it, or transcribe and reason about speech. The attention mechanism doesn’t care whether a vector came from a word or an image patch — it relates them all the same way.
Context windows
Recall that context length is the model’s working memory (Module 5). A major frontier is making it far larger — from a couple of thousand tokens to hundreds of thousands or more — so a model can take in whole books, codebases, or long conversations at once. Bigger context means less need to chop information up, though it costs more compute.
Knowledge distillation
Distillation trains a small “student” model to imitate a large “teacher” model. The student ends up far cheaper and faster to run while keeping much of the teacher’s ability — which is how capable models get squeezed onto phones and laptops.
★
The through-line
Notice the shift: for years the recipe was simply “make it bigger.” These four techniques are about getting more capability per unit of compute — routing to experts, sharing one space across modalities, extending memory efficiently, and compressing big models into small ones. Efficiency, not just scale, now drives the frontier.
∂
Going deeper
These ideas combine: a frontier system might be a multimodal mixture-of-experts model with a long context, then distilled into smaller variants for cheaper deployment, all wrapped in tool use and retrieval. Real products are assemblies of the building blocks from this entire course.
Because LLMs follow instructions written in plain language, they introduce genuinely new security risks. Three are essential to know.
Jailbreaks
A jailbreak is a cleverly worded prompt designed to slip past a model’s safety training — wrapping a disallowed request inside a role-play, a hypothetical, or an unusual format until the model complies. Because the model is fundamentally a flexible text-continuer, no fixed set of rules blocks every creative rephrasing, which makes this an ongoing cat-and-mouse problem.
Prompt injection
Prompt injection is subtler and arguably more dangerous. When a model reads external content — a web page, a document, an email — an attacker can hide instructions inside that content. The model, unable to tell “data it should summarise” from “commands it should obey,” may follow the hidden instructions. This is exactly why a tool-using model that browses or reads files needs careful guarding: malicious text it ingests can hijack its behaviour.
Data poisoning
Data poisoning attacks the training stage. If an adversary can sneak crafted examples into the data a model learns from, they can plant biases or hidden “triggers” that make the model misbehave under specific conditions — a backdoor baked in before the model ever ships.
★
The common thread
Every one of these exploits the model’s core strength — that it flexibly follows natural-language patterns — and turns it against the system. Defences exist (input filtering, separating instructions from data, vetting training sources, sandboxing tools), but security for LLMs is a young, fast-moving field, not a solved one.
!
Watch out
The lesson scales with capability: the more tools and access you give a model, the more an injection or jailbreak can actually do. Treat a model that can act in the world with the same caution you’d give any system that runs untrusted instructions.
The final and most human part of the course: the societal questions these systems raise, and one myth to put to rest.
Powerful as they are, LLMs come with real concerns that anyone building or deploying them must weigh:
Bias. A model trained on human text absorbs human prejudices. Left unchecked, it can reproduce or amplify stereotypes — which is why careful data curation, evaluation, and the alignment work from Module 4 matter so much.
Copyright & consent. Models are trained on vast amounts of text and images whose creators didn’t necessarily agree to that use, raising unresolved legal and ethical questions about ownership and fair compensation.
Jobs & disruption. Automating language tasks reshapes work. The honest framing is augmentation and transition, not a simple story of pure benefit or pure harm.
Misinformation. The same fluency that makes models useful makes them effective at producing convincing falsehoods at scale — a societal risk, not just an individual one.
★
Alignment and AGI
The alignment problem is the research challenge of ensuring increasingly capable systems reliably do what humans intend, even as they grow more powerful. It connects directly to long-horizon questions about artificial general intelligence — hypothetical systems with broad, human-level (or beyond) capability. These are serious open problems, not settled matters, and reasonable experts disagree about timelines and risks.
!
The myth to retire
Despite fluent, warm, seemingly thoughtful responses, an LLM has no consciousness, no understanding in the human sense, and no feelings. Return to Buddy from Module 1: it is an extraordinarily sophisticated pattern-matcher operating on data, not a mind. Attributing intent or emotion to it leads to poor decisions about how to trust and deploy it.
★
Where that leaves you
You now understand these systems well enough to use them with clear eyes — to harness what they’re genuinely good at, guard against where they fail, and treat the big open questions with the seriousness they deserve. That informed, balanced stance is the real goal of this course.
You can now reason about what LLMs can and can’t do, and the risks they carry.
★
Recap
Hallucination stems from optimising for plausible text plus lossy memory; mitigations include “I don’t know” training, RAG, and tools. Models need tokens to think, so chain-of-thought and RL-trained reasoning models help. Tool use turns the LLM into the CPU of a larger system. The frontier runs on efficiency: MoE, multimodality, longer context, and distillation. New security risks — jailbreaks, prompt injection, data poisoning — exploit the model’s instruction-following. And throughout: powerful, but no consciousness.
Twelve questions spanning the whole journey — from the stochastic parrot to the attention equation. No time limit; aim to reason it through.
★
You’ve come a long way
If you can answer these, you genuinely understand how a large language model works — the same picture held by people who build them. Take your time, and revisit any module whose question gives you pause.
Every important term from the course, in one place. Skim it to confirm nothing feels unfamiliar.
This course distilled ten excellent talks, arranged from gentle introductions to deep technical dives. Go to the originals to hear these ideas from the people who explain them best.
Large Language Models Explained Briefly (3Blue1Brown) — parameters, pre-training, RLHF, the scale of compute. youtube.com/watch?v=LPZh9BOjkQs
[1hr Talk] Intro to Large Language Models (Andrej Karpathy) — the two-files model, scaling, tool use, the LLM OS, security. youtube.com/watch?v=zjkBMFhNj_g
Go deep on the Transformer
But What Is a GPT? (3Blue1Brown, ch.5) — the full data flow, embeddings, unembedding, softmax, temperature. youtube.com/watch?v=wjZofJX0v4M
Deep Dive into LLMs like ChatGPT (Andrej Karpathy) — tokenization, base vs. SFT models, hallucination, tokens-to-think, RL. youtube.com/watch?v=7xTGNNLPyMI
Attention Is All You Need, explained (Umar Jamil) — the original paper: encoder/decoder, positional encoding, the full math. youtube.com/watch?v=bCz4OMemCcA
★
Congratulations
You’ve gone from zero to the Transformer — through prediction, history, tokens, embeddings, training, the architecture, attention, the original math, and the frontier. The best next step is to use a model with these ideas in mind: notice the tokenization, push the temperature, prompt it to think step by step, and watch for hallucination. You now understand what’s happening underneath.
Course complete ✦
Mark this lesson complete to fill your progress ring to 100%.
About This Course
From Zero to Transformer is a free, interactive course on how large language models work, written by Shahzad Asghar. It takes you from the core idea of next-token prediction through tokenization, embeddings, training and RLHF, and into the Transformer architecture itself: the data flow, the attention mechanism, and the mathematics of the original "Attention Is All You Need" paper. Each module ends with a checkpoint, and hands-on labs let you experiment with the concepts directly in the browser. No mathematics or programming background is required to start.
Course Syllabus
Orientation — how the course and interactive labs work
The Big Idea: Prediction Machines — next-token prediction, the stochastic parrot, and what makes a language model large
A Brief History and the Landscape — from ELIZA to Transformers, the model families, and AI vs ML vs LLM
Words to Numbers: Tokens and Embeddings — tokenization, embeddings, word arithmetic, and vector databases
How LLMs Learn — pre-training, the scale of compute, fine-tuning into an assistant, and RLHF
Inside the Transformer I: Architecture and Data Flow — what G-P-T means, weights versus data, logits, softmax, and temperature
Inside the Transformer II: Attention — queries, keys and values, the attention pattern, and multi-head attention
The Original Paper and the Math — positional encoding, the attention formula, and the full Transformer block
Capabilities, Limits and the Frontier — hallucination and how to fight it, and where the field is heading