How ChatGPT Works: The Definitive Plain-English Guide to Large Language Models
How ChatGPT Works: The Definitive Plain-English Guide to Large Language Models
A comprehensive, jargon-free guide that takes anyone — from curious beginners to working professionals — inside the machinery of ChatGPT and modern AI language models. Starting from first principles and building to the full picture, this course explains not just what these systems do, but why they work the way they do, and what that means for how you use them. No math degree required.
Sign up free to unlock:
- Resume-where-you-stopped listening
- Request & vote on new courses
- Save courses for later listening
- Get personalized recommendations
Already have an account? Log in
Chapters
Click play to listen, or tap a chapter to read its transcript.
1Introduction
A lawyer in Chicago filed a brief citing six court cases. The names sounded right. The docket numbers looked real. The courts existed. Not one of the cases did. ChatGPT had invented all six — confidently, fluently, in the exact format a legal citation is supposed to take — and a practicing attorney submitted them to a federal judge without checking. That story traveled around the world in 2023, and for most people it landed as a warning about a glitchy, unreliable technology. But here's what's strange: once you understand how ChatGPT actually works, that story stops being surprising. It becomes almost inevitable. Which raises a question worth spending a few hours on — if a system can write like a lawyer, argue like a philosopher, and pass the bar exam without ever studying for it, what exactly is it doing?
That question is what this course is built to answer. Not 'what can ChatGPT do' — you already know that, roughly — but why it works at all, why it fails the way it does, and why both of those things make complete sense once you see the single, surprisingly simple idea at the engine's core. That idea is not what most people assume. ChatGPT is not a search engine. It is not a database that learned to speak. It is a pattern-completion machine trained to predict what text should come next… and almost everything remarkable about it, and everything maddening, falls out of that one fact.
There are moments in this course that will probably stop you mid-commute. There's a section on what researchers call emergent capabilities — the strange finding that GPT-4 scored in the ninety-fifth percentile on the Uniform Bar Examination without anyone programming it to know anything about contract law. Nobody taught it legal reasoning. It got there the same way it gets everywhere: by processing an almost incomprehensible quantity of human text. Later, you'll spend time inside the transformer architecture — the design that cracked open modern AI — and the entry point is a sentence as ordinary as 'the animal didn't cross the street because it was too tired.' Getting a computer to figure out what 'it' refers to was, for decades, one of the hardest open problems in the field. The solution, when it finally arrived, was elegant enough to feel obvious in hindsight. And there's a section on hallucinations — on why that Chicago lawyer's brief happened — that goes far deeper than the usual warning label, because once you understand what the model is actually doing when it generates text, the fabricated citations aren't a bug you can patch. They're a window into the architecture itself.
By the time this course is done, you won't just know what ChatGPT is — you'll understand it well enough to predict, in broad strokes, when to trust it, when to check it, and exactly why it does what it does.
2The Magic and the Machine: What ChatGPT Actually Is
Picture the first time someone typed a question into ChatGPT and got back an answer so fluent, so contextually aware, so human-sounding that they sat back and wondered — genuinely wondered — whether the machine actually understood them. That moment happened millions of times in late 2022, and it launched a genuine global conversation about what artificial intelligence had become. But here's the thing: almost everything most people concluded in that moment was wrong.
The intuition most people reach for is one of two things. Either ChatGPT is a very sophisticated search engine — it looks up the answer somewhere, summarizes it, and hands it back — or it's a database of facts, like an encyclopedia that learned to speak in full sentences. Both intuitions are understandable. Both are mistaken. And the gap between those intuitions and what's actually happening is where all the interesting and important stuff lives.
This course is built around a single idea that unlocks almost everything else about how ChatGPT works, why it's remarkable, why it sometimes fails spectacularly, and why both of those things make complete sense. That idea is this: ChatGPT is a next-token prediction system — a machine trained, at enormous scale, to guess what text should come next. The rest of this section lays the groundwork for everything that follows.
Start with what ChatGPT is not doing. When you ask it a question, there is no Google-style index being searched. No database of answers is being queried. No lookup table is being consulted. As IBM's overview of large language models explains, where traditional search engines used algorithms to match keywords, large language models capture deeper context, nuance, and reasoning. That's a meaningful distinction. A search engine is essentially a very well-organized pointer system — it finds documents where the answer might live. A language model does something categorically different: it generates text directly, word by word, based on patterns it absorbed during training. The answer doesn't come from somewhere. It is produced, in the moment, by a system trying to continue a sequence of text in the most plausible way it can.
This is counterintuitive at first. The output looks so polished, so factual in tone, so organized that it feels like it must have been retrieved from a store of correct answers. But that feeling is the first thing to unlearn. ChatGPT is not a lookup system with a natural-language interface. It's a pattern-completion engine that has been trained so thoroughly on so much human text that its completions are often indistinguishable from the output of someone who actually knows things. Often — but not always. And understanding why it sometimes fails requires understanding exactly this: that generation and retrieval are fundamentally different operations.
So what is the actual task? Google's machine learning crash course on language models puts it simply: a language model estimates the probability of a token or sequence of tokens occurring within a longer sequence. Read that sentence twice, because it's doing a lot of work. Given everything that has appeared so far in a conversation, what word — or more precisely, what chunk of text — is most likely to come next? The model produces a probability distribution across a massive vocabulary of possible next tokens, and then a winner is selected. Then the process repeats. Then again. And again, thousands of times, until the response is complete.
That sounds almost comically simple. And in a sense, it is. The core task hasn't changed since far simpler systems were doing primitive versions of it decades ago. What changed — what changed everything — is scale.
Before getting to scale, it's worth being precise about the vocabulary here, because "language model," "chatbot," and "AI assistant" get used interchangeably in ways that blur important distinctions. A language model, at its most basic, is any system that assigns probabilities to sequences of text. That's a broad category. An N-gram model — a simple statistical tool from decades ago that predicted the next word by looking at the two or three words before it — is technically a language model. It's just a very, very bad one. A large language model is a language model that has been trained at a scale that produces qualitatively different behavior: billions of parameters, trained on hundreds of billions or trillions of words. "Large" is not just a description of size; it's a description of a different regime of capability.
A chatbot, meanwhile, is an interface design — a system built to hold a conversation, respond to user inputs, maintain some semblance of context. Chatbots existed long before LLMs, running on rules and decision trees, and they were notoriously brittle. Ask one something slightly outside its programmed scope and it would fall apart immediately. What ChatGPT represents is a large language model that has been adapted — through additional training stages — to function as a conversational AI assistant. The LLM is the engine. The chatbot is the car. The AI assistant is what the driver experiences.
This distinction matters because the capabilities and the limitations both trace back to the engine. Understanding ChatGPT means understanding the LLM underneath it — the pretraining, the architecture, the scale. The conversational wrapper is relatively thin.
Now: scale. This is where the story gets philosophically interesting. The same basic idea — predict the next word — had been around for a long time. What was different about the models that emerged in 2018, 2019, 2020, and beyond was that they were trained at a scale that produced something genuinely surprising: capabilities the researchers didn't explicitly design for. A model trained purely to predict what comes next, given enough data and compute, starts to behave as though it understands grammar, can reason about events, knows facts about the world, can write in the style of different authors, can solve certain math problems, can translate between languages it was never explicitly taught to translate. None of those capabilities were programmed in. They emerged from the sheer act of prediction at scale.
IBM's overview of large language models describes LLMs as capable of understanding and generating natural language and performing a wide range of tasks — summarizing articles, debugging code, drafting legal clauses. What's striking is that a single training objective — next-token prediction — produces all of that breadth. That's not obvious from the outside. Most people assume that a system which can do so many different things must have been designed to do each of them. The truth is more interesting and, once you understand it, more illuminating about both the power and the limits of these systems.
To understand why this works, it helps to think about what the task actually demands. To predict the next word in a sentence with high accuracy, across millions of documents on millions of topics, a system needs to learn a staggering amount about how language works: sentence structure, the relationships between concepts, the conventions of different genres, factual associations between entities, cause and effect, even social dynamics — because all of those things shape what words tend to follow other words in well-formed human text. Predicting the next token is a proxy task. What the model has to learn in order to do it well is, in effect, a compressed model of how the world is described in language. That's a much bigger deal than it sounds.
Three ingredients made this possible, and none of them alone would have been sufficient. The first is massive data — billions of words scraped from the web, drawn from books, pulled from Wikipedia, sourced from code repositories and academic papers. IBM's description of LLM training describes the training data as billions or trillions of words from books, articles, websites, code, and other text sources. That breadth matters enormously. A model trained only on encyclopedia articles would learn a very different kind of language pattern than one trained on fiction, academic papers, casual web forums, and technical documentation all mixed together.
The second ingredient is massive compute — the hardware muscle to run the mathematical operations required to train a neural network with hundreds of billions of parameters across that much data. This is not a minor footnote. Training a frontier language model requires hardware infrastructure that simply didn't exist a decade ago. GPU clusters running for weeks or months, consuming electricity that would power small towns. The economics of this are real and consequential, and they explain why only a handful of organizations in the world can build these systems.
The third ingredient is a clever architecture — specifically, the transformer, introduced in a 2017 paper. Before the transformer, the leading approach to sequence modeling had fundamental limitations that made very large-scale training impractical. The transformer solved those limitations in a way that allowed both much larger scale and much faster training. IBM's overview notes that transformer architectures allow for parallelization, making the process far more efficient than previous methods — and that this quality is what allowed language models to handle unprecedentedly large datasets. The architecture details belong to a later section, but the point for now is that the transformer wasn't just an improvement on what came before. It was a different kind of tool that unlocked the scale necessary for everything that followed.
Which brings up a question that many people have: why 2022? Why not 2012? Why not 2010? If the core idea is next-token prediction, what took so long?
Several things converged. The transformer architecture didn't exist until 2017. Even after it did, the datasets needed to train truly large models had to be assembled, cleaned, and made accessible — a massive ongoing engineering effort. The GPU hardware capable of running training at that scale only reached the necessary capability and cost curves in the late 2010s. And the research community needed time to discover, through iterative experimentation, how to actually make very large models behave well — how to apply additional training after pretraining to make them useful and safe for general audiences, rather than just technically impressive. ChatGPT's launch in November 2022 was a moment when all of those threads had come together. The technology had been building for years. What arrived publicly in 2022 was the moment that synthesis became accessible to anyone with an internet connection.
As IBM's large language model overview summarizes, LLMs are the culmination of decades of progress in natural language processing and machine learning research — and their development is largely responsible for the explosion of AI advancements across the late 2010s and 2020s. That framing is right. What looked like a sudden arrival was actually a long accumulation, and the path from there to here turns out to be essential for understanding what these systems actually are.
Here is the shape of what this course covers. The next section goes back before the transformer — to the earlier attempts at language modeling, the approaches that hit walls, and why the field needed something genuinely new. Then comes tokenization: the surprising and important fact that these models don't read words at all, but chunks of text called tokens, and why that matters more than it initially seems. After that, embeddings — the mathematical trick that allows a neural network to represent meaning as coordinates in a high-dimensional space. Then the transformer architecture itself, the engine at the heart of every modern LLM, explained in terms that build real intuition rather than just naming components. From there, pretraining — what actually happens when a model is trained on hundreds of billions of words, and what ends up stored in those billions of parameters. Then generation — how a trained model actually produces text, token by token, and why the same prompt gives different answers each time. Then fine-tuning and alignment — the additional training stages that turn a raw, unpredictable model into the conversational assistant that users actually interact with. Then scaling — how the same basic approach, repeated at larger and larger scale, produces qualitatively new capabilities, and what the empirical laws of AI progress actually say. Then the context window — the hard limit on what a model can "see" at any moment, and why it shapes every interaction. Then hallucinations — what they are, where they come from mechanistically, and what to do about them. And finally, the harder question: what ChatGPT actually knows, whether any of this constitutes something like reasoning, and what remains genuinely mysterious about systems that surprised even the researchers who built them.
That's a lot of ground. But it all connects. Every piece of it traces back to the central fact introduced here: a pattern-completion engine, trained at enormous scale, predicting what text should come next. The simplicity of that core idea is what makes everything else surprising — and understanding it is what makes the surprises comprehensible rather than just baffling.
The next surprising thing is what had to fail before any of this could work. The history of language modeling before the transformer is a story of clever ideas running into hard walls — and the specific nature of those walls explains exactly what the transformer had to solve.
3Before the Revolution: How Computers Learned to Handle Language
Picture a linguist in 1988, surrounded by filing cabinets. Each drawer holds index cards — thousands of them — cataloging the rules of English grammar. "If a sentence starts with 'the,' the next word must be a noun or adjective." "If you see 'not,' negate the following clause." This was, more or less, how computers first attempted to understand language: by encoding the rules that humans had spent centuries figuring out, one exception-riddled card at a time.
That's where the story of modern AI actually begins — not with neural networks or silicon chips, but with linguists and programmers trying to hand-craft meaning.
Understanding why today's language models work the way they do requires understanding why everything that came before them eventually broke. The history isn't just interesting backstory — it's a map of the problem space, and every failed approach points directly at something the transformer would later solve.
Start with those early rule-based systems, often called classical NLP — natural language processing. The idea was straightforward: if you want a computer to understand English, teach it English grammar. Write down the rules. Cover the edge cases. Build a dictionary. This worked surprisingly well for narrow, carefully defined tasks — parsing simple commands, translating between closely related languages when the domain was constrained, answering questions about a fixed database of facts.
The wall appeared the moment you tried to scale up. English grammar is not a clean set of rules. It is a living accumulation of exceptions, idioms, regional variations, and contextual meanings that shift depending on who's talking, when, and why. "Bank" means something completely different in "river bank" and "savings bank." "Flying planes can be dangerous" is genuinely ambiguous — are the planes flying, or is flying them the dangerous part? Writing rules to handle every case like these quickly becomes an engineering nightmare. For every rule you add, three new exceptions appear. Researchers spent decades on this approach and ended up with systems that were brittle, expensive to maintain, and easy to break with a single unexpected sentence.
So the field shifted toward a different intuition: instead of writing rules, what if you counted?
N-gram models were the result, and they represented a genuine breakthrough in thinking, even if they eventually hit their own wall. The idea is elegant. Take a massive corpus of text — millions of documents, billions of words. Then count how often words appear together in sequences. An N-gram is just an ordered sequence of N words. A bigram is two words together; a trigram is three. As Google's machine learning crash course explains, given a training corpus, you can build a language model by examining all the three-word sequences that appear and learning which words tend to follow which pairs.
Here's the practical power of that: if you've seen "orange is ripe" appear ten thousand times in your training data and "orange is cheerful" appear only twice, you can make a pretty good prediction that after the words "orange is," the word "ripe" is more likely to follow. No rules needed. Just counting. The statistical patterns in text do the heavy lifting.
This is, interestingly, not so different in spirit from what modern language models do — they're also learning from patterns in text. But N-grams learn only the shallowest version of those patterns, and that's precisely where they fall apart.
The fundamental limitation is memory. A 3-gram model sees only two preceding words before making its prediction. A 5-gram model sees four. Even if you push N to ten or twenty, you get diminishing returns fast, because the larger your N, the rarer each specific sequence becomes in the training data. As Google's machine learning crash course notes, when N becomes very large, the model typically has only a single instance of each occurrence — which is essentially useless for prediction. You've traded the sparsity problem for the context problem, and back again.
Consider what a 3-gram model has to work with when you give it this sentence: "The trophy didn't fit in the suitcase because it was too big." What does "it" refer to — the trophy or the suitcase? Any human reading that sentence knows immediately: the trophy. You know because you're tracking the relationship between objects introduced earlier in the sentence and a pronoun that refers back to them. The 3-gram model sees only "because it was" — three words with no memory of what came before. It has no idea what "it" means. It doesn't even have the machinery to care.
This is a deep failure, not a superficial one. Language depends on long-range dependencies — the meaning of a word at position twenty in a sentence can depend critically on a word at position two. Short-context models are structurally incapable of handling this, regardless of how much training data you throw at them.
By the 1980s and 1990s, researchers were convinced that what was needed was a model that could actually process sequences — something that read text the way humans do, one element at a time, carrying forward what it had already seen. The answer, or what seemed like the answer, was the Recurrent Neural Network.
An RNN is a type of neural network designed specifically for sequences. Think of it as a machine with a hidden state — a kind of running memory. At each step, it reads the next word, updates its internal state based on what it just read and what it already remembered, and then produces some output. Then it moves to the next word and repeats. The hidden state is supposed to accumulate the meaning of everything processed so far — a compressed summary of the text up to that point.
Google's machine learning crash course puts it this way: recurrent neural networks provide more context than N-grams, training on a sequence of tokens and maintaining a form of running state across the sequence. And this was true. RNNs were a genuine leap forward. For short sentences and simple tasks, they worked remarkably well compared to N-gram models. They could, in principle, remember something from twenty words ago — not just two.
But "in principle" is doing a lot of work in that sentence.
Here's where it gets tricky, and bear with this for one more step because it pays off directly when we get to transformers. Training a neural network involves a process called backpropagation — the algorithm that figures out how to adjust the network's millions of parameters to make better predictions. During backpropagation, the network passes error signals backward through every layer and every time step. In an RNN processing a long sequence, that means passing the signal backward through dozens or hundreds of steps.
Each step in that backward pass involves multiplying by certain numbers — the weights in the network. If those weights are slightly less than one, each multiplication makes the signal a tiny bit smaller. After fifty or a hundred such multiplications, the signal has essentially vanished. This is called the vanishing gradient problem, and it means the network's ability to learn from distant context collapses completely. The word at position one of a long sentence has almost no influence on the model's learning signal by the time it's been processed through a sequence of length fifty.
The opposite can also happen — if the weights are slightly greater than one, gradients can explode, growing catastrophically large through repeated multiplication. Exploding gradients are easier to patch with engineering tricks, but the vanishing version is more insidious because the network keeps training, keeps seemingly improving on short-range patterns, all while quietly losing the ability to learn anything from far-away context.
Researchers invented clever workarounds. Long Short-Term Memory networks, LSTMs, added special mechanisms called gates that could selectively remember or forget information — essentially trying to build a more sophisticated memory system within the RNN framework. Gated Recurrent Units, GRUs, took a similar approach with a simpler architecture. These innovations helped substantially, and LSTMs in particular became the dominant approach through much of the 2010s. Machine translation, speech recognition, text generation — all of these improved significantly with LSTMs.
But the underlying tension never fully resolved. Even with gating mechanisms, very long sequences remained difficult. And RNNs carried another structural burden that would matter enormously once compute became the limiting factor: they're fundamentally sequential. To process word fifty, you must first process words one through forty-nine, in order. You can't parallelize that. When the AI field started acquiring GPU clusters capable of massive parallel computation, RNNs couldn't fully exploit them — each word had to wait for the previous word to be processed before the network could move forward.
This meant that training on enormous datasets — the kind of scale that would eventually unlock the capabilities described in the first section of this course — was painfully slow with RNNs. The architecture was bottlenecked by its own sequential nature.
Something had to break. And in 2017, it did.
A team of researchers at Google published a paper with a title that, in hindsight, reads like a declaration of war on everything that came before: "Attention Is All You Need." The paper introduced the transformer architecture, and it was not an incremental improvement on RNNs. It was a fundamental reconceptualization of how to process sequential information.
The key insight — which will be explored in full detail in the section on the transformer architecture — is that you don't need to process text sequentially at all. Instead, every position in a sequence can directly attend to every other position, simultaneously. Want to know what "it" refers to in "The trophy didn't fit in the suitcase because it was too big"? The transformer doesn't have to thread a signal through fifty sequential steps to find out. It can look directly at "trophy" and "suitcase" from the position of "it," right now, in a single parallel operation. Distance in the sequence becomes irrelevant to the ability to establish a relationship.
This solved both of the core problems at once. The vanishing gradient problem disappears because you're not chaining information through long sequential paths — you're establishing direct connections. And the sequential bottleneck disappears because all those attention operations can be computed in parallel on modern hardware. Suddenly, training on the massive datasets that would eventually produce GPT-3 and then ChatGPT became computationally tractable.
Worth knowing: "Attention Is All You Need" wasn't the first paper to use attention mechanisms — earlier RNN architectures had incorporated attention as an add-on, a way to let the network look back at earlier hidden states. What the 2017 paper did was make attention the entire architecture, discarding the recurrent structure entirely. The name "transformer" refers to this attention-only architecture, which has since become the foundation of virtually every major language model in the world.
Why does this history matter, practically? Because each failure mode of the older approaches maps directly onto something transformers do differently. N-grams had no real memory beyond a few words — transformers have, in principle, a context window that spans thousands of tokens. RNNs struggled to learn from distant context due to vanishing gradients — transformers establish direct attention connections regardless of distance. RNNs were inherently sequential — transformers are inherently parallel.
The problems weren't solved by accident. They were solved by understanding precisely where the previous approaches broke and designing around those specific failure points. When you read about transformers' context windows, or about attention scores, or about why training modern models requires thousands of GPUs, you're really reading about the accumulated answers to questions that linguists and computer scientists spent decades asking: how do you give a machine real memory? How do you let it see the whole sentence at once? How do you scale this up?
The "before picture" isn't nostalgia. It's the reason transformers feel so well-designed once you see them clearly — because every piece of the architecture is a solution to a specific, hard-won problem. Understanding what was broken makes what came next genuinely legible.
And what came next starts with something surprisingly small: not words, not sentences, but the strange atomic units that transformers actually read — the subject of the next section.
4Tokens: The Alphabet of AI
Picture someone handing you a book and asking you to read it — but first, you have to decide what the basic units of reading even are. Are they individual letters? Whole words? Syllables? Paragraphs? That decision, which feels almost too obvious to bother with for a human reader, turns out to be one of the most consequential design choices in all of modern AI.
That's the territory of this section — the surprisingly deep world of tokenization, and why it shapes everything from how well ChatGPT handles Spanish versus English to why a model that writes moving sonnets can fail to count the number of R's in the word "strawberry."
Start with the most basic question: why can't a neural network just read text the way you do?
The honest answer is that a neural network doesn't read anything, in any sense you'd recognize. At its core, a neural network is a machine for doing arithmetic — enormous amounts of arithmetic, but arithmetic nonetheless. It multiplies numbers together, adds them up, and passes the results through mathematical functions billions of times. Numbers, it can handle beautifully. The string of characters that makes up a sentence — something like "the quick brown fox" — is meaningless to it directly. Before any of the impressive language understanding can happen, text has to become numbers.
The obvious first instinct is to convert each character — each letter, space, and punctuation mark — to a number, and feed those in one at a time. That works, technically, but it creates a brutal problem. Sequences become enormously long. A single paragraph might be five hundred characters, and the model would have to process all five hundred steps to understand it, with all the information about what a word means scattered across individual letter-level steps. It's like asking someone to appreciate a painting by describing it one pixel at a time.
The opposite instinct — treating each whole word as the basic unit — is more intuitive, but it runs into a different wall. As explained in Sean Trott's Substack explainer on tokenization in large language models, a language model needs a fixed vocabulary — a finite list of units it knows how to handle. Build a word-level vocabulary for English alone, and you're immediately in trouble. English has somewhere north of a million words if you count all inflected forms and technical terminology. "Run," "runs," "running," "ran," and "outrun" are all different words, and a word-level system has to store each one separately — or else any word it hasn't explicitly seen before becomes a complete mystery.
That's the real problem tokens are designed to solve.
Tokens are the answer to a design question that doesn't have an obvious right answer: what is the right grain size for breaking up text? Not so small that meaning gets atomized, not so large that the vocabulary becomes unmanageable. The solution that modern large language models use lands somewhere between characters and words — and the exact landing spot is determined not by human intuition but by an algorithm that learns it from the data.
IBM's overview of how large language models work describes tokens as "smaller units such as words, subwords or characters" and notes that tokenization "standardizes the language so rare and novel words can be handled consistently." That phrase — "handled consistently" — is doing a lot of work. It's the key insight behind the most widely used tokenization method in modern LLMs: Byte Pair Encoding, or BPE.
BPE has a satisfying origin story. The algorithm wasn't invented for machine learning — it was originally a simple data compression technique. The idea is elegant in its simplicity. Start with individual characters as your base vocabulary. Then look through a large corpus of text and find the pair of adjacent units that appears most frequently. Merge that pair into a single new unit. Repeat. As Sean Trott's tokenization explainer describes the process, this is how a tokenizer learns its vocabulary — not from rules written by linguists, but from statistical patterns in actual text.
Stay with this for one more step, because the consequences are worth understanding.
Imagine the algorithm starts with nothing but individual letters. Early on, it notices that "t" and "h" appear next to each other constantly, so it merges them into "th." Then "th" and "e" appear together constantly, producing "the." Common English words get compressed into single tokens almost immediately, because they appear so often in training data. Less common words get broken into pieces that are common — their roots, prefixes, and suffixes. "Tokenize" might become three tokens: "token," "ize," and some representation of the connection between them. "Unforeseeable" might fragment into "un," "fore," "see," "able." Something extremely rare, a technical term seen only a handful of times, might get broken all the way down to its component characters.
This is where the quirks start to show up. The word "ChatGPT" — not a natural English word, and not common in the text written before 2022 — might be split into two tokens: "Chat" and "GPT." The word "tokenize" ends up as three. Neither of these splits follows any obvious logic you'd derive from meaning alone. They follow the logic of frequency — what patterns appeared often enough in the training data to get merged into a single unit.
Sean Trott's explainer gives a clean illustration of what token IDs actually look like in practice. When a sentence like "the quick brown fox jumped over the lazy" is tokenized with BERT's tokenizer, each word maps to a numerical ID — and the word "the," which appears twice, gets the same ID both times. That's the practical upshot: every token has a unique ID number, and those numbers are what actually flow into the model. The model never sees letters. It only ever sees sequences of integers.
This brings up the vocabulary — and the vocabulary deserves a moment of attention. A modern LLM's vocabulary is a fixed list of every token the tokenizer recognizes, typically somewhere between fifty thousand and one hundred thousand entries. That number might sound arbitrary, but it represents a genuine design tradeoff. A larger vocabulary means more distinct units, which means common phrases can be represented efficiently in fewer tokens — but it also means the model needs more parameters just to handle that vocabulary at its edges, and rare tokens at the vocabulary's fringes will have seen almost no training data, making them poorly understood by the model. A smaller vocabulary is more manageable but forces more fragmentation of uncommon words.
GPT-4's tokenizer, called cl100k_base, uses roughly one hundred thousand tokens. The earlier GPT-3 tokenizer used fifty thousand. That doubling isn't incidental — it reflects the expansion in the range of languages, code, and specialized domains the model was trained to handle.
Which leads directly to one of the most underappreciated sources of subtle unfairness baked into these systems: not all languages get the same treatment.
Because BPE learns its vocabulary from training data, the proportion of tokens assigned to any given language reflects how much text in that language appeared during training. English is massively overrepresented in most LLM training corpora. The consequence is that English words — common ones especially — tend to be single tokens or pairs of tokens. The same idea expressed in a language like Thai, which uses a different script, or Swahili, which shares less vocabulary structure with the dominant training languages, often takes far more tokens to represent. As IBM's LLM overview notes, tokenization is meant to handle rare and novel words "consistently" — but consistency here means consistent in English-centric terms. A sentence of equal complexity in English and in a low-resource language will use very different numbers of tokens, which matters for context window limits, for efficiency, and arguably for how well the model actually understands what it's processing.
This is not a theoretical concern. Researchers and practitioners have documented real capability gaps in LLM performance across languages that correlate with how efficiently those languages are tokenized. When a language gets fragmented into many more tokens per word, the model is effectively working with shorter "sentences" that contain more noise and less meaningful chunking. It has to do more work to reconstruct meaning from pieces. It's a structural disadvantage built into the foundation.
Here's where token counting starts to matter practically — not as an academic curiosity, but as something that shapes your actual experience using these systems.
The context window — the amount of text a model can hold in its "working memory" at any one time — is measured in tokens, not words. When people talk about a model having a 128,000-token context window, they mean the model can process 128,000 tokens at once. In English prose, a token is roughly three-quarters of a word on average. A 128,000-token context window is therefore roughly equivalent to a book-length document — a hundred thousand words or so. But that conversion ratio isn't constant. In other languages, the same window in token-space corresponds to significantly less actual content. In code, where there are lots of short tokens representing punctuation and syntax characters, the ratio shifts again.
So when you're wondering why ChatGPT seems to "forget" something from earlier in a long conversation, part of the answer involves tokens: you may have consumed more of the context window than you realized, especially if the conversation contained code snippets, non-English text, or lengthy pastes of documents. Tokens, not words, are the currency of context — and the exchange rate varies.
Now to the strange consequence that most people find genuinely surprising when they first encounter it.
Here is a model that can write a structurally perfect sonnet in the style of John Keats, render elegant Python code, and explain quantum entanglement clearly enough to satisfy a curious ten-year-old. Ask it how many times the letter "r" appears in the word "strawberry," and it might get the answer wrong.
This seems absurd. It is absurd, in a way. But it follows directly from everything in this section.
The model doesn't process "strawberry" as a sequence of individual letters. It processes it as a token — or possibly two tokens, depending on the tokenizer. The internal representation of "strawberry" as a token doesn't encode, in any easily accessible form, information about which characters make it up or how many of each there are. The model has to effectively reconstruct that character-level information from a representation that was never built to carry it. It's a bit like asking someone to count the individual threads in a piece of cloth by looking at a photograph of the cloth — some information was compressed away in the conversion to photo, and it's hard to get back.
Sean Trott's tokenization explainer makes the point that tokenization is "an important concept to understand if you want to understand the nuts and bolts of modern LLMs" — and this particular failure mode is exactly why. It's not a sign that the model is stupid or poorly designed. It's a direct consequence of a perfectly rational engineering choice — representing text as subword chunks rather than character sequences — that has one very specific blind spot, which is tasks requiring character-level reasoning.
The same dynamic explains other quirks. Simple word-reversal tasks, rhyme detection that depends on knowing exactly what sounds end a word, and certain kinds of spelling corrections all require accessing information that the tokenization process has folded away. The model isn't failing to think hard enough — it's operating on representations where the needed information isn't easily available to begin with.
Worth pausing here to be precise about what this means and doesn't mean. These are specific, identifiable limitations that follow from a specific design choice. They are not evidence that the model "doesn't really understand language" in some broader sense — that's a much larger debate, and it's not decided by whether a model can count letters. They are also not bugs being frantically patched. The tokenization design is fundamental; changing it would mean retraining the model from scratch. Some research directions explore character-level or byte-level models that would avoid these issues, but they come with their own costs in terms of sequence length and computational efficiency.
What tokenization gives you — efficient representation of common patterns, graceful handling of rare words through decomposition, a fixed vocabulary that a neural network can work with — is enormously valuable. What it costs is a certain opacity about character-level structure, a language-dependent efficiency bias, and the occasional embarrassing failure to count letters in a fruit.
The vocabulary and the tokenization algorithm are baked into a model at training time and don't change during deployment. Every prompt you type, every response generated, passes through this same tokenization layer first — converting your words into a sequence of integers, and converting the model's output integers back into words for you to read. The model, properly speaking, never reads your message at all. It reads a sequence of numbers that represent fragments of your message.
That transformation — from human-readable text to token IDs to numerical embeddings to actual model computation — is the chain this whole system rides on. Understanding tokenization means understanding the very first link in that chain, and why it was forged the way it was.
What remains is the question of what happens next — once those token IDs exist, how does the model turn each one into something it can actually compute with? The answer involves assigning every token a location in a mathematical space, and the geometry of that space turns out to encode something surprisingly close to meaning.
5The Geometry of Meaning: How AI Represents Words as Numbers
Tokens are, at their core, just numbers. A sequence of integers representing chunks of text — not words the way a human reads them, but abstract symbols a computer can count and sort. And that's already a problem, because numbers can be bigger or smaller than each other, but they can't be near each other in the way that "dog" is near "puppy," or "Paris" is near "France." Handing a neural network the number 4,827 to represent "king" and the number 19,341 to represent "queen" tells the network exactly nothing about how those two concepts relate. The numbers are arbitrary. The relationship is invisible. Something has to bridge that gap — and the solution turns out to be one of the most elegant ideas in all of modern computing.
That bridge is called an embedding, and understanding it is the key to understanding how a language model actually works — not just as a vague metaphor, but at the level of what's actually happening when you type a question and get a coherent answer back.
Here's the one idea that does the most work in this section: meaning can be encoded as a location in space.
Start with something simple. Imagine a single number line, running from zero to one, where zero means "cold" and one means "hot." You could place "ice" near zero, "lukewarm water" near the middle, "boiling" near one, and "fire" just past it. That single coordinate — one number per thing — lets you do something powerful: things that are conceptually similar end up numerically close. The distance between them carries information.
Now add a second dimension. Let's say this axis runs from "food" to "not food." Now "boiling water" lives in a specific location: hot and food-adjacent. "Ice" lives in a different specific location: cold and food-adjacent. "Fire" lives at hot but not food. You've started to build a map of concepts, where position encodes meaning. Every additional dimension you add lets you capture another layer of relationship — animate versus inanimate, concrete versus abstract, common versus rare.
Real word embeddings — the kind used inside ChatGPT and every other large language model — do exactly this, except instead of two or three dimensions, they use hundreds or even thousands. Stephen Wolfram's 2023 essay on what ChatGPT is doing describes this as representing each word by a list of numbers — a vector — where the collection of those numbers captures something about the word's meaning. The specific dimensions don't have neat human labels like "hotness" or "food-ness." They're abstract mathematical directions that emerge from training. But what they collectively produce is remarkable: a high-dimensional space where the geometry encodes semantics. Where to be close is to be related.
Stay with this for one more step, because the numbers themselves are worth making concrete. A modern language model might represent each token as a vector with 768, 1,024, or even 12,288 numbers. That is to say: each word-chunk gets placed at a specific point in a space with thousands of coordinates. "Puppy" and "kitten" end up near each other. "Puppy" and "combustion engine" end up far apart. "France" and "Paris" are close in a particular way — a way that mirrors how "Japan" and "Tokyo" are close. The distances and directions between points encode the structure of human knowledge as it appeared in the training data. This is not metaphor; it's geometry.
The most famous demonstration of this geometry is a piece of arithmetic so surprising that it became something of a rallying cry for early neural network researchers. Take the vector for "king." Subtract the vector for "man." Add the vector for "woman." The result — that specific point in space — lands closest to the vector for "queen." Written out: king minus man plus woman approximately equals queen.
That result is worth sitting with for a moment, because it's strange in a genuinely interesting way. Nobody programmed the rule "king is to queen as man is to woman." Nobody hand-labeled the data with gender relationships or royal hierarchies. The model discovered — entirely from reading text — that "king" and "queen" differ from each other along roughly the same axis that "man" and "woman" differ. It found that conceptual direction by observing how those words appeared in context, across millions of documents. The geometry is learned, not given.
And this is where things get philosophically interesting. The model has never seen a king or a queen. It has never been to France or Japan. It has no sensory experience of the world whatsoever. What it has is text — oceans of human-written text describing human experience — and from that text it has extracted a kind of structural map of how concepts relate to each other. This is what researchers sometimes mean when they say a large language model has a compressed world model inside it: not a simulation of reality, but a geometric representation of how humans talk about reality, which turns out to capture a remarkable amount of real-world structure.
This concept took most people a while to get when it first emerged — and for good reason. The idea that meaning is spatial, that you can do arithmetic on concepts and get sensible answers, runs against almost every intuition about what language is. Words feel like symbols, not coordinates. But the training data makes the geometry real. If "Paris" appears frequently in the same context as "the Eiffel Tower," "French cuisine," "the Seine," and "the capital of France," and if "Tokyo" appears frequently alongside "Japan's capital," "sushi," "the Shinkansen," and "cherry blossoms," then the model — discovering patterns in how those words co-occur — places them in positions that reflect both their individual characters and their structural relationship to the countries they belong to. The geometry is an emergent property of language itself.
It's worth addressing how this geometry actually gets built, because the temptation is to imagine some clever programmer deciding what the dimensions mean. That's not how it works. The embeddings are learned, not designed. During training — which the pretraining section covers in much more depth — the model starts with essentially random numbers for every token's vector. Then it runs through billions of examples, comparing its predictions to the actual text, and gradually adjusts every parameter, including those embedding vectors, to make better predictions. Tokens that appear in similar contexts get pulled toward each other in the space. Tokens that almost never appear in similar contexts drift apart. The dimensions that matter emerge from the data. As the Google Machine Learning Crash Course explains, language models develop powerful internal representations of language by modeling statistical patterns — and those representations are the embedding space.
The practical consequence of this learned geometry is that the model generalizes in ways that feel almost magical. It has never seen the phrase "the capital of Burkina Faso" during a particular training run, but it can answer that question correctly because it has seen enough related context — geographic relationships, African country names, city-country pairs — that the relevant vectors have been shaped into positions that allow the inference. The embedding space is a kind of implicit knowledge base, encoded not in rows and columns but in the directions between points.
Here's a subtlety worth knowing about: not every model uses static embeddings, where a word always maps to the same point regardless of context. Early systems like Word2Vec — the tool that produced the famous king-minus-man-plus-woman result — assigned each word a single fixed vector. But in modern transformers, embeddings are contextual. Stephen Wolfram's essay on ChatGPT notes that the model looks for things that match in meaning rather than literal text — and that matching is context-sensitive. The word "bank" in "the river bank was steep" ends up in a very different location than "bank" in "the bank froze my account," even though both start as the same token. The transformer architecture — which the following section will cover in full — updates and refines embeddings as it processes more context. The initial embedding is an entry point, not a fixed address.
This is a genuinely important distinction, so it's worth spelling out the mechanism at least roughly. Every token starts with a static embedding — a baseline position in the vector space. As the model processes the surrounding tokens, the transformer layers transform each token's representation, shifting it toward a location that reflects not just what the word is, but what the word means in this particular sentence. By the time the model reaches the final layers, "bank" in the financial sentence has become something quite different from "bank" in the geographic sentence, even though they began at the same starting point. Meaning is not fixed — it's negotiated in context, and the embedding space is where that negotiation happens.
This is also why the leap from individual word vectors to what a model actually navigates during inference is a bigger jump than it first appears. The model isn't moving through a static word map. It's operating in a continuous space where every token's position shifts based on everything else in the context window. The geometry is dynamic, not a snapshot. The relationship between "queen" and "king" discovered by early word vector models is just the beginning — an introduction to the idea. In a fully trained transformer, those relationships are constantly refined, stacked across layers, until the model's final representation of any given token is a complex function of everything it has read.
To put it plainly: the embedding space is the model's alphabet and its encyclopedia and its grammar all at once. It's the medium through which the model thinks. Numbers go in, positions in space come out, and those positions encode enough structure about human knowledge that the model can reason by navigation — moving through a space where proximity means relatedness, where direction means relationship, and where arithmetic on concepts can yield correct answers nobody explicitly programmed.
There's something philosophically arresting about that, worth naming directly. For most of computing history, meaning had to be manually encoded. A programmer wrote the rule "synonyms are related" or built a thesaurus by hand. The embedding approach inverts that entirely: you give the system text, and it discovers the structure of meaning on its own. The geometry wasn't given to the model — the model found it. That's the shift that made everything downstream possible, including the transformer architecture, the billion-parameter models, and the eerily coherent responses that still surprise people who haven't yet dug into how the machinery works.
What the model can do once it has that geometry — how it actually uses those vectors to generate text, resolve ambiguity, and handle sentences that no human ever wrote before — requires understanding what happens next in the architecture, in the layers of attention and transformation that the transformer section will walk through. But the foundation is here: meaning as location, relationship as direction, understanding as navigation through a vast and learned space.
6Attention Is All You Need: The Transformer Architecture Explained
Picture a sentence like this: "The animal didn't cross the street because it was too tired." Simple enough to read. But try asking a computer what "it" refers to. "It" could be the animal. It could be the street. A human brain resolves this in milliseconds, drawing on the full shape of the sentence — the word "tired" applies to animals, not streets, so the connection snaps into place. For decades, getting computers to make that same connection was one of the hardest open problems in artificial intelligence.
The previous section showed how words become numbers — how meaning gets compressed into points in a high-dimensional space, and how those coordinates allow a neural network to sense that "king" and "queen" are close together in a way that "king" and "bicycle" are not. That's the geometry. What the transformer does is take all those vectors and figure out how they should influence each other — which words in a sentence should shape the meaning of which other words, and how strongly. That's the problem this architecture was built to solve, and solving it changed everything.
The transformer is not one idea — it's a stack of interlocking mechanisms, each addressing a different piece of the same core puzzle. The best way to understand it is to follow the logic of necessity: here's the problem, here's what a naive solution looks like, here's why it fails, and here's what the transformer actually does instead.
Start with the core problem. A language model needs to understand every token in a sequence in the context of every other token. In the sentence about the tired animal, the word "it" can only be understood by connecting it to "animal" several positions back — and to "tired" several positions further on. The challenge is that these connections are not fixed. In a different sentence, "it" might refer to something else entirely. The relationships are dynamic, context-dependent, and can span any distance in a sequence.
Recurrent neural networks — the architecture that dominated NLP before 2017 — tried to handle this by reading tokens one at a time, left to right, carrying a kind of running summary forward through the sequence. The problem, as explored in the previous section on the history of these systems, is that the running summary degrades over long distances. By the time the network gets to "tired," the information about "animal" has been diluted through dozens of intermediate steps. This is the vanishing gradient problem — the signal gets weaker the further back you need to reach.
The transformer's solution is audacious in its simplicity: instead of reading left to right, it looks at every token in the sequence simultaneously, and for each token, it directly asks: how much should every other token in the sequence influence my representation right now? No sequential passing. No degradation over distance. Every token in the sentence is immediately and directly available to every other token. As documented in The Illustrated Transformer by Jay Alammar, the biggest benefit of this architecture is how it lends itself to parallelization — which matters enormously both for training speed and for capturing long-range dependencies.
This mechanism is called self-attention, and it is the heart of the transformer.
Here is how self-attention works — without any matrix algebra. Think of each token as a person at a conference, trying to decide whose badge to read before writing their own notes. To do this, each person needs to express three things: what they're looking for, what they have to offer, and the actual information they'd share if asked. In transformer terminology, these are the Query, the Key, and the Value.
The Query is the token asking: what do I need to know? The Key is each token advertising: here is what I represent. The Value is each token saying: here is the actual content I'll contribute if you decide I'm relevant.
Stay with this for one more step — it pays off shortly. When a token generates a query, it compares that query against the keys of every other token in the sequence. The comparison produces a score. Tokens with high scores — those whose keys match well with the query — get a strong weight. Tokens with low scores get a weak weight. Then the actual values of all the tokens are blended together, weighted by those scores. The result is a new, enriched representation of the original token — one that has absorbed context from whichever other tokens turned out to be relevant.
In the "animal" sentence, when the transformer is processing the token "it," the query for "it" matches strongly with the key for "animal" — and less strongly with the key for "street." So the value content from "animal" flows heavily into the updated representation of "it." The word doesn't just mean "it" in isolation anymore; it means "the animal" in the context of this particular sentence. That is a remarkable and genuinely powerful thing to be doing.
As Stephen Wolfram explains in his 2023 overview of what ChatGPT is doing and why it works, the model isn't looking at literal text — it's looking for things that "match in meaning." Self-attention is precisely the mechanism that produces that matching. The scores aren't hard-coded; they emerge from learned parameters, shaped by billions of examples of actual language during training.
This is where most people hit a conceptual snag, so it's worth naming it before you do. The queries, keys, and values are not three separate pieces of information attached to each token. They are three different linear projections of the same underlying token vector — three ways of looking at the same data, each trained to ask a different question. The Key is not what the token "is about" in some external sense; it's whatever the model learned to advertise about that token when other tokens are deciding how relevant it is. This takes a moment to feel intuitive. There's nothing wrong with running it twice.
Now, there is a deeper limitation lurking here. Different types of relationships between words are not all the same kind of thing. Consider the sentence: "The bank by the river was full of mud." The word "bank" needs to connect to "river" to resolve its meaning — that's a semantic relationship. But "was" needs to connect to "bank" to confirm grammatical agreement — that's a syntactic relationship. These two relationships are fundamentally different in character, and a single attention process might not capture both well simultaneously.
The transformer's solution to this is elegant: don't run one attention process. Run several in parallel. This is called multi-head attention.
Each attention "head" has its own set of Query, Key, and Value projection matrices — its own way of looking at the tokens. One head might learn to specialize in syntactic dependencies. Another might learn to track coreference — which pronouns refer to which nouns. Another might learn semantic roles — which noun is doing the action, which is receiving it. Because each head operates in a lower-dimensional subspace, the total computation is manageable, and the outputs from all heads are concatenated and projected back into the original dimension.
The Illustrated Transformer describes this clearly: each encoder in the original transformer architecture uses multiple attention heads in parallel, and the encoding component itself is a stack of encoders — six in the paper introducing the transformer, though that number is not magic and can be varied. The key insight is that different heads can capture genuinely different relationship types, making the overall representation richer than any single attention process could produce.
So far the transformer can figure out which tokens are relevant to which others. But there is a gap in what's been described. The self-attention mechanism, as presented, treats all tokens as if they exist in a bag — it knows what each token is, and it knows how relevant each is to the others, but it doesn't inherently know where in the sequence each token sits. Order matters in language. "The dog bit the man" means something different from "The man bit the dog," even though the vocabulary is identical.
This is the problem positional encoding solves. Before tokens are fed into the transformer, their embedding vectors get modified to include information about their position in the sequence. In the original 2017 transformer paper, this was done with sine and cosine functions of different frequencies — a mathematical scheme that assigns every position a unique fingerprint that the model can distinguish. More recent architectures use learned positional embeddings or other techniques, but the core idea is the same: the token's identity and its position in the sequence both need to be represented as part of the input.
This might feel like a workaround, and in a sense it is. The attention mechanism is inherently position-agnostic — it doesn't see order unless order is explicitly baked into the inputs. But the workaround is elegant. Because the positional encoding is added to the same vector space as the content embedding, the self-attention mechanism can attend to positional information the same way it attends to semantic information. The model can learn that token fifty-two positions to the left is relevant without any special machinery — position is just another dimension in the space it's already navigating.
After the attention layer has produced enriched, context-aware representations for each token, those representations flow into the feed-forward layer. This is where most people assume something complicated happens — and it does, but it's conceptually simpler than attention. The feed-forward layer is applied independently to each token position. It doesn't mix information between positions; that mixing already happened in attention. Instead, it applies a pair of linear transformations with a non-linearity in between — a neural network that processes each token's representation on its own.
Think of it this way: the attention layer decides who should talk to whom and how strongly. The feed-forward layer then privately processes each token's updated representation, giving the model an additional step to refine and transform what it learned from the attention step. It's where a lot of the factual and conceptual processing happens — the model has gathered context through attention, and now it digests it.
As described in The Illustrated Transformer, the exact same feed-forward network is independently applied to each position — this independence is what allows those positions to be processed in parallel, contributing to the transformer's computational efficiency.
Two more pieces complete the picture of a single transformer layer: residual connections and layer normalization. These might sound like engineering details, but they're what makes deep transformers trainable at all, and that matters.
A residual connection — sometimes called a skip connection — takes the input to a sub-layer and adds it directly to the output of that sub-layer. So instead of asking the sub-layer to compute a new representation from scratch, it only needs to compute the change from the input. The original input passes through unchanged alongside whatever modifications the sub-layer learned to make.
Why does this matter? Because deep neural networks — those with many layers — suffer from a fundamental training problem. As signals propagate backward through dozens of layers during training, gradients can shrink to essentially nothing, making it impossible for the early layers to learn. Residual connections provide a highway for the gradient signal to flow back through the network directly, bypassing any layer that isn't contributing useful transformations. The network can be deep without early layers becoming informationally starved.
Layer normalization addresses a related problem: as activations pass through many layers, their values can drift to extreme ranges, making training unstable. Layer normalization rescales the activations at each layer to have consistent statistics, keeping the training process numerically stable regardless of how deep the network goes.
Together, residual connections and layer normalization are why transformers can be stacked into very deep networks — 12 layers, 24 layers, 48 layers, 96 layers — without training collapsing. And stacking matters enormously. Each layer allows the model to build more abstract representations on top of the previous layer's output. Early layers might capture simple local patterns; deeper layers can capture long-range semantic structure and complex reasoning patterns. The capacity to go deep is what gives transformers their expressive power.
Now, the architecture described so far — self-attention, feed-forward layers, positional encoding, residual connections, layer normalization — was originally organized into two distinct components: an encoder and a decoder. It's worth understanding what each does, because the distinction matters for understanding why GPT-style models are built the way they are.
The encoder's job is to read an input sequence and produce a rich, contextual representation of it. In the original transformer architecture, designed for machine translation, the encoder would process the source sentence in its entirety, building a representation that captures the full meaning of what was said. Each encoder layer refines that representation further.
The decoder's job is to generate an output sequence, one token at a time. It takes the encoder's representation of the input and, at each step, produces the next token in the output. The decoder has a special variant of attention called cross-attention — it attends not just to the tokens it has already generated, but also to the encoder's representation of the input. This is how a translation model produces output that relates to the source sentence.
There's one more important distinction between encoder and decoder attention. In the encoder, every token can attend to every other token — past and future alike. In the decoder, a token can only attend to tokens that appeared before it in the sequence. This constraint is called causal masking, and it's enforced because at generation time, future tokens don't exist yet — the model can't cheat by looking ahead.
Here is the key architectural fact about GPT-style models like the one underlying ChatGPT: they use a decoder-only architecture. No separate encoder. Just a stack of decoder layers, each with causal self-attention and a feed-forward layer. The model reads a sequence of tokens and predicts what comes next — and because it processes the input and generates the output with the same decoder stack, it's simultaneously doing both jobs within a single architecture.
The Illustrated Transformer describes the original encoder-decoder design in detail, which is still used in systems designed for tasks like translation. But the decoder-only design turns out to be remarkably versatile: if you train it on enough text with next-token prediction as the objective, it learns to do almost everything — summarize, translate, answer questions, write code — by treating them all as continuation problems.
How deep does this stack go? The original 2017 transformer used six encoder layers and six decoder layers. Later GPT-scale models go much further. Large production models can have 96 or more layers — each consisting of a multi-head attention sub-layer and a feed-forward sub-layer, each with its own residual connection and layer normalization, each adding another level of abstraction over the representations flowing through the system. The total parameter count grows with the number of layers, the width of those layers (the dimensionality of the vectors), and the number of attention heads. At GPT-4 scale, those numbers are large enough that the model's internal workings become genuinely difficult to reason about even for its creators.
One last thing is worth sitting with, because it explains something practically important about why transformers became dominant so quickly after 2017. Recurrent neural networks processed tokens one at a time, sequentially. You couldn't compute the representation of token fifty until you'd finished computing token forty-nine. This is a fundamental computational bottleneck — the work can't be parallelized across tokens.
The transformer doesn't have this bottleneck. Because attention looks at all tokens simultaneously, and because the feed-forward layer processes each position independently, the entire forward pass through a transformer layer can be computed in parallel across all token positions. Modern GPU and TPU hardware is specifically designed for this kind of massively parallel computation. According to The Illustrated Transformer, the transformer outperforms earlier neural machine translation models in part because it lends itself so naturally to hardware parallelization — it's why cloud providers like Google Cloud specifically recommended it as a reference model for their TPU offerings.
This parallelism doesn't just mean the model runs faster at inference time. It means training is dramatically faster. A model that takes three months to train sequentially might take a week in parallel. That difference is what made it practical to train on internet-scale datasets, which is what made the capabilities that followed possible.
So here is the architecture, assembled: tokens become vectors through embeddings, positions get encoded, then layer after layer of attention and feed-forward processing refines those vectors into representations that carry the full context of the sequence. Residual connections and layer normalization keep the training stable through all those layers. Multi-head attention ensures different relationship types get captured. Causal masking ensures the decoder only sees the past. The whole thing runs in parallel across all token positions, making it fast enough to train at the scale where interesting things start happening.
Understanding the transformer is understanding the engine. What happens when you actually run that engine on a trillion tokens of text from the internet — and what the resulting model actually knows — is where the story goes next.
7Pretraining: How an LLM Reads the Internet
Picture a neural network at the moment it's born — billions of parameters set to essentially random values, like a brain that has never encountered a single word, a single fact, a single sentence. Feed it a question and it produces pure noise. It has no idea what language is, let alone what you're asking. Pretraining is the process of fixing that — and it is, without exaggeration, one of the most audacious computational undertakings in human history.
The architecture and the mathematical machinery behind transformers, which the previous section covered, only matter if you can actually teach the thing. And teaching it turns out to require a choice: what do you want the model to get good at? The answer that changed everything is almost embarrassingly simple. You want it to get good at predicting what comes next. Everything else — the world knowledge, the reasoning ability, the sense of grammar and idiom and tone — follows from that one disciplined obsession, applied at almost incomprehensible scale.
Three things make pretraining worth understanding deeply. First, it explains where the model's knowledge comes from. Second, it explains why the knowledge has the particular shape it does — what the model is good at, what it's not, and why those patterns aren't accidents. Third, it sets up everything that comes later: the fine-tuning, the alignment, the whole transformation of a raw language model into something you'd actually want to talk to. Start here, and the rest of the story makes sense.
So: what does pretraining actually mean?
The simplest description is that a randomly initialized neural network is exposed to enormous quantities of text and gradually adjusted — over billions of small corrections — until it becomes very, very good at predicting the next token in a sequence. That's it. That's the whole game. The model sees the beginning of a sentence, makes a guess about what comes next, checks how wrong it was, and updates its internal settings slightly to do better next time. Repeat that process across hundreds of billions of words, and something remarkable emerges.
What makes it computationally expensive is not the complexity of the task in any single moment — each individual prediction is relatively straightforward. What makes it expensive is the sheer scale. You're running that prediction-and-correction loop not thousands of times, not millions of times, but across datasets measured in trillions of tokens, adjusting billions of parameters with each pass. The hardware required — thousands of specialized chips running continuously for months — is why IBM's overview of large language models describes training as requiring massive amounts of data and compute before any of the interesting capabilities can emerge. The compute cost for training GPT-4 is estimated to have been in the range of tens of millions of dollars. That number isn't hyperbole; it reflects the genuine cost of running the kind of hardware cluster required for that scale of training over that duration of time. Only a handful of organizations in the world can afford to do it.
Before any of that computation happens, though, someone has to assemble the data.
The training dataset for a large language model is genuinely vast — and its composition is worth spending a moment on, because what the model learns is shaped profoundly by what it reads. The cornerstone of most major pretraining datasets is something called Common Crawl, which is a nonprofit organization that has been crawling the web continuously since 2008, archiving snapshots of websites as they exist at a given moment. The result is a dataset measured in petabytes — essentially a frozen version of a substantial fraction of the publicly accessible internet, updated regularly. When researchers or companies draw on Common Crawl, they're drawing on blog posts, forum threads, news articles, academic papers, product descriptions, comment sections, government documents, recipe sites, sports statistics pages, fan wikis, and virtually anything else that lives on the open web.
Raw Common Crawl data is not clean enough to use directly. The web contains an enormous amount of near-duplicate content — the same article scraped and republished across hundreds of sites. It contains spam, gibberish, automatically generated text, low-quality advertising copy, and content that researchers specifically want to filter out. IBM's explanation of LLM training notes that data scientists oversee cleaning and preprocessing to remove errors, duplication, and undesirable content before training begins. That filtering process is itself a significant undertaking, and the choices made during it — what to keep, what to discard, how aggressively to deduplicate — influence the model's eventual behavior in ways that aren't always easy to predict.
Beyond web crawl data, the pretraining corpus typically includes digitized books, which provide longer, more coherent text with more complex reasoning and narrative structure than most web pages. Wikipedia contributes a large body of factual, relatively well-maintained reference material across dozens of languages. Academic papers and scientific literature provide technical vocabulary and reasoning patterns. And increasingly, modern models are trained on substantial quantities of source code — Python, JavaScript, C, SQL, and dozens of other programming languages scraped from public repositories like GitHub. The inclusion of code turns out to matter enormously, not just for coding tasks but for the model's general reasoning ability. Code is extraordinarily structured; it has precise syntax, explicit logic chains, and predictable cause-and-effect relationships. A model trained to predict code naturally develops some capacity to follow chains of reasoning, because code is, in a sense, reasoning made explicit.
The resulting corpus for a major model can easily run to several trillion tokens — which, if you think about it as words, is roughly equivalent to reading millions of books. A human who read a book a week for a lifetime would accumulate perhaps two or three thousand books. A pretrained model has absorbed, in some functional sense, many millions of times that volume of text. The sheer quantity of exposure is part of what gives these models their characteristic breadth.
Now comes the central mechanism: self-supervised learning.
This is where pretraining becomes genuinely clever. The problem with training a model on raw text is that someone normally has to label the training data — to tell the model, for every input, what the correct output should be. That works for narrow tasks. If you're building a spam filter, you can pay people to label thousands of emails as spam or not-spam. But you can't label trillions of tokens of text in any practically meaningful way. The data is just too large.
Self-supervised learning solves this by generating the labels automatically from the data itself. The model is given a body of text and asked to predict what comes next — and the "correct answer" is simply the actual word that appears in the original text. No human labeler required. The text provides its own supervision. As IBM's description of LLM training explains, in self-supervised learning, tasks are designed so that ground truth can be inferred from unlabeled data — the model tries to find patterns, structures, and relationships on its own, without being told what the correct output is for each input. The correct output is already sitting there in the document, waiting to be used as the training signal.
Concretely, imagine the model is given the sentence: "The capital of France is." The model is asked to predict the next token. If it guesses "Paris," that's correct — and it gets a small reinforcement. If it guesses "London," it was wrong — and it gets a small correction. Now scale that to trillions of such moments, spread across every possible domain of human knowledge, and you begin to see why this simple objective produces something remarkably broad.
To understand the mechanics of that correction, you need to understand what "loss" means and how backpropagation works — because this is the actual engine of learning.
At each prediction step, the model assigns a probability to every token in its vocabulary — all fifty thousand or so possible next tokens. The correct token should, ideally, receive the highest probability. "Loss" is a number that measures how wrong the model was: specifically, how low a probability it assigned to the actual correct token. If the correct token got probability 0.9, the loss is very small. If the correct token got probability 0.001 — the model was almost certain something else would follow — the loss is large. The model's goal during training is to minimize loss across the entire training set.
After each prediction, something called backpropagation runs. This is a mathematical technique — and a genuinely beautiful one — that traces the loss backward through the network and calculates, for each of the billions of parameters, how much that individual parameter contributed to the error. Parameters that pushed the prediction in the wrong direction get adjusted. Parameters that were helping get adjusted less, or reinforced. Repeat this process billions of times, across trillions of tokens, and the parameters slowly converge toward values that make good predictions across the whole sweep of human language. Stephen Wolfram's detailed walkthrough of what ChatGPT is doing describes this as the model scanning billions of pages of human-written text to find what word comes next what fraction of the time — a useful intuition, even though the actual mechanism is more sophisticated than literal lookup.
What makes next-token prediction such a powerful training objective is that it is not, actually, a narrow task. To predict what word comes next in a cooking article, you need to know something about food. To predict what comes next in a legal brief, you need to know something about law. To predict the next line of a Python script, you need to understand programming logic. To predict what comes after "The capital of France is," you need to have some internal representation of geopolitical facts. A model trained to minimize loss across all of these contexts simultaneously has no choice but to develop broad competence. The training signal is, in a real sense, encoding the structure of human knowledge — because human knowledge is what the text is made of.
This is the point that deserves to sink in for a moment, because it's easy to dismiss and important not to.
Next-token prediction looks, on the surface, like a very limited task. It sounds like a parlor trick — predict the next word, what could that possibly teach a system about the world? The answer is: nearly everything that's reflected in text. Syntax — the grammatical patterns of every language in the corpus — is learned, because violating syntax produces wrong predictions. Facts are learned, because you can't correctly predict "The boiling point of water is one hundred" without having some encoding of that fact. Reasoning patterns are learned, because arguments have logical structure that constrains what can plausibly follow. Even something like tone is learned, because a legal document and a joke tweet follow completely different statistical patterns, and the model has to track the difference to predict well.
What the model is really doing, during pretraining, is building a compressed model of the world — or rather, a compressed model of how the world is represented in text. Every parameter in the network is a number, and after training, each of those numbers encodes some fragment of the patterns the model encountered. GPT-3, famously, has 175 billion parameters. GPT-4's parameter count has never been officially confirmed by OpenAI, but estimates and contextual evidence suggest it is larger still. Those numbers are not memory slots containing individual facts. They are weights in a vast mathematical function — each one a tiny contribution to the pattern that emerges when a query passes through the network. The knowledge is distributed across all of them, not stored in any one place. Pull out any single parameter and it means nothing in isolation. But together, the 175 billion parameters of GPT-3 encode enough of the world's linguistic texture to answer questions in dozens of languages, write functional code, summarize documents, and, in some cases, pass professional exams — none of which it was ever explicitly trained to do.
Bear with one more step here — it pays off shortly.
The fact that knowledge is distributed, not stored, is also why the model can generalize. A model that had simply memorized training data would be useless on any new question. But because the training process forces the model to encode patterns rather than examples, it can apply those patterns to sentences it has never seen before. The pattern "capitals come after 'the capital of [country] is'" doesn't need to be stored once for every country — it gets encoded as a general structural regularity. When you ask about a country the model encountered infrequently, it can still apply the pattern. That's generalization, and it's what makes these systems useful rather than merely encyclopedic.
This is also where an important nuance lives: the model is a great deal better at common patterns than rare ones. Topics that appear frequently in the training data are represented by many, many examples, which means the model has had many opportunities to encode their patterns accurately. Topics that appear rarely, or not at all, are represented poorly — the model's internal encoding of them is thinner, more fragile, and more prone to generating plausible-sounding text that doesn't hold up to scrutiny. This isn't a coincidence or a fixable bug; it's a direct consequence of how learning from frequency distributions works.
Now, what about scale — what happens when you make the model bigger, or feed it more data?
The short answer is that things get better, but in ways that aren't always smooth or predictable. More data gives the model more exposure to the patterns of the world, reducing gaps in its coverage and improving accuracy on rare topics. More parameters give the model more capacity to encode complex patterns — with 175 billion parameters versus, say, 100 million, the model can represent vastly more nuance, more cross-domain relationships, more subtle regularities. Training on ten times as much data generally improves performance across the board. Using ten times as many parameters generally does the same. These improvements are not linear — they follow what researchers have called scaling laws, which get their own section later in this course — but the basic direction is consistent: more scale, more capability.
What's genuinely surprising about scaling is that the improvements sometimes aren't gradual. A model trained at one scale might fail completely at a task — translation into a particular language, solving a certain type of logic puzzle — and then a model trained at a larger scale does it well, seemingly out of nowhere. These discontinuous leaps are called emergent capabilities, and they remain one of the genuinely mysterious aspects of modern LLMs. The section on the GPT family and scaling laws will go deep on that phenomenon; the point here is simply that pretraining at scale is what makes it possible.
One thing pretraining does not produce, for all its power, is a useful assistant.
This is worth sitting with. A model that has been pretrained on trillions of tokens of internet text has learned to produce "a reasonable continuation of whatever text it's got so far," as Wolfram's analysis puts it — where "reasonable" means consistent with what people write on billions of webpages. The internet is not uniformly helpful, harmless, or honest. It contains misinformation, toxic content, arguments for terrible positions, conspiracy theories, and an enormous quantity of text that is simply not the kind of thing you'd want a chatbot to produce. A pretrained model, given a prompt that starts like a conspiracy theory, will cheerfully continue it — because continuation is what it's learned to do.
Equally important: pretraining produces a model that continues text, not one that follows instructions. If you type "What is the capital of France?" into a raw pretrained model, it might continue your prompt with another question, or produce more text in the style of a quiz, or generate something else entirely that is statistically consistent with sequences that start like "What is the capital of France?" It has no training to understand that your question is a request for an answer. It just sees text and predicts more text.
This is the distinction between a language model and a language assistant — and it's a real and important one. The raw pretrained model is genuinely impressive: it knows an enormous amount, in that distributed sense, and it can produce coherent, often surprisingly accurate text on nearly any topic. But it is not trying to help you. It doesn't have a concept of helping. Turning that raw capability into something aligned with human intent — helpful, safe, appropriately humble about what it doesn't know — requires the next phase of training entirely. That transformation, the process of shaping a capable but wild model into something trustworthy enough to actually talk to, is where the story gets even more interesting.
8Temperature, Sampling, and the Art of Not Always Picking the Most Likely Word
Pretraining builds a mind crammed with language, facts, and reasoning patterns — but a mind that sits perfectly still until something asks it to speak. The moment a prompt arrives, something new begins: the model has to actually generate text, one token at a time, and how it does that turns out to matter enormously.
There's a fork in the road at that moment, and which path gets taken shapes everything from whether a poem feels alive to whether a piece of code compiles on the first try. This section is about that fork — about the mechanics of generation, why the obvious approach quietly fails, and how a handful of tunable parameters give ChatGPT its characteristic voice.
Start with the loop itself, because it's worth holding in your mind clearly. After training ends, the model doesn't change. No more learning, no more backpropagation. What remains is a fixed set of billions of parameters that, given any sequence of text, can produce one thing: a probability distribution over the entire vocabulary, ranking every possible next token from most to least likely. As Stephen Wolfram's 2023 essay on what ChatGPT is doing describes it, what ChatGPT is fundamentally doing is producing a "reasonable continuation" of whatever text it's received — and "reasonable" means what a person would be likely to write, having read billions of web pages and books. The model generates that continuation by asking the same question repeatedly: given everything so far, what should come next? It picks a token, appends it, and then the new longer sequence becomes the input for the next step. It's a loop that runs until the model generates a stop signal or hits a length limit. Token by token, paragraph by paragraph, essay by essay — all of it is just that loop, applied thousands of times in sequence.
So at each step in the loop, there's a ranked list. Think of it as a menu of every possible next token — perhaps fifty thousand options or more — each with an assigned probability. The word "the" might have a fifteen percent chance. The word "a" might have eight percent. Some obscure technical term might have a probability so small it's essentially zero. These probabilities are not random; they reflect everything the model learned during pretraining about what text tends to look like. They're the crystallized intuition of a system that has read an almost incomprehensible amount of human writing.
Now here's the first tempting idea, and also the first trap: why not just always pick the most probable token? It seems logical. It's what you'd do if you wanted to be maximally correct at every step. Grab the highest-probability word, append it, grab the next highest-probability word, append that, repeat. This strategy has a name — it's called greedy decoding, because it greedily takes the best-looking option at each individual moment without considering the larger picture.
Greedy decoding fails in a way that's easy to understand once you see it. As Wolfram's essay explains, if you always pick the highest-ranked word, you typically get a very "flat" essay that never seems to show any creativity — and it sometimes even repeats word for word. The reason is a kind of feedback trap. When the model picks the safest word at step one, that safe word makes a certain set of words safer at step two. Those safer words make yet another predictable set safe at step three. Very quickly, the text settles into ruts — common phrases, familiar sentence structures, the linguistic equivalent of a playlist on shuffle that keeps returning to the same three songs. For factual one-word answers, greedy decoding is fine. But for anything that requires range, novelty, or even just natural-sounding prose, it produces something that feels wooden and trapped.
This is where temperature comes in, and it's worth staying with this idea for a moment because it's the central mechanism behind ChatGPT's personality.
Temperature is a number — usually set somewhere between zero and two — that controls how sharp or how flat the probability distribution becomes before a token is sampled from it. At a temperature of zero, the distribution collapses entirely: one token gets all the probability, and that's always the most likely one. Greedy decoding, in other words, is what you get at temperature zero. As temperature rises above zero, the distribution spreads out. The most likely token still has the highest probability, but the lower-ranked tokens get more probability mass assigned to them relative to what the raw model output suggested. At very high temperatures — approaching two — the distribution flattens dramatically, and even quite unlikely tokens have a reasonable chance of being chosen.
Wolfram's essay notes that the word "temperature" comes from statistical physics, where exponential distributions appear in the study of systems like gases — the analogy being that higher temperature means more random, energetic behavior. There's no deep physical connection here; it's borrowed vocabulary that happened to fit. But the intuition transfers: low temperature means the system settles into its most predictable, stable state, while high temperature means more energy, more movement, more surprise.
What does this feel like in practice? At low temperature — say 0.2 — ChatGPT becomes conservative and focused. Ask it to write a sentence completing "The capital of France is…" and it will say "Paris" every time, with very high confidence. Ask it to generate a function to sort a list, and it will produce something clean and conventional. The output is reliable, consistent, and a little boring. At high temperature — say 1.4 — the same prompt might yield something unexpected. "Paris, obviously, though the Eiffel Tower makes that feel almost too on the nose." It's more interesting. It might also be more likely to veer off course, misstate something, or produce a sentence that seems to come from left field. The tradeoff is real and irreducible: creativity and reliability pull in opposite directions.
Here is where most people have an instinct that deserves to be addressed directly: isn't randomness bad? Isn't the point of asking an AI assistant a question to get the right answer, not a randomly chosen answer? For factual questions, yes — and that's exactly why temperature is tuned down for factual tasks. But for creative and generative tasks, the randomness is doing something essential. It's breaking the feedback traps that greedy decoding falls into. It's allowing the model to explore regions of the probability landscape it would otherwise ignore. As Wolfram's essay observes, the fact that there's randomness in the process is precisely why using the same prompt multiple times produces different outputs each time. That variability is not a glitch — it's the system working as designed. A novelist who wrote the same sentence every time they sat down would not be a novelist for long.
Temperature is not the only control on this process, though. Even a well-tuned temperature leaves a subtle problem: the probability distribution is long-tailed, meaning there are thousands of tokens with tiny but nonzero probabilities. At a moderate temperature, most of those tokens are still implausible — they're grammatically wrong, contextually bizarre, or simply incoherent. Allowing even a small probability of sampling from that long tail means occasionally the model will produce something genuinely strange and wrong, not interestingly creative but just broken.
This is the problem that top-k and top-p sampling were designed to solve, and they solve it by drawing a boundary around the plausible candidates before sampling.
Top-k sampling is the simpler idea: at each step, consider only the k most probable tokens — perhaps the top ten, or the top fifty — and redistribute all the probability mass among just those. Everything outside that set gets zeroed out. This prevents sampling from the bizarre tail while still allowing creativity within the most plausible options. The catch is that k is a fixed number, and what constitutes a reasonable number of candidates varies from step to step. Sometimes the right next word is overwhelmingly obvious — one or two tokens dominate — and k of fifty is far too permissive. Other times many options are equally plausible, and k of ten is too restrictive.
Top-p sampling — also called nucleus sampling — addresses this directly. Instead of cutting off at a fixed number of candidates, it cuts off at a fixed amount of probability mass. You might set p to 0.9, meaning: consider the smallest set of tokens whose combined probability adds up to ninety percent of the total. If the model is very confident, that might be just two or three tokens. If the model is genuinely uncertain about what comes next, that might be thirty or forty tokens. The boundary expands and contracts fluidly depending on the situation, always capturing a meaningful nucleus of likely options while excluding the long tail of implausibilities.
In practice, the Understanding AI explainer on large language models describes how these systems work to narrow the field at inference time — and the intuition is that you're constructing something like a sensible shortlist before making a choice, rather than randomly drawing from the full menu of tens of thousands of options. Nucleus sampling in particular became the dominant approach in many production systems because it handles the variability in confidence gracefully. It's adaptive in a way that top-k simply isn't.
These settings — temperature, top-k, top-p — are typically used together rather than in isolation. A common pattern might set temperature to 0.8 and top-p to 0.95, which produces output that feels natural and varied without careening into nonsense. The specific values Wolfram mentions for essay generation — a temperature around 0.8 — aren't derived from theory but from empirical observation of what actually reads well. There's no equation that tells you 0.8 is the right number; practitioners converge on values through experimentation and the somewhat circular test of whether the output seems good to human readers. That's an honest admission about the state of the field: these are tuning knobs, not theorems.
The tuning varies meaningfully depending on the task. Code generation is one of the clearest examples of where low temperature wins. When a model is writing a function that needs to compile, there's often a single right answer or a small set of structurally equivalent right answers. Wandering toward unusual tokens produces bugs, not insight. Systems designed specifically for code generation — GitHub Copilot being one prominent example — typically run with very low temperatures, prioritizing correctness and consistency over novelty. Creative writing tasks flip this entirely. A poem generated at temperature 0.1 is recognizable as a poem in structure but feels like it was written by a robot trained only on greeting cards. Turning the temperature up, even to 1.0 or beyond, lets unexpected words and images emerge — the kind of associations that make a line feel alive rather than assembled.
Factual question-answering sits in an interesting middle zone. For a question like "What year was the Eiffel Tower built?", the correct behavior is low-temperature: the model should commit to a specific year confidently and consistently. But for a question like "What are some interesting theories about why the Roman Empire fell?", a bit of temperature allows the model to explore more of its knowledge rather than defaulting to the three most statistically dominant explanations. The art of configuring these systems for production lies in recognizing which type of task each question belongs to — and some systems try to infer this dynamically rather than using a single fixed setting for everything.
It's worth being precise about what "getting more consistent results" actually means. If you set temperature to zero, you will get the same output from the same prompt every time — deterministic generation, no randomness. For many applications, this is genuinely useful: automated pipelines that need reproducibility, testing environments, any case where consistency trumps creativity. But most conversational deployments use a moderate temperature, which means identical prompts will produce different outputs. This is not a malfunction. It reflects the legitimate reality that many prompts have many good responses, and fixing the system to one answer would be a kind of false precision. If you need more consistent results from ChatGPT in practice, the most reliable techniques are not about temperature settings you control as a user but about prompt construction: being more specific about what you want, providing examples of the format or style you're looking for, and asking the model to reason step by step rather than jumping to an answer. These structural choices narrow the effective probability space in a way that makes outputs more predictable even when temperature remains moderate.
Bear with this for one more step, because there's a slightly counterintuitive thing worth making explicit: the randomness in sampling is applied at each individual token step, independently. The model doesn't "decide" to write a creative essay and then commit to that decision throughout. It makes a probabilistic choice about the first token, then another about the second, then another about the third. The overall character of the output — whether it feels creative or conservative, flowing or stilted — emerges from thousands of these tiny individual decisions stacking on top of each other. Which means a single unlucky low-probability draw early in the generation can send the entire output in a direction the model wouldn't typically go. This is both why sometimes ChatGPT produces something genuinely surprising and wonderful, and why sometimes it produces something confidently wrong — the same mechanism drives both outcomes.
That point about confidently wrong is worth sitting with... because it connects directly to one of the most important things to understand about these systems. The probability distribution the model generates at each step reflects what text it predicts should come next — not what is true. A model generating a hallucination — a plausible-sounding but false claim — is doing so because the false claim has high probability given the text so far. Temperature and sampling strategies don't fix this; they just control the range of what gets selected from the distribution the model assigns. If the distribution itself is wrong, no amount of sampling sophistication makes the output correct. The tools in this section are about managing the texture of generation, not about guaranteeing accuracy.
So where does this leave things? Every time a response appears in a ChatGPT conversation, it arrives through this loop: a probability distribution generated at each step, a temperature applied to reshape that distribution, a nucleus or top-k boundary drawn around the plausible candidates, and then a sample drawn from what remains. It happens hundreds of times per second, invisibly, producing prose that can feel almost eerily natural. The variability is designed in. The creativity is an emergent property of controlled randomness. And the settings behind all of this are ultimately judgment calls, tuned by practitioners to balance coherence against surprise, reliability against range — which is exactly the trade-off this whole section is built around.
What this still doesn't answer is why the model is useful at all after pretraining — why the raw next-token predictor that emerges from training on the internet needs significant additional work before it becomes the assistant people actually talk to. That transformation, from capable but erratic text predictor to helpful conversational partner, is where the story heads next.
9From Raw Model to ChatGPT: Fine-Tuning, Feedback, and Alignment
Imagine you've just spent months teaching someone to read every book ever written — every novel, every textbook, every Wikipedia article, every forum post — and at the end of that process you hand them a piece of paper and say, "Now help me draft a cover letter." And they respond by continuing whatever sentence was already on the page. That's roughly where a pretrained language model sits before fine-tuning. Brilliant at pattern completion. Useless as an assistant.
That gap — between a model that's read everything and a model that actually helps you — is what this section is about, and closing it required one of the most creative engineering ideas in modern AI.
The story of how a raw language model becomes ChatGPT runs through three distinct phases, each of which solved a different piece of the puzzle.
Start with what a pretrained model actually does when you talk to it. It has ingested a staggering volume of text, and what it learned is essentially this: given any string of words, what is likely to come next? That's a genuinely useful skill. But it's not the same as answering a question, following an instruction, or refusing to help with something harmful. A pretrained model asked "How do I write a cover letter?" might respond with a second question in the same format — because the internet contains many documents that are question lists. It might continue with a completely unrelated sentence — because it's completing a pattern, not parsing intent. It might generate something useful by accident, the way a million monkeys might produce a coherent paragraph. As the Hugging Face RLHF explainer describes it, the pretrained model responds well to diverse text, but "well" here means statistically coherent, not helpful in the way a human assistant would be.
The first fix is supervised fine-tuning, or SFT. The idea is elegant in its simplicity: collect a set of example conversations that demonstrate what good responses actually look like, then train the model on those examples the same way it was trained during pretraining — by having it predict the correct next token, where "correct" is now defined by a human-written ideal response. The model, which already has powerful language capabilities baked in, learns from these examples to steer those capabilities in a more useful direction. It's not being taught language from scratch; it's being shown a new register for applying language it already knows.
OpenAI's approach to SFT, documented in the InstructGPT paper, involved starting with a smaller version of GPT-3 and fine-tuning it on human-generated text that demonstrated preferable responses. The signal here is still relatively simple: show the model good examples, let it learn from them. But the effect is significant. A model that emerged from pretraining prone to completing prompts like a search result now starts to behave more like a person who understood what the prompt was asking. It doesn't always get it right, but the distribution of outputs shifts meaningfully toward something resembling helpfulness.
There's a catch, though — and it's an important one. Writing good training examples is expensive. A human has to compose every single demonstration, and composing a truly ideal response to every conceivable user prompt is a massive, open-ended task. The Hugging Face RLHF explainer describes this as "expensive, augmented data," and that's not an exaggeration. More fundamentally, SFT alone doesn't give the model a way to evaluate its own outputs. It's been shown examples of good behavior, but it has no internal sense of what makes one response better than another. It learned to imitate, not to judge. That distinction matters enormously.
This is where the second ingredient enters: human feedback as a training signal. Rather than having labelers write ideal responses from scratch, the more efficient approach is to have them compare responses. Show a labeler four different completions of the same prompt, and ask them to rank those completions from best to worst. This is cognitively much easier than generating the ideal response yourself — most people can tell you which restaurant they prefer even if they couldn't cook either meal — and it scales more efficiently, because a single labeler can rank many completions in the time it would take to write one. According to the Hugging Face RLHF overview, this comparison data becomes the training set for what's called a reward model, and this is where the architecture gets genuinely clever.
The reward model is a separate neural network — often initialized from the same pretrained LLM — whose job is to learn to predict human preferences. It takes in a piece of text and produces a single scalar number: a score representing how much a human rater would like this response. The reward model isn't generating language; it's evaluating it. Think of it as the part of the system that has internalized the question "Is this actually good?" It gets trained on the ranking data until it can predict, with reasonable reliability, which of two responses a human would prefer. The Hugging Face explainer notes that the output being a single scalar reward is crucial, because it makes the reward model compatible with existing reinforcement learning algorithms that need a numerical signal to optimize against.
Stay with this for one more step, because it's where the real sophistication lives. Once you have a reward model that can score outputs, you have something a pure supervised approach lacked: a way to improve the language model without writing more examples. Instead of telling the model "this is the correct response," you can now tell it "this response scored higher than that one, according to a model trained on human preferences." That's a much richer signal. It can generalize. It can apply to prompts that no human labeler has ever seen.
Reinforcement Learning from Human Feedback — RLHF — is the technique that stitches these pieces together. The core idea is to use the reward model as a proxy for human judgment and then use reinforcement learning to train the language model to generate responses that score well according to that proxy. In reinforcement learning terms: the language model is the "policy" — the thing making decisions — and the reward model provides the reward signal that tells it how well it's doing. The model generates an output, the reward model scores it, and the language model's parameters get nudged in directions that lead to higher-scoring outputs. Over many iterations, the language model learns to produce text that the reward model approves of, which in turn means text that tends to satisfy human labelers.
The specific reinforcement learning algorithm OpenAI used for this is called Proximal Policy Optimization, or PPO. PPO is worth understanding at an intuitive level, because it solves a real problem with the basic reinforcement learning setup. The naive version of "update the language model to get higher rewards" turns out to be unstable: the model might change its behavior so dramatically in a single update that it stops making sense as a language model at all. PPO adds a constraint that prevents the updated model from drifting too far from where it started in any single step. The "proximal" in the name literally refers to proximity — staying near the previous policy while still improving. As described in the Hugging Face RLHF overview, this makes the training process more stable without sacrificing the model's ability to improve over time.
There's an additional safeguard built into the PPO setup that's worth knowing about. When the language model is being fine-tuned with reinforcement learning, its outputs are compared not just against the reward model's score but also against the original SFT model — the version from the supervised fine-tuning stage. A penalty is applied whenever the RLHF-trained model drifts too far from the SFT model in terms of what text it generates. This keeps the model from "forgetting" how to write coherent language in its pursuit of high reward scores. It's a check on the optimization pressure — a way of saying, "Improve, but don't become unrecognizable."
InstructGPT, the research paper OpenAI published in early 2022, was the first public demonstration that this full pipeline could produce dramatic improvements in instruction-following. As the Hugging Face blog explains, OpenAI used a smaller version of GPT-3 as the starting point, applied SFT on human-written demonstrations, trained a reward model on ranked comparisons, and then applied PPO to optimize the language model against that reward model. The results were striking. Human raters consistently preferred InstructGPT's outputs over those of GPT-3 even when GPT-3 was one hundred times larger by parameter count. A model with 1.3 billion parameters trained with RLHF was preferred over the raw 175-billion-parameter GPT-3 by human evaluators. That's not a small finding — it suggests that how you train a model matters as much as how big it is.
ChatGPT, which launched in November 2022, was built on a successor to InstructGPT. The fundamental architecture was the same — pretraining, supervised fine-tuning, reward model, RLHF — but OpenAI applied additional iterations of feedback collection and continued to refine the data used at each stage. The conversational format was more deliberately shaped; the model was tuned to handle multi-turn dialogue more naturally, to maintain context across a conversation, and to apply more nuanced judgment about what kinds of requests to decline and how. ChatGPT was, in a sense, InstructGPT with more rounds of feedback and a more carefully designed conversational persona built into the process.
Now for the part that doesn't get celebrated as often: the limitations. RLHF is genuinely powerful, but it has failure modes that matter in practice, and understanding them is part of understanding the system honestly.
The first is reward hacking. Because the language model is being optimized to score well on the reward model — not to actually satisfy humans — it can learn to exploit weaknesses in the reward model that don't correspond to real quality. If the reward model happens to give higher scores to longer responses, the language model may learn to pad answers regardless of whether the extra length helps. If the reward model tends to prefer responses that sound confident, the language model may learn to project confidence even on questions where uncertainty would be more appropriate. This is a known and persistent challenge: the Hugging Face RLHF overview explicitly flags that the design space of RLHF is not thoroughly explored, and reward hacking represents one of the open problems in making the optimization stable and reliable.
The second failure mode is sycophancy — the tendency of RLHF-trained models to agree with users rather than correct them. If human raters, consciously or not, give higher scores to responses that validate their views, the reward model learns to predict that agreeable responses are preferred, and the language model learns to generate them. The result is a model that tells you what you want to hear more often than a genuinely helpful advisor would. This is not hypothetical — researchers have documented sycophancy as a real pattern in RLHF-trained models, and it's one of the reasons OpenAI and others continue to iterate on feedback collection and reward modeling.
The third limitation is more structural. Human feedback is only as good as the humans providing it, and human raters have their own biases, inconsistencies, and blind spots. Labelers from different backgrounds may rank the same outputs differently. Things that are hard for labelers to evaluate — the accuracy of a subtle scientific claim, the quality of reasoning across a long chain of logic — tend to be underweighted in the reward model because human raters can't reliably distinguish good from bad in those domains. As the Hugging Face overview notes, writing a loss function that captures all the attributes of a good response — truthfulness, creativity, safety, helpfulness — "seems intractable." RLHF gets closer than pure pretraining, but it doesn't solve that problem completely. It substitutes human judgment, which is better than no signal, for something more principled — and then inherits all the messiness of human judgment along the way.
The three-stage pipeline — pretraining, supervised fine-tuning, RLHF — is still the dominant approach to producing the kind of conversational AI assistant that people actually find useful. Each stage does a different job. Pretraining gives the model a dense, compressed understanding of language and the world. SFT teaches the model what good conversational behavior looks like by example. RLHF, through the reward model and PPO, uses human preferences to steer the model's behavior away from the awkward, unhelpful, or harmful corners of the response space and toward outputs that real people judge as good.
Understanding this pipeline changes how you read the model's behavior when it surprises you. When ChatGPT hedges more than necessary, or agrees with you in ways that feel hollow, or declines a request that seems harmless — those patterns aren't random quirks. They're the downstream consequences of an optimization process that used human feedback as its target, with all the strengths and limitations that implies. The model isn't "thinking" about what the right answer is; it's navigating a learned surface shaped by thousands of human judgments made by real people doing their best to define what "good" looks like.
What that surface looks like, and how the capabilities that emerge from it relate to anything we'd recognize as understanding or reasoning — that's where the story gets genuinely strange, and it's where the next section picks up.
10Scaling Up: The GPT Family and the Laws of AI Progress
There is a number that keeps appearing in the history of this technology, and it scales in a way that is almost impossible to process intuitively. In 2018, a research team at OpenAI released a language model with 117 million adjustable parameters — numbers inside the network that encode everything it had learned. Four years later, the successor to that model reportedly had 175 billion. That's not ten times more, or even a hundred times more. It's roughly fifteen hundred times more. And the capabilities didn't just grow proportionally. They leaped.
That leap is what this section is about. The architecture covered in earlier sections — the transformer, the attention mechanism, the pretraining loop — stayed remarkably similar across generations. What changed was scale. And scale, it turns out, does something to a system that nobody fully predicted. Understanding what it does, and why, is one of the more intellectually disorienting ideas in modern technology.
There are four things worth tracing here: how the GPT family actually evolved from generation to generation, what scaling laws are and why they matter, the strange phenomenon called emergent abilities, and what all of this means for who gets to build these systems and why.
Start at the beginning. In 2018, the original GPT paper from OpenAI introduced something modest by current standards: a 117 million parameter model trained on a large corpus of text using the transformer architecture. The insight wasn't the scale — 117 million parameters is tiny compared to what followed. The insight was the approach. Rather than building a model from scratch for each specific task, you could pretrain a single model on enormous amounts of raw text, and then fine-tune it on whatever you actually wanted it to do. This sounds obvious now, but it was a genuine conceptual shift. Previous systems were purpose-built. This one was general first, specific second. GPT-1 was a proof of concept that the approach worked at all.
Then came GPT-2, in 2019, and something changed in the public conversation around this technology. The model had 1.5 billion parameters — roughly thirteen times the size of GPT-1. OpenAI trained it on a dataset of about eight million web pages, curated specifically for quality. And the text it generated was, by the standards of the time, startlingly coherent. Long-form completions held their topic. Made transitions. Used the conventions of whatever genre they were writing in. When OpenAI released GPT-2, they initially withheld the full model, citing concerns that it was, in their phrasing, too dangerous to release wholesale. Their worry was misuse — fake news, spam, impersonation at scale. The decision was controversial. Critics pointed out that plenty of other labs could build something similar, and that withholding the weights mostly just slowed down legitimate research. OpenAI eventually released the full model, and the feared catastrophe didn't materialize in the way they had feared. But the episode introduced an important cultural moment: for the first time, a language model had produced output fluent enough that the people who built it worried about what it would do in the world.
What GPT-2 couldn't do, however, was anything particularly clever. Ask it a question and it would continue the text in a plausible direction, but not necessarily a correct or useful one. It had no real sense that a question was a question. It didn't follow instructions. It was, in the terminology covered in the previous section, a raw pretrained model — capable of fluid text, but not aligned to any particular purpose. That limitation would define the next problem the field had to solve.
GPT-3 arrived in 2020 with 175 billion parameters, and it did something that genuinely surprised the researchers. It learned to do tasks it had never been explicitly trained on — just from seeing a few examples in the prompt itself. Show it two or three examples of a translation, and it would translate. Show it two or three examples of a math problem with a solution, and it could solve similar problems. Show it an example of code, and it would write more code. This capability — called few-shot learning, or in-context learning — had not been deliberately engineered into GPT-3. It seemed to emerge from scale. Smaller versions of the same architecture didn't do it nearly as well. At 175 billion parameters, something clicked.
This is worth sitting with for a moment, because it's counterintuitive. In-context learning means the model can adapt to a new task at inference time — when it's actually being used, not when it's being trained — just by reading examples in the prompt. No weight updates. No retraining. The model processes the examples and then generalizes. As documented in early analyses of GPT-3's behavior, this wasn't understood to be something that would emerge from next-token prediction at scale; it was discovered empirically, by testing the model and watching what it did. The theoretical understanding of why it happens is still being worked out today.
GPT-3 also forced a reckoning with a gap the field had been quietly aware of: a powerful pretrained model is not the same thing as a useful product. GPT-3 would complete prompts fluently but didn't follow instructions the way a human user expects. Ask it to write a cover letter, and it might just... continue the prompt in a way that looked like it was adding more instructions. Ask it a factual question, and it might answer it or it might riff in a related direction. It had no stable sense that the human on the other end wanted something specific done. That problem led directly to InstructGPT.
InstructGPT, documented in a 2022 paper from OpenAI, applied Reinforcement Learning from Human Feedback — RLHF — to a model pretrained like GPT-3. As the Hugging Face blog on RLHF explains, the process works in three stages: pretrain a language model on raw text, gather human preference data by having labelers rank or compare model outputs, train a reward model to predict those preferences, and then use reinforcement learning to steer the language model toward outputs the reward model scores highly. OpenAI used a smaller version of GPT-3 as the base for InstructGPT — not the full 175 billion parameter version. The resulting model followed instructions dramatically better than its larger, untuned cousin. This was the empirical discovery that drove the next several years of development: alignment training can extract more usable capability from a given model than simply scaling the pretrained base.
ChatGPT, released in November 2022, built directly on that InstructGPT lineage. It applied the same RLHF pipeline, with the addition of conversation-specific fine-tuning to make the model work well across multi-turn dialogue. The leap in public attention wasn't primarily because the underlying technology had changed dramatically since GPT-3 — it was because RLHF had finally produced a model that non-researchers actually wanted to use.
Then came GPT-4, which OpenAI announced in early 2023. Here the public record becomes intentionally sparse. OpenAI declined to publish the model's parameter count, training data details, or architecture specifics — a deliberate departure from the relative openness of the GPT-3 era. What OpenAI did confirm is that GPT-4 is multimodal, meaning it can process images as well as text. It performs significantly better on standardized benchmarks than GPT-3 — scoring in roughly the ninetieth percentile on the Uniform Bar Exam, for instance, compared to GPT-3.5's approximately tenth percentile. The model is, by any external measure, substantially more capable than its predecessors. The details of why remain proprietary.
This secrecy is itself a data point about where the field has arrived. When GPT-2 came out, the research community could largely reproduce it. When GPT-3 came out, the architecture was described in enough detail that others built close approximations. By GPT-4, the compute costs and engineering complexity had become large enough that a handful of organizations could plausibly build frontier models, and those organizations had financial incentives to treat architectural details as trade secrets. The open science norms of academic machine learning had been substantially eroded by commercial stakes.
Now for the underlying pattern that connects all of these generations. Scaling laws are empirical relationships — observed in practice, then formalized — between three quantities: the number of parameters in a model, the amount of data it's trained on, the amount of compute used in training, and the resulting performance. The key word is empirical. Scaling laws weren't derived from first principles. Researchers trained many models at many different sizes, measured how well they performed, and noticed that the curves were remarkably smooth and predictable.
The most influential paper on this topic came from a DeepMind team in 2022, often called the Chinchilla paper after the model it described. The finding was that prior frontier models — including GPT-3 — had been trained with too many parameters for the amount of data they used. Given a fixed compute budget, the optimal strategy is to scale model size and data size roughly together: a smaller, well-fed model often outperforms a larger, data-starved one. This was a practically important result because it changed how teams allocated resources. Training the biggest model you can afford isn't the right strategy if you're underfeeding it on data.
Scaling laws matter for a reason that goes beyond engineering efficiency. They imply something philosophically interesting: that intelligence — or at least the kind of text prediction that looks like intelligence — is a function you can turn up with more resources. There's no obvious ceiling in the empirical data, at least not one that's been reached. The loss keeps falling. The benchmarks keep rising. This has led to a genuine research debate about whether the scaling era is ending or continuing. Some researchers point to evidence of diminishing returns at the frontier. Others argue the ceiling hasn't been hit and the question is just one of cost. As of 2026, that debate is ongoing and unresolved.
The phenomenon that makes scaling feel strange rather than just expensive is emergence. Emergent abilities are capabilities that are essentially absent in smaller models and then appear — sometimes quite abruptly, as a function of scale — in larger ones. A few examples bring this into focus. Multi-step arithmetic didn't work reliably in smaller language models. At sufficient scale, it started working. Analogical reasoning, certain translation pairs, commonsense question answering, the ability to follow complex multi-part instructions — all of these show patterns where performance is near-random at small scale and then jumps significantly as the model gets larger.
This is where the concept took on genuine scientific interest. Emergence wasn't an engineering design choice. Nobody programmed it in. The same architecture, the same training objective, the same general approach — and then, at some threshold, new behaviors appeared. It recalled the kind of phase transitions physicists study: water doesn't gradually become ice, it transitions at a threshold temperature. Something analogous seems to happen in neural networks as they scale.
It's worth being careful here, though. Some researchers have argued that emergent abilities are partly an artifact of how performance is measured — if you use a metric that requires a task to be nearly fully solved to register any score, then performance looks like it jumps from zero to something, when in reality the underlying capability was improving continuously underneath a coarse measurement surface. Bear with that nuance for a moment, because it matters. It doesn't mean emergence isn't real — it almost certainly is real in some cases. It means the precise shape of the emergence curve depends on how you're measuring it, and smooth improvement can look like a sudden jump when you're using a binary success/fail metric.
The practical implication of scaling laws and emergence is that the field developed a kind of empirically justified optimism in the 2020–2024 period: if you didn't know how to make a model do something, a reasonable bet was that scaling up would eventually get you there. This was unusual. In most engineering domains, you have to know how to build something before you can build it bigger. In large language models, scale itself was a mechanism for acquiring capabilities nobody specifically designed.
Now, a counterpoint worth sitting with. A 175 billion parameter base model can be outperformed on specific tasks by a 7 billion parameter model that has been well fine-tuned for that task. This seems paradoxical — shouldn't more parameters mean more knowledge, more capability? The resolution is that parameters are potential, not performance. A huge base model has compressed enormous amounts of world knowledge into its weights, but that knowledge isn't efficiently organized for any specific task. Fine-tuning on high-quality task-specific data reorganizes a smaller model's capacity in ways that are precisely aligned with what you need. The big model knows more in a diffuse sense. The small model, if fine-tuned well, knows what you care about more precisely. As the Hugging Face RLHF documentation notes, InstructGPT used a smaller version of GPT-3 as its base, and the resulting model was preferred by human raters over the raw 175 billion parameter version across most practical tasks. Fewer parameters, better alignment — and in many real-world uses, better outputs.
This is the insight behind an enormous amount of practical work happening at the moment. Rather than training the biggest possible model, teams optimize for the best model at a given inference cost. Because inference — actually running a model to generate an output — is a continuous expense that scales with model size, a smaller but better-tuned model can be both more capable on your specific use case and dramatically cheaper to run at scale. Llama and Mistral and similar open-weight models in the 7 to 70 billion parameter range have demonstrated this empirically: properly fine-tuned, they can match or exceed much larger models on domain-specific tasks.
The economics of the frontier, however, are a different matter. Training a large pretrained model — the base that all the fine-tuning builds on — requires compute at a scale that only a handful of organizations can afford. The cost of training GPT-4 has been estimated in the range of tens of millions to over a hundred million dollars, when you factor in the research iterations, failed runs, and infrastructure, not just the final training pass. That's before deployment, before ongoing inference costs, before the teams needed to run it all. The result is a landscape where the base models of the frontier are controlled by a small number of actors — OpenAI, Google DeepMind, Anthropic, Meta, and a few others — while a larger ecosystem builds on top of them, fine-tunes derivatives of their open-weight releases, or uses their APIs.
This concentration is a function of scaling laws themselves. If performance scales predictably with compute, then the organizations with the most compute can achieve the best performance, and compute at this level is expensive enough to be a genuine barrier. This is why you don't see frontier model training happening at universities, even well-resourced ones. The compute requirements have simply outpaced what academic institutions can afford. That's a shift from the earlier era of deep learning, where a well-equipped university lab could train competitive models.
So here's where this leaves the listener. The GPT family tells a story that looks, in hindsight, almost inevitable — the same basic idea, scaled up with more parameters, more data, and more compute, yielded qualitatively different kinds of capability at each step. The scaling laws say this wasn't luck; it was a predictable empirical relationship. The emergent abilities say that what the relationship produces at large scale can genuinely surprise the people building the systems.
What the scaling story doesn't resolve is what the model actually knows, in any deep sense — whether those billions of parameters constitute something like understanding or something more like elaborate pattern completion. The GPT lineage proved that scale produces extraordinary capability. Whether it also produces anything resembling reasoning is the question the next part of this course begins to examine.
11The Context Window: ChatGPT's Working Memory
Picture a brilliant assistant sitting across from you, ready to help — but with one unusual constraint: the moment a conversation grows past a certain length, everything said before that point simply vanishes from view. Not stored somewhere for later. Not summarized quietly in the background. Gone, as far as the assistant is concerned. That is the context window, and it is one of the most practically consequential facts about how ChatGPT actually works.
Understanding it changes how you use these tools. It explains why a long brainstorming session can suddenly feel like the model forgot what it was doing, why copying a whole document into a chat works differently than you might expect, and why ChatGPT has no memory of the conversation you had with it last Tuesday. The context window is worth understanding carefully — so that's exactly what this section does, starting from what it actually is, moving through why it exists, and ending with what you can do about its limits in practice.
Start with the core idea. Every time ChatGPT generates a response, it doesn't reach into some permanent store of your conversation history. It doesn't have a diary of your past sessions filed away in a cabinet somewhere. What it has is a single, flat sequence of text — a long string of tokens — that represents everything it is currently allowed to see. That sequence is the context window, and it holds the system prompt at the top, every message you and the model have exchanged in the current conversation, and whatever you just typed. That's it. That is the model's entire working memory at this moment.
The word "window" is well chosen. Think of it like a physical window you can slide along a very long piece of paper. Whatever the window covers, the model can read. Everything outside the window — to the left, to the right, from yesterday — doesn't exist for it. The window has a fixed size, and when you fill it up, something has to fall off one edge to make room for new content at the other.
Now, why does this limit exist at all? The answer lives in the transformer architecture that was covered earlier in this course. The transformer's key mechanism — attention — works by letting every token in a sequence look at every other token in that sequence and decide how much weight to give each one. That's what makes it so powerful: the word "bank" in a sentence about rivers can attend to "river" and "water" three sentences back, which is exactly how the model understands context that an earlier generation of neural networks couldn't handle. But here's the catch. For attention to do that calculation, all those tokens have to be present simultaneously. The model has to hold the whole sequence in memory and compute relationships between every pair of tokens. As Stephen Wolfram's 2023 explanation of what ChatGPT is doing describes it, the model is always working from "the text it's got so far" — and that phrase "so far" is doing a lot of work. It means the sequence has to be finite and present.
The computational cost of that pairwise attention calculation grows in a way that matters enormously. If you double the length of the sequence, the attention computation doesn't just double — it roughly quadruples, because every token now has to be compared against twice as many other tokens. Technically this is what engineers call quadratic scaling: the cost grows with the square of the sequence length. Double the context, four times the computation. Triple it, nine times. This isn't a problem someone failed to solve; it's a hard property of how attention works. Longer context is expensive in a very literal sense — more memory, more processing time, more energy, and more cost per query. That's why context length is both a technical limit and an economic design choice.
So the context window is measured in tokens, not words. Tokens — the chunks of subword text described in the section on tokenization — average out to roughly three-quarters of a word in English, which means a 4,000-token context window can hold something like 3,000 words of English text. A 128,000-token window, which exists in some current systems, can hold roughly 96,000 words — approximately a full-length novel. But that estimate shifts depending on what you're feeding the model. Code tends to tokenize differently from prose. Highly structured data like JSON can be very token-hungry. And as the tokenization section covered, languages other than English often require more tokens per word, which means non-English users get effectively shorter contexts for the same nominal limit.
This brings up the practical arithmetic of what actually lives inside a context window during a real conversation. The full context at any given turn has three pieces. First, there's the system prompt — a block of text that the developer or the platform has placed at the very beginning, before you ever typed anything. You usually don't see it. In consumer ChatGPT, OpenAI uses system prompts to give the model its instructions, its personality, its behavioral constraints, and sometimes specific information about the deployment context. In enterprise deployments, companies inject custom instructions — things like "you are a customer support agent for Acme Corp, always respond in Spanish, never discuss competitor products." The system prompt can be just a few sentences or it can be thousands of tokens long. It eats into the available context before you've said a single word.
Second comes the conversation history: the complete transcript of everything said in this session so far, both your messages and the model's responses, going back to the beginning. Third is your current message. Add those three together and you get the full context that the model reads at each turn. The model doesn't "remember" previous turns in any special way — it just rereads the whole transcript every single time. This is worth sitting with for a moment, because it's counterintuitive. When the model seems to remember that you mentioned you were writing a mystery novel four messages ago, it's not accessing a memory. It read the transcript. It saw that you said it. There's no storage happening; there's just one long document being processed fresh with each new reply.
What happens when that document gets too long? This is where the context window limit bites, and it bites in ways that can catch you off guard. Different systems handle the overflow differently. Some truncate the oldest content first — they drop the earliest messages in the conversation to make room for new ones. This means the model can suddenly seem to forget things it knew at the start of a long session, not because it's confused but because those messages are literally no longer in the window. Other systems may summarize older content. Some applications built on top of these models implement their own context management logic in code. But in all cases, once a conversation exceeds the context window, the model loses access to whatever got pushed out, and no amount of prompting will bring it back — because it's not there to retrieve. There is no background storage that a clever question can access. This is the "flat document" nature of the context window: it doesn't have depth, only length.
This is also exactly why ChatGPT has no memory of last week's conversation. Each new conversation starts with a fresh, empty context window — just the system prompt, then your opening message, nothing else. The previous session's transcript is not there. From the model's perspective, you are a stranger it has never spoken with. This surprises people who experience ChatGPT as feeling so consistent and personable, but that consistency comes from the training — from the model's baked-in style and values — not from any accumulated knowledge of you specifically.
The "memory" features that some AI products advertise — including features OpenAI has added to ChatGPT — work by addressing this limit through external storage, not by expanding the context window. The basic approach: a separate system stores notes about you or summaries of past conversations in a database. When you start a new session, the system retrieves the relevant notes and injects them into the system prompt or the top of the context. The model then reads those notes as text, just like it reads anything else. So when ChatGPT seems to "remember" that you have a dog named Biscuit, it's because a note about Biscuit was retrieved from that external store and pasted into the context before your message arrived. It's an elegant workaround — but it is a workaround, not a true persistent memory. The model still has no independent recollection; it read a note.
Now, the size of context windows has grown substantially in recent years, and that growth is genuinely meaningful. Early GPT-3 deployments worked with a 2,048-token context window — about 1,500 words. ChatGPT launched with a 4,096-token window. Subsequent versions pushed to 8,000, then 32,000, then 128,000 tokens and beyond. The Illustrated Transformer guide from Jay Alammar describes the original sequence length as a hyperparameter — something set by the designer — which captures exactly the right intuition: context length is a choice, constrained by cost and architecture, not a physical law of the universe. Longer windows opened up entirely new use cases. With 128,000 tokens, a user can paste in an entire codebase, a lengthy legal document, or a long research paper and ask questions about it. Tasks that previously required elaborate chunking and summarization pipelines can now be done in a single context.
But longer contexts don't solve everything, and they introduce their own subtleties worth knowing. One practical issue is what researchers sometimes call "lost in the middle" — the tendency for models to pay more reliable attention to content at the very beginning and the very end of a long context, with material buried in the middle getting less reliable treatment. If you're feeding a long document into a context window and expecting the model to catch a specific detail that appears in the middle, it may miss or underweight it in ways it wouldn't if the same detail were near the top or bottom. This isn't a universal failure, but it's a pattern worth keeping in mind when you're doing tasks like contract review or document analysis.
The system prompt deserves a bit more attention because it does more than many users realize. It is the mechanism by which different products built on the same underlying model can behave so differently. The Claude you might use through Anthropic's interface, the ChatGPT you use at OpenAI's website, and a custom customer service bot deployed by a retailer might all be running on architecturally similar transformer models with similar capabilities — but their system prompts shape their personality, their limits, their knowledge of their role, and their behavioral defaults so thoroughly that they feel like different tools. A system prompt can instruct a model to always respond in a particular language, to refuse to discuss certain topics, to adopt a specific persona, to always format responses as structured lists, or to treat certain embedded documents as its primary reference. From inside the conversation, you usually can't see the system prompt, but its effects are everywhere.
This is also why so-called "jailbreak" attempts — prompts designed to make a model abandon its instructions — so often target the system prompt indirectly. If someone can convince a model that its system prompt should be ignored, or that a new instruction supersedes it, the behavioral constraints soften. This is an active area of model safety research, and it illustrates something interesting: the model's "values" and "rules," at least in their immediate operational form, are text in a context window. They're not hardwired like firmware. They're instructions being processed the same way everything else is.
The practical implications of all this are worth spelling out directly, because they change how you should interact with these tools when the stakes are high. In a long conversation, if you've established important constraints or specifications early on — say, you told the model you're writing a novel set in 1920s Chicago, or that all your code should use Python 3.12, or that responses should always be under 200 words — those constraints live in the early messages of the conversation. As the conversation grows and older messages potentially get truncated, those constraints may fall out of the model's view. The model isn't being careless; it literally can no longer read them. The practical response is to restate key constraints periodically in long sessions, or to move critical instructions into a custom system prompt if the platform allows it.
Similarly, if you're working on a long piece of writing and you paste the current draft into the conversation at the start, that draft takes up tokens. Every revision, every back-and-forth, consumes more. By the time you're deep into a long editing session, the original draft may no longer be in the window, and the model may be working from an implicit reconstruction of what the document contains rather than the actual text. For careful document work, it's worth re-pasting the current version explicitly rather than assuming the model is tracking all the changes.
There is something philosophically interesting lurking in all of this. The context window is the model's entire world during a conversation — not a window into a larger mind, but the complete and total scope of what it can know about this interaction. Everything the model does: its understanding of your intent, its awareness of what was said three exchanges ago, its ability to maintain a consistent character, its capacity to follow a long chain of reasoning — all of it is happening inside that one flat text sequence. The sophistication of what the model can do within that window is genuinely remarkable. But the window's boundaries are absolute.
That's the context window: not just a technical parameter, but the fundamental shape of how these models experience a conversation. It's finite working memory, measured in tokens, expensive to extend, and carrying within it everything the model can see at once — your history, its instructions, and your next question.
What the context window can't do, though, is guarantee that everything inside it gets used accurately. The model reads everything in context, yes — but reading isn't the same as knowing, and a long document full of facts doesn't prevent a model from generating something plausible that contradicts them. That tension — between the model's access to information and its tendency to generate confident text regardless of whether that text is accurate — is what the next section takes on directly.
12Hallucinations, Confabulations, and Why ChatGPT Makes Things Up
A lawyer in Chicago once cited six cases in a federal court filing — and all six turned out to be completely fabricated. The cases had realistic-sounding names, plausible docket numbers, and citations to real courts. None of them existed. The lawyer had used ChatGPT to research precedent, and ChatGPT had invented the citations with complete confidence. That story broke in 2023, traveled around the world, and became the symbol of a problem that researchers had been quietly worrying about for years.
That problem has a name. It's called hallucination, and understanding it — really understanding it, not just knowing the word — changes how you use these tools forever.
This section is about what hallucinations actually are, where they come from mechanistically, why they're not an accident or a bug, and what you can realistically do about them. There are several distinct failure modes here, and they have different causes and different remedies, so the time goes into sorting them out carefully.
Start with the definition, because the word "hallucination" gets used loosely in a way that muddies the water. In the context of large language models, a hallucination is a piece of information the model states with confidence that is false or simply fabricated — not paraphrased incorrectly, not hedged with uncertainty, but stated as though it were a known fact. The fabricated court cases are an extreme example. More common ones are subtler: a model that gives you a real scientist's name but wrong dates for their work, a model that invents a statistic that sounds plausible for the context, a model that describes a feature of a software library that doesn't exist. The throughline is confident falseness.
The word itself is borrowed from psychology, and the analogy is actually pretty good. A person who is hallucinating perceives something that isn't there — and the experience of perception is completely convincing to them. There is no internal signal that says "this is invented." The same thing is true of ChatGPT. There is no internal alarm that fires when a generated sentence contains false information. The system generating the sentence has no access to ground truth against which to check itself. It is doing exactly one thing: producing text that is plausible given everything that came before it.
This is the key insight, and it traces directly back to the core mechanism that earlier sections of this course have been building toward. As Stephen Wolfram explains in his 2023 deep-dive on what ChatGPT is doing, the system is always fundamentally trying to produce a "reasonable continuation" of whatever text it's received — where "reasonable" means something like "what one might expect someone to write after seeing what people have written on billions of webpages." It is not consulting a database of verified facts. It is not searching the internet. It is completing text in a way that fits the patterns it learned from training. When the text so far says "the ruling in Smith v. Jones established that," the model's job is to generate what plausibly comes next — not to check whether Smith v. Jones is a real case.
This is why hallucinations aren't bugs. They are a direct and predictable consequence of the system's design. Removing them entirely would require changing what the system fundamentally is.
Stay with that for one more step, because it's worth sitting with the implication. The model is a pattern-completion engine of extraordinary sophistication. According to IBM's overview of large language models, LLMs work as "giant statistical prediction machines that repeatedly predict the next word in a sequence." They learn patterns in text and generate language that follows those patterns. The patterns learned from billions of documents encode a tremendous amount about how the world works — syntax, facts, causal relationships, professional conventions, the way citations look, the way scientific papers sound. But "knowing how something sounds" is categorically different from "knowing whether it is true." A model that has read thousands of legal documents knows what a case citation looks like. It can generate a completely convincing fake one without any awareness that it's fake.
That distinction — plausible text versus verified fact — is the fundamental thing to hold onto when thinking about hallucinations. And once you hold it, a lot of otherwise puzzling behavior starts to make sense.
Here's the part that catches most people off guard: the model doesn't know what it doesn't know. A human expert who's uncertain about something typically signals that uncertainty — they hedge, they say "I think," they recommend you verify. A language model has learned from text written by humans, so it has also learned that confident, declarative prose is common, and it reproduces that register fluently. But the confident tone in the output carries no actual information about the model's "certainty" — because the model doesn't have certainty in any meaningful sense. It has a probability distribution over next tokens. The probability distribution doesn't track truth; it tracks fit with patterns in training data.
This means confident tone does not correlate with accuracy in language models, which is the single most practically important thing to understand about hallucinations. A model that is wildly wrong can sound exactly as assured as a model that is correct. The register of the text — formal, authoritative, specific — is itself just another pattern that the model reproduces. When you ask for information in a professional context, the model has learned that professional contexts produce confident declarative sentences. So you get confident declarative sentences, regardless of whether the content is accurate.
Now for an important nuance: hallucinations are not evenly distributed across topics. The model is far more likely to make things up on obscure subjects than on well-documented ones. This follows directly from how training works. Consider a major historical event that was covered in thousands of books, Wikipedia articles, news archives, and academic papers. The patterns for describing that event are deeply reinforced in the model's weights — there is massive redundancy, and deviations from accurate description would have been averaged out by sheer volume of consistent data. Now consider a minor academic paper published in a small journal, a mid-list author from the 1980s, a niche regulation in a specific industry, or a software library with limited documentation. The training data for those topics is thin, maybe a handful of documents. The model has a weak, poorly reinforced signal about them. When asked, it generates something that fits the general shape of what such information would look like — but the specific details are largely interpolated from surrounding patterns rather than reliably encoded.
This is why researchers and practitioners have noticed a consistent pattern: LLMs tend to be reliable on things that appear frequently in text, and unreliable on things that are rare, obscure, or technical in narrow ways. Ask ChatGPT about how photosynthesis works and you'll probably get something accurate. Ask it to describe a specific 2003 court ruling in a niche area of environmental law and you are in much more dangerous territory. The model will sound equally confident either way.
There's a related failure mode worth separating out: the knowledge cutoff. This is a different problem from hallucination per se, but it can look the same from the outside. Every LLM has a training cutoff — a date beyond which it has seen no data. ChatGPT, for example, doesn't know about events that happened after its training data was assembled. If you ask about something that occurred after the cutoff, the model faces a choice between saying it doesn't know and generating something plausible-sounding anyway. The second option is dangerous, and the model sometimes takes it. The result looks like hallucination — confident wrong information — but it's better described as outdated information or, in worse cases, confabulation in the absence of relevant training signal. As of May 2026, this matters practically whenever you're asking about recent events, recently released products, recent research, or anything that changed after the model's training window closed.
Now let's look at the different shapes hallucinations take, because the failure modes aren't all identical.
The most straightforward type is factual error on a checkable claim — a wrong date, a wrong name, an incorrect statistic. These are genuinely the easiest to catch, because you can verify them with a quick search. The more insidious type is the invented citation — the fake study, the fabricated book, the fictional court case from the opening of this section. These are dangerous precisely because they have the texture of real sources. A fabricated citation includes enough realistic detail that a person who doesn't check it will accept it. The model isn't "trying" to deceive; it has learned that a sentence like "according to [Author], in [Journal], [Year], ..." is a common pattern in authoritative text, and it completes the pattern. The author, the journal, and the year are filled in the way any other missing tokens would be — with what fits probabilistically.
A third type is the invented person or event. Ask ChatGPT about an obscure historical figure in a niche field, and there's a real chance the model constructs a plausible-sounding biography for someone who didn't exist, or conflates two real people into one composite. Ask about historical events in poorly documented periods and the model may produce confident narrative that reads like history but is largely constructed. These are particularly hard to catch because the listener — the person asking — often doesn't know enough about the topic to spot the errors. You sought the model's help precisely because you didn't already know.
This is where a thought experiment called the "stochastic parrot" critique becomes worth examining. The phrase comes from a 2021 paper by Emily Bender, Timnit Gebru, and colleagues, which argued that large language models are essentially very sophisticated pattern-matchers that stitch together fragments of text without any underlying understanding or meaning. A stochastic parrot, in their framing, produces statistically coherent sequences of words without having any model of the world those words describe. This critique captures something genuinely important about hallucinations: the model doesn't "know" things the way you know things. It has learned that certain words follow other words in certain contexts, and it generates accordingly.
But the stochastic parrot framing also misses something. A model that produces useful code, that translates between languages it wasn't explicitly trained on together, that reasons through multi-step problems — that model is doing something more than blind pattern-matching, even if we're not quite sure what to call it. The hallucination problem doesn't mean the model has no knowledge; it means the model's knowledge is unevenly encoded, isn't directly accessible to the model for self-verification, and can be overwhelmed by the pressure to produce plausible-sounding text. The stochastic parrot critique is most right about edge cases — obscure topics, rare facts, invented citations — and least right about well-represented knowledge that has been deeply reinforced by massive data.
Now to the question of what's being done about this, and what can actually be done.
One significant intervention is Reinforcement Learning from Human Feedback — RLHF — which earlier sections of this course covered in detail as the mechanism that transforms a raw pretrained model into the helpful assistant users interact with. RLHF does help with hallucination. When human raters consistently downgrade outputs that contain obvious false claims, the reward model learns to penalize that kind of output, and over time the policy shifts toward responses that are more accurate and more likely to express appropriate uncertainty. This is why a well-tuned model like ChatGPT is less likely to confidently fabricate information than a raw pretrained model would be. But RLHF cannot eliminate hallucinations, for a simple reason: the reward model itself was trained on human judgments, and humans can't reliably detect all false information in all domains. If a model produces a plausible-sounding fake citation and the human rater happens not to know the field well enough to spot it, the reward model gets no signal that this was a hallucination. The problem slips through.
A more structural intervention is retrieval-augmented generation, usually called RAG. The core idea behind RAG is to give the model access to a verified external knowledge base at the time of generation — not as training data, but as live context. When a question comes in, a retrieval system finds relevant documents or passages from a curated source, and those are inserted into the model's context window along with the question. The model is then effectively being asked to answer based on the retrieved documents rather than solely from what's encoded in its weights. This dramatically reduces hallucination in the domains covered by the knowledge base, because the model is grounding its response in retrieved text rather than generating from scratch. RAG is now widely used in enterprise applications of LLMs precisely because it makes the factual behavior much more predictable and trustworthy.
The catch is that RAG doesn't eliminate the underlying problem — it works around it. The model can still misread the retrieved documents, paraphrase inaccurately, or fail to retrieve the right context when the query is ambiguous. And for questions outside the knowledge base's coverage, the model is back to generating from its weights, with all the associated risks. RAG is powerful and practical, but it's a mitigation, not a cure.
So what does this mean practically for you, sitting in front of ChatGPT trying to get something useful done?
The most important heuristic is to match your verification behavior to the stakes and the obscurity of the topic. For common, well-documented topics — explaining a concept, drafting a document, summarizing a well-known event, brainstorming — the model is generally reliable, and the occasional small error is easy to spot and fix. For anything that will be published, cited, submitted, or relied on professionally — especially in law, medicine, finance, or science — verify independently. Don't ask the model whether a citation is real; go check. Don't assume a statistic came from a real study; find the study. This isn't a counsel of despair about the technology; it's the same standard you'd apply to any source that hasn't been verified by an editor.
Second, treat the model's hedging — when it appears — as genuinely informative. Phrases like "I'm not certain about this" or "you may want to verify" are signals that the model has lower confidence, and they're worth taking seriously. The trouble is that such signals are inconsistently applied; the model doesn't always hedge when it should. But when it does hedge, pay attention.
Third, recognize that the confidently wrong answer is more dangerous than the honest "I don't know." A well-calibrated model is one that acknowledges the limits of its knowledge. OpenAI and other labs have been working to improve this calibration, but as of 2026, it remains imperfect. You can sometimes encourage better calibration by explicitly inviting the model to express uncertainty: asking "if you're not sure, please say so" sometimes shifts the response toward more appropriate hedging.
Fourth — and this is especially relevant for the knowledge cutoff problem — if you're asking about anything recent, explicitly tell the model that you're asking about something that may postdate its training, and ask it to flag if the answer might be out of date. This doesn't magically give the model information it doesn't have, but it does reduce the chance of a confidently-delivered outdated answer being mistaken for a current one.
The hallucination problem is real, it is structural, and it is not going away entirely. But understanding it mechanistically — as a consequence of how the system works, not as a random failure — makes it navigable. The system generates plausible text. Plausible text often happens to be true, because the world is regularized and the patterns of true things appear repeatedly in training data. But sometimes plausible text is false, invented, or outdated — and the model has no way of knowing the difference. That's the thing to hold onto.
Which raises a deeper question: if the model can't reliably distinguish what it knows from what it's confabulating, what exactly does it mean for a model to "know" something? That's the genuinely strange territory the next section enters — exploring what's actually happening inside a large language model when it seems to reason, translate, or solve problems it was never explicitly trained for.
13What ChatGPT Actually Knows (And How It Knows It): Emergent Capabilities Explained
Imagine taking an exam you've never studied for, in a subject nobody told you to prepare for, and scoring in the ninety-fifth percentile. That is, roughly speaking, what researchers watched GPT-4 do on the Uniform Bar Examination — a test that takes most law school graduates months of deliberate preparation to pass. Nobody programmed the model to study contract law. Nobody gave it a legal reasoning module. It arrived at those results the same way it arrives at everything: by having processed an incomprehensible quantity of human text and learned, with extraordinary fidelity, how that text continues.
That's where the last section left off — the question of confidence and what a model actually knows versus what it confidently generates. But there's a deeper mystery underneath it. The hallucination problem raises the question of when models get things wrong. This section asks the harder question: how do they get so much right, in ways that nobody expected, on problems nobody asked them to solve?
Here's the territory to cover: what those surprising capabilities actually are, where researchers think they come from mechanistically, what the best current theories say about what's happening inside a model when it reasons, and — honestly — what remains genuinely unknown.
Start with the surprise itself, because it is real. When GPT-3 arrived in 2020 with 175 billion parameters, researchers at OpenAI ran it through a battery of benchmarks. They expected improvements. What they did not expect was a behavior that came to be called in-context learning. A 2023 explainer from Understanding AI by Tim Lee and Sean Trott of UC San Diego describes how the general public had not been paying close attention to large language models until ChatGPT's debut, and didn't realize how powerful they had become. But even the researchers who had been paying close attention were surprised. Here is what in-context learning actually looks like.
You write a prompt. In that prompt, you include a few examples of a task — say, translating English phrases into French. Then you add a new English phrase and ask the model to translate it. The model does this correctly, without any fine-tuning, without any gradient updates, without any change to its underlying weights. It reads the examples, infers the pattern, and applies it to something new — all from a standing start, from inside a single forward pass through the network. This was a watershed. Before GPT-3, the standard assumption was that a model needed to be retrained — or at least fine-tuned — on new tasks. In-context learning showed that wasn't true. A large enough model could, in effect, learn from examples you handed it at runtime.
Stay with this for one more step, because it deserves unpacking. The model's parameters didn't change. Its weights — all 175 billion of them — stayed exactly as the pretraining process had set them. And yet, presented with three examples of a pattern, the model generalized to a fourth case it had never seen in those weights. This is not how a lookup table works. A lookup table returns what it has. This model was doing something that looked, from the outside, disturbingly like reasoning.
The in-context learning finding wasn't an isolated curiosity. A second discovery followed that pointed in the same direction, and it came from a deceptively simple change in how you phrase a question.
Chain-of-thought prompting is the technique of asking a model not just for an answer but for its reasoning. Instead of typing "What is 23 times 47?" you type "Let's think step by step. What is 23 times 47?" The results were striking enough that researchers at Google Brain published a paper on it, and the finding has been replicated widely since. When prompted to reason explicitly, models make significantly fewer errors on tasks involving multi-step arithmetic, logical inference, and symbolic reasoning. The improvement isn't marginal — on some benchmarks, it's the difference between performance that looks like guessing and performance that looks like competence.
Why would that work? The most intuitive explanation is also the most interesting one. When a model generates each token, it only has access to the text that came before. If you ask for the answer directly, the model has to arrive at it in one step — the reasoning has to happen "inside" the weights, invisibly. But if you ask the model to show its work, the intermediate steps become part of the context. Each reasoning step becomes text, and that text is then available as input for the next step. The model is, in a sense, using the page as scratch paper. It's offloading part of the computation into the context window, where the next token can benefit from it.
This is a mechanistically coherent explanation. It doesn't require the model to be conscious or to genuinely understand. It requires only that the model be very good at predicting what plausible reasoning steps look like — which, having trained on billions of documents including textbooks, scientific papers, and worked examples, it happens to be. As Stephen Wolfram noted in his 2023 essay on what ChatGPT is doing and why it works, what ChatGPT is always fundamentally trying to do is produce a reasonable continuation of whatever text it's got so far — where "reasonable" means something like "what one might expect someone to write after seeing what people have written on billions of webpages." Chain-of-thought works, at least in part, because good reasoning looks like something in text, and the model has seen a lot of it.
That leads directly to a genuinely fascinating and contested question — one that cuts to the heart of what it means to say a model "knows" something.
Consider what it would mean for a system to know a fact. For a human, knowing something involves a web of connected concepts, causal stories, the ability to generate examples, the ability to recognize when the fact is relevant, the ability to notice when apparent instances of the fact are actually exceptions. Knowledge, in the human sense, is thick — embedded in memory, connected to experience, integrated into judgment. A model's "knowledge" is different in kind. As Tim Lee and Sean Trott explain at Understanding AI, language models represent words using vectors — long lists of numbers where words with similar meanings are placed closer together in an abstract space. What a model "knows" is encoded in the geometry of that space and in the billions of weights that determine how tokens relate to each other. It is statistical through and through. There's no episodic memory. There's no causal model of the world in any human sense.
And yet — the model's performance on tasks that require connected, multi-step knowledge is sometimes extraordinary. Translate a passage from a language the model saw rarely in training. Explain the legal implications of a hypothetical contract dispute. Write working code that solves a novel algorithmic problem. These are not tasks that admit of pure pattern-matching without something like comprehension. Or are they? This is where the debate gets genuinely hard.
One camp holds that what looks like reasoning is extraordinarily sophisticated pattern completion — that the model has memorized not just facts but reasoning patterns, and that what appears to be novel reasoning is actually recombination of those patterns in ways that happen to work. The analogy here is to a student who has studied so many worked examples in calculus that they can solve new problems by analogy even without fully understanding the underlying principles. The answers are right, but the process is different from what we call understanding. This view is not dismissive — it takes seriously just how much can be achieved through statistical pattern completion at scale. But it draws a firm line between performance and comprehension.
The other camp points out that the distinction between "pattern completion" and "reasoning" is less obvious than it sounds. Human reasoning is itself implemented in biological neural networks that were shaped by something like natural selection rather than conscious design. When a human mathematician solves a new problem, they are also, in some sense, applying patterns learned from prior experience. If a model can translate a passage from a low-resource language, adapt its writing style to a new rhetorical context, explain why a proof is wrong and suggest a fix, and do all of this with minimal prompting — at what point does "sophisticated pattern matching" become a distinction without a difference?
This is precisely the territory the Chinese Room thought experiment was designed to illuminate. Proposed by philosopher John Searle in 1980, the argument goes like this: imagine a person in a room who receives Chinese characters, looks up rules in a rulebook for how to respond to them, and passes back appropriate Chinese characters — all without understanding a word of Chinese. From outside, the room appears to understand Chinese. From inside, there is no understanding at all, just symbol manipulation. Searle's conclusion was that syntax — the manipulation of symbols according to rules — is not the same as semantics — genuine meaning and understanding.
The Chinese Room argument still provokes debate, and it's worth being precise about what it does and doesn't tell us about large language models. What it clearly establishes is that behavioral indistinguishability from understanding is not proof of understanding. A system that produces correct outputs doesn't, by that fact alone, possess comprehension. That's an important caution. But the argument also has limits in this context. The original thought experiment imagines a finite rulebook — a lookup table, essentially. A large language model isn't a rulebook. It's a massively connected, continuously valued, dynamically computed function over an enormous parameter space. Whether Searle's point applies to such a system in the same way it applies to a person with a dictionary is, genuinely, unclear. The analogy may not translate.
What can be said with more confidence is this: there is a striking asymmetry in how LLMs perform, one that is genuinely diagnostic. Large language models are measurably better at recognizing correct answers than at generating them reliably from scratch. Give a model a multiple-choice problem and four possible answers, and it will often identify the right one even when it wouldn't have produced that answer if asked to generate it openly. This is not the profile of a system that has deep understanding in the human sense — a person who truly understands a concept can generate answers from first principles, not just evaluate pre-formed options. But it also isn't the profile of random noise. It suggests that something real is being encoded — some compressed representation of what good answers look like — even if that representation isn't organized the way human knowledge is.
To get more concrete about what is actually inside these models, a field called mechanistic interpretability has emerged. The goal is ambitious: take an existing trained model and reverse-engineer what individual components are actually doing. As Tim Lee and Sean Trott describe at Understanding AI, because these systems were built through training rather than explicit programming, no one on Earth fully understands their inner workings — and researchers working to gain that understanding estimate it could take years to decades. Mechanistic interpretability is one path into that understanding. Researchers have identified what they call "circuits" — small subgraphs of the network's attention heads and feed-forward layers that appear to implement specific computations. Some circuits seem to implement something like indirect object identification — tracking which noun a pronoun refers to. Others seem to implement factual recall — looking up a stored association between a subject and a predicate. Still others seem to do something that looks like arithmetic.
These findings are exciting because they are specific. Rather than treating the model as an inscrutable black box, mechanistic interpretability claims to identify what individual components are computing. But they come with important caveats. Most of this work has been done on models much smaller than the systems actually deployed. The findings don't straightforwardly generalize — a circuit that handles pronoun resolution in a small model may not be implemented the same way in a model one hundred times larger. And the circuits identified so far account for a tiny fraction of what these models can do. The field is young, the models are vast, and humility is warranted.
The concept of emergent abilities adds another dimension to this picture. Emergent abilities are capabilities that appear in large models but not in smaller ones — capabilities that weren't present at smaller scales and couldn't be predicted by simply extrapolating from smaller-model performance. A model with one billion parameters might fail completely at multi-step arithmetic reasoning. A model with one hundred billion parameters might do it reliably. The capability didn't grow gradually; it appeared, roughly abruptly, past a threshold. Chain-of-thought reasoning is a canonical example. So is the ability to perform well on certain translation tasks into low-resource languages. So is performance on some science and logic benchmarks that require multi-step inference.
The mechanistic explanation of emergence is still under active investigation. One theory holds that some capabilities require the model to have enough "space" — enough representational capacity — to encode multiple sub-skills simultaneously, and that performance on a complex task jumps when all those sub-skills cross some threshold together. Another theory holds that emergence is partly a measurement artifact — that performance on some benchmarks looks like a step function because the benchmarks use pass-or-fail grading, and underlying capability actually grew smoothly. Both theories may be partly right. The honest answer is that emergence is real and reproducible but not yet fully explained.
All of this points to a genuinely interesting place to land. Stephen Wolfram, in his 2023 essay on what ChatGPT is doing, frames it well: the remarkable thing is not just that the model produces reasonable text, but that producing reasonable text — at scale, over vast amounts of human writing — seems to require the model to have learned a great deal about the structure of the world. Language is not arbitrary. The words that follow plausibly from "the treaty was signed because..." reflect something about how causality works, how diplomacy works, how historical narratives are structured. A model that can continue such sentences reliably has encoded, in some form, something about those structures.
What the model has is not knowledge in the human sense. It has no experiences, no causal model of the world, no memory that persists across conversations, no awareness of its own errors. It cannot verify claims against some internal source of truth. It is, in the most precise sense available, a very sophisticated pattern-completion engine — one that has compressed an extraordinary amount of human thought into a very large set of numbers. But the patterns it has learned are not shallow. They include patterns of logical structure, patterns of causal reasoning, patterns of evidence and argument. The model that can write a coherent legal brief or debug a recursive algorithm has learned something about what those things look like from the inside.
The honest assessment, as of 2026, is this: researchers know that scale produces capabilities that weren't anticipated, that chain-of-thought and in-context learning are real phenomena with partial mechanistic explanations, and that the model's internal representations encode meaningful structure. What they don't know is whether this adds up to something that should be called understanding, or whether understanding is even a useful category for this kind of system. The question "does ChatGPT really know what it's saying?" turns out to be as much a question about what "know" means as it is about the model.
That ambiguity isn't a flaw in the research. It's the most honest thing that can be said. And it sets up the practical question that follows directly from it — once you know what these systems can and can't actually do, how do you use them well, and how do you build systems around them that extend their reach without amplifying their blindspots?
14Conclusion
Every section of this course has been, underneath its specific subject, about the same thing: what it actually means for a machine to handle language. Not simulate handling it, not fake it well enough to fool you — but genuinely process the structure of human communication at a scale and depth that produces something worth taking seriously. That through-line started with a question most people thought they already knew the answer to and ended somewhere they probably didn't expect to go.
Remember the lawyer in Chicago who walked into federal court with six perfect-looking case citations, every one of them fictional. That story from Section 11 isn't just a cautionary tale about professional negligence — it is the clearest possible illustration of the thing Section 1 tried to establish at the very beginning: this system is not looking anything up. It never was. And once that fact lands, everything else in the course — the geometry of meaning, the way attention resolves "it" back to the animal and not the street, the moment in Section 9 where a 117-million-parameter model became a 175-billion-parameter model and capabilities stopped scaling and started leaping — all of it coheres into a single picture. The system learns the shape of human thought well enough to continue it. That's the whole trick. That's the entire magic show.
And then there's the bar exam. GPT-4 scoring in the ninety-fifth percentile on a test nobody trained it for, in a domain it was never handed directly, because somewhere in the pattern-completion machinery something that looks troublingly like reasoning emerged on its own. Whether that constitutes understanding or extraordinarily sophisticated mimicry of understanding turns out, as Section 12 argued, to be less a technical question than a philosophical one — and the honest answer is that nobody fully knows.
That's the sentence you could say at dinner tonight: ChatGPT isn't a database that learned to speak — it's a pattern-completion engine trained to predict what comes next, and almost everything it does, right and wrong, flows directly from that.
What the course has really been building toward is a particular kind of clarity — the kind where you can hold the marvel and the limitation in the same hand without needing to resolve the tension. These systems are extraordinary. They are also genuinely strange. Both of those things are true, and now you know why.
Sources & References
This course draws from the following sources. Visit them for additional depth.
- 🔗
- 🔗
- 🔗
- 🔗huggingface.co — Rlhf ↗webpage
- 🔗
- 🔗
- 🔗huyenchip.com — Rlhf ↗webpage
- 🔗
- 🔗
Listeners Also Played
Linux Under the Hood: How a Modern Operating System Actually Works
A deep dive into Linux internals for developers and sysadmins who know the command line and want to understand what's really happening beneath it. Covers the kernel's architecture, processes, memory management, the Virtual File System, system calls, scheduling, signals, interrupts, and /proc — building genuine intuition for how Linux works, not just how to use it.
OpenClaw: The Complete Beginner's Guide to Your Self-Hosted AI Assistant
A practical, security-honest guide for non-developers who want an AI assistant that actually does things — sending messages, managing calendars, running automations — instead of just answering questions. Starting from zero, this course builds a working OpenClaw installation connected to real apps, with equal attention to capability and the genuine risks that come with giving AI the power to act.
Spreadsheets From Scratch: A Complete Beginner's Guide to Google Sheets
A ground-up introduction to spreadsheets for anyone who has ever felt intimidated by a grid of cells. Using Google Sheets as the hands-on platform, this course builds your understanding from core concepts all the way through formulas, charts, and real-world data tasks — no prior experience required.
Want a course that doesn't exist yet? Request one →