Skip to content

How to Train an LLM From Scratch: Data, Compute, Code and Cost (Step by Step)

A complete, practical guide to training your own large language model from zero: when it makes sense, the nine stages, datasets and tokenizers, choosing model size with scaling laws, the 6ND compute formula with worked GPU-hour and cost examples, architecture choices, a minimal training loop, hyperparameters, debugging, post-training, evaluation and tools.

7 min read

How to Train an LLM From Scratch — how to train an llm from scratch

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?

OptionCostWhen it makes sense
Use an APILowest upfrontPrototypes, general tasks
Fine-tune an open model (LoRA/QLoRA)LowCustom style, format or domain behaviour; see What is LoRA?
Continued pretrainingMediumLarge domain corpus (legal, medical, code, a new language)
Train from scratchHighLearning 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

StageWhat you doKey output
1. Goal and budgetDefine model size, domain, compute budgetTraining plan
2. DataCollect, filter, deduplicate, mixClean dataset
3. TokenizerTrain or choose a tokenizerVocabulary and token IDs
4. Model sizeUse scaling laws to match parameters and tokensArchitecture config
5. ImplementationBuild and test a decoder-only transformerWorking model code
6. PretrainingNext-token prediction at scaleBase model
7. Post-trainingSupervised fine-tuning, preference tuning, RLInstruction-following model
8. EvaluationBenchmarks, held-out loss, human review, safetyReport
9. DeploymentQuantize and serveUsable 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 typeExamplesNotes
Web textFineWeb (about 15 trillion tokens), FineWeb-Edu, RedPajama, DolmaFiltered Common Crawl
CodeThe Stack v2Licence filtering matters
Books and papersPublic-domain books, arXivCheck licences
Maths and scienceOpenWebMath, curated datasetsImproves reasoning
Domain dataYour documentsThe reason many people train custom models
Synthetic dataGenerated by stronger modelsIncreasingly 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.

ParametersChinchilla-optimal tokens"Over-trained" (common today)
124M~2.5B10–100B
1B~20B100B–2T
7–8B~150B2–15T
70B~1.4T15T+

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.

ModelTokensTraining FLOPsH100-hours (40% MFU)Approx. cost at $3.92/hr
124M10B7.4 × 1018~5~$20
350M30B6.3 × 1019~44~$170
1B20B1.2 × 1020~83~$330
1B100B6 × 1020~420~$1,600
7B1T4.2 × 1022~29,000~$114,000
70B15T6.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:

ComponentCommon modern choiceWhy
Positional encodingRoPEGood length generalisation; see RoPE explained
NormalisationRMSNorm, pre-normStable training
ActivationSwiGLUBetter quality per parameter
AttentionGrouped-query attention (GQA)Smaller KV cache; see MHA vs MQA vs GQA vs MLA
Attention kernelFlashAttentionFaster and memory-efficient; see FlashAttention
Bias termsUsually removedSimpler, stable
Mixture of expertsOptional for large modelsMore parameters at same compute; see mixture of experts

Example small configs:

ModelLayersHidden sizeHeadsContext
124M12768121,024
350M241,024162,048
1B16–242,04816–322,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

SettingTypical value
OptimizerAdamW (β1 0.9, β2 0.95)
Peak learning rate~6e-4 for ~100M models, lower (~3e-4 or less) for larger
ScheduleLinear warmup (~1–2% of steps), then cosine or warmup-stable-decay
Weight decay0.1
Gradient clipping1.0
PrecisionBF16 mixed precision (FP8 on Hopper/Blackwell for large runs)
Batch size~0.5M tokens for small models; several million for large
Sequence length1,024–8,192, extended later

Scaling to many GPUs

TechniqueWhat it splitsWhen to use
Data parallel (DDP)Data batchesModel fits on one GPU
FSDP / ZeROParameters, gradients, optimizer statesModel too big for one GPU's memory
Tensor parallelismIndividual layersVery large models, fast interconnect
Pipeline parallelismGroups of layersVery large models across nodes

See distributed training parallelism, NVLink and InfiniBand vs Ethernet.

Common training problems

ProblemLikely fix
Loss spikes or NaNsLower learning rate, check data for corrupt samples, gradient clipping, QK-norm
Loss plateaus earlyLearning rate too low, data issues, bug in masking
Slow throughputUse torch.compile, FlashAttention, larger batch, faster data loading
Out of memoryActivation checkpointing, smaller micro-batch, FSDP
Great training loss, poor resultsData quality, contamination, overfitting

Step 8: Post-training

A base model predicts text but doesn't follow instructions well. Post-training adds:

StageMethodPurpose
Supervised fine-tuning (SFT)Train on instruction–response pairsFollow instructions, chat format
Preference tuningDPO or RLHFPrefer helpful, harmless answers
Reinforcement learning with verifiable rewardse.g. GRPO on maths and codeImprove reasoning; see reasoning models
Safety tuningRefusals, red-teaming dataReduce 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

ToolBest for
nanoGPT / modded-nanoGPTLearning, small GPT models
llm.cMinimal C/CUDA training, educational
LitGPTReadable recipes for pretraining and fine-tuning
Hugging Face Transformers + AccelerateFlexible training
TorchTitanPyTorch-native large-scale pretraining
Megatron-LM / NeMoVery large models on NVIDIA clusters
DeepSpeedZeRO memory optimisation
Weights & Biases / TensorBoardExperiment tracking

Hardware options

ScaleHardware
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
FrontierTens 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

Think you understand it now? Prove it.

Solve real Tensor Core math in the TensorCore.si Challenge and earn a certificate with your name.

Take the challenge

Leave a Reply

Your email address will not be published. Required fields are marked *