Build a Small LLM from Scratch: The Complete 2026 Roadmap
A step-by-step roadmap to build a 25M–100M parameter LLM on one GPU: tokenizer, data, architecture, pretraining, SFT, alignment, evaluation and deployment.
A polytechnic student in Indore can buy a scooter, or she can rebuild a 100cc engine on the workshop bench. The rebuilt engine will never beat a showroom bike. But after one rebuild she knows exactly what the piston, carburettor and clutch do, and she can diagnose any engine for the rest of her career.
Training a tiny language model yourself is that workshop engine. You will not compete with the frontier labs. You will understand, line by line, what happens between a pile of raw text and a model that answers "What is the capital of Madhya Pradesh?"
What does it mean to build an LLM from scratch?
Building an LLM from scratch means you design the tokenizer, write the transformer code, and train all of the model's weights yourself, starting from random numbers, instead of downloading a pretrained checkpoint and fine-tuning it.
In the engine analogy, the tokenizer is cutting raw metal into standard parts, pretraining is running the engine in until it moves smoothly, and supervised fine-tuning (SFT) is tuning it for a specific rider. Alignment (DPO or reinforcement learning) is the final road test where you adjust behaviour based on feedback.
If the words "token", "attention" or "pretraining" are new, read how tokenization works, transformers and attention and how LLMs are trained first. This series assumes that background and stays hands-on.
What are the stages of building an LLM?
Every serious LLM, from a 30M toy to a frontier model, goes through the same broad stages. The difference is scale, not shape.
Each stage takes the previous stage's output as input. A weak tokenizer or dirty data hurts every stage after it.
Here is the series as a map. Each row is one tutorial, in reading order.
| # | Stage | Tutorial | What you produce |
|---|---|---|---|
| 1 | Plan the build | This roadmap | A model size, token budget and hardware plan |
| 2 | Tokenizer | Train a BPE tokenizer | tokenizer.json with a small vocabulary and chat tokens |
| 3 | Data | Prepare pretraining and chat data | Clean, deduplicated, tokenized .bin and .jsonl files |
| 4 | Architecture | Small LLM architecture in code | A PyTorch decoder with RMSNorm, RoPE, GQA and SwiGLU |
| 5 | Pretraining | Pretrain the model | A base model that continues text |
| 6 | SFT | Supervised fine-tuning | A chat model that follows a template |
| 7 | Distillation | Knowledge distillation | A student that learns from a larger teacher |
| 8 | DPO | DPO training | A model that prefers better answers |
| 9 | RL | PPO and GRPO hands-on | A model tuned by rewards, such as correct maths |
| 10 | Evaluation | Evaluate your small LLM | Loss, perplexity, benchmark and side-by-side results |
| 11 | Deployment | Export and serve your LLM | Hugging Face format, GGUF, Ollama and an API |
Stages 2 to 6 are the core. Stages 7 to 9 are optional polish. Stages 10 and 11 turn an experiment into something you can show.
Which stages are optional?
You can stop after stage 6 and still have a working chat model. Distillation helps most when you can borrow outputs from a stronger model. DPO and RL help most when you can define "better" with pairs or an automatic checker. Skip them on your first build and come back later.
Quick check
Which stages give you a working chat model on the shortest path?
SFT on top of a pretrained base model is the shortest route to chat. DPO and GRPO are optional refinements.
How big should your first model be?
The right size depends on three numbers: parameters, tokens and GPU hours. They are tied together by a well-known rule of thumb: training compute is roughly 6 × parameters × tokens floating-point operations.
A second rule, from DeepMind's Chinchilla paper, says a compute-efficient model sees roughly 20 training tokens per parameter. Small hobby models often go well beyond that, because extra tokens keep improving a small model and data is cheaper than a bigger GPU.
This series uses one running example, plus a smaller variant for quick experiments. Both share the same tokenizer and chat format:
| Setting | Small variant | Running example |
|---|---|---|
| Vocabulary | 6,400 | 6,400 |
| Hidden size | 512 | 768 |
| Layers | 8 | 8 |
| Query / KV heads | 8 / 4 | 8 / 4 |
| Feed-forward size | 1,408 | 2,432 |
| Parameters | about 27M | about 64M |
| Tokens at 20 per parameter | about 0.55B | about 1.3B |
You can check the compute and time yourself. The block below uses an assumed sustained throughput of 25 TFLOPS. That is a rough planning figure for a recent consumer GPU running bf16 at realistic utilisation, not a measurement, so change it to match your card.
# Rough compute and time plan for a small LLM (6*N*D rule of thumb)
models = {"small": 27e6, "running": 64e6}
tokens_per_param = 20
sustained_tflops = 25 # assumption: tune for your GPU
rupees_per_gpu_hour = 60 # assumption: check current cloud prices
for name, n_params in models.items():
tokens = n_params * tokens_per_param
flops = 6 * n_params * tokens
hours = flops / (sustained_tflops * 1e12) / 3600
print(f"{name:8s} params={n_params/1e6:5.0f}M tokens={tokens/1e9:4.2f}B "
f"compute={flops:.1e} FLOPs time~{hours:4.1f} h cost~Rs {hours*rupees_per_gpu_hour:,.0f}")The small variant needs about an hour of pure pretraining compute; the 64M running example needs five to six hours. Real runs take longer because of data loading, evaluation and checkpoints, so budget roughly 1.5 to 2 times the estimate.
What GPU do you need?
Memory matters more than speed for a first build. With mixed precision and the AdamW optimiser, training costs roughly 16 bytes per parameter for weights, gradients and optimiser state, plus activations that grow with batch size and sequence length.
# Training memory estimate: fp32 master weights + grads + 2 Adam moments
bytes_per_param = 4 + 4 + 8
for name, n in {"27M": 27e6, "64M": 64e6, "350M": 350e6}.items():
static_gb = n * bytes_per_param / 1e9
print(f"{name:5s} static training state ~{static_gb:4.2f} GB (+ activations)")The 64M model's fixed state is about 1 GB, so an 8 GB to 12 GB card works if you keep the micro-batch small and use gradient accumulation. A 24 GB card lets you use longer sequences and bigger batches. No GPU at all? A rented cloud GPU for a day is enough for the running example.
Quick check
Using the 6 x parameters x tokens rule, roughly how many FLOPs does it take to train a 50M parameter model on 1B tokens?
6 x 50,000,000 x 1,000,000,000 = 3 x 10^17 floating-point operations.
What can a 30M to 100M parameter model actually do?
Be honest with yourself before you start. A model this size can:
- Write grammatical, on-topic sentences in the language and style of its training data.
- Follow a chat template, answer short factual questions it saw often in training, and stop at the right place.
- Learn narrow, checkable skills after fine-tuning, such as a fixed output format or simple tool-call JSON.
It cannot reliably do multi-step reasoning, long documents, accurate rare facts or code beyond short snippets. It will hallucinate confidently. Expect benchmark scores close to random guessing on hard multiple-choice tests; the evaluation tutorial shows how to measure this fairly.
That is fine. The goal is understanding. Once your 64M model works, the same code scales to larger models on rented hardware, and you will read research papers with far more confidence.
How to follow this series step by step
- Set up Python and PyTorch. You need Python 3.10+, PyTorch 2.x with CUDA, and the Hugging Face
tokenizers,datasetsandtransformerslibraries. New to Python? Start with getting started and for loops. - Pick your data early. English, Hindi or both. Your tokenizer and data choices lock in which language the model can handle.
- Build the tokenizer and data pipeline, then freeze them. Changing the tokenizer later forces you to retrain from zero.
- Write the model and run a tiny overfit test. Train on 100 sentences until the loss is near zero. If it can't memorise 100 sentences, it has a bug.
- Pretrain, then SFT. Save a checkpoint every few hundred steps.
- Evaluate, then add distillation, DPO or GRPO only if they solve a problem you can see.
- Export and serve. Put your model behind an API, the same way you would run an open model locally.
A suggested project layout keeps each stage separate:
my-small-llm/
tokenizer/ tokenizer.json, tokenizer_config.json (chat template)
data/ raw/, clean/, pretrain_train.bin, pretrain_val.bin, sft.jsonl
model/ config.py, model.py
train/ pretrain.py, sft.py, dpo.py, grpo.py
checkpoints/ pretrain_last.pt, sft_epoch1.pt
eval/ prompts.txt, results/
export/ hf/, gguf/Common mistakes on a first LLM build
- Starting too big. A 300M model that takes a week teaches you less than ten 30M runs that each take an hour.
- Skipping the overfit test. Most "my model outputs garbage" problems are bugs, such as labels not shifted or a broken causal mask.
- Changing the tokenizer midway. Every checkpoint is tied to its tokenizer.
- Judging the model by one prompt. Use a fixed prompt set and a held-out loss so you can compare runs.
- Expecting ChatGPT. Compare your model with your previous run, not with frontier models.
If you prefer learning with mentors in a classroom, Debugshala's Generative AI course, taught in English and Hindi, runs offline classes in Old Palasia, Indore.
Key takeaways
- An LLM build has 11 stages; stages 2 to 6 (tokenizer, data, architecture, pretraining, SFT) are the core.
- Plan with two rules of thumb: compute is about 6 × parameters × tokens, and about 20 tokens per parameter is compute-efficient.
- A 27M to 64M model fits one consumer GPU and trains in hours, not weeks.
- Run an overfit test before any long run, and freeze the tokenizer early.
- A small model is for learning how LLMs work, not for replacing hosted assistants.
FAQ
Can I build my own LLM from scratch on a laptop?
Yes, for a very small model. A laptop GPU with 6 GB to 8 GB of memory can train a model of roughly 10M to 30M parameters on a few hundred million tokens, though slowly. Without a GPU, use a CPU only for the overfit test, then rent a cloud GPU for the real run.
How long does it take to train a small LLM from scratch?
For a 25M to 30M parameter model on about half a billion tokens, expect roughly one to three hours of GPU time on a modern consumer card.
A 64M model on about 1.3B tokens needs roughly five to ten hours, and a 100M model on 2B tokens most of a day. These are planning estimates from the 6 × N × D rule, not guarantees.
How much data do I need to train an LLM?
A useful starting point is 20 tokens per parameter, so about 1.3B tokens for the 64M model in this series. A gigabyte of clean English text holds roughly 250M tokens with a small vocabulary. Small models keep improving beyond 20 tokens per parameter, so more clean data usually helps.
Is building an LLM from scratch worth it if I can fine-tune an open model?
For products, fine-tuning an open model is usually the better choice; see LoRA fine-tuning. For learning, building from scratch is worth it because you debug every stage yourself and understand what fine-tuning really changes.
Does Debugshala in Indore offer a Generative AI course?
Debugshala is an IT training and placement institute in Old Palasia, Indore, focused on Data, AI and Full Stack Development, and Generative AI is one of its courses. Classes are taught in English and Hindi, fresh graduates and non-IT learners are accepted, and you can attend a free demo class first. For self-testing, try the quizzes on Debugshala Test.
From the team behind this site
Go further with the Generative AI Course at Debugshala
These tutorials are written by Debugshala, a training and placement institute at Old Palasia, Indore. The classroom course adds live mentoring, real projects and interview preparation.
- Offline classes at Old Palasia, Indore
- Free demo class before you pay
- Non-IT, fresher and year-gap friendly
- Placement assistance
700+ students placed · 200+ hiring partners · 4.9★ Google rating