Train an LLM from Scratch: the Full Tutorial Repo

TL;DR
30 sec6 min coredeep dive optional

Train an LLM from Scratch is a free MIT repository that walks the entire training pipeline in seven steps, from downloading data and building a transformer piece by piece to aligning the result with DPO and chatting with it, and a free Colab GPU is enough to finish it.

  • Seven steps cover data, architecture from small pieces, pretraining, generation, post-training, evaluation, and a chat interface.
  • The 13-million-parameter track fits a free Colab or Kaggle T4; the 2-billion track fits a single 24GB consumer GPU.
  • Post-training includes SFT, a reward model, and reference-free alignment options like ORPO in one stage.
  • 10,905 stars, MIT, with a Streamlit control panel and a documentation site included.

Most explanations of how language models are built stop at the math and never show you the pipeline. Train an LLM from Scratch, at FareedKhan-dev/train-llm-from-scratch, is the other kind of resource: a repository where the full path from raw data to a chat-capable model is laid out as runnable code, and where a free cloud GPU is genuinely enough to complete the journey.

Train LLM from Scratch repository on GitHub showing the seven step pipeline from data preparation to chatting with the trained model

At 10,905 stars and trending this week, the repository has become the default answer to a specific question: not how do I use an LLM, and not how do I serve one, but what does it take to actually make one. This guide maps the pipeline, the hardware reality, and where an LLM from scratch build fits against the learning resources we have covered before, so you can decide in ten minutes whether your next free weekend belongs to it.

The seven steps, end to end

The repository is organized as a pipeline, and the order teaches as much as the content. Step one prepares real data: tokenization first, then the chat format with a loss mask, the detail that trains the model to produce assistant turns rather than imitate users. Step two builds the architecture from small pieces, multi-layer perceptron, single-head attention, multi-head attention, the transformer block, then the full stack, so each component is individually legible before it composes. Step three pretrains, step four generates text from the result, and step five is where most tutorials quietly end but this one continues: supervised fine-tuning, a reward model, and alignment algorithms including DPO, ORPO, and KTO, with ORPO available as a reference-free single stage that folds fine-tuning and alignment together. Steps six and seven evaluate the model and put a chat interface in front of it.

That completeness is the differentiator. The distance from tokens to an assistant you can talk to, executed rather than described, is what separates an LLM from scratch education from a paper summary.

The hardware truth, printed honestly

The repository publishes a GPU compatibility table instead of vague capability claims, and it changes who can participate. The 13-million-parameter track, the designed learning path, runs on a free Colab or Kaggle T4. The 2-billion-parameter track needs a single 24-gigabyte consumer card, a 3090, 4090, or the newer 5090, and an A100 reaches roughly 6 to 8 billion. Smaller cards scale down proportionally, with an 8-gigabyte 4060 topping out around a billion parameters. Memory-saving flags in the pretraining script, mixed precision, gradient checkpointing, and gradient accumulation, pull larger configs onto smaller boards when needed.

The honest framing that follows from the table: nothing here trains a frontier model, and nothing in the repository pretends to, which is rarer restraint than it should be. The scale is chosen so that every stage runs on hardware a learner can actually find, which is the entire pedagogical point. Learners with bigger ambitions get a clean scaling path instead of a wall: the same pipeline, larger configs, published limits per card.

What you actually learn that transfers

The transferable knowledge is not the model you end with, it is the judgment acquired at each stage. Data preparation teaches why chat formatting and loss masking decide whether a fine-tune produces an assistant or a parrot. Building the architecture piece by piece makes attention and the block structure concrete in the way our LLM concepts deep dive explains conceptually. Watching a loss curve descend on your own pretraining run calibrates expectations about what training progress looks and feels like. And running the alignment stage yourself, choosing between DPO and the reference-free ORPO, converts alignment vocabulary from discourse into configuration.

For engineers who work around LLMs daily, one run through this pipeline typically reorganizes their intuition: tokenizer behavior, context windows, and fine-tuning stop being API facts and become consequences of choices they have personally made.

The loss-mask moment, and other details worth slowing down for

Several details in this pipeline repay disproportionate attention, because they are where hand-wavy understanding usually hides. The chat format with loss mask in step one is the clearest example: masking the user turns so the model is only trained to produce assistant responses looks like a configuration footnote and is actually the difference between a model that converses and one that echoes. The piece-by-piece construction in step two is another, since assembling attention from a single head upward forces the question of what each part contributes, a question that frameworks-trained engineers have often never had to ask. And the loss curve commentary in step three teaches the habit that separates people who train models from people who watch them: reading the shape of descent, noticing plateaus, and resisting the urge to intervene on noise.

A practical study method for the repository: at each step, predict what the output will look like before running it, then compare. The gaps between prediction and result are the precise locations of your misconceptions, and a from-scratch build is the only context where that feedback is cheap enough to collect deliberately.

The convenience layer: control panel and docs site

Beyond the pipeline itself, the repository ships operational touches that matter for regular use. A Streamlit control panel drives the stages without living in a terminal, which lowers the barrier for learners less fluent in shells and makes parameter experimentation visual. A documentation site built with mkdocs carries the written material in browsable form. And the install is modular: the base package is light, with optional extras for training dependencies, the UI, and the docs, so the environment stays proportional to what you are actually doing.

git clone https://github.com/FareedKhan-dev/train-llm-from-scratch.git
cd train-llm-from-scratch
pip install -e .
pip install -e ".[train]"   # datasets + wandb, when you are ready to run

Where it fits among the learning resources

Against our previous coverage, the position is complementary. The LLM Course roadmap teaches the theory with notebooks; this repository is the execution of that theory as one connected build. The infrastructure projects walkthrough covers the serving side of the stack; this covers the training side, and together they bracket the lifecycle. A reasonable sequence for a systems-minded learner: concepts first, this build second, then serving, at which point every layer of the stack has been personally touched.

Why build a 13-million-parameter model that cannot do anything useful?

Because the pedagogy scales down better than it scales up. Every mechanism in the pipeline, tokenization, loss masking, attention, pretraining dynamics, fine-tuning, alignment, operates identically at 13 million parameters and at 13 billion; only the hardware bill and the wall-clock change. A model too small to be useful is also too small to hide behind, meaning every design mistake shows up clearly in behavior you can inspect, while a large model’s competence can mask flawed understanding in its trainer. The small track also completes, an underrated property: a learner who finishes the whole pipeline in a weekend holds the full mental model, whereas a pipeline that requires rented clusters gets abandoned at the interesting parts. Usefulness is not the product of this exercise, comprehension is, and the small model is the right price for it.

How do the alignment options differ in practice at this scale?

At learning scale, the differences are visible in the training loop, which is what makes them teachable. Supervised fine-tuning alone turns a base model into something that follows chat format, competent but agreeable. Adding a reward model and DPO teaches preferences with a reference policy in the loop, which shows the learner why alignment needs something to align away from. The reference-free options, ORPO and KTO, drop the reference model, and ORPO specifically folds the fine-tuning and alignment stages into a single run, which on small hardware is the practical choice, one run instead of two, with no separate reference to store. The configuration surface makes this concrete: alignment is a loss-type flag, not a philosophy seminar. The understanding that transfers is that these algorithms are pipeline choices with cost and quality profiles, not rival ideologies, and having toggled between them on a model you built yourself is worth more than a hundred forum arguments about which is correct.

What should you do after finishing the pipeline?

Three directions, in ascending ambition. First, scale within reach: rerun the pipeline at the largest size your hardware allows and observe what changes, which builds intuition for scaling behavior the small run cannot show. Second, change the data: swap in a domain corpus you care about and fine-tune on it, which converts the exercise from education to a small real tool, a domain-specific assistant you actually use. Third, go deeper on one stage: the repository’s steps each connect to specialist literature, and picking the stage that fascinated you most, tokenization, attention variants, alignment, is the right way to choose what to study formally next. What to avoid: mistaking completion for mastery and immediately renting a cluster to chase scale. The pipeline teaches mechanisms, and mechanisms compound; chasing parameters first mostly teaches you about cloud billing.

Is this the right resource for someone without a machine-learning background?

Almost, with one bridge to cross first. The repository names its prerequisites precisely: object-oriented programming, neural network basics, and working PyTorch, and it links starter videos for each gap. A competent programmer without the ML foundations can cross that bridge in a focused week or two and then succeed here, because the pipeline teaches the transformer as it assembles it. Someone without comfortable programming should not start here; a concepts course first, then this, is the path that ends in completion rather than frustration. The self-assessment that works: read the prerequisites list, and if each item sounds like something you could do with documentation open, you are ready; if two or more items sound like courses you have not taken, take them first, because every step of this pipeline leans on all three at once, and prerequisite gaps compound in a build, unlike in a course, where each lesson can be separately patched.

How does this compare with Karpathy-style nanoGPT builds?

The genre has two lineages and they optimize for different lessons. The nanoGPT lineage builds a compact, elegant implementation of the core, pretraining a small GPT on a clean dataset, and its virtue is minimalism: nothing stands between you and the essential loop. This repository trades some minimalism for pipeline completeness, adding the stages a real assistant requires, chat formatting, supervised fine-tuning, reward modeling, alignment, evaluation, and a serving interface. Neither replaces the other. The minimalist build teaches the forward pass and training loop with the least distraction; the full pipeline teaches why the base model was never the product. Learners with time for both should do the minimalist build first for the foundations and this one second for the lifecycle, and learners choosing one should choose by which gap they are actually trying to close. A third lineage is worth naming for completeness, the serving-side build courses, which start where this pipeline ends, and the three together cover the full lifecycle from tokens to deployment.

What do people get wrong on their first run?

Four mistakes account for most failed first attempts. Skipping the prerequisites assessment and stalling in step two, because the architecture assembly assumes genuine PyTorch fluency rather than acquaintance. Underestimating data-stage patience, where tokenization errors surface confusingly later in the pipeline, so the habit of validating token counts and chat formatting before training saves hours. Hardware mismatch, attempting a config above the published table and meeting the out-of-memory wall midway, when the memory flags exist precisely for that moment. And intervening on the loss curve too early, restarting runs that were progressing normally, which teaches nothing and costs the momentum that finishes pipelines. The repository’s own structure prevents most of these if followed in order, which is the strongest argument for resisting the urge to jump to the interesting steps first. If a run fails anyway, the recovery discipline is boring and effective: shrink the config until it runs, confirm each stage on the small config, then scale back up one change at a time.

Can the fine-tuned result be used for anything real?

As a tool, rarely; as a component, occasionally. A 13-million-parameter assistant will not compete with anything served by a frontier lab, and pretending otherwise disappoints. Where small personally-trained models genuinely work: domain-specific classifiers and extractors, where the fine-tuning data is narrow and the competition is a rule-based script rather than a large model; local prototyping, validating that a data pipeline behaves before spending on real training; and education delivery, producing a model whose every behavior you can explain, which has genuine value in teams where LLM literacy is being built. The honest mental model is that the output is a checkpoint-shaped certificate of understanding, and any incidental utility is a bonus. Teams that keep expectations calibrated this way get full value from the exercise; teams that expect a usable product have misunderstood what free-GPU scale was ever going to deliver. The sweet spot expectation is a model that demonstrates every stage convincingly on inputs you chose, which is exactly what the pipeline is engineered to produce Set that expectation on purpose, write it at the top of your notes on day one, and the build stays educational end to end rather than curdling into disappointment at step seven, when the chat window opens and a very small model answers..

What is the Streamlit control panel actually good for?

Beyond convenience for terminal-shy learners, the control panel earns its place as a teaching instrument. Watching hyperparameters change behavior through a visible interface builds calibration faster than editing config files, because the feedback loop closes in seconds and the comparison between runs is laid out in front of you rather than buried in logs. It also makes the pipeline demonstrable to others, which matters in teams and classrooms, where showing a colleague the loss curve of a model you trained beats describing it. The pragmatic warning that comes with any control panel: stay in it long enough to build intuition, then graduate to the scripts, because the panel hides exactly the invocation details a real training workflow eventually requires you to know cold.

Run the 13-million-parameter track on a free GPU first, every step, before touching any larger configuration. The value of training an LLM from scratch is not the model you produce but the machinery you can no longer be mystified by, and this repository is the most complete free path from curiosity to that machinery we have reviewed.