Learn
Training & fine-tuning

How do you train a 7B language model from scratch?

The short answer

Training a 7B model from scratch means choosing an architecture and tokenizer, assembling and cleaning a corpus of one to fifteen trillion tokens, running a months-long distributed pretraining job with checkpointing and failure recovery, then fine-tuning and evaluating the result. It is a data and infrastructure project as much as a modelling one.

On this page

What 7B actually means

Seven billion parameters is a budget class, not a specification. The count includes the token embedding table, every attention and feed-forward weight in every layer, and the output projection. A Llama-shaped 7B model uses 32 layers, a hidden size of 4096, 32 attention heads of dimension 128, a feed-forward width of 11008 and a vocabulary of 32,000, which lands at about 6.7 billion parameters. Change the vocabulary to 128,000 and you add roughly three billion parameters in embeddings alone, which is why multilingual models of the same depth are much larger than their English counterparts.

The shape matters more than the total. Depth determines how many sequential transformations a token passes through, width determines how much information each layer can hold, and the ratio between attention and feed-forward parameters determines the split between mixing information across tokens and processing it per token. A model with the same parameter count but half the depth will train faster per token and behave differently on tasks that need multi-step composition.

The parameter count also fixes your serving economics. At 16-bit precision, 7B weights occupy about 14GB, which is why a 24GB GPU can serve one model with a modest context. The KV cache then grows with context length: for this configuration it costs roughly 512KB per token across all layers, so a single 4096-token conversation holds about 2GB of cache. Four concurrent users at that length and you have exhausted the card. Training decisions quietly become deployment constraints.

Step one: the tokenizer

The tokenizer converts text into the integer sequence the model actually sees, and it is the one component you cannot change later without retraining from scratch. Most models use byte-level byte-pair encoding: start from raw bytes so nothing is ever out of vocabulary, then greedily merge the most frequent adjacent pairs until you reach the target vocabulary size. The merge table is learned from a sample of the corpus, typically a few tens of billions of characters, and it is frozen for the life of the model.

Vocabulary size is a trade-off with no free lunch. A 32,000-token vocabulary keeps the embedding table and the output softmax small, which saves parameters and speeds up training, but it produces longer sequences: English text averages around 1.3 tokens per word, and code or Hindi can be far worse. A 128,000-token vocabulary shortens sequences, which reduces attention cost and increases effective context, but it inflates the embedding and output layers and gives each rare token fewer training examples. Fertility, the average number of tokens per word, is the metric to watch, and it should be measured per language and per domain rather than overall.

Practical rules: train the tokenizer on a sample that matches your intended data mix, not on Wikipedia alone. Reserve explicit special tokens for beginning and end of sequence, for the chat roles you plan to use, and for any tool-call delimiters, and add them before training rather than patching them in later. Normalise Unicode consistently, decide explicitly how you handle digits and whitespace, and test the tokenizer on the ten inputs you care most about before committing. A tokenizer with no token for a common script will make that script permanently expensive, and the mistake surfaces only after the training bill is paid.

Step two: architecture choices

Almost every open 7B model is a decoder-only transformer with rotary position embeddings, RMSNorm applied before each sublayer, SwiGLU feed-forward blocks and grouped-query attention. This convergence is not because the alternatives are bad but because it is what the tooling, kernels and inference servers support. Choosing an unusual architecture means writing your own fused kernels and losing the ecosystem, which is a large tax for a small expected gain.

The choices that genuinely matter are narrower than they look. Grouped-query attention, where several query heads share one key-value head, cuts KV cache size by the group factor and is close to free in quality terms, so it is now standard. Whether to tie the input embedding and output projection matters mainly for small models, where it saves parameters; at 7B it is usually left untied. Context length is set by the rotary base and the data you train on, and extending it later requires additional long-context training rather than a configuration flag. Dropout is normally zero at this scale because the dataset is large enough that regularisation is not the binding constraint.

  • Prefer the architecture your inference stack already supports: vLLM, TensorRT-LLM and llama.cpp all assume Llama-like layouts.
  • Use bf16 throughout; fp16 needs loss scaling and is more fragile at scale.
  • Set the rotary base for the context length you will actually train on, and record it, since changing it invalidates checkpoints.
  • Keep a config file in version control with every dimension, and assert that the parameter count matches what you intended before launching.

Step three: building the corpus

Data work is the majority of the project and the majority of the quality. A realistic pipeline starts from web crawls such as Common Crawl, extracts main text from HTML with a readability model or a trafilatura-style parser, identifies language, filters for quality, removes duplicates, strips personal information and decontaminates against your evaluation sets. Each stage has a measurable yield, and a healthy pipeline discards ninety percent or more of what it ingests.

Quality filtering is where most of the leverage sits. Simple heuristics, such as minimum length, ratio of alphabetic characters, repeated-line fraction and presence of boilerplate, remove a large fraction of junk cheaply. A classifier trained on a small set of pages you consider high quality, in the style of FineWeb-Edu, removes far more. Deduplication matters more than people expect: exact hashing catches copies, but near-duplicate detection with MinHash and locality-sensitive hashing catches the paraphrased and templated pages that otherwise get memorised. Duplication both wastes compute and increases regurgitation risk.

The final mix is a policy decision. Code improves reasoning and structured output but can degrade prose if over-weighted. Mathematical text improves quantitative ability but is narrow. Multilingual data costs capacity that could go to English unless you need it. Record the mix as percentages and keep the sampled shards so the run is reproducible. Tokenise offline into packed sequences with an end-of-sequence token between documents, shuffle at the shard level, and never let a document straddle a batch boundary without a separator, or the model learns that unrelated texts run together.

Step four: memory and parallelism

A 7B model does not fit on one GPU once you account for optimizer state. In mixed-precision Adam, each parameter needs two bytes for the weight, two for the gradient, four for the fp32 master copy and four each for the two moment estimates: sixteen bytes, or about 112GB for 7B parameters. Activations add more, and their size scales with batch size and sequence length. This is why every serious run uses sharding.

The common recipe is fully sharded data parallel, or ZeRO-3, which partitions weights, gradients and optimizer state across all ranks and gathers them layer by layer during the forward and backward pass. It works well up to a few hundred GPUs. Beyond that, or when a single layer will not fit, tensor parallelism splits individual matrices across GPUs within a node and pipeline parallelism splits layers across nodes, at the cost of bubbles and extra communication. Activation checkpointing recomputes activations in the backward pass instead of storing them, trading about thirty percent more compute for a large memory saving, and FlashAttention avoids materialising the full attention matrix at all.

  • Start with the smallest configuration that fits, measure tokens per second per GPU, then scale out only if the step time is the bottleneck.
  • Keep global batch size in tokens, not sequences, so changing sequence length does not silently change the learning rate schedule.
  • Use a distributed filesystem that can absorb checkpoint writes; a 7B checkpoint in bf16 plus optimizer state is well over 100GB.
  • Write sharded checkpoints and keep a rolling window, so a corrupted write does not end the run.

Step five: optimisation settings

The defaults that work are boring and well documented. AdamW with beta1 0.9 and beta2 0.95, epsilon around 1e-8, weight decay 0.1 applied to matrices but not to norms or biases, gradient clipping at 1.0, a linear warmup of one to two thousand steps, then cosine decay to about ten percent of peak. A 7B model typically peaks around 3e-4 with a global batch of two to four million tokens; smaller batches need lower learning rates, larger batches can take slightly higher ones.

Schedule by tokens consumed rather than by epochs, because the corpus is effectively infinite and epochs are meaningless at this scale. Log gradient norm, loss, learning rate and tokens per second at every step, and log per-layer gradient norms occasionally. A sudden increase in gradient norm usually precedes a loss spike by a few dozen steps, which gives you time to act. Adding a small auxiliary loss on the log-sum-exp of the output logits, the z-loss used in PaLM, costs almost nothing and materially improves stability at large learning rates.

Step six: keeping the run alive

At a thousand GPUs, things break constantly. Individual accelerators fail, NVLink errors appear, a dataloader stalls, a checkpoint write silently truncates, and a node quietly returns wrong results. Expect to lose a node every few hours on a large cluster and design for it: a supervisor that detects a hang, kills the job, and restarts from the last good checkpoint. Checkpoint every thirty to sixty minutes early in the run and less often later, and always verify that the checkpoint loads before deleting the previous one.

Loss spikes are normal and are not automatically a reason to restart. The usual response is to skip the offending data batch, roll back a few hundred steps to a checkpoint before the spike, and lower the learning rate slightly or increase warmup for the remainder. Persistent spikes after rollback usually indicate a data problem, such as a shard of garbage or a tokenizer mismatch, rather than a hyperparameter problem. Keep a hash of every data shard and log which shards were consumed, or you will never find the bad one.

Step seven: evaluation

Training loss tells you the model is learning the corpus; it does not tell you the model is good. Track held-out loss on a clean validation set drawn from the same distribution, then a panel of downstream tasks: reading comprehension, reasoning, code generation, multilingual accuracy. Compare against a baseline trained with the same tokenizer and a similar budget, because benchmark numbers are only meaningful relative to something.

Contamination is the trap. If benchmark questions appear in your crawl, the score measures memorisation. Run n-gram overlap checks between your training data and every evaluation set before you trust a number, and prefer benchmarks released after your data cutoff where possible. Also evaluate the base model as it will actually be used, which for most products means after instruction tuning, since base-model benchmark scores and assistant quality correlate only loosely.

Step eight: post-training and release

A freshly pretrained model is a text continuator, not an assistant. Supervised fine-tuning on instruction-response pairs teaches the chat format and basic compliance, preference optimisation such as DPO sharpens which of several valid answers is preferred, and safety training reduces harmful outputs. Each stage needs its own held-out evaluation, and the regression suite from pretraining should keep running so you notice when alignment damages capability.

Before release, red-team the model on the categories that matter for your deployment, document the data mix and known gaps in a model card, and state the licence and the intended use plainly. Publish the tokenizer and config alongside the weights; without them the checkpoint is not reproducible, and reproducibility is most of what makes a from-scratch release useful to anyone else.

A realistic budget and timeline

For a 7B model at one trillion tokens, the compute is around 4.2e22 FLOPs. At forty percent MFU on H100s that is roughly 70,000 to 80,000 GPU-hours, or three days on a thousand GPUs, costing 150,000 to 250,000 dollars at market rental rates. Doubling the token count doubles the bill. Add thirty to fifty percent for failed runs, ablations and the smaller-scale experiments that tell you which recipe to use.

The schedule is usually longer than the compute suggests. Data pipeline work takes two to four months, tokenizer and architecture ablation a few weeks, the pretraining run a week or two of wall clock once the cluster behaves, and post-training and evaluation another month. A small team should budget six to nine months end to end, most of it on data. The teams that finish are the ones that built the evaluation harness and the data pipeline before renting the GPUs.

Page feedback

Was this helpful?

A quick signal helps improve these notes.

Report a mistake Straight to the lab inbox

Put it to work

See the models, datasets and gateway this lab runs.