Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

A Survey of Pre-training Techniques

Over the previous ten chapters, we built and pre-trained a GPT model step by step:

Overall, what we implemented is basically the GPT-2 architecture (GPT-3 mainly scaled it up and used sparse attention in some layers). But compared with today’s mainstream large models (Llama, Qwen, DeepSeek, Gemma, and others), almost every part has changed a great deal, from tokenization to attention, and from module details to training data.

These new architectures are hard to demonstrate with small code and small data. In this chapter we survey the cutting-edge techniques of the pre-training stage and draw a complete technology map. Interested readers can dig deeper from here.

Large model technology evolves quickly; the content of this chapter is current as of November 2026.

Technology comparison

A comparison table shows how the GPT we implemented differs from modern mainstream large models:

ComponentOur GPTModern mainstream large models
TokenizationCharacter-level, vocabulary of about 65Byte-level BPE, vocabulary of 30,000 to 250,000
Position encodingTrainable absolute position embeddingRotary position embedding (RoPE)
AttentionMulti-head attention (MHA), all globalGrouped-query attention (GQA) or multi-head latent attention (MLA); alternating local and global layers, sparse attention, and in some models linear attention
NormalizationLayer normalization (LayerNorm), pre-normRoot mean square normalization (RMSNorm), pre-norm, and QK-Norm in some models
Feed-forward networkGELU, hidden layer 4×SwiGLU, hidden layer about 2.7× to 3.5×, or mixture of experts (MoE)
Linear layer biasYesUsually none
DropoutYesUsually none
Input and output embeddingsIndependentOften shared in small models, usually independent in large ones
Numerical precisionFP32BF16 mixed precision, FP8, FP4 explored in some cases
OptimizerAdamWAdamW, Muon in some models
Learning rate scheduleWarmup + cosine decayWarmup + cosine decay, or warmup-stable-decay (WSD)
Context size256128K to 1M
Training dataAbout 1.1 million characters of Shakespeare’s playsTrillions of tokens, cleaned, deduplicated, and mixed

Tokenization

Character-level tokenization

We use character-level tokenization: each character is a token, and the vocabulary has only a few dozen entries. It is simple, but the cost is high:

The other extreme is word-level tokenization: each word is a token. Sequences get shorter, but the vocabulary becomes huge, and words that were never seen (out of vocabulary, OOV) cannot be handled, such as newly coined words, misspellings, and personal names.

Subword tokenization

Subword tokenization is the compromise: common words are kept whole, and rare words are split into smaller pieces. There are three main algorithms:

Tokenizers are commonly trained with SentencePiece (which trains directly on raw text and treats spaces as ordinary characters, suitable for languages without spaces such as Chinese and Japanese) and Hugging Face’s tokenizers library.

Byte-level BPE

The most mainstream scheme today is byte-level BPE: merging starts from the 256 bytes instead of from characters. Any text can be represented as a byte sequence, so OOV never occurs, and there is no need to reserve room for the characters of various languages. It has been used since GPT-2.

Before BPE tokenization there is usually also a pre-tokenization step: a regular expression first roughly splits the text into words, numbers, punctuation, and so on, and BPE is then applied inside each piece, which avoids merges that cross the natural boundaries of words. OpenAI’s tiktoken is a commonly used fast encoding library, but it only encodes and does not train tokenizers.

Vocabulary size

Vocabulary size is a trade-off:

Typical vocabulary sizes:

The trend is toward ever larger vocabularies, especially to support more languages better.

Special tokens

Besides text pieces, the vocabulary also contains some special tokens: tokens marking the beginning and end of a sequence, padding tokens, and tokens that distinguish the system, user, and assistant roles in a conversation. The end token is especially important: the model relies on it to learn “when to stop”. We will see how they are used in the fine-tuning chapters.

Multimodal tokens

Multimodal models likewise need to turn images and audio into token sequences:

Embedding sharing

In our model, the weights of the token embedding in the embedding layer and the weights of the linear layer in the output layer are two independent matrices. But their shapes happen to be the same: both are (vocabulary size, embedding size) (the weights of our linear layer are stored as (output, input)).

Weight tying makes the two use the same set of parameters. GPT-2 does exactly this. When the vocabulary is large and the model is small, the embedding and output layers take a considerable share of the parameters, so small models (such as Gemma, the small sizes of Llama 3.2, and the small sizes of Qwen) often adopt it; once the model gets larger, this part is a small share and is usually no longer shared.

Position encoding

Absolute position embedding

We use a trainable absolute position embedding: each position has its own position vector, which is added to the word vector. It has two limitations:

The evolution of position encoding

Rotary position embedding

Rotary position embedding (RoPE) does not add a position vector to the word vector, but expresses position by rotating vectors.

RoPE divides the dimensions of the query vector (qq) and the key vector (kk) into groups of two, treats each group as a vector in a two-dimensional plane, and rotates it by an angle mθim\theta_i proportional to the token position mm, with different groups using different frequencies θi\theta_i. After the rotation, when the query vector at position mm and the key vector at position nn take a dot product, the result depends only on their relative distance and has nothing to do with their absolute positions mm and nn:

(Rmq)⊤(Rnk)=q⊤Rn−mk(R_m q)^\top (R_n k) = q^\top R_{n-m} k

Where:

This design gives the model a natural sense of relative position, and there is no need to add a position vector to the word vector any more. The vast majority of mainstream open-source large models adopt RoPE, including Llama, Qwen, DeepSeek, Gemma, and Mistral.

Context extension

The context size during training is often far smaller than the final supported size, because training on long sequences is expensive. The common practice is:

Attention

Both the computation of self-attention and the size of the attention score matrix are proportional to the square of the sequence length nn: O(n2d)O(n^2d). When the context grows from 4K to 128K, the computation of the attention part increases about 1000 times.

This is the core driver of attention research in pre-training: how to make attention faster and cheaper, or to bypass the quadratic complexity altogether.

Reducing key-value heads

In standard multi-head attention (MHA), each query head has its own set of keys and values. It is expressive, but at inference time too many keys and values need to be cached, which costs a lot of GPU memory and bandwidth. Letting several heads share keys and values shrinks the cache by a multiple:

The main motivation of these algorithms is to reduce the key-value cache (KV cache) at inference time, but they all change the structure of the model, and are usually fixed during pre-training. There are also approaches that start from an MHA model and convert it to GQA with a small amount of continued training. Most mainstream large models today adopt GQA, while DeepSeek, Kimi, and others adopt MLA.

Efficient attention computation

Standard attention has to write the complete attention score matrix to GPU memory and read it back for the Softmax and the weighted sum, so a lot of time is spent moving data.

FlashAttention uses tiling: it cuts the queries, keys, and values into small blocks and completes the Softmax and the weighted sum in the fast cache, without writing the complete attention matrix to GPU memory. This reduces the memory use of this part from O(n2)O(n^2) to O(n)O(n) and also speeds things up significantly. Its output is identical to standard attention: it is exact computation, not an approximation. Improved versions for newer GPU architectures have followed FlashAttention. Today the pre-training of mainstream large models almost always enables it by default.

Sparse attention

Most of the weights in the attention matrix are actually close to 0, so we can choose to compute only the most important positions:

Linear attention and state space models

Another path is to bypass the quadratic complexity entirely. Linear attention and state space models (SSM, such as Mamba) rewrite attention in a recurrent form: they summarize the history with a fixed-size state instead of an ever-growing KV cache. The computation grows linearly with the sequence length, and the memory use at inference time is constant.

But compressing into a fixed-size state has a price: on tasks that need to recall a precise detail, pure linear models are weaker than full attention. So since 2025 a hybrid architecture has become the more common practice: most layers use linear attention or state space layers, and a few keep full attention. Examples are Qwen3-Next (Gated DeltaNet and gated attention), Kimi Linear ( linear attention and MLA), and Nemotron 3 (Mamba layers, attention layers, and MoE).

Attention stability

QK-Norm normalizes the query and the key before computing the attention scores, which prevents scores that are too large from saturating the Softmax and makes training more stable. Qwen3, Gemma 3, OLMo 2, and other models all adopt it.

The evolution of the Transformer block

The Transformer block we implemented is: normalization → attention → dropout → residual connection; normalization → feed-forward network → dropout → residual connection. Modern large models have improved every submodule.

Normalization

Feed-forward network

The gated linear unit (GLU): the feed-forward network is no longer “linear → activation → linear”, but adds a gating mechanism:

FFN(x)=(Swish(xW1)⊙xW3)W2\text{FFN}(x) = \left(\text{Swish}(x W_1) \odot x W_3\right) W_2

Where:

One path, after the activation, “gates” the other, linear path. This structure is called SwiGLU; at the same parameter count it performs consistently better than GELU and has become standard in most mainstream large models.

The feed-forward network has two more improvements:

Several design points of MoE:

Residual connection

A standard residual connection has only one “main road”. Hyper-connections widen the residual stream into several parallel channels and let them mix with each other, which strengthens expressiveness. But unconstrained mixing amplifies the signal in deep networks and makes training unstable. The mHC (Manifold-Constrained Hyper-Connections) proposed by DeepSeek constrains the mixing matrix to a specific manifold, restoring the identity mapping property of the residual connection. DeepSeek-V4 has adopted mHC. This is still a direction under exploration.

Dropout

We use dropout in our model to prevent overfitting. But the pre-training of modern large models usually does not use it: the training data usually goes through only once, the model is underfitting rather than overfitting, and dropout would only slow down convergence.

Only when the amount of data is insufficient and several epochs of repeated training are needed (as with our model) does dropout become worthwhile. The weight decay used in large-model pre-training also does not mainly serve to prevent overfitting, but to work with the learning rate to shape the dynamics of optimization.

Linear layer bias

The linear layers of modern large models usually drop the bias, which reduces parameters and simplifies the implementation. Some models once kept the bias in the QKV projections of attention (for example Qwen2) and later dropped it as well (Qwen3 switched to QK-Norm to stabilize training).

Training objectives

What we train is the most basic next-token prediction: each position predicts the next token. Modern large models extend it in a few ways:

Optimization

Optimizers

The AdamW we use is also a commonly used optimizer today. Common configurations for large-model pre-training include:

Muon is the most closely watched alternative to AdamW in recent years. It is applied only to two-dimensional weight matrices: it first orthogonalizes the momentum and then updates the parameters, while the remaining parameters (such as embeddings and normalization) still use AdamW. Muon keeps only one momentum buffer, so its optimizer state takes less GPU memory than AdamW’s, and its sample efficiency is also an advantage. Kimi K2 (1.04T parameters, 15.5T tokens) used its improved version MuonClip, and GLM-4.5, GLM-5, and DeepSeek-V4 also used Muon.

Learning rate schedulers

We use the warmup cosine decay learning rate scheduler, which raises the learning rate to a peak through warmup and then decays it through cosine decay.

But it has a drawback: the total number of training steps must be fixed in advance, which is inflexible.

WSD (Warmup-Stable-Decay) does not need the amount of training to be fixed in advance:

This way, we can start from any checkpoint in the stable phase and decide how to finish, and it is also convenient to continue training or adjust the data after the stable phase.

Scaling hyperparameters

Hyperparameters tuned on a small model are often no longer optimal on a large one. The usual practice is: the peak learning rate of a large model is smaller than that of a small model, and the batch size is gradually increased during training. There are also methods such as μP (Maximal Update Parametrization), which adjust the initialization and the learning rate scaling of each layer so that hyperparameters tuned on a small model can be transferred directly to a large one.

Training stability

Large-model pre-training often lasts weeks or even months, and a loss spike or even divergence in the middle of training is very costly. Common causes include: a learning rate that is too large, attention scores growing too fast and saturating the Softmax, numerical overflow, and a few abnormal data points. Commonly used countermeasures:

Training data

The abilities of a model depend largely on data. Data work usually takes most of the energy of a pre-training team.

Data sources

Public large-scale pre-training datasets, such as FineWeb (about 15 trillion tokens), let researchers reproduce the complete data processing pipeline.

Data cleaning

Raw data must go through several processing steps before it can be used. A typical pipeline is:

Data mixing

The proportions in which data from different sources are mixed have a large impact on model ability. Mixtures can be tuned through experiments on small models, and there are also methods such as DoReMi that search for the mixture automatically. The gain from reusing the same data diminishes: some studies have found that data repeated up to 4 epochs works about as well as fresh data.

The pre-training of modern large models is usually staged, with higher data quality in the later stages. Take Qwen3 as an example:

  1. Stage 1: about 30 trillion tokens with a sequence length of 4K, to build general language ability and knowledge;

  2. Stage 2: about 5 trillion tokens, increasing the share of knowledge-intensive data such as STEM, code, and reasoning, and speeding up the learning rate decay;

  3. Stage 3: several hundred billion tokens of long text, to extend the context to 32K.

Adding high-quality data during the learning rate decay phase is also called annealing. These later stages are sometimes called mid-training separately.

Synthetic data

High-quality natural data is limited, so synthetic data is used more and more:

The risk of synthetic data is that a model repeatedly trained on its own generated data may gradually lose diversity. So it must be filtered strictly and mixed with real data.

Scaling laws

The relationship between loss and scale

Scaling laws found that the loss of a model has a predictable power-law relationship with the number of model parameters NN, the amount of training data DD, and the amount of compute CC. A commonly used form is:

L(N,D)=E+ANα+BDβL(N, D) = E + \frac{A}{N^{\alpha}} + \frac{B}{D^{\beta}}

Where:

The compute of training is about C≈6NDC \approx 6ND. With scaling laws, we can fit curves on small-scale experiments and extrapolate to predict the loss of large models, making decisions before investing huge amounts of compute.

Compute-optimal

Given a fixed compute budget, how large a model should we train, and with how much data? Early research (Kaplan et al.) tended to spend more of the budget on enlarging the model. The later Chinchilla research revised the conclusion: the number of parameters and the amount of data should grow together, and the compute-optimal ratio is about 20 tokens per parameter.

Overtraining

Compute-optimal considers only the cost of training. But a model is trained once and used for inference countless times, and a smaller model is cheaper for inference. So modern large models are often overtrained: a smaller model is trained with far more data than is compute-optimal. For example, the 8B model of Llama 3 was trained on about 15 trillion tokens, nearly a hundred times the Chinchilla ratio; Qwen3 used 36 trillion tokens.

For MoE models, the parameter count in the scaling law should be the number of activated parameters, and the data requirement changes accordingly.

Emergent abilities

After a model’s scale exceeds some threshold, certain abilities seem to appear suddenly; these are called emergent abilities. But there is also research pointing out that this depends largely on the evaluation metric: a metric that scores only “completely correct” shows abrupt jumps, while with a smooth metric the ability actually improves gradually. For readers, the more important conclusion is that the trend of abilities improving with scale is predictable, but when a specific ability becomes usable still needs to be measured.

New dimensions of scaling have also appeared in the post-training and inference stages: the compute for reinforcement learning and the compute at inference time, which later chapters introduce.

Training systems

Parallelism strategies

A large model cannot fit in one GPU, so training must be split across hundreds or thousands of GPUs. Commonly used parallelism methods are:

Real training usually combines these methods. Megatron-LM, DeepSpeed, and torchtitan are commonly used training frameworks.

Memory and efficiency

A commonly used metric of training efficiency is model FLOPs utilization (MFU): the fraction of the hardware’s theoretical peak that is actually achieved. The MFU of large-scale training is usually between 30% and 50%.

Fault tolerance and persistence

The larger the scale, the more normal failures become. When Llama 3 was trained on 16K H100 GPUs, there were more than 400 unexpected interruptions in about 54 days, most of them hardware failures. So large-scale training must have:

Evaluation

The goal of evaluation in the pre-training stage is to judge what the model has learned and whether training is going in the right direction:

What pre-training yields is a base model, and its evaluation differs from that of a chat model, which is introduced in the fine-tuning survey.


In this chapter, we surveyed the mainstream techniques of pre-training:

The GPT model we implemented from scratch is the starting point of these techniques. The basic structure of the Transformer is still the skeleton of mainstream models today, and later improvements mostly patch this skeleton, while the hybrid architectures since 2025 have begun to change the skeleton itself.

References