Short answer
Learning how to train an LLM from scratch comes down to nine stages: define the goal and budget, collect and clean text data, train a tokenizer, choose a model size, implement a transformer, pretrain it on next-token prediction, post-train it to follow instructions, evaluate it, and deploy it. Compute is the main cost: training needs roughly 6 × parameters × training tokens floating-point operations. A small 124M-parameter GPT-2-style model can be trained in hours for tens of dollars, a 1B model on 20B tokens takes roughly 80–100 H100 GPU-hours (a few hundred dollars), while a 7B model on 1 trillion tokens needs around 30,000 H100-hours (over $100,000). For most real products, fine-tuning an existing open model is cheaper and better; training from scratch is ideal for learning, research and specialised domains.
Should you train from scratch?
| Option | Cost | When it makes sense |
|---|---|---|
| Use an API | Lowest upfront | Prototypes, general tasks |
| Fine-tune an open model (LoRA/QLoRA) | Low | Custom style, format or domain behaviour; see What is LoRA? |
| Continued pretraining | Medium | Large domain corpus (legal, medical, code, a new language) |
| Train from scratch | High | Learning how LLMs work, research, unusual data, full control of data and licence |
If your goal is a production assistant, start with fine-tuning. If your goal is to understand or innovate, training from scratch is invaluable.
The nine stages
| Stage | What you do | Key output |
|---|---|---|
| 1. Goal and budget | Define model size, domain, compute budget | Training plan |
| 2. Data | Collect, filter, deduplicate, mix | Clean dataset |
| 3. Tokenizer | Train or choose a tokenizer | Vocabulary and token IDs |
| 4. Model size | Use scaling laws to match parameters and tokens | Architecture config |
| 5. Implementation | Build and test a decoder-only transformer | Working model code |
| 6. Pretraining | Next-token prediction at scale | Base model |
| 7. Post-training | Supervised fine-tuning, preference tuning, RL | Instruction-following model |
| 8. Evaluation | Benchmarks, held-out loss, human review, safety | Report |
| 9. Deployment | Quantize and serve | Usable model |
Step 1: Define the goal and budget
Decide:
- Purpose: learning, research, a domain model, a small on-device model?
- Compute budget: GPU-hours and dollars. Use our training cost calculator and LLM training cost guide.
- Constraints: context length, languages, target hardware for inference.
Step 2: Collect and prepare data
Data quality matters more than almost anything else.
| Source type | Examples | Notes |
|---|---|---|
| Web text | FineWeb (about 15 trillion tokens), FineWeb-Edu, RedPajama, Dolma | Filtered Common Crawl |
| Code | The Stack v2 | Licence filtering matters |
| Books and papers | Public-domain books, arXiv | Check licences |
| Maths and science | OpenWebMath, curated datasets | Improves reasoning |
| Domain data | Your documents | The reason many people train custom models |
| Synthetic data | Generated by stronger models | Increasingly important; check licences |
Processing pipeline:
1. Extract text from HTML/PDF. 2. Language identification. 3. Quality filtering (heuristics and classifiers, such as FineWeb-Edu's educational-quality classifier). 4. Deduplication (exact and fuzzy, e.g. MinHash). 5. Remove personal data and toxic content. 6. Decontaminate: remove benchmark test sets from training data. 7. Mix sources in chosen proportions. 8. Tokenize and shard into binary files for fast loading.
Step 3: Train a tokenizer
Most LLMs use byte-pair encoding (BPE) or similar subword methods. Typical vocabulary sizes range from 32,000 to over 200,000 tokens. Larger vocabularies compress text better (fewer tokens per word, especially for multilingual text) but add embedding parameters.
from tokenizers import Tokenizer, models, trainers, pre_tokenizers
tok = Tokenizer(models.BPE())
tok.pre_tokenizer = pre_tokenizers.ByteLevel()
trainer = trainers.BpeTrainer(vocab_size=32000, special_tokens=["<|endoftext|>"])
tok.train(["data.txt"], trainer)
tok.save("tokenizer.json")Or reuse an existing tokenizer (GPT-2's via tiktoken, or an open model's). See What are tokens in AI?
Step 4: Choose model size with scaling laws
DeepMind's Chinchilla study (2022) found compute-optimal training uses roughly 20 tokens per parameter. Modern models often train far longer than that (for example, Meta trained Llama 3 8B on about 15 trillion tokens, nearly 2,000 tokens per parameter) because smaller, over-trained models are cheaper to run. See scaling laws explained.
| Parameters | Chinchilla-optimal tokens | "Over-trained" (common today) |
|---|---|---|
| 124M | ~2.5B | 10–100B |
| 1B | ~20B | 100B–2T |
| 7–8B | ~150B | 2–15T |
| 70B | ~1.4T | 15T+ |
Step 5: Estimate compute, time and cost
Training FLOPs ≈ 6 × N × D, where N is parameters and D is training tokens.
Assume an H100 at 989 TFLOPS dense BF16 running at 40% utilisation (MFU) ≈ 4 × 1014 useful FLOP/s, and the November 2026 median H100 rental price of $3.92/hour from our GPU price tracker.
| Model | Tokens | Training FLOPs | H100-hours (40% MFU) | Approx. cost at $3.92/hr |
|---|---|---|---|---|
| 124M | 10B | 7.4 × 1018 | ~5 | ~$20 |
| 350M | 30B | 6.3 × 1019 | ~44 | ~$170 |
| 1B | 20B | 1.2 × 1020 | ~83 | ~$330 |
| 1B | 100B | 6 × 1020 | ~420 | ~$1,600 |
| 7B | 1T | 4.2 × 1022 | ~29,000 | ~$114,000 |
| 70B | 15T | 6.3 × 1024 | ~4.4 million | ~$17 million |
Real costs are higher: experiments, failed runs, evaluation and data processing add a lot. For reference, Meta reported about 1.46 million H100 GPU-hours to train Llama 3.1 8B. Andrej Karpathy's llm.c project reproduced GPT-2 (124M) in about 90 minutes on one 8×A100 node for roughly $20 in 2024. See MFU explained.
Step 6: Choose the architecture
Most modern LLMs are decoder-only transformers with a few standard improvements:
| Component | Common modern choice | Why |
|---|---|---|
| Positional encoding | RoPE | Good length generalisation; see RoPE explained |
| Normalisation | RMSNorm, pre-norm | Stable training |
| Activation | SwiGLU | Better quality per parameter |
| Attention | Grouped-query attention (GQA) | Smaller KV cache; see MHA vs MQA vs GQA vs MLA |
| Attention kernel | FlashAttention | Faster and memory-efficient; see FlashAttention |
| Bias terms | Usually removed | Simpler, stable |
| Mixture of experts | Optional for large models | More parameters at same compute; see mixture of experts |
Example small configs:
| Model | Layers | Hidden size | Heads | Context |
|---|---|---|---|---|
| 124M | 12 | 768 | 12 | 1,024 |
| 350M | 24 | 1,024 | 16 | 2,048 |
| 1B | 16–24 | 2,048 | 16–32 | 2,048–4,096 |
Background: What is a transformer?
Step 7: Write and test the training loop
A minimal PyTorch training step:
import torch
model = GPT(config).cuda()
model = torch.compile(model)
opt = torch.optim.AdamW(model.parameters(), lr=6e-4, betas=(0.9, 0.95), weight_decay=0.1)
for step, (x, y) in enumerate(loader):
with torch.autocast("cuda", dtype=torch.bfloat16):
logits = model(x)
loss = torch.nn.functional.cross_entropy(logits.view(-1, logits.size(-1)), y.view(-1))
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
for g in opt.param_groups:
g["lr"] = lr_schedule(step)
opt.step()
opt.zero_grad(set_to_none=True)Sanity checks before scaling up:
- Initial loss should be about ln(vocabulary size) (around 10.8 for GPT-2's 50,257-token vocabulary).
- The model should overfit one small batch to near-zero loss.
- Loss should decrease smoothly on a tiny run.
- Checkpoint saving and resuming must work exactly.
See gradient descent and backpropagation and mixed precision training.
Typical pretraining hyperparameters
| Setting | Typical value |
|---|---|
| Optimizer | AdamW (β1 0.9, β2 0.95) |
| Peak learning rate | ~6e-4 for ~100M models, lower (~3e-4 or less) for larger |
| Schedule | Linear warmup (~1–2% of steps), then cosine or warmup-stable-decay |
| Weight decay | 0.1 |
| Gradient clipping | 1.0 |
| Precision | BF16 mixed precision (FP8 on Hopper/Blackwell for large runs) |
| Batch size | ~0.5M tokens for small models; several million for large |
| Sequence length | 1,024–8,192, extended later |
Scaling to many GPUs
| Technique | What it splits | When to use |
|---|---|---|
| Data parallel (DDP) | Data batches | Model fits on one GPU |
| FSDP / ZeRO | Parameters, gradients, optimizer states | Model too big for one GPU's memory |
| Tensor parallelism | Individual layers | Very large models, fast interconnect |
| Pipeline parallelism | Groups of layers | Very large models across nodes |
See distributed training parallelism, NVLink and InfiniBand vs Ethernet.
Common training problems
| Problem | Likely fix |
|---|---|
| Loss spikes or NaNs | Lower learning rate, check data for corrupt samples, gradient clipping, QK-norm |
| Loss plateaus early | Learning rate too low, data issues, bug in masking |
| Slow throughput | Use torch.compile, FlashAttention, larger batch, faster data loading |
| Out of memory | Activation checkpointing, smaller micro-batch, FSDP |
| Great training loss, poor results | Data quality, contamination, overfitting |
Step 8: Post-training
A base model predicts text but doesn't follow instructions well. Post-training adds:
| Stage | Method | Purpose |
|---|---|---|
| Supervised fine-tuning (SFT) | Train on instruction–response pairs | Follow instructions, chat format |
| Preference tuning | DPO or RLHF | Prefer helpful, harmless answers |
| Reinforcement learning with verifiable rewards | e.g. GRPO on maths and code | Improve reasoning; see reasoning models |
| Safety tuning | Refusals, red-teaming data | Reduce harmful outputs |
See What is reinforcement learning?
Step 9: Evaluate and deploy
- Held-out validation loss on your data.
- Benchmarks with EleutherAI's lm-evaluation-harness: HellaSwag, ARC, MMLU, GSM8K, HumanEval. See AI benchmarks explained.
- Human evaluation for your use case.
- Safety evaluation.
- Deploy: convert to GGUF or serve with vLLM; quantize for efficiency. See run an LLM locally and LLM quantization.
Tools and frameworks
| Tool | Best for |
|---|---|
| nanoGPT / modded-nanoGPT | Learning, small GPT models |
| llm.c | Minimal C/CUDA training, educational |
| LitGPT | Readable recipes for pretraining and fine-tuning |
| Hugging Face Transformers + Accelerate | Flexible training |
| TorchTitan | PyTorch-native large-scale pretraining |
| Megatron-LM / NeMo | Very large models on NVIDIA clusters |
| DeepSpeed | ZeRO memory optimisation |
| Weights & Biases / TensorBoard | Experiment tracking |
Hardware options
| Scale | Hardware |
|---|---|
| Learning (≤350M) | One RTX 4090/5090 or a rented GPU |
| Small models (1B) | 1–8 H100s for days |
| Mid-size (7B) | Dozens to hundreds of H100/B200s |
| Frontier | Tens of thousands of GPUs |
See best GPU for deep learning, rent vs buy a GPU and NVIDIA H100 specs.
Frequently asked questions
How much does it cost to train an LLM from scratch?
From about $20 for a 124M toy model to hundreds of thousands of dollars for a 7B model and tens or hundreds of millions for frontier models, mostly depending on parameters × tokens.
Can I train an LLM on my own computer?
Yes, small models (up to a few hundred million parameters) on a single high-end GPU. Larger models need cloud clusters.
How much data do I need to train an LLM?
At least about 20 tokens per parameter for compute-optimal training; modern small models use far more.
How long does it take to train an LLM?
Hours for tiny models, days to weeks for 1–7B models on GPU clusters, and months for frontier models.
Is it better to train from scratch or fine-tune?
Fine-tuning is better for most applications. Train from scratch to learn, research new methods, or when you need full control over data.
Sources and further reading
- Hoffmann et al., Training Compute-Optimal Large Language Models (Chinchilla, 2022)
- Kaplan et al., Scaling Laws for Neural Language Models (2020)
- Penedo et al., The FineWeb Datasets (2024)
- Andrej Karpathy, llm.c and nanoGPT
- Sebastian Raschka, Stages of building an LLM from scratch
- Meta, Llama 3.1 model card (training GPU hours)




Leave a Reply