Slides · Fine-tuning

Training practice and distributed training

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 tokenslog⁡p(tokent∣tokens before t)\text{loss} = -\sum_{t \in \text{target tokens}} \log p(\text{token}_t \mid \text{tokens before } t)
SymbolMeaning
tokent\text{token}_tThe correct next token at position tt of the training text
p(⋅)p(\cdot)The probability the model gave that token, given everything before it
∑t∈target tokens\sum_{t \in \text{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 loss is 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.

Source1 SFT Trainer (TRL documentation)

Diagram

One SFT step

Diagram: An example is rendered with the chat template and tokenised, the model predicts every next token, and the loss counts only the answer...

Example: prompt + answer

Chat template, tokens

Forward: next-token odds

Loss on answer tokens

Backward, then update

Diagram summary: An example is rendered with the chat template and tokenised, the model predicts every next token, and the loss counts only the answer tokens. The backward pass and optimiser update follow, then the loop repeats on the next batch.

Source1 SFT Trainer (TRL documentation)

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 printedResult
Tokens after templating51
Positions masked with -10039
Positions that carry the loss12
Decoded loss tokensthe answer sentence plus the end token and a newline
Anything the data did not containa 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=False left zero masked positions in the same test.
  • assistant_only_loss=True serves 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.

Source1 SFT Trainer (TRL documentation)

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 exampleWhat the helper showed
Default max_length of 1024 on this short examplenothing cut; 12 loss tokens
max_length=4444 tokens, and the loss text stopped mid-sentence, with no end token
max_length=30, shorter than the prompt sideevery example had no loss token left and the training set came out empty
  • Truncation keeps the start of the sequence (truncation_mode defaults 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.

Source1 SFT Trainer (TRL documentation)

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_length are 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.

Sources1 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=2030 / 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 runWhy
Train and validation lossThe overfitting gap
Learning rate and gradient norm (TRL logs it before clipping)Spikes and a stalled schedule
Tokens per second and GPU memoryCost and headroom
The task metric on a held-out setThe thing you ship on
SFTConfig default (TRL 1.16.0)Value
learning_rate2e-5
num_train_epochs3.0
max_grad_norm1.0
max_length1024
gradient_checkpointingTrue
bf16True 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.

Source1 SFT Trainer (TRL documentation)

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

LeverSavesCosts
Gradient accumulationActivations, by using a smaller batch per passMore passes per update, so slower wall-clock
Gradient checkpointingActivations, by not storing them allExtra compute from recomputing
LoRA or QLoRAGradients and optimiser state of the frozen baseA ceiling on adapter capacity
Shorter sequencesActivationsCut-off text may hold the answer
Packing or padding-freeWasted paddingNeeds supported attention kernels; packing mixes examples in a row
Activation offloadingGPU memorySlightly more training time, per the TRL page
Sharding or offloading statesModel-state memoryCommunication or slower transfers

Sources2 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\text{effective batch} = \text{sequences per pass} \times \text{accumulation steps} \times \text{data-parallel GPUs}
SymbolMeaning
sequences per pass\text{sequences per pass}The micro-batch each GPU holds in memory at once
accumulation steps\text{accumulation steps}Passes whose gradients are added before one optimiser step
data-parallel GPUs\text{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=962 \times 6 \times 8 = 96 sequences per update.

Source3 Performing gradient accumulation with Accelerate

Diagram

Accumulation, drawn

Diagram: Several small batches each run a forward and backward pass and add their gradients.

Micro-batch 1

Add up gradients

Micro-batch 2

Micro-batch N

One optimiser step

Diagram summary: Several small batches each run a forward and backward pass and add their gradients. The optimiser steps once, so the update reflects the larger combined batch while activation memory follows the small one.

Source3 Performing gradient accumulation with Accelerate

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 combineGradient vs the full batch
Sum of token losses, divided by all non-padding tokensidentical (difference 0.0)
Each micro-batch averaged on its own, then divided by 422 percent relative difference
Same naive method, all sequences the same lengthidentical (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.

Source3 Performing gradient accumulation with Accelerate

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)=16256 / (2 \times 8) = 16 accumulation steps. With 12 steps the effective batch is 2×12×8=1922 \times 12 \times 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 checkpointingequal
Times the block’s forward ran in the checkpointed pass2 (once forward, once recomputed)
  • If model states are what overflow, checkpointing will not rescue the run.

Source2 Reducing Memory Usage (TRL documentation)

Compare

Padding, packing and truncation

OptionWhat it doesWatch for
TruncationCuts sequences at max_lengthCut text may hold the answer
Packing, bfdPacks sequences into rows; overflow tokens are discardedDefault strategy in the docs
Packing, bfd_splitSplits long sequences first, so all tokens are keptPieces of one example can land in different rows
Packing, wrappedConcatenates everything, cuts fixed blocksThe docs warn it may mix unrelated examples
Padding-freeFlattens a batch into one sequence, examples kept wholeNeeds FlashAttention 2 or 3 per the docs
  • Check how your own stack keeps packed examples apart before you turn packing on.

Sources2 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.

Source4 ZeRO: Memory Optimizations Toward Training Trillion Parameter Models

Math

Per-GPU model states

Here PP is parameters and NN is GPUs, with Adam in mixed precision.

data parallel: 16P\text{data parallel: } 16PZeRO-1: 4P+12PN(optimiser state split)\text{ZeRO-1: } 4P + \frac{12P}{N} \quad \text{(optimiser state split)}ZeRO-2: 2P+14PN(plus gradients split)\text{ZeRO-2: } 2P + \frac{14P}{N} \quad \text{(plus gradients split)}ZeRO-3: 16PN(plus parameters split)\text{ZeRO-3: } \frac{16P}{N} \quad \text{(plus parameters split)}
TermMeaning
2P2P16-bit parameters
2P2P16-bit gradients
12P12POptimiser 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.

Sources4 ZeRO: Memory Optimizations Toward Training Trillion Parameter Models5 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.

StrategyFormula (P=11P = 11, N=8N = 8)States per GPURoom left on 48 GB
Data parallel16×1116 \times 11176 GBdoes not fit
ZeRO-14×11+12×11/84 \times 11 + 12 \times 11 / 860.5 GBdoes not fit
ZeRO-22×11+14×11/82 \times 11 + 14 \times 11 / 841.25 GB6.75 GB
ZeRO-316×11/816 \times 11 / 822 GB26 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.

Source4 ZeRO: Memory Optimizations Toward Training Trillion Parameter Models

Compare

The same ideas in PyTorch FSDP

ShardingStrategyWhat 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_OPShards gradients and optimiser states during compute; parameters are not resharded after the forward, only after the backward
NO_SHARDReplicates everything, like DistributedDataParallel; gradients are all-reduced
HYBRID_SHARDFull shard within a node, replicate across nodes
  • FULL_SHARD matches the ZeRO-3 memory picture; SHARD_GRAD_OP sits 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_shard API, so check which one your library version uses.

Source6 FullyShardedDataParallel (PyTorch 2.14 documentation)

Worked example

What full sharding pays

StrategyCommunication per step (ZeRO paper)
Data parallel baseline2 units
ZeRO-1 and ZeRO-22 units, the same as the baseline
ZeRO-33 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.

Sources4 ZeRO: Memory Optimizations Toward Training Trillion Parameter Models6 FullyShardedDataParallel (PyTorch 2.14 documentation)

Diagram

Choosing a strategy

Diagram: Use plain data parallelism when everything fits, an adapter method when that is enough, and sharding for a full tune that does not fit.

yes

no

yes

no

All fits on one GPU?

Plain data parallel

LoRA or QLoRA enough?

Adapter on few GPUs

Shard: ZeRO-3 or FSDP

Still too big: offload

Diagram summary: Use plain data parallelism when everything fits, an adapter method when that is enough, and sharding for a full tune that does not fit. Offloading is the last step because it is the slowest.

Source5 Zero Redundancy Optimizer (DeepSpeed tutorial)

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.

Source5 Zero Redundancy Optimizer (DeepSpeed tutorial)

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/N16P / N at most 80 GB, so NN is at least 208/80=2.6208 / 80 = 2.6, which rounds up to 3 GPUs for the states alone, with almost nothing left for activations. With N=4N = 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 seeCommon causeFirst action
Loss starts very lowPrompt included in the loss, leaked targets, or duplicates across splitsDecode labels; audit the split
Flat from step 0 (or NaN, depending on the trainer)Labels all masked, adapter not training, rate far too lowCount trainable parameters; decode labels
Spikes or NaNRate too high, bad batch, no clippingLower the rate; inspect gradient norm and batch
Train falls, validation risesOverfittingFewer epochs, earlier checkpoint, more varied data
Validation loss falls, task metric fallsLoss is not the taskChoose the checkpoint by the task metric
Never stops generatingEnd token missing or mismatchedFix 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).

CheckResult
Starting loss before any training4.606; ln⁡(100)\ln(100) is 4.605, as expected for a model that guesses uniformly
Overfit 8 examples, 150 AdamW steps at 3e-3loss fell to 0.0076
Every label set to -100the 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.

Source7 A Recipe for Training Neural Networks

Diagram

The debugging order

Diagram: Work from the cheapest, most informative check to the most expensive.

1 Decode one example

2 Overfit 8 to 16

3 Compare train and serve prompts

4 Run the base model

5 Change one thing

Diagram summary: Work from the cheapest, most informative check to the most expensive. Print what the model actually receives, show it can memorise a handful of examples, diff the prompts used in training and serving, measure the untuned model, then vary one thing per run with seed, versions and data hash fixed.

Source7 A Recipe for Training Neural Networks

Process

The order, step by step

  1. Decode. Print one example after templating, masking and truncation. Is the answer there, the prompt masked, the end token present?
  2. Overfit a tiny batch. Eight to sixteen examples until the loss is near zero.
  3. Compare prompts. Training and serving prompts, character by character. A template that differs at serve time makes a good model look bad.
  4. Baseline. Run the untuned model on the evaluation set to know what you actually gained.
  5. 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.

Source7 A Recipe for Training Neural Networks

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 config2×4×1=82 \times 4 \times 1 = 8
3 LoRA steps on a tiny model with this configran; 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.

Source1 SFT Trainer (TRL documentation)

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, then 4P + 12P/N, 2P + 14P/N and 16P/N for 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)

  1. SFT Trainer (TRL documentation) (opens in a new tab)

    Hugging Face2026Documentation

    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.

  2. Reducing Memory Usage (TRL documentation) (opens in a new tab)

    Hugging Face2026Documentation

    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.

  3. Performing gradient accumulation with Accelerate (opens in a new tab)

    Hugging Face2026Documentation

    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.

  4. ZeRO: Memory Optimizations Toward Training Trillion Parameter Models (opens in a new tab)

    Samyam Rajbhandari, Jeff Rasley, Olatunji Ruwase, Yuxiong He2019Preprint

    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.

  5. Zero Redundancy Optimizer (DeepSpeed tutorial) (opens in a new tab)

    DeepSpeed project2026Documentation

    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)

  1. FullyShardedDataParallel (PyTorch 2.14 documentation) (opens in a new tab)

    PyTorch2026Documentation

    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.

  2. A Recipe for Training Neural Networks (opens in a new tab)

    Andrej Karpathy2019Article

    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.