Knowledge Base · Learning paths
How to Build Your Own LLM from Scratch: The 5-Stage Pipeline Behind GPT and Claude
Leading LLMs like GPT and Claude are built through a five-stage pipeline: data preparation, pre-training, supervised fine-tuning, reward modeling, and reinforcement learning. This guide breaks down the core principles and practical steps of each stage, helping you build a clear mental model of how raw text transforms into intelligent AI assistants.
Translated from Chinese by AI. Spotted an issue? Use the feedback button.
Original post: https://x.com/eng_khairallah1/status/2073334640123769289
Most people use ChatGPT and Claude every day without having any idea how they are actually built.
Save this post :)
Only a small fraction of people truly understand the exact process: how raw internet text is transformed into a model that can write, reason, and code. Once you understand this pipeline, the way you use these tools will change forever — because you’ll finally see what’s happening under the hood instead of treating it as magic.
The difference between these two groups of people isn’t whether they have a math degree.
It’s whether they have a clear mental model.
Here’s a fact that almost no one explains in simple terms: every frontier model — GPT, Claude, and all the rest — is built using the exact same five-stage pipeline. What differs between companies is scale, data, and countless engineering details, but the overall shape of the process is the same everywhere. Once you learn this shape, you’ll understand how all of them are made.
Before we begin, let me set an honest expectation. You cannot train a model that rivals GPT or Claude from scratch on your laptop. These models require tens of millions of dollars in compute and large engineering teams. But that’s not the goal here. The goal is to give you deep enough understanding of the pipeline that you can build a working miniature version yourself, reason about why large models behave the way they do, and stop seeing them as mysterious. This level of understanding is far more valuable than most people realize — and it’s completely within your reach.
Here are the five stages, in the order they actually occur.
Stage 1: Data — The Foundation Everything Is Built On
Before the model exists, there is text. An enormous amount of text.
The first stage is collecting and preparing the data that the model will learn from. For frontier models, this means an astonishing volume of text: vast portions of the public internet, books, code repositories, and many other sources. But raw text is extremely messy, so most of the work in this stage is not collection — it’s cleaning.
Data is filtered to remove garbage, duplicates are eliminated, and low-quality or harmful material is discarded. If the same paragraph appears a thousand times, it will distort what the model learns. This cleaning process is far more important than most people think. The old principle still holds: garbage in, garbage out. A model trained on cleaner, higher-quality data will often outperform one trained on larger but noisier data. Data quality is one of the most important yet least glamorous levers in the entire field.
Next comes a step that surprises most beginners: tokenization. Models cannot read text directly. Text is broken into tokens — roughly pieces of words. For example, the word “tokenization” might be split into three or four tokens. Every piece of training data is converted into these tokens. From that point on, the model only ever sees numbers representing tokens, never letters. This is why models sometimes miscount the number of letters in a word: they have never seen letters, only tokens.
The output of this stage is a massive, clean, tokenized dataset. The model has not yet learned anything. You have simply prepared the raw material.
How to learn this stage
- Feed text into a tokenizer and observe how it gets split into tokens to truly understand what tokenization does
- Take a small text dataset and practice cleaning it: deduplication, filtering junk, normalizing format
- Compare what small models learn from clean data versus messy data to see why data quality beats data quantity
- Read how the major labs describe their data filtering pipelines and note how much effort they invest in it
Stage 2: Pre-training — Where the Model Actually Learns Language
This is the stage that costs millions of dollars — and the phase where the model acquires almost all of its knowledge.
Pre-training has one remarkably elegant and simple objective: predict the next token. The model sees a sequence of tokens and is asked to guess what comes next. It makes a prediction, that prediction is compared to the actual next token, and the billions of numbers inside the model (its parameters) are slightly adjusted so it will guess slightly better next time. Then it repeats. Again and again. Across trillions of tokens.
That’s the entire training objective. At massive scale, the model simply predicts the next token over and over. And from this seemingly absurdly simple goal, remarkable capabilities emerge. To become better at predicting the next token across all of human text, the model is forced to learn grammar, facts, reasoning patterns, coding syntax, and argumentative structures — because all of these help it predict more accurately. No one explicitly teaches it grammar. It learns grammar because grammar helps it guess the next word.
The result of pre-training is called a base model. It is a powerful language engine, but still quite raw. A base model doesn’t know it’s supposed to be a helpful assistant. Ask it a question and it might simply continue your sentence or generate something that looks like another question, because all it has learned is to continue text in a plausible way. It contains vast amounts of knowledge, yet has zero manners. It is an extraordinarily powerful tool that doesn’t yet know what its job is.
Understanding this stage is the biggest unlock in the entire article. Once you truly internalize that these models are fundamentally built to predict the next token at enormous scale, their fluency and hallucinations start to make perfect sense. They were built to continue text plausibly — not to tell the truth. Truthfulness must be added in later stages and through your own engineering.
How to Learn This Stage
- Internalize the “predict the next token” objective so well that you can explain it to a friend in one clear sentence.
- Train a tiny language model on a small dataset. Follow well-known beginner tutorials and experience the loop firsthand.
- Understand the relationship between parameters, data, and compute, and why scaling all three together improves the model.
- Observe how this single stage simultaneously explains why models are so fluent and why they confidently make things up.
Stage 3: Supervised Fine-Tuning — Teaching the Model to Be Useful
Now you take that smart but unruly base model and teach it what its actual job is.
The base model understands language but doesn’t know it should answer questions helpfully. Supervised Fine-Tuning (commonly abbreviated as SFT) is designed to fix exactly that. You show the model thousands of examples of the behavior you want: a question paired with a good answer, an instruction paired with the correct response, a problem paired with a clear solution.
The training method is the same as pre-training — still predicting tokens. But this time the data consists of carefully curated demonstrations that explicitly show how a helpful assistant should respond. The model learns the “useful” format: when it sees a question, it should generate a helpful answer instead of continuing the text or wandering off-topic.
The quality of these examples is extremely important. They are usually written or meticulously curated by humans. The volume of data is far smaller than in pre-training — sometimes just thousands or tens of thousands of examples instead of trillions of tokens — but the data is high-quality, intentionally designed, and purpose-driven. A relatively small number of excellent demonstrations can transform a raw base model into one that behaves like a proper assistant.
After SFT, you have a genuinely useful model. It follows instructions, answers questions, and stays on task. For many applications, this is already a working assistant. However, it has not yet reached the level of helpfulness, harmlessness, and polish you expect from the models you actually use every day. That is what the final two stages aim to achieve.
How to Learn This Stage
- Read responses from both base models and fine-tuned models side by side to clearly see the difference.
- Build or study a small instruction dataset: create question-answer pairs that demonstrate the behavior you want the model to exhibit.
- Fine-tune a small open-source model on a focused task and observe how its behavior changes.
- Pay attention to how much more important the quality of demonstration data is compared to its quantity.
Stage 4: Reward Modeling – Teaching the Model What “Good” Looks Like
This is the stage most explanations skip over, yet it is the subtle core that makes modern models so remarkably refined.
The problem labs faced after Supervised Fine-Tuning (SFT) was this: the model could now produce decent answers, but “good” proved extremely difficult to define through examples alone. For most questions, there is no single correct answer—only better ones and worse ones. If you can’t write explicit rules, how do you teach the model to prefer better answers?
The solution was elegant. You let the model generate several different answers for the same prompt. Then you ask humans to look at those answers and rank them: this one is better than that one. You collect a large amount of this human preference comparison data. Instead of using the comparisons directly, you train a second model called the reward model. Its only job is to look at any answer and predict how a human would rate it.
Think about what this achieves. It’s impossible to have humans evaluate every single answer the main model might generate in the future—that simply doesn’t scale. But you can train a reward model on a batch of human judgments. Now you have an automated surrogate that can represent human preferences and score millions of answers. The reward model bridges the gap between “what humans like” and “what a computer can optimize.”
The reward model never talks directly to users. It is a behind-the-scenes judge. Yet it is the key that unlocks the final stage, because it provides a way to push the main model toward answers that humans truly prefer—at a scale no human team could ever match.
How to Study This Stage
- Understand why ranking answers (“this is better than that”) is much easier and more scalable for humans than writing perfect answers
- Grasp the core idea: the reward model learns to imitate human judgments, automatically scoring answers
- Read about how preference data is collected through human comparisons
- See how this stage connects the messy reality of human taste to a clean signal that the training pipeline can optimize
Stage 5: Reinforcement Learning – Polishing the Model into the One You Actually Use
The final stage takes everything built so far and refines the model into the helpful, thoughtful, and careful assistant you interact with.
This stage is commonly known as RLHF—Reinforcement Learning from Human Feedback. The pieces fit together like this: you take the fine-tuned model from Stage 3 and the reward model from Stage 4. The fine-tuned model generates answers. The reward model scores them. The fine-tuned model is then gently updated through reinforcement learning to produce higher-scoring answers. It’s a loop: generate, score, improve, repeat.
Because the reward model can keep scoring indefinitely, the main model can practice and improve far beyond what direct human examples could ever provide. After many rounds, it becomes more helpful, more coherent, better at following subtle instructions, and better at refusing things it shouldn’t do. This stage gives the model its polished feel, good judgment, and a wide range of safety behaviors.
A modern variant worth knowing about is that some human feedback can be replaced or supplemented by feedback generated according to a set of written principles. This approach is sometimes called RLAIF or Constitutional AI. The spirit remains the same: instead of relying entirely on humans to evaluate everything, you scale up the feedback that shapes the model’s behavior under clearly stated values.
After this stage, you have the finished product—a model that gained fluency through pre-training, usefulness through fine-tuning, and refinement plus alignment through reinforcement learning. When you open ChatGPT or Claude, this is the model you are talking to. Five stages, each built on top of the previous one.
How to Study This Stage
- Understand the loop: the model generates, the reward model scores, and the model improves toward higher scores
- Realize why this allows the model to practice far beyond the limits of direct human examples
- Read about the difference between learning from human feedback and learning from principle-guided AI feedback
- See how this final stage produces the helpfulness, judgment, and safety behaviors you experience as a user
The Entire Pipeline Explained in One Breath
Let me tie it all together so it really sticks in your mind.
You collect and clean a mountain of text, turn it into tokens, and train a model to predict the next token across all that text. From this simple objective emerges a base model that understands language but has no manners. You fine-tune it with curated examples so it learns to behave like a helpful assistant. You collect human rankings of its answers and train a reward model to imitate human judgment. Finally, you use that reward model to refine the assistant through reinforcement learning until it becomes polished, helpful, and properly aligned.
Data, pre-training, fine-tuning, reward modeling, reinforcement learning. Five stages. Every frontier model is built this way.
The Real Story Behind Building Your Own LLM
You’re not going to build something that surpasses frontier labs from your bedroom—and that was never the point.
The point is understanding. Once this entire pipeline becomes clear in your mind, you stop being a passive user of these tools and start becoming someone who can truly reason about them. You understand why models hallucinate—because at their core they’re just predicting the next token. You understand why prompts work—because you’re shaping what will be predicted next. You understand why some models feel more “aligned” than others—because the quality of Stage 4 and Stage 5 differs. You understand why your own data matters so much in your personal fine-tuning experiments. This kind of understanding is the common foundation shared by the most capable AI builders.
The truly empowering part is this: for the sake of learning, you can build a tiny, working version of every single stage at a small scale. People constantly train miniature models, fine-tune small open-source models, and experiment with preference data. You won’t create Claude. But you can create something that gives you a genuine, first-hand understanding of how Claude was built—and that knowledge will compound throughout the rest of your career in this field.
Most people will use these models for years without ever understanding how they’re actually made.
You’ve just read the entire pipeline. You’re already ahead of nearly everyone who simply types prompts into these tools every day.
The only question left is: will you actually build a small version yourself and turn that understanding into something you can truly do?
The five stages are right above. Pick the first one and start.
If you found this useful, feel free to follow me @eng_khairallah1 for more content like this. I post breakdowns, courses, and tools every week.
Hope this helped, Khairallah ❤️