Skip to content
King Jin

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.

StageData / signalMain goal
PretrainingLarge-scale self-supervised corpusLearn broad representations, patterns, knowledge and generation ability
SFTHigh-quality prompt-response demonstrationsLearn the instruction interface and the expected answering behavior
RLHFHuman comparisons between answersShift 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.

PretrainingSFTRLHFText corpustrillions of tokensPretrainingnext-token lossBase modelcontinues textSFTprompt → demo answerSFT policyfollows instructionsAligned modelpreferred answersPPOactor = SFT policyReward modelscores a whole answerHuman rankingcompare answer pairsKL keeps it near the SFT policy

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:

LCLM=−∑t=1Tlog⁡pθ(xt∣x<t)\mathcal L_{CLM} =-\sum_{t=1}^{T}\log p_\theta(x_t\mid x_{<t})

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:

θ^≈arg⁡min⁡θLpretrain(θ)\hat\theta\approx\arg\min_\theta\mathcal L_{pretrain}(\theta)

The adaptation stage that follows starts from θ^\hat\theta and optimizes a different objective:

θ∗≈arg⁡min⁡θLadapt(θ),θ0=θ^\theta^*\approx\arg\min_\theta\mathcal L_{adapt}(\theta), \qquad \theta_0=\hat\theta

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.

ArchitectureTypical context patternCommon pretraining objectiveTypical strength
Encoder-onlyBidirectional attentionMasked language modelingRepresentation, classification, retrieval
Decoder-onlyCausal attentionNext-token predictionOpen-ended generation, dialogue, code
Encoder-decoderBidirectional encoder + causal decoderDenoising / span corruption, or a sequence-to-sequence objectiveConditional 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 tt 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:

  • NN = parameter count
  • DD = training-token count
  • CC = approximate training compute

For dense Transformer training, compute is often approximated as proportional to NDND. Scaling-law studies fit empirical curves of how loss changes with these quantities, then pick the NN and DD that minimize loss for a fixed CC.

Simplified, the Chinchilla-era result is that parameters and data should grow at the same rate:

Nopt∝C0.5,Dopt∝C0.5N_{opt}\propto C^{0.5},\qquad D_{opt}\propto C^{0.5}

The 70B Chinchilla model was trained on about 1.4T tokens:

1.4T70B≈20 tokens/parameter\frac{1.4T}{70B}\approx20\ \text{tokens/parameter}

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 NN and DD 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 xx and a target response y=(y1,…,yT)y=(y_1,\dots,y_T):

LSFT=−∑t=1Tlog⁡pθ(yt∣x,y<t)\mathcal L_{SFT} = -\sum_{t=1}^{T}\log p_\theta(y_t\mid x,y_{<t})

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:

DimensionQuestion it answersExamples
Training stage / objectiveWhat supervision signal do we train on?SFT, preference optimization, RL
Parameter update scopeWhich parameters get updated?Full fine-tuning, PEFT
Data / behavior targetWhat 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:

MethodUpdate scopeMain trade-off
Full fine-tuningAll or most parametersHigh capacity, but high cost in training memory, checkpoint storage and multi-task maintenance
PEFTA small set of new or selected parametersCheap and easy to keep many adapters, but capacity and merge/deployment strategy need checking
LoRA / QLoRALow-rank adapters; QLoRA also quantizes the base weightsA 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:

h=W0xh=W_0x

LoRA changes it to:

h=(W0+ΔW)x,ΔW=BAh=(W_0+\Delta W)x, \qquad \Delta W=BA

where A∈Rr×dinA\in\mathbb R^{r\times d_{in}}, B∈Rdout×rB\in\mathbb R^{d_{out}\times r}, and r≪min⁡(din,dout)r\ll\min(d_{in},d_{out}). During training:

  • W0W_0 stays frozen.
  • Only AA and BB receive gradients.
  • ΔW\Delta W is dense after the multiplication, but its rank is at most rr.

The trainable parameters for this layer drop from doutdind_{out}d_{in} to r(din+dout)r(d_{in}+d_{out}). For din=dout=4096d_{in}=d_{out}=4096 and r=8r=8, 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 W0+ΔWW_0+\Delta W 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 ywy_w (preferred) and the other one yly_l (rejected). The reward model outputs a scalar score for each:

rψ(x,yw),rψ(x,yl)r_\psi(x,y_w),\qquad r_\psi(x,y_l)

A common choice is the pairwise loss:

LRM=−log⁡σ(rψ(x,yw)−rψ(x,yl))\mathcal L_{RM} =-\log\sigma\left(r_\psi(x,y_w)-r_\psi(x,y_l)\right)

The more ywy_w outscores yly_l, 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:

RoleJob
ActorThe language model being trained
CriticEstimates state value, which helps compute the advantage
Reward modelEstimates human preference for a complete response
Reference modelKeeps the actor from drifting too far from the SFT policy
Actor_oldA 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

ItemSame as RLHF?Notes
SFTNoOften the stage before RLHF; can also be used alone
Reward modelNoThe component in RLHF that carries the preference signal
PPONoThe policy optimizer used in classic RLHF
DPONoOptimizes the policy directly from preference pairs, without explicitly training a reward model or running online PPO
RLAIFA variantReplaces 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.

References

OlderAttention Is All You Need →