
25 July 2026
How an LLM Gets Trained
In July I merged five notes from my LLM study roadmap that cover training: pretraining, compute-optimal scaling, SFT, LoRA and RLHF. Roughly, an LLM gets trained like this: pretraining on a huge amount of text gives you a base model, SFT on demonstrations teaches it to answer instructions, and RLHF turns human preferences into a training signal. This post follows that line.
The big picture
Pretraining is one stage in a model's lifecycle. Large-scale self-supervised data goes through a pretraining objective and comes out as a base model. The base model then goes through SFT, preference optimization or domain adaptation and becomes a model that can do specific tasks or work as an assistant. Everything after pretraining is called post-training.
| Stage | Data / signal | Main goal |
|---|---|---|
| Pretraining | Large-scale self-supervised corpus | Learn broad representations, patterns, knowledge and generation ability |
| SFT | High-quality prompt-response demonstrations | Learn the instruction interface and the expected answering behavior |
| RLHF | Human comparisons between answers | Shift the model toward answers people prefer |
Post-training has more in it than SFT and RLHF: DPO, GRPO, and domain or task adaptation all belong here too. This post only walks the classic path, pretraining → SFT → RLHF.
Pretraining: text supplies its own supervision
Pretraining data is far too large to label by hand. Luckily, text can supply its own learning signal: hide part of a sequence, shift it by one, corrupt it, or transform it some other way, then train the model to predict the missing or next content.
For today's decoder-only LLMs, the typical objective is causal language modeling, predicting the next token at every position:
This is just one common objective within pretraining; other architectures use other objectives, covered below. Pretraining is also more than pushing one loss number down: data distribution, architecture, optimizer, compute budget, training dynamics and evaluation together decide what capabilities form.
The optimization view
Pretraining approximately solves:
The adaptation stage that follows starts from and optimizes a different objective:
Training is path-dependent. SGD only follows local gradients, so starting from the region pretraining found leads to different reachable solutions than starting from a random initialization.
Why pretrain first
- Reusable representations: language structure, semantics, patterns and world knowledge don't have to be relearned from zero each time.
- Better initialization: adaptation starts in a useful region of parameter space.
- Sample efficiency: task data can focus on specialization and behavior.
- Easier optimization: good solutions may be easier to reach near pretrained parameters.
- Transfer: one base model can support many different downstream adaptations.
That's why fine-tuning usually needs far less data than training from scratch: the base model's representations are already there. It doesn't mean every downstream task needs only a tiny dataset.
Architectures and pretraining objectives
Architecture and objective are related, but they aren't the same thing.
| Architecture | Typical context pattern | Common pretraining objective | Typical strength |
|---|---|---|---|
| Encoder-only | Bidirectional attention | Masked language modeling | Representation, classification, retrieval |
| Decoder-only | Causal attention | Next-token prediction | Open-ended generation, dialogue, code |
| Encoder-decoder | Bidirectional encoder + causal decoder | Denoising / span corruption, or a sequence-to-sequence objective | Conditional generation and transformation |
Encoder-only: BERT-style masked language modeling predicts selected tokens from context on both sides. In the original BERT setup, the selected positions are handled in fixed proportions (80% / 10% / 10%): replaced with [MASK], replaced with a random token, or left unchanged.
Saying encoder-only models "can't do language modeling" is inaccurate, since masked language modeling is itself a language-modeling objective. The more precise statement: their typical pretraining objective isn't autoregressive next-token generation, so they aren't naturally used as free-running generators.
Decoder-only: a causal mask makes sure token only attends to the past and current positions it's allowed to see. I covered how the mask is applied in the Attention Is All You Need post. The next-token objective used in training matches autoregressive generation at inference directly, which helps explain why decoder-only models dominate general-purpose generative LLMs.
Encoder-decoder: T5-style span corruption removes spans from the input and trains the decoder to reconstruct them. That matches the shape of conditional sequence generation and transformation tasks.
How to split compute between data and model
Pretraining also raises a very practical question: with a fixed compute budget, should you spend it on a bigger model or on more data? That's what compute-optimal scaling tries to answer. Let:
- = parameter count
- = training-token count
- = approximate training compute
For dense Transformer training, compute is often approximated as proportional to . Scaling-law studies fit empirical curves of how loss changes with these quantities, then pick the and that minimize loss for a fixed .
Simplified, the Chinchilla-era result is that parameters and data should grow at the same rate:
The 70B Chinchilla model was trained on about 1.4T tokens:
This matters because a model can be undertrained: too many parameters, too few tokens. Under fixed compute, moving budget toward more data and a smaller model can give lower loss and a model that is cheaper to serve.
Three ideas need to be kept apart here:
- Scaling law: an empirical relationship among loss, parameters, data and compute.
- Compute-optimal recipe: the allocation that minimizes a chosen objective under a chosen budget.
- 20 tokens/parameter: a value from one specific study and setup. It works as a historical rule of thumb and is not a universal constant.
Real decisions about and also depend on inference cost, data quality, whether data gets repeated over several epochs, architecture, tokenizer, context length, optimizer, and the downstream behavior you want.
SFT: teaching a base model to follow instructions
SFT (supervised fine-tuning) keeps training a base model on high-quality prompt-response demonstrations. It's usually the first step of post-training: a base model is only good at next-token prediction, and after SFT it can organize an answer around an instruction. The SFT model is also often used as the starting policy for RLHF, DPO or GRPO.
The mechanism fits in one sentence: given a prompt and a target response, use teacher forcing to compute the cross-entropy loss on the target tokens. Teacher forcing means feeding the true previous token at every step; I wrote about it in From RNN to Seq2Seq. For an input and a target response :
Training usually computes the loss only on response tokens. The prompt tokens condition the model but don't necessarily enter the loss. In form it's almost the same as the causal LM loss from pretraining; what changes is that the data is now demonstration answers and the loss only covers the answer.
What SFT teaches
- Behavior interface: teaches the model to answer instructions. A base model only knows how to continue text.
- Task / domain adaptation: points existing capabilities in a specific direction with a relatively small set of demonstrations.
- Warm start: gives preference optimization or online RL a usable initial policy.
- Format control: teaches structure, style, tool-call formats and safety boundaries.
Where SFT falls short
High-quality demonstrations are expensive, and their coverage is limited. Open-ended tasks have no single correct answer, so training on one target response squeezes out the variety of reasonable answers.
Token-level cross-entropy also has no sense of how bad a mistake is. Getting a dosage wrong and getting a punctuation mark wrong both just show up as a prediction error on the corresponding token. The real difference in risk can only be expressed through data design, evaluation, or a preference / reward signal.
The model may also copy the surface format of the demonstrations without learning a robust capability.
Three dimensions that get mixed up
When people talk about fine-tuning, three separate dimensions often get blurred together:
| Dimension | Question it answers | Examples |
|---|---|---|
| Training stage / objective | What supervision signal do we train on? | SFT, preference optimization, RL |
| Parameter update scope | Which parameters get updated? | Full fine-tuning, PEFT |
| Data / behavior target | What behavior are we trying to teach? | Instruction tuning, domain adaptation, task adaptation |
So:
- Instruction tuning is usually done through SFT.
- Full fine-tuning can implement SFT.
- LoRA / QLoRA can implement the same SFT objective too.
- LoRA isn't a supervision objective, and SFT doesn't mean full fine-tuning.
Treating SFT, instruction tuning and LoRA as three parallel methods is inaccurate. SFT is a training objective or stage, instruction tuning is a behavior and data setting, and LoRA is a way of updating parameters. All of them can show up in the same training run.
On the "which parameters" dimension, the common choices are:
| Method | Update scope | Main trade-off |
|---|---|---|
| Full fine-tuning | All or most parameters | High capacity, but high cost in training memory, checkpoint storage and multi-task maintenance |
| PEFT | A small set of new or selected parameters | Cheap and easy to keep many adapters, but capacity and merge/deployment strategy need checking |
| LoRA / QLoRA | Low-rank adapters; QLoRA also quantizes the base weights | A common PEFT implementation that suits limited GPU resources |
LoRA: the update as a product of two small matrices
LoRA belongs to PEFT (parameter-efficient fine-tuning). It decides how the update is parameterized. What signal trains that update is decided by SFT, DPO or some other objective.
For a pretrained linear layer:
LoRA changes it to:
where , , and . During training:
- stays frozen.
- Only and receive gradients.
- is dense after the multiplication, but its rank is at most .
The trainable parameters for this layer drop from to . For and , that's about 16.8 million down to about 65.5 thousand.
The idea behind it: adapting to a task may only need movement in relatively few effective directions, even though many of the final weight entries end up changing.
A common misreading is that "LoRA only updates a few of the original weights." What it actually learns is two small factors whose product is a dense low-rank update, so many entries of the effective weight change.
What LoRA saves, and what it doesn't
LoRA saves:
- Trainable parameter count
- Gradient memory for the frozen base weights
- Optimizer-state memory
- Per-task checkpoint storage
What it doesn't save: the base model's weights and activations still take up memory, and LoRA doesn't make activation memory go away. QLoRA additionally quantizes the frozen base weights while the adapter trains.
So training memory isn't proportional only to the trainable parameter count. Frozen weights, activations, temporary buffers, sequence length, batch size and quantization all affect it.
LoRA and SFT each cover one dimension, so they combine directly:
SFT objective + LoRA parameterization = LoRA-based supervised fine-tuning
DPO objective + LoRA parameterization = LoRA-based preference optimization
The problem RLHF solves
I mentioned SFT's limits above: open-ended tasks have no single answer, and cross-entropy can't tell a serious mistake from a trivial one. Going further back, pretraining's next-token objective isn't the same as "answers that are more helpful, more honest, safer" either. Many quality standards can't be written down as one correct answer. For example:
- Both summaries read fine. Which one is more accurate?
- Both answers solve the problem. Which one explains it more clearly?
- Which answer sounds authoritative but is actually making things up?
RLHF (reinforcement learning from human feedback) has annotators compare complete answers, compresses those preferences into a reward model, and then uses reinforcement learning to optimize the policy that generates answers.
The classic RLHF pipeline
The classic pipeline is SFT → preference data / reward model → policy optimization. In more detail: people write demonstrations for a set of prompts, which trains the SFT policy. The SFT policy samples several responses to the same prompt, people rank them, and those rankings train the reward model. Finally, the SFT policy becomes the actor and goes through policy optimization under the reward model's scores, giving the aligned policy.
The first step is just the SFT described above: get an initial model that can follow instructions.
Reward model
For one prompt, call the response people preferred (preferred) and the other one (rejected). The reward model outputs a scalar score for each:
A common choice is the pairwise loss:
The more outscores , the smaller this loss gets. Pairwise comparisons are used instead of absolute scores because people are usually better at judging "which of these two is better." Once trained, the reward model is frozen during policy optimization.
Policy optimization
In this step the actor generates responses, the reward model scores each full response, the reference model provides a KL constraint, and the optimizer updates the actor based on all of that. The classic InstructGPT setup used PPO. Modern post-training also uses methods like DPO and GRPO, which have different data flows and objectives, and they shouldn't all be written as synonyms for RLHF.
PPO in RLHF needs these roles:
| Role | Job |
|---|---|
| Actor | The language model being trained |
| Critic | Estimates state value, which helps compute the advantage |
| Reward model | Estimates human preference for a complete response |
| Reference model | Keeps the actor from drifting too far from the SFT policy |
| Actor_old | A snapshot of the policy at rollout time, used for the PPO ratio |
I won't go into PPO's internals here: value, advantage, GAE, the ratio, clipping and rollout reuse.
What RLHF is and isn't
| Item | Same as RLHF? | Notes |
|---|---|---|
| SFT | No | Often the stage before RLHF; can also be used alone |
| Reward model | No | The component in RLHF that carries the preference signal |
| PPO | No | The policy optimizer used in classic RLHF |
| DPO | No | Optimizes the policy directly from preference pairs, without explicitly training a reward model or running online PPO |
| RLAIF | A variant | Replaces part of the human feedback with AI feedback |
RLHF is not PPO. RLHF defines the whole framework from feedback to policy; PPO defines how to update the policy stably. Likewise, having preference data doesn't automatically make it RLHF: DPO uses preference pairs directly, usually without training a separate reward model or doing online PPO rollouts.
Limits of RLHF
- Noisy preferences: annotators disagree, and they may prefer answers that sound right even when they aren't.
- Reward hacking: the actor may exploit holes in the reward model and produce high-scoring, low-quality answers.
- Over-optimization: chasing a fixed reward model for too long can hurt truthfulness, diversity or language quality.
- Distribution shift: on response distributions it hasn't seen, the reward model's scores can be off.
- Cost: preference labeling, rollouts and running several models at once are all expensive.
Common confusions
- Pretraining and architecture aren't synonyms. Decoder-only describes the computation and masking; causal LM describes the training objective.
- Low pretraining loss doesn't guarantee a useful assistant. The objective, data, capability evals, post-training and deployment context all matter.
- Fine-tuning doesn't always stay close to the pretrained parameters. How far it moves depends on the optimizer, learning rate, number of steps, data, regularization, and which parameters are trainable.
- Fine-tuning isn't the same as post-training. Post-training is the larger stage and also includes reward modeling, DPO, PPO, GRPO and other methods.