Pretraining a language model
Pretraining is where a model learns almost everything it knows. It reads trillions of words and practices one task over and over: guess the next piece of text. This page covers every part of it.
Data: the biggest lever
The data decides what a model can know. Teams that publish their recipes agree that cleaning and choosing data matters more than almost any change to the model itself.
Where the text comes from
- Web crawls. Public snapshots of billions of web pages, collected every month or two. This is the bulk of every model's data.
- Code. Public source code, with licenses checked. Code teaches structure and step-by-step logic, and helps reasoning even outside programming.
- Math and science. Math pages pulled out of the web, papers, textbooks and worked problems.
- Books and reference. Public-domain books, encyclopedias and other long, edited text.
- Many languages. Recent open models train on more than 100 languages. Chinese is the second-largest share in most bilingual models, and Chinese teams have published large cleaned Chinese web sets.
- Synthetic data. Text written by other models: rewritten web pages, textbook-style lessons, worked math and code exercises. Used carefully, it raises quality; overused, it narrows what the model knows.
How it is cleaned
- Extract the main text from each page and drop menus, ads and boilerplate.
- Identify the language of each document with a small fast classifier.
- Rule filters remove pages that are too short, mostly symbols, full of repeated lines, or machine-made spam.
- Remove duplicates. Exact copies first, then near-copies found with MinHash (a fast way to spot documents that share most of their word groups). The web is full of copies, and training on them wastes compute and makes models repeat themselves.
- Quality filter. A small classifier, trained to recognize "educational" or "reference-like" text, scores every page. Keeping only the top slice of pages has given some of the largest gains reported in open work.
- Remove private data such as email addresses and phone numbers, and toxic content.
- Decontaminate: delete anything that overlaps with the test sets used to measure models, or the scores mean nothing.
Mixing
The final mix sets how much of each kind of text the model sees: for example mostly web text, a sizable slice of code, and smaller slices of math, books and multilingual text. Teams find good mixes by training many small models on different mixes and scaling up the winner. Late in training, the mix shifts toward the highest-quality data.
The tokenizer: turning text into numbers
A model does not read letters. It reads tokens: common chunks of text, each with a number. "Running" might be one token; a rare word might be three.
- Byte-pair encoding is the standard method. Start from single bytes, then repeatedly merge the most common pair into a new token, until the vocabulary reaches its target size.
- Working at the byte level means any text in any language can be encoded, with no "unknown" symbol.
- Vocabulary size has grown from about 32,000 tokens to 100,000 to 250,000 in multilingual models. A bigger vocabulary packs more text into each token, which matters a lot for languages like Chinese, where a small vocabulary would spend one or more tokens per character.
- Numbers are often split into single digits so the model can do arithmetic more reliably.
- The tokenizer is fixed before training and can't be changed later without retraining, so it is worth testing on every language and kind of text you care about.
Architecture: the transformer
Almost every language model is a decoder-only transformer: a stack of identical blocks. Each block lets every token look back at the tokens before it (attention), then passes each token through a small neural network (feed-forward).
The design has settled on a common set of choices, each tested in public:
- Normalize before each layer (pre-norm) with RMS normalization. It keeps training stable as models get deep.
- Gated feed-forward layers (SwiGLU) instead of the original simple ones: a little better for the same compute.
- Rotary position embeddings. Positions are encoded by rotating parts of each query and key by an angle that depends on position. This method was first described in Chinese in 2021 and is now in nearly every model.
- Grouped-query attention: several attention heads share one set of keys and values, which shrinks the memory needed when the model writes text.
- Multi-head latent attention: keys and values are squeezed into one small shared vector and expanded when needed, cutting that memory much further. Introduced in an open Chinese model in 2024.
- No bias terms, and often normalization of queries and keys (QK-norm) to stop attention values from blowing up.
Mixture of experts
In a mixture-of-experts model, the feed-forward part of each block is split into many smaller "experts". A small router picks a few experts for each token. The model can hold a huge amount of knowledge while each token only uses a small part of it.
- Total vs. active size. Open models now reach about 1 trillion total parameters with only about 30 to 40 billion active per token. One such model trained on 14.8 trillion tokens with about 2.8 million accelerator-hours, far less than a dense model of similar quality.
- Fine-grained experts. Using many small experts (for example 256, with 8 picked per token) works better than a few big ones.
- Shared experts that every token uses hold common knowledge, so the routed experts can specialize.
- Load balancing. If the router sends everything to a few experts, the rest go unused. Older models added a penalty to the loss. A newer method adds a small adjustable bias to each expert's routing score instead, nudging traffic toward idle experts without hurting quality.
- The cost: all experts must sit in memory, and sending tokens between chips to reach their experts needs careful engineering.
Scaling laws: how big, how long
Loss (how wrong the model's guesses are) falls smoothly and predictably as you add parameters, data and compute. That lets teams test ideas on small models and predict the large one.
training compute ≈ 6 × parameters × tokens
- Compute-optimal: for a fixed training budget, the best result comes from about 20 tokens per parameter. A 10-billion-parameter model would see about 200 billion tokens.
- Train longer for cheaper use. A model is trained once but used billions of times. So teams now train small models far past that point: 7 to 8 billion parameter models on 15 trillion tokens or more, over 1,000 tokens per parameter. They keep improving.
- Running out of data. High-quality public text is finite. This is why data cleaning, reuse of the best data for a few passes, and synthetic data matter more each year.
- Predicting from small runs. Fit a curve to a series of small models, then check the big run against it. A run that drifts off the curve has a problem.
Optimizers and schedules
- AdamW is the default optimizer: it adapts the step size for each weight and decays weights slightly to keep them small.
- Warmup: start with a tiny learning rate and raise it over the first few thousand steps.
- Cosine decay lowers the learning rate smoothly to near zero by the end. Its downside: you must pick the total length in advance.
- Warmup-stable-decay holds the learning rate flat for most of training, then drops it quickly at the end. You can branch off a finished model at any point, keep training without restarting, and test data mixes cheaply during the decay. This schedule came out of open small-model work in China and is now common.
- Muon is a newer optimizer that makes each update matrix "orthogonal" (balanced in every direction). Published work showed it scaling to a trillion-parameter model with about twice the efficiency of AdamW, with a clipping trick on attention scores to prevent loss spikes.
- Hyperparameter transfer. With careful scaling rules for initialization and learning rates (often called μP), the best settings found on a small model carry over to a large one.
- Batch size grows during training: small batches early, larger later, often reaching millions of tokens per step.
Number precision
- Training in 16-bit numbers (bfloat16) is the standard. Master copies of the weights and optimizer state are kept in 32-bit.
- 8-bit training (FP8) roughly doubles speed and halves memory for the heavy matrix math. The trick that made it work at very large scale is fine-grained scaling: each small tile of numbers gets its own scale factor, so a few large values don't wreck the precision of the rest. Sums are kept in higher precision.
- Some numbers stay in higher precision no matter what: normalization, the router in expert models, the final output layer and the loss.
Running thousands of chips as one
The measure of success is utilization: the share of the chips' peak math speed actually used. Good large runs reach roughly 35 to 55 percent. Overlapping communication with computation is most of the work. Several Chinese teams have open-sourced their communication libraries, pipeline schedules, matrix-math kernels and even a distributed file system built for training.
Keeping a run stable
- Loss spikes are sudden jumps in error. Small ones recover; big ones can ruin a run.
- Common fixes: lower the learning rate, clip gradients, normalize queries and keys, add a small penalty that keeps output scores from drifting (z-loss), and skip the batch that caused the spike.
- Save checkpoints often. When a run breaks, roll back to the last good checkpoint and continue with a different data order.
- Watch hardware: at the scale of thousands of chips, a failed chip or a silent math error happens every few days. Automatic restarts and health checks are essential.
- Track many signals, not just the loss: gradient size, the size of the largest activations, and small evaluations every few thousand steps.
Long context
Training on very long texts is expensive, because attention cost grows with the square of the length. So models are trained mostly on short texts (4,000 to 8,000 tokens) and then extended in stages: to 32,000, then 128,000, sometimes 1 million tokens.
- Stretch the positions. Raising the base frequency of the rotary embeddings, or rescaling them in smarter ways, lets the model handle positions it never saw.
- Train on real long documents (books, long code files, papers) for a few billion tokens at each new length.
- Cheaper attention: some layers look only at a sliding window of recent tokens; some models replace most attention layers with linear attention, which costs the same per token no matter how long the text, and keep a few full attention layers. Others pick the most relevant earlier tokens for each query (sparse attention).
Mid-training and annealing
Between pretraining and post-training, many teams run a mid-training stage: a few hundred billion to a few trillion tokens of the best data they have, as the learning rate falls to zero. Math, code, reasoning examples, long documents and instruction-like text get a much larger share. This step often brings the biggest jump in test scores for the compute spent.
Some models also learn to predict several future tokens at once during pretraining. It gives a denser learning signal and the extra prediction heads can be reused later to speed up text generation.