Slides · Fine-tuning
Training practice and distributed training
1 / 36
Training practice and distributed training
Run a fine-tune, make it fit, spread it over GPUs, and read the curves without being fooled.
By the end you can say which tokens an SFT run optimises, compute the effective batch, pick the right memory lever for what is actually too big, work out per-GPU state memory under ZeRO stages 1 to 3, and debug a misbehaving run in a sensible order.
Concept
Most failed runs fail quietly
- Three days of training went well. On the fourth, the answers get slightly worse, and the log shows nothing alarming.
- The job finishes, the loss goes down, and the model is worse. No error, no crash.
- Two habits save the most time: know exactly which tokens the loss measures, and know the price of every memory lever.
- A setup error such as the wrong tokens counted, a missing end token or a silent truncation can give a smooth, healthy-looking curve for a broken model.
Math
What SFT minimises
loss=−t∈target tokens∑logp(tokent∣tokens before t)| Symbol | Meaning |
|---|---|
| tokent | The correct next token at position t of the training text |
| p(⋅) | The probability the model gave that token, given everything before it |
| ∑t∈target tokens | Only unmasked positions; padding and masked positions use an ignore index |
- The TRL documentation calls this the token-level cross-entropy, in other words the log-loss of the target sequence given its input.
- The logged
lossis the average over non-masked tokens in the logging interval. - Cross-entropy measures how well the model imitates the answers it trains on. That is a different thing from doing the job well.
Diagram
One SFT step
Worked example
Worked example: what the loss really covers
One prompt-completion example, run through SFTTrainer (TRL 1.16.0, a tiny test model, 2026-10-24).
| What was printed | Result |
|---|---|
| Tokens after templating | 51 |
Positions masked with -100 | 39 |
| Positions that carry the loss | 12 |
| Decoded loss tokens | the answer sentence plus the end token and a newline |
| Anything the data did not contain | a default system message added by this tokenizer’s chat template |
- The default for prompt-completion data is loss on the completion only. Setting
completion_only_loss=Falseleft zero masked positions in the same test. assistant_only_loss=Trueserves chat data, and needs a chat template that marks assistant text.- Decoding one templated example is the cheapest way to see what the model sees.
Code
A decode helper, and three ways it catches problems
Python
def show_loss_tokens(tok, ex):
ids, labels = ex["input_ids"], ex["labels"]
kept = [t for t, l in zip(ids, labels) if l != -100]
return {"total": len(ids), "loss": len(kept), "loss_text": tok.decode(kept)}| Test on the same example | What the helper showed |
|---|---|
Default max_length of 1024 on this short example | nothing cut; 12 loss tokens |
max_length=44 | 44 tokens, and the loss text stopped mid-sentence, with no end token |
max_length=30, shorter than the prompt side | every example had no loss token left and the training set came out empty |
- Truncation keeps the start of the sequence (
truncation_modedefaults to keep-start in that version), so the answer is what gets cut. - An answer that is cut off still trains. The curve looks fine.
- Run the helper on a handful of examples before any long run.
Concept
The end token and the length limit
- If the end-of-sequence token is missing from the targets, or differs from what the chat template uses, the tuned model may not learn to stop. The TRL page says to align the end token with the template to ensure responses terminate correctly.
- Sequences above
max_lengthare truncated. The memory page warns that a value that is too small discards a significant share of tokens, and a value that is too large invites memory spikes. - The same page offers a utility that plots the length distribution of your data. Look at it before picking a value.
- Both faults are silent: the run completes and the curve is smooth.
Sources[1] SFT Trainer (TRL documentation)[2] Reducing Memory Usage (TRL documentation)
Check yourself
Check: where does the signal come from
Each training example has 120 prompt tokens and 30 answer tokens. With loss on the full sequence, what share of the counted tokens is the answer? What share with answer-only loss? What does the first choice do to the number you read off the dashboard?
Answer
Full sequence: 30/150=20 percent answer. Answer-only: 100 percent. With the full-sequence choice, prompt tokens make up four fifths of the tokens being averaged, so the dashboard number is mostly a score on prompt text the model never needs to produce, and a poor proxy for the behaviour you are teaching.
Concept
Imitation loss versus task score
- Cross-entropy measures imitation of the training answers. It does not tell you that the JSON parses, the label is right or the tone fits.
- The two usually move together, until they do not.
- Pick the checkpoint with the best score on a held-out task metric such as JSON-valid rate, exact match or a graded rubric. Keep validation loss only as a guard against overfitting.
- Save checkpoints often. For a LoRA run a checkpoint is just the adapter, so it is cheap.
- A small evaluation every few hundred steps costs little and stops the wrong number from choosing for you.
Compare
What to log, and what the defaults are
| Log every run | Why |
|---|---|
| Train and validation loss | The overfitting gap |
| Learning rate and gradient norm (TRL logs it before clipping) | Spikes and a stalled schedule |
| Tokens per second and GPU memory | Cost and headroom |
| The task metric on a held-out set | The thing you ship on |
SFTConfig default (TRL 1.16.0) | Value |
|---|---|
learning_rate | 2e-5 |
num_train_epochs | 3.0 |
max_grad_norm | 1.0 |
max_length | 1024 |
gradient_checkpointing | True |
bf16 | True when fp16 is not set |
- The docs add a tip that adapter training typically uses a higher rate, about 1e-4. These are library defaults at one version, not advice for your data.
Concept
First ask what is too big
- Model states: weights, gradients and optimiser state, about 16 bytes per parameter for a full tune with Adam in mixed precision.
- Activations: they grow with the batch and the sequence length.
- Each lever attacks one of these. A lever aimed at the wrong one costs time and saves nothing.
- Before changing anything, look at where memory goes: a small model with long sequences and a large model with short sequences fail for different reasons.
Compare
Levers, savings and prices
| Lever | Saves | Costs |
|---|---|---|
| Gradient accumulation | Activations, by using a smaller batch per pass | More passes per update, so slower wall-clock |
| Gradient checkpointing | Activations, by not storing them all | Extra compute from recomputing |
| LoRA or QLoRA | Gradients and optimiser state of the frozen base | A ceiling on adapter capacity |
| Shorter sequences | Activations | Cut-off text may hold the answer |
| Packing or padding-free | Wasted padding | Needs supported attention kernels; packing mixes examples in a row |
| Activation offloading | GPU memory | Slightly more training time, per the TRL page |
| Sharding or offloading states | Model-state memory | Communication or slower transfers |
Sources[2] Reducing Memory Usage (TRL documentation)[3] Performing gradient accumulation with Accelerate
Math
Effective batch size
effective batch=sequences per pass×accumulation steps×data-parallel GPUs| Symbol | Meaning |
|---|---|
| sequences per pass | The micro-batch each GPU holds in memory at once |
| accumulation steps | Passes whose gradients are added before one optimiser step |
| data-parallel GPUs | Replicas, each seeing its own micro-batches |
- The Accelerate guide describes accumulation as a way to train on bigger batches than the machine would fit.
- Example: 2 sequences per pass, 6 accumulation steps and 8 GPUs give 2×6×8=96 sequences per update.
Diagram
Accumulation, drawn
Worked example
The accumulation trap with unequal lengths
Eight sequences of 3 to 12 tokens, split into four micro-batches of two. Gradient compared with one full batch (torch 2.14.1).
| Way to combine | Gradient vs the full batch |
|---|---|
| Sum of token losses, divided by all non-padding tokens | identical (difference 0.0) |
| Each micro-batch averaged on its own, then divided by 4 | 22 percent relative difference |
| Same naive method, all sequences the same length | identical (difference 7e-9) |
- The micro-batches held 12, 17, 9 and 14 tokens. Averaging the averages over-weights the micro-batches with fewer tokens.
- The Accelerate guide states the correct token-level rule: total loss across the accumulation step over the total number of non-padding tokens.
- Mature trainers handle it. Check it in any hand-written loop.
Check yourself
Check: reach a target batch
You want an update over 256 sequences on 8 GPUs, and memory allows only 2 sequences per pass. How many accumulation steps? If you kept 12 steps instead, what batch would you really train with?
Answer
256/(2×8)=16 accumulation steps. With 12 steps the effective batch is 2×12×8=192, three quarters of the target, so the learning rate and the number of updates per epoch would not match the plan.
Worked example
Gradient checkpointing: compute for activation memory
- Instead of storing every intermediate activation in the forward pass, the trainer stores some and recomputes the rest during the backward pass. The TRL page enables it by default in its trainers.
- Only the activation side changes. The model states keep exactly their size.
Test with torch.utils.checkpoint (torch 2.14.1) | Result |
|---|---|
| Gradients with and without checkpointing | equal |
| Times the block’s forward ran in the checkpointed pass | 2 (once forward, once recomputed) |
- If model states are what overflow, checkpointing will not rescue the run.
Compare
Padding, packing and truncation
| Option | What it does | Watch for |
|---|---|---|
| Truncation | Cuts sequences at max_length | Cut text may hold the answer |
Packing, bfd | Packs sequences into rows; overflow tokens are discarded | Default strategy in the docs |
Packing, bfd_split | Splits long sequences first, so all tokens are kept | Pieces of one example can land in different rows |
Packing, wrapped | Concatenates everything, cuts fixed blocks | The docs warn it may mix unrelated examples |
| Padding-free | Flattens a batch into one sequence, examples kept whole | Needs FlashAttention 2 or 3 per the docs |
- Check how your own stack keeps packed examples apart before you turn packing on.
Sources[2] Reducing Memory Usage (TRL documentation)[1] SFT Trainer (TRL documentation)
Check yourself
Check: pick two levers
A LoRA run on a 7B model goes out of memory only on batches full of long documents. A profile says activations are the bulk. Name two levers, what each costs, and one lever that would not help.
Answer
Gradient checkpointing, if it is not already on (extra recompute; TRL trainers enable it by default, so with TRL confirm it rather than add it), and a smaller per-pass batch with gradient accumulation (more passes per update, slower wall-clock) both attack activations. A shorter max_length also helps if the cut text is not the answer. Sharding the model states would not help, because with LoRA the states are tiny and the problem is activations.
Concept
Sharding: split the books, not just the readers
- Picture eight GPUs. Data parallelism gives each one a full copy of the model states and splits the data.
- Sharding splits the states too. Each GPU keeps an eighth and fetches the rest from the others when needed.
- You save memory and pay in communication. The ZeRO paper makes this exact for training memory.
- Three kinds of state can be split: optimiser state, gradients, and the parameters themselves.
Source[4] ZeRO: Memory Optimizations Toward Training Trillion Parameter Models
Math
Per-GPU model states
Here P is parameters and N is GPUs, with Adam in mixed precision.
data parallel: 16PZeRO-1: 4P+N12P(optimiser state split)ZeRO-2: 2P+N14P(plus gradients split)ZeRO-3: N16P(plus parameters split)| Term | Meaning |
|---|---|
| 2P | 16-bit parameters |
| 2P | 16-bit gradients |
| 12P | Optimiser state: 32-bit master weights and two Adam moments |
- The DeepSpeed tutorial describes the same three stages: optimiser states, then gradients, then 16-bit parameters partitioned across processes.
- These are floors: activations and temporarily gathered layers come on top.
Sources[4] ZeRO: Memory Optimizations Toward Training Trillion Parameter Models[5] Zero Redundancy Optimizer (DeepSpeed tutorial)
Worked example
Worked example: 11B parameters, 8 GPUs of 48 GB
Illustrative numbers, bytes per parameter times billions of parameters.
| Strategy | Formula (P=11, N=8) | States per GPU | Room left on 48 GB |
|---|---|---|---|
| Data parallel | 16×11 | 176 GB | does not fit |
| ZeRO-1 | 4×11+12×11/8 | 60.5 GB | does not fit |
| ZeRO-2 | 2×11+14×11/8 | 41.25 GB | 6.75 GB |
| ZeRO-3 | 16×11/8 | 22 GB | 26 GB |
- ZeRO-2 fits on paper but leaves under 7 GB for activations. ZeRO-3 leaves far more, and pays more communication.
- Measure both before choosing. The table is a floor.
Source[4] ZeRO: Memory Optimizations Toward Training Trillion Parameter Models
Compare
The same ideas in PyTorch FSDP
ShardingStrategy | What the 2.14 docs say it does |
|---|---|
FULL_SHARD (default) | Shards parameters, gradients and optimiser states; parameters are all-gathered before forward and reshard afterwards |
SHARD_GRAD_OP | Shards gradients and optimiser states during compute; parameters are not resharded after the forward, only after the backward |
NO_SHARD | Replicates everything, like DistributedDataParallel; gradients are all-reduced |
HYBRID_SHARD | Full shard within a node, replicate across nodes |
FULL_SHARDmatches the ZeRO-3 memory picture;SHARD_GRAD_OPsits between data parallelism and full sharding. The docs do not state these equivalences, so treat them as a study aid.- The page read here does not mention the newer
fully_shardAPI, so check which one your library version uses.
Source[6] FullyShardedDataParallel (PyTorch 2.14 documentation)
Worked example
What full sharding pays
| Strategy | Communication per step (ZeRO paper) |
|---|---|
| Data parallel baseline | 2 units |
| ZeRO-1 and ZeRO-2 | 2 units, the same as the baseline |
| ZeRO-3 | 3 units, 1.5 times the baseline |
- The extra traffic comes from gathering parameters before the forward pass and again around the backward pass, then combining and splitting gradients (all-gather and reduce-scatter in the FSDP docs).
- Whether 1.5 times hurts depends on how fast your links are. Measure tokens per second.
- When the whole job fits on a single card, replicating it avoids all of this extra traffic.
Sources[4] ZeRO: Memory Optimizations Toward Training Trillion Parameter Models[6] FullyShardedDataParallel (PyTorch 2.14 documentation)
Diagram
Choosing a strategy
Concept
Offloading, briefly
- The DeepSpeed tutorial describes ZeRO-Offload as moving optimiser and gradient states to CPU memory within ZeRO-2.
- ZeRO-Infinity, added to ZeRO-3, can move the whole model state to CPU or NVMe.
- Both trade speed for memory, so they come after sharding, not before it.
- Tensor parallelism splits a single layer across devices and pipeline parallelism splits the model by layers. They matter for models too large for one node and are beyond this lesson.
Check yourself
Check: how few GPUs
A 13-billion-parameter full fine-tune must fit its model states on 80 GB GPUs. What is the smallest GPU count at which ZeRO-3 fits the states alone, and with 4 GPUs which of ZeRO-1, ZeRO-2 and ZeRO-3 fit?
Answer
ZeRO-3 needs 16P/N at most 80 GB, so N is at least 208/80=2.6, which rounds up to 3 GPUs for the states alone, with almost nothing left for activations. With N=4: ZeRO-1 needs 91 GB (does not fit), ZeRO-2 needs 71.5 GB (fits, with about 8.5 GB spare) and ZeRO-3 needs 52 GB (fits, with about 28 GB spare).
Compare
Reading the curves
| What you see | Common cause | First action |
|---|---|---|
| Loss starts very low | Prompt included in the loss, leaked targets, or duplicates across splits | Decode labels; audit the split |
| Flat from step 0 (or NaN, depending on the trainer) | Labels all masked, adapter not training, rate far too low | Count trainable parameters; decode labels |
| Spikes or NaN | Rate too high, bad batch, no clipping | Lower the rate; inspect gradient norm and batch |
| Train falls, validation rises | Overfitting | Fewer epochs, earlier checkpoint, more varied data |
| Validation loss falls, task metric falls | Loss is not the task | Choose the checkpoint by the task metric |
| Never stops generating | End token missing or mismatched | Fix template and targets |
- Each row is a hypothesis to check, not a proof.
- Overfitting shows as a train-validation gap. Forgetting stays invisible in validation loss measured on your data alone, so the evaluation has to test it.
Worked example
Worked example: three checks, run
A tiny randomly initialised decoder with a vocabulary of 100 (torch 2.14.1, Transformers 5.20.2).
| Check | Result |
|---|---|
| Starting loss before any training | 4.606; ln(100) is 4.605, as expected for a model that guesses uniformly |
| Overfit 8 examples, 150 AdamW steps at 3e-3 | loss fell to 0.0076 |
Every label set to -100 | the loss came back as NaN |
- The starting-loss check follows a point in Karpathy’s training recipe: verify that the loss starts at the value the setup predicts.
- If a tiny batch cannot be overfitted, the pipeline is broken and more data will not fix it.
- A run with all labels masked can show as flat or as NaN depending on the trainer, which is why decoding labels comes first.
Diagram
The debugging order
Process
The order, step by step
- Decode. Print one example after templating, masking and truncation. Is the answer there, the prompt masked, the end token present?
- Overfit a tiny batch. Eight to sixteen examples until the loss is near zero.
- Compare prompts. Training and serving prompts, character by character. A template that differs at serve time makes a good model look bad.
- Baseline. Run the untuned model on the evaluation set to know what you actually gained.
- One change at a time. Pin the seed, library versions and a hash of the data.
- This order is practice advice, not a documented standard. Steps 2 and 5 echo Karpathy’s recipe (overfit a single batch, add one change at a time); steps 1, 3 and 4 are common sense for fine-tuning pipelines.
Check yourself
Check: diagnose from the numbers
Training loss falls smoothly and validation loss is flat. The JSON-valid rate on your held-out set is 91 percent, but in production only 60 percent of replies parse. What do you suspect, and what do you check first?
Answer
Suspect a training-versus-serving prompt mismatch, not overfitting, since validation loss and the held-out rate agree with each other. Check step 3 of the order: compare the exact rendered prompts, including the system message and the chat template, character by character. Then re-run the held-out set through the production path.
Code
The knobs as a TRL config
Python
from trl import SFTConfig
args = SFTConfig(
per_device_train_batch_size=2, # sequences per pass, per GPU
gradient_accumulation_steps=4, # effective = 2 x 4 x number of GPUs
gradient_checkpointing=True, # already the default in TRL; shown explicitly
max_length=64, # pick from your length distribution
learning_rate=1e-4, # adapter run
report_to="none",
)| Test (TRL 1.16.0, CPU, one process) | Result |
|---|---|
| Effective batch from the config | 2×4×1=8 |
| 3 LoRA steps on a tiny model with this config | ran; loss, gradient norm and learning rate logged each step |
Trainable parameters (with LoraConfig(r=4, lora_alpha=8, target_modules="all-linear"), not shown in the code above) | 1,408 of 2,436,424 |
- The tiny model barely learned in 3 steps; the test shows the config runs and logs, not that it is a good recipe.
- Keep the base model revision, tokenizer and template, data hash, configuration, seed and code commit with every run.
Summary
Recap
- SFT is next-token cross-entropy, usually on answer tokens only. Decode an example to check masking, the end token and truncation.
- Choose checkpoints by task score on held-out data. Validation loss only guards against overfitting.
- Effective batch is sequences per pass times accumulation steps times GPUs. Accumulation saves activations, costs time, and needs token-level loss normalisation.
- Checkpointing saves activations at the price of recompute. Neither lever shrinks model states.
- Per-GPU states:
16P, then4P + 12P/N,2P + 14P/Nand16P/Nfor ZeRO-1, 2 and 3. Full sharding costs about 1.5 times the communication. If it fits, do not shard. - Debug in order: decode, memorise a tiny batch, diff the prompts, check the baseline, change one thing.
References
References & Sources (1 of 2)
SFT Trainer (TRL documentation) (opens in a new tab)
Hugging Face2026Documentation
https://huggingface.co/docs/trl/sft_trainer
Used for SFT as token-level cross-entropy (negative log-likelihood), the ignore index of -100, completion-only and assistant-only loss, the end-token alignment warning, the adapter learning-rate tip, the logged metrics, and the SFTConfig defaults at TRL v1.16.0.
Reducing Memory Usage (TRL documentation) (opens in a new tab)
Hugging Face2026Documentation
https://huggingface.co/docs/trl/reducing_memory_usage
Used for The max_length trade-off, the length-distribution utility, the three packing strategies, padding-free batching, activation offloading, and gradient checkpointing being on by default.
Performing gradient accumulation with Accelerate (opens in a new tab)
Hugging Face2026Documentation
https://huggingface.co/docs/accelerate/usage_guides/gradient_accumulation
Used for Gradient accumulation as a way to train on larger batches than memory allows, and the token-level loss rule: total loss over the accumulation step divided by the total number of non-padding tokens.
ZeRO: Memory Optimizations Toward Training Trillion Parameter Models (opens in a new tab)
Samyam Rajbhandari, Jeff Rasley, Olatunji Ruwase, Yuxiong He2019Preprint
arXiv 1910.02054 (opens in a new tab)https://arxiv.org/abs/1910.02054
Used for Per-GPU model-state formulas for data parallelism and ZeRO stages 1 to 3 with mixed-precision Adam, and the communication volumes of 2 units for stages 1 and 2 against 3 units for stage 3.
Zero Redundancy Optimizer (DeepSpeed tutorial) (opens in a new tab)
DeepSpeed project2026Documentation
https://www.deepspeed.ai/tutorials/zero/
Used for What stages 1 to 3 partition, ZeRO-Offload within ZeRO-2 and ZeRO-Infinity with ZeRO-3.
References
References & Sources (2 of 2)
FullyShardedDataParallel (PyTorch 2.14 documentation) (opens in a new tab)
PyTorch2026Documentation
https://docs.pytorch.org/docs/2.14/fsdp.html
Used for FULL_SHARD (the default), SHARD_GRAD_OP, NO_SHARD and HYBRID_SHARD behaviour, and the all-gather and reduce-scatter collectives, as documented for PyTorch 2.14.
A Recipe for Training Neural Networks (opens in a new tab)
Andrej Karpathy2019Article
https://karpathy.github.io/2019/04/25/recipe/
Used for Checking that the loss starts at the value the setup predicts, overfitting a small batch before anything else, and adding one change at a time.
Keys: ← → move, Home End first and last, F full screen.