AI Card Bao DASH.AICARDBAO.COM
Home / 开源 / Train LLM from Scratch
AI TOOL / #12858

Train LLM from Scratch

A tutorial series that guides you through step-by-step process of building and training large Transformer models using PyTorch from scratch – ranging from downloading data to generating text. The entire architecture is implemented based on the principles outlined in the paper "Attention is All You Need".

Introduction

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.

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
  • Prerequisites and Training Time
  • Setup
  • No GPU? Train on Your Laptop
  • Code Structure
  • Step 1: Preparing the Data
  • Step 2: The Model, Built From Small Pieces
  • Multi Layer Perceptron (MLP)
  • Single Head Attention
  • Multi Head Attention
  • The Transformer Block
  • The Full Transformer
  • The Modern Version of the Same Model
  • Step 3: Pretraining the Base Model
  • Step 4: Generating Text
  • Step 5: Post-Training, Turning a Base Model Into an Assistant
  • SFT (Supervised Fine-Tuning)
  • The Reward Model
  • DPO, ORPO and KTO
  • PPO
  • GRPO / RLVR
  • Step 6: Evaluation
  • Benchmarking the base model
  • Step 7: Talking to the Model
  • The Streamlit Control Panel
  • The Documentation Site
  • Run the Whole Thing
  • Type Safety and Tests
  • Run it in Docker
  • What's Next

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:

TopicVideo Link
OOPOOP Video
Neural NetworkNeural Network Video
PytorchPytorch 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 NameMemory2B LLM Training13M LLM TrainingMax Practical LLM Size (Training)
NVIDIA A10040 GB✔✔~6B to 8B
NVIDIA V10016 GB✘✔~2B
NVIDIA RTX 409024 GB✔✔~4B
NVIDIA RTX 509032 GB✔✔13M verified, larger configs TBD
NVIDIA RTX 309024 GB✔✔~3.5B to 4B
NVIDIA RTX 408016 GB✘✔~2B
NVIDIA RTX 40608 GB✘✔~1B
Tesla T416 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 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, the same one GPT-3 used. Text becomes a list of integers, and we append a special `` token (id 50256) at the end of every document so the model learns where one piece of text stops and the next begins. (The laptop track trains its own, much smaller tokenizer instead; BPE from scratch shows how.)

For the legacy path, download a slice of The Pile and tokenize it into HDF5:

python scripts/data_download.py            # downloads the validation file + 1 training shard
python scripts/data_preprocess.py          # tokenizes to data/train/pile_train.h5 and data/val/pile_dev.h5

The newer, faster path streams and batch-encodes the same data straight into a flat token array:

python scripts/prepare_pretrain_data.py --split val   --out data/pile_dev.h5
python scripts/prepare_pretrain_data.py --split train --num_shards 1 --out data/pile_train.h5

Once tokenized, the data is just a long line of integers. Here is a real peek at the validation file I prepared for this README (8.76 million tokens), the first ten ids, and what they decode back to:

#### OUTPUT ####
dtype: int32 | shape: (8762951,) | total tokens: 8762951
first 10 token ids: [18610, 286, 3993, 3081, 319, 4088, 11, 4640, 2163, 11]
decoded back to text:
'Effect of sleep quality on memory, executive function, and language
 performance in patients with refractory focal epilepsy ...'

That is the whole idea of tokenization in one output: text in, a flat array of integers out, and the integers decode straight back to the original words.

The chat format and loss mask

For everything after pretraining the model has to know who is talking. The r50k_base tokenizer has only one special token, so instead of inventing new ones we use plain text role markers that the model simply learns during SFT. A single turn looks like this (see src/post_training/chat_template.py):


{user content}
{assistant content}

For math and reasoning we ask the assistant to show its work in a fixed structure, because the reinforcement learning reward later checks the number inside the answer tags:

step by step reasoning ...42

The important trick is the loss mask. When we encode a conversation we also build a 0/1 mask that is 1 only on the assistant tokens (and the `` that ends the turn). That way SFT trains the model to write answers, not to parrot the prompt back. Here is the exact code that builds the ids and the aligned mask:

def encode_chat(messages, add_generation_prompt=False):
    ids, mask = [], []
    for m in messages:
        role = m["role"]
        # Role header is always masked out (we never train the model to emit it).
        header_ids = _encode_ordinary(_header_for(role))
        ids.extend(header_ids)
        mask.extend([0] * len(header_ids))

        content_ids = _encode_ordinary(m["content"])
        is_completion = role == "assistant"
        ids.extend(content_ids)
        mask.extend([1 if is_completion else 0] * len(content_ids))   # train on assistant only

        ids.append(EOT_ID)                                            # turn terminator
        mask.append(1 if is_completion else 0)                        # learn to stop
    return ids, mask

Here is a real rendered conversation and the verifier reward in action, printed from this repo:

#### OUTPUT ####
rendered chat:

What is 13 + 29?
13 + 29 = 4242

extract_answer("42")        -> 42.0
reward_gsm8k("42", 42.0)    -> 1.2    # correct AND well formatted
reward_gsm8k("7",  42.0)    -> 0.2    # wrong, but it used the format

And here is one real packed SFT row, showing how only the assistant tokens are trained (the mask is 1 on 48 of the 512 tokens in this row):

#### OUTPUT ####
tokens shape: (2131, 512) | loss_mask shape: (2131, 512)
row 0: trained (mask=1) tokens = 48 / 512
row 0 decoded:

  What is the world's oldest annual marathon based on the reference text below? ...

  The Boston Marathon is the world's oldest annual marathon, beginning on April 19th 1897.

The data prep scripts for these stages are:

python scripts/prepare_sft_data.py          # Alpaca + Dolly + GSM8K  -> sft_packed.h5
python scripts/prepare_preference_data.py   # HH-RLHF + UltraFeedback -> preferences.jsonl
python scripts/prepare_rl_prompts.py        # GSM8K + arithmetic      -> rl_prompts.jsonl

Step 2: The Model, Built From Small Pieces

A Transformer looks scary as one block of code, so we build it from four small pieces and then stack them. Each piece is a tiny nn.Module. We start at the bottom.

Multi Layer Perceptron (MLP)

The MLP is the part of each block that does the per-token "thinking". It takes each token vector, expands it to four times its size, applies a ReLU, and squeezes it back down. The expansion gives the layer room to mix features before projecting back.

class MLP(nn.Module):
    """A simple Multi-Layer Perceptron with one hidden layer."""
    def __init__(self, n_embed):
        super().__init__()
        self.hidden = nn.Linear(n_embed, 4 * n_embed)   # expand to 4x
        self.relu = nn.ReLU()                           # non-linearity
        self.proj = nn.Linear(4 * n_embed, n_embed)     # project back down

    def forward(self, x):
        x = self.relu(self.hidden(x))
        x = self.proj(x)
        return x

The __init__ sets up the two linear layers and the activation. The forward runs them in order. Input and output shapes are the same, (B, T, n_embed), so blocks can be stacked without any reshaping. The code is in src/models/mlp.py.

Single Head Attention

Attention is the part that lets a token look at other tokens. Each head builds three views of the input: a query (what am I looking for), a key (what do I contain), and a value (what I will pass on if chosen). We score every query against every key, scale the scores, hide the future with a causal mask, turn the scores into weights with a softmax, and take a weighted sum of the values.

class Head(nn.Module):
    """A single attention head with causal masking."""
    def __init__(self, head_size, n_embed, context_length):
        super().__init__()
        self.key   = nn.Linear(n_embed, head_size, bias=False)
        self.query = nn.Linear(n_embed, head_size, bias=False)
        self.value = nn.Linear(n_embed, head_size, bias=False)
        # a lower-triangular matrix used to mask out future positions (rebuilt on load, never saved)
        self.register_buffer('tril', torch.tril(torch.ones(context_length, context_length)), persistent=False)

    def forward(self, x):
        B, T, C = x.shape
        k = self.key(x)
        q = self.query(x)
        scale_factor = 1 / math.sqrt(k.size(-1))                       # 1 / sqrt(head_size)
        attn_weights = q @ k.transpose(-2, -1) * scale_factor          # (B, T, T) scores
        attn_weights = attn_weights.masked_fill(self.tril[:T, :T] == 0, float('-inf'))  # no peeking ahead
        attn_weights = F.softmax(attn_weights, dim=-1)
        v = self.value(x)
        out = attn_weights @ v                                         # weighted sum of values
        return out

The causal mask is what makes this a language model: position t can only attend to positions 0..t, never to the future it is trying to predict. The code is in src/models/attention.py.

Multi Head Attention

One head learns one kind of relationship. We want many, running in parallel, so the model can track several patterns at once (for example, a pronoun and the noun it refers to). We run n_head heads, concatenate their outputs, and pass the result through one more linear layer.

class MultiHeadAttention(nn.Module):
    def __init__(self, n_head, n_embed, context_length):
        super().__init__()
        self.heads = nn.ModuleList(
            [Head(n_embed // n_head, n_embed, context_length) for _ in range(n_head)]
        )
        self.proj = nn.Linear(n_embed, n_embed)   # mixes the heads back together

    def forward(self, x):
        x = torch.cat([h(x) for h in self.heads], dim=-1)   # concat along the feature dim
        x = self.proj(x)
        return x

Each head works in a smaller subspace of size n_embed // n_head, so the concatenation lands right back at n_embed. The final projection lets the heads talk to each other.

The Transformer Block

Now we combine attention and the MLP into one block. The block uses pre-norm residual connections: we normalize, run a sub-layer, and add the result back to the input. The "add back" (the residual) is what lets gradients flow through a deep stack without vanishing.

<
Visits:4 Updated:2026-12-03 AI tools

Related