How Large Language Models Are Trained: A Three-Stage Pipeline Explained
This article explains the three-stage training pipeline for large language models: pretraining, supervised fine-tuning (SFT), and reinforcement learning based on human feedback. It covers next-token prediction, causal masking, positional encoding and extrapolation, Pre-Norm versus Post-Norm, base models, instruction-response fine-tuning, and reward modeling with relative rankings. Readers will gain a structured understanding of what each stage optimizes, what data it uses, and how the stages connect.
1. Overall Framework
Large model training is typically divided into three stages: pretraining, supervised fine-tuning (SFT), and reinforcement learning based on human feedback. Each stage has a different objective. Pretraining lets the model learn the statistical patterns of language itself; fine-tuning teaches it to answer in instruction format; reinforcement learning makes outputs better align with human preferences. The output of one stage is the starting point for the next, and the three stages are closely connected.
2. Stage 1: Pretraining
2.1 Training Objective: Next-Token Prediction
The core task of pretraining is autoregressive language modeling: predicting the next token based on the preceding context. Let a sequence be x1 to xT. The training objective is to minimize the negative log-likelihood:
L = -Σ log P(x_t | x_<t)
The model repeatedly performs this task on massive amounts of text, gradually learning grammar, factual knowledge, and reasoning patterns. This stage does not require manual annotation; the data comes from cleaned general-purpose text.
2.2 Causal Mask: Keeping Training and Generation Consistent
The self-attention layer in a decoder architecture uses a causal mask. When computing attention at position t, the model can only attend to tokens at positions no greater than t. Attention scores for future positions are set to negative infinity, so their weights become zero after softmax.
The reason for this design is that future tokens do not exist during text generation. If the model were allowed to see the future during training, it would learn to copy answers rather than predict them, and the information distribution during training and inference would be severely mismatched.
Bidirectional encoders use both left and right context at the same time, making them better suited to text understanding tasks, but they cannot be directly used for token-by-token generation. The value of the causal mask is that it keeps the training process consistent with the generation process, rather than simply improving generalization.
def causal_mask(seq_len):# Lower triangle is True (visible); upper triangle is False (masked)return [[j <= i for j in range(seq_len)] for i in range(seq_len)]def apply_mask(scores, mask):# Fill masked positions with negative infinity; after softmax their probability approaches 0for i in range(len(scores)):for j in range(len(scores[i])):if not mask[i][j]:scores[i][j] = float("-inf")return scores
2.3 Positional Encoding and Extrapolation
Transformer attention computation is inherently insensitive to order, so position information must be explicitly injected. There are three common approaches.
The first is absolute positional encoding, which assigns a fixed vector to each position. Positions beyond the training length have no corresponding training samples, so representation quality can degrade.
The second is relative positional encoding, which focuses on the distance between tokens rather than absolute coordinates. It transfers better to inputs of different lengths than absolute encoding.
The third is rotary positional encoding, which rotates query vectors and key vectors by position angle so that their inner product depends only on relative distance. This approach performs well in relative position modeling and length extrapolation, so it is widely used in recent large models.
Extrapolation refers to the phenomenon in which the input length during training and inference are inconsistent, causing model performance to degrade. Mitigating extrapolation problems usually requires multiple measures, including training with samples of various lengths, interpolating positional information, and performing a small amount of continued training on long-text data. Positional encoding is only one part of this.
2.4 Normalization Placement: Pre-Norm and Post-Norm
In a residual block, LayerNorm can be placed after the sublayer, which is called Post-Norm, or before the sublayer, which is called Pre-Norm. The original Transformer used Post-Norm.
In deep networks, Post-Norm gradients must pass through multiple normalization layers before reaching shallow layers, making vanishing gradients or unstable training more likely. Pre-Norm keeps the residual path as an identity mapping, so gradients can flow directly back to shallow layers, making training more stable. It is therefore widely adopted in large-scale models. The cost is that an additional normalization layer is usually needed before the final output to keep the representation scale stable.
def pre_norm_block(x, attn, ffn, norm1, norm2):x = x + attn(norm1(x)) # Normalize sublayer input first; add residual directlyx = x + ffn(norm2(x))return x
It should be noted that some materials mistakenly describe Pre-Norm as Post-Norm. Readers should distinguish the structural difference between the two.
2.5 Pretraining Output: Base Model
After pretraining is complete, the result is a base model. Its main ability is continuation: given a prefix, it can continue generating text according to the distribution of the training corpus. A base model can complete articles, but it may not understand instructions, follow formats, or refuse inappropriate requests, so subsequent stages are needed to shape it further.
3. Stage 2: Supervised Fine-Tuning (SFT)
3.1 Goal of Fine-Tuning
Supervised fine-tuning continues training the base model on manually written or curated instruction-response data. A common data format is as follows:
{"instruction": "Explain causal masking in one sentence.","response": "Causal masking lets the model see only the content to the left of a position when computing that position."}
During training, the model uses the instruction as context and learns to generate the corresponding response. The loss is usually computed only on response tokens; the instruction part serves as conditional input and is not included in the loss calculation.
3.2 From Continuation to Dialogue
After fine-tuning, the model’s behavior shifts from “continuing text” to “responding to instructions.” The quality of data at this stage directly affects the model’s answer style, format-following ability, and task coverage. The diversity of instructions and the accuracy and consistency of responses matter more than quantity.
3.3 On the Term “Supervised”
In practice, people often refer to pretraining and fine-tuning together as the “supervised” stage, but strictly speaking, the two have different natures. Pretraining uses unlabeled text and is unsupervised learning; fine-tuning uses paired instructions and responses and is supervised learning. Understanding this helps in judging the data types and costs required at each stage.
4. Stage 3: Reward Modeling and Reinforcement Learning
4.1 Why Use Relative Rankings
When training a reward model, directly asking annotators to give an absolute score to each response makes results difficult to unify. Different annotators have different scoring scales, and the same annotator’s standards may also change at different times.
A more stable approach is to ask annotators to compare multiple responses to the same question and rank them. Judging “which one is better” is much easier than judging “what score it deserves,” and ranking data is more consistent.
Take the question “What is an apple?” as an example. Suppose the model generates three responses A1, A2, and A3 to the same question, where A3 is “An apple is a fruit.” The annotators consider A2 better than A1 and A1 better than A3, denoted as A2 > A1 > A3.
4.2 Reward Model Structure
A reward model usually uses the SFT model as its base. The final layer that originally outputs vocabulary probabilities is replaced with a linear output layer containing a single neuron. For an input consisting of a question plus a response, the model outputs a scalar score r. This score is a regression output used to measure response quality.
