How Training Works¶
What "training a language model" means, from the first formula to the choices you make in a config. Each idea comes with the palingenesis command or key that controls it.
A model predicts the next token¶
A language model reads text as tokens: whole words, pieces of words, punctuation or special markers, each an integer id in a fixed vocabulary (about 150,000 entries for Qwen models). Given the tokens so far, one forward pass returns a probability for every token in the vocabulary being the next one. Generating text means picking one of them, appending it and running the model again.
What turns tokens into probabilities are the model's weights \(\theta\): billions of numbers. Training changes nothing but the weights.
What training does¶
Training needs a number that says how wrong those probabilities are: the loss. For one position whose correct next token is \(y\), the standard loss is the cross-entropy, the negative log of the probability the model gave to \(y\):
| \(p_\theta(y)\) | 0.9 | 0.5 | 0.1 | 0.01 | uniform over 151,936 tokens |
|---|---|---|---|---|---|
| loss \(-\log p\) | 0.11 | 0.69 | 2.30 | 4.61 | 11.93 |
A confident right answer costs almost nothing, a confident wrong one costs a lot, and a model that knows nothing (all tokens equally likely) sits at \(\log V\) for a vocabulary of \(V\) tokens. The training loss of a run is the mean over every trained token of the batch:
where \(x\) is the token sequence, \(T\) the positions that are trained (next section) and \(N\) their number.
The gradient \(\nabla_\theta \mathcal{L}\) gives, for every weight, how fast the loss changes when that weight moves: computed by backpropagation ("backward"), at about twice the cost of the forward pass. For cross-entropy it has a readable form at the output: the score of every token \(v\) is pushed by \(p_v - \mathbb{1}[v = y]\), so the correct token is pushed up by what it lacked (\(1 - p_y\)) and every other token down in proportion to the probability it took.
The optimizer then moves each weight a small step against its gradient. In its simplest form (gradient descent) with learning rate \(\eta\):
The default optimizer, AdamW (train.optimizer: adamw), uses a running average of each weight's gradient, divides it by the root of a running average of its square (so every weight moves at a similar pace), and adds weight decay (train.weight_decay), but the picture is the same: small steps downhill, as many as the data allows.
step= counter in the log counts these. The micro-batches of a step are train.per_device_batch_size rows each, on every GPU.The learning rate is the most consequential number in a config. Too small and the loss barely moves; too large and each step jumps past the low point it was heading for:
train.learning_rate sets η; the schedule (train.lr_scheduler, after train.warmup_ratio of warm-up from zero) changes it over the run.Run it over the data and you get a loss curve. Three shapes cover most of what you will see:
data.eval_dataset, every data.eval_every steps); with it, palingenesis keeps the checkpoint with the lowest eval loss in best/. Without held-out data you cannot tell the right-hand case from the left-hand one.Which tokens are trained¶
A chat dataset holds whole conversations, but you want the model to learn to write the assistant's replies, not to predict the user's questions or the system prompt. So the conversation is rendered with the model's own chat template, and only the assistant's tokens get a loss; everything else is masked: still read as context, never a target. This is the most important practical idea in post-training. If masking is wrong (the whole conversation trained, or nothing), the run looks normal and teaches the wrong thing.
palingenesis derives the mask from the model's own chat template, so tool calls written by the assistant are trained, tool results are not (unless data.include_observations: true), and reasoning blocks are trained unless data.train_on_reasoning: false. Check it on your data before every new run, without a GPU:
pgs inspect --config sft.yaml --num_samples 3 # trained tokens in green, masked in gray
pgs validate --config sft.yaml --num_samples 200 # the same check over many rows
Details: What gets loss and, for multi-turn tool use, the agentic guide.
Pre-training and post-training¶
Pre-training runs the loop above on trillions of tokens of raw text, every token trained. The result is a base model: it continues text, but does not reliably answer, follow instructions or stop. Post-training is everything after: far less data, chosen to shape behaviour. It is what turns a base model into an assistant, a reasoning model or an agent, and what you do when you adapt such a model to your task. Most open models are published already post-trained (the "-Instruct" or chat versions); you usually continue from one of those. palingenesis is a post-training library (raw-text sources, mode: pretrain, cover continued pre-training on a domain).
The post-training methods¶
The methods differ in two things: which text the model trains on (sequences fixed in advance, or the model's own samples generated during training) and what signal each token gets.
SFT (supervised fine-tuning) imitates examples: the cross-entropy above, on the assistant tokens of conversations you supply. It is how a model learns a format, a tool-calling style, a language register or a domain, and usually the first stage. Data guide, agentic guide.
DPO (direct preference optimization) learns from pairs: a prompt \(x\), a chosen answer \(y_w\) and a rejected one \(y_l\). It raises the chosen answer's log-probability relative to the rejected one's, each measured against a frozen copy of the starting model \(\pi_{\text{ref}}\):
where \(\log \pi(y \mid x)\) is the sum of the answer's token log-probabilities, \(\sigma\) the logistic function and \(\beta\) dpo.beta (0.1).
Use it when "better" is easier to show than to write: tone, length, when to refuse. DPO guide.
Off-policy distillation trains on fixed sequences like SFT, but each trained token's target is a larger teacher's whole next-token distribution \(p_T\) instead of one correct token. The default divergence is the forward KL, \(\sum_v p_T(v) \log \frac{p_T(v)}{p_S(v)}\) for student distribution \(p_S\); with a teacher that puts all its mass on the data's token it is exactly the cross-entropy, so SFT is the special case of a one-hot teacher. The extra signal is in the other tokens: how likely the teacher found each alternative. Teacher and student must share a vocabulary. Off-policy distillation guide.
On-policy distillation reverses who writes: the student samples a completion, the teacher scores those exact tokens, and the loss is the reverse KL from student to teacher at every token of the student's own sample, \(\sum_v p_S(v) \log \frac{p_S(v)}{p_T(v)}\). The student is corrected in the states it actually reaches, including the ones its mistakes create. Works across tokenizers and with several teachers. On-policy distillation guide.
RL (reinforcement learning) needs no target text at all, only a way to score an answer: a checked math result, passing tests, a finished agent task. For each prompt the model samples a group of rollouts, each gets a reward \(r_j\), and each rollout's tokens are reinforced in proportion to how much better than its group it did (and pushed down if it did worse):
where \(\bar r\) is the group's mean reward and \(\sigma\) a standard deviation (by default the batch's: loss.advantage_std). This is GRPO's group-relative advantage; the default loss also clips the update.
A group where every rollout scores the same gives no signal, so RL only helps on tasks the model already solves some of the time. RL guide.
Merging is not training: it combines the weights of checkpoints of the same model, in seconds and without a GPU. The common case pulls a fine-tune partway back toward its start, \(W = W_{\text{start}} + \lambda (W_{\text{end}} - W_{\text{start}})\), to keep most of a gain and drop its side effects. Merging guide.
Which one do I need?¶
| Goal | Method | Start | Run |
|---|---|---|---|
| Teach a format, a behaviour, a domain, from examples | SFT | pgs init sft |
pgs train --config sft.yaml |
| Prefer one kind of answer over another (style, length, refusals) | DPO | pgs init dpo |
pgs train --config dpo.yaml |
| Compress a bigger model with the same vocabulary, on a corpus | Off-policy distillation | pgs init kd |
pgs train --config kd.yaml |
| Copy a teacher's reasoning or agent behaviour, fix the student's own errors and loops | On-policy distillation | pgs init distill |
pgs distill --config distill.yaml |
| Get better at tasks you can check: math, code, tools, agents | RL | pgs init rl |
pgs rl --config rl.yaml |
| Keep part of a fine-tune, or add an expert, without training | Merging | two checkpoints | pgs merge interpolate START END --lam 0.3 -o OUT |
A common order is SFT first, then DPO, on-policy distillation or RL on top, then a merge if the last stage cost something elsewhere. Each pgs init example is a complete config with small models and a public or example dataset: point the model and the data at yours.
The knobs you will meet¶
Every value below is a config key (configuration reference); any of them can also be set on the command line, e.g. pgs train --config sft.yaml --train.learning_rate 1e-5.
| Knob | Keys (default) | What it means |
|---|---|---|
| Length of the run | train.epochs (1), train.max_steps (-1: from the epochs) |
An epoch is one pass over the data. A streamed dataset has no known length, so it needs max_steps. Small datasets take more epochs (how much data). |
| Batch | train.per_device_batch_size (1), train.gradient_accumulation_steps (16) |
Rows per optimizer step = batch size × accumulation × GPUs. Accumulation gives a large batch with the memory of a small one. |
| Learning rate | train.learning_rate (2e-5), train.warmup_ratio (0.05), train.lr_scheduler (cosine), train.min_learning_rate |
The step size η and how it changes: up from 0 during warm-up, then down to the minimum. The shipped examples use 2e-5 for full SFT, 2e-4 for LoRA, 5e-7 for DPO and 2e-6 for RL: methods that start from a good model move it gently. |
| Gradient clipping | train.max_grad_norm (1.0) |
A step whose gradient is longer than this is scaled down to it, so one bad batch cannot throw the weights far. |
| Sequence length | data.max_seq_length (8192) |
The longest row, in tokens. Longer conversations are cut at turn boundaries. Memory for activations grows with it. data.packing: true fills each row with several short conversations. |
| Memory | train.gradient_checkpointing (selective), memory.chunked_loss (true), memory.seco (false) |
Full fine-tuning with AdamW needs about 12 bytes per parameter before activations (bf16 weights and gradients, two fp32 optimizer states): 48 GB for a 4B model. Checkpointing recomputes activations in the backward pass instead of storing them; chunked loss never builds the full [tokens × vocabulary] logits; SeCO trains very long sequences chunk by chunk with exact gradients (long sequences). pgs fit --config sft.yaml measures the fastest setting that fits your GPU (single GPU). |
| Fewer trained weights | plugins.custom: [{class: palingenesis.lora:LoRA, ...}] |
LoRA freezes the model and trains small low-rank adapters: far less optimizer memory, usually a little less learned (LoRA guide). |
| Evaluation | data.eval_dataset, data.eval_every (100), data.eval_samples (200) |
Held-out loss during training, and best/. |
Eval loss is not quality. A lower eval loss says the model predicts your reference answers better; it does not say the model got better at the task, and it says nothing about what it lost elsewhere. Pick the checkpoint with the loss, then judge it with real evaluations: the task's own checks (tests, exact answers), general benchmarks to catch regressions, and reading what the model writes. data.eval_sources tracks a separate held-out loss per capability, which catches some regressions early (validation data).
Reading your run¶
Every step logs one line (keep it: pgs train --config sft.yaml 2>&1 | tee train.log):
| Field | Watch for |
|---|---|
loss |
falling fast, then slowly. Its absolute value depends on the data: compare runs on the same data only. |
grad_norm |
the gradient's length before clipping. Steady or slowly falling is normal; judge it against the run's own recent values, not a fixed number. |
lr |
the schedule: rising during warm-up, then decaying. |
tok/s, dt |
throughput and seconds per step. The first step is slow (compilation). |
eval |
on evaluation steps only: the held-out loss. |
pgs monitor reads that log and gives the state in one line (status, loss trend, throughput, time left); pgs loss analyses the whole curve:
pgs monitor --log_file train.log --brief --max_steps 500
# [HEALTHY] step=120 loss=1.3421 trend=-2.1% tok/s=6011 eta=7.7m
pgs loss --log_file train.log
| Sign | Likely cause | First thing to try |
|---|---|---|
loss=nan, or loss climbing with grad_norm spikes |
learning rate too high | lower train.learning_rate (÷3) |
SPIKE SKIPPED lines |
a few bad batches (the step is skipped, train.spike_detection) |
many of them: look at the rows with pgs inspect, clean with pgs prepare |
| loss flat from the start | wrong masking, or learning rate too low | pgs inspect, then raise the rate |
| eval rising while train falls | overfitting | fewer epochs; use best/ |
| train loss near zero | the data is memorised (many epochs, little data) | fewer epochs, more data |
tok/s drops during the run |
data loading cannot keep up | data.num_workers, data.pretokenize |
More signals (health/* metrics, warnings) are in health monitoring; RL and on-policy distillation log their own (rewards, KL, rollout lengths), described in their guides and in observability.
Going further¶
Why fine-tuning makes models forget¶
The weights that hold a model's general skills are the same weights a fine-tune moves, so a gain on your task comes with drift elsewhere: instruction following, knowledge, other languages. This is catastrophic forgetting. It grows with the learning rate, the number of steps and how far the data is from what the model already does, and it tends to be most visible on small models. It does not show in the training loss: measure it with evaluations of what you want to keep. Three ways to limit it:
- Replay: mix general data into the run as another
data.sourcesentry. Answers the model itself wrote to general prompts work better than a dataset's answers (data guide). - Interpolate back:
pgs merge interpolatetoward the starting model with \(\lambda\) around .3 to .5 keeps much of the gain and recovers much of what was lost (merging). - Change less: a lower learning rate, fewer steps, or LoRA.
Why on-policy methods exist¶
SFT and off-policy distillation are teacher-forced: every prediction is made after a prefix from the data, never after the model's own words. At inference the model reads its own output, and one early mistake puts it in a state no training row contained, where the next mistake is more likely. This is exposure bias; it shows up as loops, drift and agents that do not recover from their own errors. On-policy distillation and RL train on the model's own samples, so those states are in the training data, and the teacher or the reward tells the model what to do there. Within SFT, data.loop_recovery and its companions show the model the way out of enumerated loop forms (agentic guide, on-policy distillation).
KL to a reference¶
A frozen copy of the starting model, the reference \(\pi_{\text{ref}}\), measures how far training has moved the model. Per token, the usual measure is the KL divergence
which is zero when the two distributions agree. Adding it to the loss trades some of the task signal for staying close to a model you know works. DPO has it built in (\(\beta\) sets how strongly the reference holds; it is dpo.reference_model, by default the model as loaded). In pgs rl it is off by default, as in current published recipes: loss.kl_ref: start logs it as policy/kl_ref, and loss.kl_coef adds it to the loss. On-policy distillation's reverse KL has the same form with the teacher in place of the reference: the student is pulled toward a better model instead of held near its old self.
Next: Your first real training on your own data, then the guide of the method you picked above.