MCPcopy Create free account
hub / github.com/FareedKhan-dev/train-llm-from-scratch

github.com/FareedKhan-dev/train-llm-from-scratch

Chat with this repo
repository ↗ · DeepWiki ↗ · release v1.0.0 ↗ · + Follow · compare 2 versions

A straightforward method for training your LLM, from downloading data to generating text.

644 symbols 3,306 edges 137 files ⚖ MIT 264 documented · 41% ● updated 20d agolatest release v1.0.0 · 2026-11-16★ 13,3791 open issues
What it actually does AI analysis from the code graph

What it actually is

This is an educational, from-scratch implementation of a full LLM training pipeline in PyTorch — covering tokenisation (src/tokenizer/bpe.py), pretraining a Transformer, and post-training alignment (SFT, DPO/ORPO/KTO, PPO, GRPO) through to evaluation and chat inference. It targets developers and researchers who want to understand or run every stage of the "raw text → tokens → base model → aligned model" pipeline themselves, without relying on trl, peft, or transformers. It is designed to scale from a 13M-parameter model trainable on CPU up to billion-parameter models on a single GPU.

Why it's growing

The repository has 13,382 stars but gained none in this period, and there's only a single tagged release (v1.0.0, 2026-11-16) despite the project existing since January 2025 — so star growth clearly predates this window and isn't explained by recent activity. Commit history shows active, substantive engineering (bug fixes to PPO entropy, GSM8K reward checker, MoE routing loss, gradient accumulation in SFT) rather than marketing-driven changes, suggesting the project's draw is its comprehensiveness and pedagogical completeness rather than recent news.

The full breakdown is free — sign in to read it.

open as a page →

Browse by type

⨍ Functions 604◇ Types & classes 40
README

main image

Train LLM From Scratch

Python CI License Contributions Docs

I am Looking for a PhD position in AI. GitHub

I implemented a transformer model from scratch using PyTorch, based on the paper Attention is All You Need. You can use my scripts to train your own billion or million parameter LLM using a single GPU, or a small one on a laptop CPU with no GPU at all.

This started as a pretraining tutorial. It now goes all the way from raw text to an aligned, reasoning style model, with every algorithm hand written in plain PyTorch (no trl, no peft, no transformers). The whole journey is one idea repeated: turn text into numbers, predict the next token, then keep changing the data and the loss until the model does what we want.

Next to the original model there is now a modern one, built the way current open models are (rotary positions, RMSNorm, SwiGLU, grouped-query and latent attention, Mixture of Experts, a KV cache), and every stage can train either. The newer training tricks are here too, each written out by hand: the Muon optimizer, LoRA, IPO and SimPO, Dr. GRPO, DAPO and GSPO, speculative decoding and int8 weights.

From raw text to an aligned reasoning model

Here is the path we will walk, end to end:

raw text  ->  tokens  ->  a Transformer  ->  next-token loss  ->  a base model
base model  ->  SFT  ->  Reward Model  ->  {PPO, DPO}  ->  GRPO  ->  evaluation and chat

Below is the output of a trained 13 million parameter LLM, just so you can see where the small end of this starts:

In ***1978, The park was returned to the factory-plate that
the public share to the lower of the electronic fence that
follow from the Station's cities. The Canal of ancient Western
nations were confined to the city spot. The villages were directly
linked to cities in China that revolt that the US budget and in
Odambinais is uncertain and fortune established in rural areas.

Table of Contents

Who this is for

I tried to write this so one page works for very different readers:

  • If you are a student, read top to bottom. Every block of code comes after a plain explanation of what it does and why, and most blocks are followed by the output you should expect.
  • If you are a developer, the commands and file paths are all here. You can copy, run, and read the referenced source files directly.
  • If you are a researcher, the post-training half is the interesting part: SFT, a Bradley-Terry reward model, PPO with GAE, DPO/ORPO/KTO, and GRPO, all from scratch on the same small Transformer, trained on real public datasets.

Every diagram in this README is colored the same way, so the colors mean something:

  • green is raw data
  • teal is stored, tokenized data on disk
  • blue is a plain processing step
  • yellow is the model or a training step
  • orange is the reinforcement learning and reward parts
  • red is a loss
  • grey is a saved checkpoint
  • purple is the final output or evaluation

Prerequisites and Training Time

You need a basic understanding of object oriented programming, neural networks, and PyTorch. Below are some resources to help you get started:

Topic Video Link
OOP OOP Video
Neural Network Neural Network Video
Pytorch Pytorch Video

You do not need a GPU to start: the laptop track trains a small model on a CPU in minutes. For the bigger models you will need a GPU. A free Colab or Kaggle T4 is enough for the 13 million parameter model, but it will not fit a billion parameter model. Here is a rough guide:

GPU Name Memory 2B LLM Training 13M LLM Training Max Practical LLM Size (Training)
NVIDIA A100 40 GB ✔ ✔ ~6B to 8B
NVIDIA V100 16 GB ✘ ✔ ~2B
NVIDIA RTX 4090 24 GB ✔ ✔ ~4B
NVIDIA RTX 5090 32 GB ✔ ✔ 13M verified, larger configs TBD
NVIDIA RTX 3090 24 GB ✔ ✔ ~3.5B to 4B
NVIDIA RTX 4080 16 GB ✘ ✔ ~2B
NVIDIA RTX 4060 8 GB ✘ ✔ ~1B
Tesla T4 16 GB ✘ ✔ ~1.5B to 2B

If a large config runs out of memory, the pretraining script has opt-in flags (--amp, --grad-checkpointing, --grad-accum) that bring the memory down a lot. More on those later.

Setup

Clone the repository and install it in editable mode. The editable install puts config, src, data_loader, and ui on your import path, so you do not need to set PYTHONPATH by hand anymore:

git clone https://github.com/FareedKhan-dev/train-llm-from-scratch.git
cd train-llm-from-scratch
pip install -e .

If you use uv, uv sync does the same and also installs the test tools. On a Linux machine without an NVIDIA GPU, install the small CPU build of PyTorch first (pip install torch --index-url https://download.pytorch.org/whl/cpu), because the default Linux wheel bundles CUDA.

There are optional extras for the parts you want:

pip install -e ".[train]"   # datasets + wandb, for downloading data and logging
pip install -e ".[ui]"      # streamlit + pandas + altair, for the control panel
pip install -e ".[docs]"    # mkdocs, for the documentation site
pip install -e ".[all]"     # everything

There are two config systems, and it helps to know which is which from the start:

  • config/config.py is the original, simple config for the legacy pretraining script scripts/train_transformer.py. It is plain Python constants.
  • config/post_training_config.py plus the JSON files in configs/ drive everything else (pretraining the bigger base, SFT, reward, DPO, PPO, GRPO). You edit a small JSON file per stage, and any field can also be overridden on the command line, for example --lr 2e-5 --batch_size 16.

For fast checks there is a tiny configs/smoke/ variant of every stage that shrinks the model so a full run finishes in seconds on a CPU or a single GPU.

No GPU? Train on Your Laptop

You can train a real (small) language model on a laptop CPU, from raw text to generated stories, in about ten minutes. Three commands:

python scripts/prepare_tiny_data.py                              # TinyStories + a BPE tokenizer trained from scratch
python scripts/train_transformer.py --preset tiny --arch modern  # 369K parameters, about 5 minutes on a CPU
python scripts/generate_text.py --model_path models/tiny.pt      # write a story

The first command downloads 25 MB of TinyStories (short stories written for training tiny models) and trains a 4,096 token BPE tokenizer on it, written from scratch in src/tokenizer/bpe.py. A small vocabulary keeps the embedding table small, which is what makes a tiny model fast. Here is what the tiny model wrote after five minutes of training on my laptop:

#### OUTPUT ####
Once upon a time, there was a little girl named Lily. She liked to eat some food together.
One day, Lily found a big box in a box. She wanted to pick it up and find it. She thought it
would make it happy. She looked at her bear and said, "Yes, I will find me. I want to help you get it."

Real words, real sentences, a character and a plot of sorts, from 369 thousand parameters. Bigger presets (student, small) take longer and write better stories. scripts/benchmark.py measures how fast each preset trains on your machine before you commit to a long run, and scripts/model_report.py tells you how big a model is, how much compute it needs, and whether it fits in memory.

The full guide, with the presets, the expected losses and experiments to try, is in docs/student.

Code Structure

train-llm-from-scratch/
├── src/
│   ├── models/                  # the Transformer, built from small pieces
│   │   ├── mlp.py               # the feed-forward block
│   │   ├── attention.py         # single head and multi head attention
│   │   ├── transformer_block.py # one block: attention + MLP + residuals
│   │   ├── transformer.py       # the full model: embeddings + blocks + lm_head
│   │   ├── modern/              # the modern decoder: RoPE, RMSNorm, SwiGLU, GQA/MLA, MoE, KV cache
│   │   ├── factory.py           # build_model(cfg): classic or modern from one config
│   │   └── lora.py              # LoRA adapters, from scratch
│   ├── optim/                   # Muon, and cosine / WSD / linear learning-rate schedules
│   ├── tokenizer/               # a byte-level BPE tokenizer, from scratch
│   ├── inference/               # sampling (top-k, top-p, min-p), speculative decoding, int8
│   ├── post_training/           # SFT, reward model, PPO, DPO, GRPO, eval, inference
│   ├── checkpoint.py            # saving and loading checkpoints from any wrapper
│   └── device.py                # picks CUDA, Apple MPS, CPU (or an experimental TPU)
├── config/
│   ├── config.py                # legacy pretraining config (plain constants)
│   ├── presets.py               # named model sizes: tiny, student, small, 13m, 77m, 3b
│   ├── post_training_config.py  # typed dataclasses for every post-training stage
│   └── loader.py                # merges defaults < base.json < stage.json < CLI, checks types
├── configs/                     # editable JSON, one file per stage (+ smoke/)
├── data_loader/                 # batch iterators for each kind of data
├── scripts/                     # every runnable step lives here
├── tests/                       # pytest: models, losses, configs, and every script end to end
├── ui/                          # the Streamlit control panel
├── docs/                        # the MkDocs site (theory + diagrams)
├── images/                      # the diagrams in this README (+ the generator)
└── pyproject.toml               # pip install -e .

Step 1: Preparing the Data

A model only ever sees integers. So the first job is always the same: take text, turn it into token ids, and store those ids on disk in a format that is fast to read during training. We do this four times, once for each kind of training we will do later.

The data pipeline

The four streams are:

  1. Pretraining text from The Pile, stored as a flat array of token ids in an HDF5 file.
  2. Instruction data (Alpaca, Dolly, GSM8K) for SFT, packed into fixed length rows with a mask that says which tokens are the assistant's answer.
  3. Preference pairs (Anthropic HH-RLHF, UltraFeedback) for the reward model and DPO, stored as {prompt, chosen, rejected}.
  4. RL prompts (GSM8K and a small arithmetic warm-up) for PPO and GRPO, stored as {prompt, gold}.

Tokenization

We use the r50k_base tokenizer from OpenAI's tiktoken, t

Core symbols most depended-on inside this repo

browse all functions →

Shape

Function 494
Method 110
Class 40

Languages

Python100%

Modules by API surface

scripts/train_transformer.py27 symbols
config/post_training_config.py16 symbols
src/tokenizer/bpe.py15 symbols
ui/jobs.py14 symbols
src/post_training/utils.py13 symbols
src/models/modern/config.py12 symbols
src/models/modern/model.py11 symbols
docs/diagrams/make_plots.py11 symbols
src/post_training/distributed.py10 symbols
src/tokenizer/__init__.py9 symbols
src/models/lora.py9 symbols
src/post_training/rollout.py8 symbols

Dependencies from manifests, versioned

jaxtyping0.2.28 · 1×
torch2.3 · 1×
tqdm1×
h5py1×
regex1×
requests1×
zstandard1×

For agents

$ claude mcp add --transport http codehub https://codehub.bot/mcp

One hosted endpoint, no key: your agent can search, read and trace FareedKhan-dev/train-llm-from-scratch and every other graph here. Cursor, Windsurf and other clients →

⬇ download graph artifact

Ask about this repo answers extend the page