Training practice and distributed training

  • Production
  • 40 min
  • Lesson 4 of 7 in Fine-tuning
  • Last verified

Open slides(36 slides)

Before you start

You will be able to

  • Explain what an SFT run optimises and which tokens carry the loss, and say why validation loss alone should not pick the checkpoint.
  • Compute the effective batch size, and choose among gradient accumulation, gradient checkpointing, LoRA and sequence limits for a run that runs out of memory, stating what each saves and costs.
  • Compute per-GPU model-state memory for plain data parallelism and ZeRO stages 1 to 3 from the 16-bytes-per-parameter rule, and say what full sharding pays for its saving.
  • Diagnose a run from its loss curves and task metric, and apply the debugging order: decode the labels, overfit a tiny batch, change one thing at a time.

Three days of training went well. On the fourth, Aarav’s answers get slightly worse. Kavya writes the score from each run on the whiteboard.

By Friday there is a long column of numbers. Ananya reads it from the bottom up, then from the top down.

“Don’t change anything yet,” she says. What does the curve say?

Concept

Lesson 1 asked whether to tune and what it costs, and lesson 3 chose the method (LoRA or full). This lesson is the run itself: what a supervised fine-tuning (SFTSFTShort for supervised fine-tuning: fine-tuning on pairs of a prompt and an ideal response.Open the glossary entry) job actually optimises, what to do when it does not fit in memory, how to spread it over several GPUs, and how to tell from the curves what went wrong. The 16-bytes-per-parameter memory model and the 6ND compute estimate come from When to tune, and what it costs; this lesson uses them and does not re-derive them.

Most failed tuning runs fail quietly. The job finishes, the loss goes down, and the model is worse. The skills here are mostly about not being fooled by a number.

Why It Matters

A run costs GPU hours and, more often, a day of someone’s attention. Two habits save both. The first is knowing exactly which tokens the loss measures, because a setup error (the wrong tokens counted, a missing end token, silent truncation) produces a smooth, healthy-looking curve for a broken model. The second is knowing the price of every memory lever, so that when a run goes out of memory you pick the cheapest fix instead of the first one you remember. Interviewers ask about both because they separate people who have read about tuning from people who have run it.

Mental Model

Think of a training run as a log with several columns, each telling you something different: how well the model handles the examples it trains on, how well it handles examples it has never seen, and how well it does the real job in use. A good run improves the last column. A bad one can improve the first while the others stay put or fall.

Where the analogy breaks: a person whose work gets worse is tired. A model that gets worse after more training is usually fitting the training examples too closely, or was set up on the wrong examples in the first place. It does not need rest. It needs a look at the data and the setup.

The SFT objective

SFT trains the model to predict each next token of a target answer. The loss is the token-level cross-entropy (negative log-likelihood): for each target token, how much probability the model gave the correct one, given everything before it. The TRL documentation describes the SFT goal as minimising the negative log-likelihood of the target sequence conditioned on the input.

Diagram: One SFT step renders an example with the chat template, predicts each next token, and scores only the answer tokens with cross-entropy.

Example: prompt + answer

Tokens, rendered with the chat template

Forward pass: probability of each next token

Cross-entropy on the answer tokens only
prompt tokens masked

Backward pass: gradients

Optimiser step: update trainable weights

Diagram summary: One SFT step renders an example with the chat template, predicts each next token, and scores only the answer tokens with cross-entropy. The backward pass computes gradients and the optimiser updates the trainable weights, then the loop continues with the next batch.

Three setup details decide whether that number means what you think.

  • Which tokens count. You usually want the loss on the response only, so the number measures the behaviour you are teaching. TRL exposes this as completion_only_loss for prompt-completion data (by default the loss is on the completion for those datasets, and on the full sequence for plain text datasets) and as assistant_only_loss for chat data, which needs a chat template that marks the assistant text. Padding is excluded by an ignore index, -100 by default.
  • The end token. If the end-of-sequence token is missing from the targets, or does not match the chat template, the tuned model never learns to stop. TRL’s documentation warns that the end token must be aligned with the chat template so responses terminate correctly.
  • Length limit. Sequences longer than max_length are truncated, and TRL’s documentation says too small a value discards a significant share of tokens. If the truncated part held the answer, you trained on prompts with the answers cut off, and the loss will not warn you.

Measure the token-length distribution of your data before you pick a limit. The TRL docs offer a utility for this.

Loss is not the task metric

Cross-entropy measures how well the model imitates the training answers. It does not measure whether the JSON parses, whether the label is right, or whether the tone fits. These usually move together, until they do not. The checkpoint to ship is the one that scores best on a task metric over a held-out set (JSON-valid rate, exact match, a graded rubric), with validation loss as a sanity check. A periodic small evaluation during the run costs little and keeps you from picking by the wrong number.

What to log in every run: training and validation loss, learning rate, gradient norm (TRL logs it before clipping), tokens per second, MFUModel FLOPs utilisation (MFU)The share of a GPU's peak arithmetic rate that a training job actually sustains. Wall-clock time is the job's FLOPs divided by peak times MFU.Open the glossary entry if you can get it, GPU memory, and the task metric. Save checkpoints often so a crash or a bad epoch does not cost the whole run. For LoRA a checkpoint is just the adapter.

Hyperparameters are starting points

TRL’s SFTConfig documentation shows a default learning rate of 2e-5, three epochs, a maximum gradient norm of 1.0, and a tip that when training adapters you typically use a higher rate, about 1e-4, because only new parameters are being learned. These are library defaults at the version read (v1.16.0), not recommendations for your data, and defaults change between releases. Sweep the learning rate first on a short run over a subset, then epochs, then LoRA rank, and never tune on the final test set. More epochs on a small set invite overfittingOverfittingA model memorising its training examples and generalising worse.Open the glossary entry.

Memory levers

When a run goes out of memory, first work out what is too big. Lesson 1 gave the model-state part (about 16 bytes per parameter for full fine-tuning). The rest is activations, which grow with the batch and the sequence length. Each lever below attacks one of these, and each has a price.

LeverWhat it savesWhat it costs
Gradient accumulationActivation memory, by using a smaller batch per passMore passes per update; slower wall-clock; same update
Gradient checkpointingActivation memory, by not storing them allExtra compute, as the forward pass is partly re-run
LoRA or QLoRAGradients and optimiser state for the frozen baseLimited adapter capacity
Shorter sequences, truncationActivations, directlyCut-off text may hold the answer
Packing or padding-free batchesWasted paddingNeeds supported attention kernels; packing mixes examples in a row
Activation offloading to CPUGPU memorySlightly more training time (TRL docs)
Sharding or offloading statesModel-state memoryCommunication or slower transfers (next section)

Gradient accumulation, and its trap

Gradient accumulation adds up gradients over several small batches and steps the optimiser once. The Accelerate guide describes it as a way to train on bigger batch sizes than the machine would fit. The update is the same as one large batch; you pay for it in time. The effective batch size per optimiser step is:

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}

Illustrative: 4 sequences per pass, 8 accumulation steps and 8 GPUs give 4×8×8=2564 \times 8 \times 8 = 256 sequences per update.

Diagram: Gradient accumulation runs several small batches, adding their gradients, and steps the optimiser once.

Micro-batch 1: 4 sequences
forward and backward

Add up gradients

Micro-batch 2

... micro-batch 8

One optimiser step
effective batch = 4 × 8 × 8 GPUs = 256

Diagram summary: Gradient accumulation runs several small batches, adding their gradients, and steps the optimiser once. The update equals one large batch, so you trade time for activation memory.

The trap is in the loss. For token-level losses on sequences of different lengths, the Accelerate guide says the correct loss is the total loss across the whole accumulation step divided by the total number of non-padding tokens, which is not the same as the average of the per-batch averages. A run that averages the averages weights short sequences too heavily. Mature trainers handle this; a hand-written loop often does not.

Gradient checkpointing, and what it does not do

Gradient checkpointing trades compute for memory: it does not store all intermediate activations in the forward pass, and recomputes them in the backward pass (TRL documentation). It leaves the weights, gradients and optimiser state alone. TRL’s trainers enable it by default, according to the docs read. If your trouble is model states, checkpointing will not rescue you.

Packing and padding

Padding wastes compute on tokens that carry no loss. Packing fills each row with several examples up to the length limit. TRL’s docs describe strategies that differ in what happens at the edges: bfd discards overflow tokens, bfd_split keeps them by splitting, and wrapped concatenates everything and cuts blocks, which “may mix unrelated examples”. Padding-free batching flattens a batch into one sequence while keeping each example whole, and TRL notes it needs FlashAttention 2 or 3. Before you turn packing on, check how your library keeps examples apart.

Sharding across GPUs

If the model states do not fit on one GPU, spread them. The mental model is a library with eight desks. Data parallelism gives every desk a full copy of the books and splits the readers. Sharding splits the books too: each desk keeps an eighth, and borrows the rest from its neighbours when it needs them. You save shelf space and you pay in walking.

The ZeRO paper makes this exact. With PP parameters, Adam and mixed precision, plain data parallelism keeps 16P16P bytes per GPU. With NN GPUs:

StrategyWhat is split across GPUsModel-state bytes per GPU
Data parallel (replicated)Nothing16P16P
ZeRO-1Optimiser states4P+12P/N4P + 12P/N
ZeRO-2Optimiser states and gradients2P+14P/N2P + 14P/N
ZeRO-3Optimiser states, gradients and parameters16P/N16P/N

PyTorch FSDP (FULL_SHARD, its default strategy) shards parameters, gradients and optimiser states like ZeRO-3. SHARD_GRAD_OP shards gradients and optimiser states during computation and shards parameters only outside it: it gathers them before the forward, does not reshard after the forward, and reshards after the backward (a trade in the spirit of ZeRO-2, my comparison rather than the docs). And NO_SHARD replicates everything like DDP. HYBRID_SHARD shards inside a node and replicates across nodes, to reduce the traffic. DeepSpeed describes stages 1 to 3 in the same way.

Worked example (illustrative)

A 13B-parameter model, full fine-tuning, 8 GPUs of 80 GB. Plain data parallelism needs 16×13=20816 \times 13 = 208 GB of states per GPU: it cannot fit. Under the formulas:

  • ZeRO-1: 4×13+12×13/8=52+19.5=71.5 GB4 \times 13 + 12 \times 13 / 8 = 52 + 19.5 = 71.5\ \text{GB}.
  • ZeRO-2: 2×13+14×13/8=26+22.75=48.75 GB2 \times 13 + 14 \times 13 / 8 = 26 + 22.75 = 48.75\ \text{GB}.
  • ZeRO-3: 16×13/8=26 GB16 \times 13 / 8 = 26\ \text{GB}.
StrategyFormula (P=13BP = 13\text{B}, N=8N = 8)Model-state memory per GPUFits in 80 GB?
Data parallel16×1316 \times 13208 GBNo
ZeRO-14×13+12×13/84 \times 13 + 12 \times 13 / 871.5 GBBarely, little room for activations
ZeRO-22×13+14×13/82 \times 13 + 14 \times 13 / 848.75 GBYes
ZeRO-316×13/816 \times 13 / 826 GBYes, with the most room

ZeRO-3 leaves roughly 54 GB of each card for activations and for the full layers gathered temporarily during compute, which the formulas do not count. ZeRO-2 at 48.75 GB also fits on paper, so the choice is a trade: ZeRO-3 leaves more room for activations, and ZeRO-2 avoids the extra parameter traffic described below. Measure both. The numbers are a floor, as in lesson 1.

What sharding pays

Memory is not free. In the ZeRO paper, stages 1 and 2 keep the communication volume at the level of data parallelism, and stage 3 costs 1.5 times as much (33 units against 22). FSDP’s documentation shows where it comes from: parameters are gathered by all-gather before the forward and again around the backward pass, and gradients are combined and split by reduce-scatter. Whether 1.5 times hurts depends on how fast your links are, so measure tokens per second. The decision rule:

Diagram: Start by asking whether everything fits on one GPU; if so, plain data parallelism is simplest and avoids sharding traffic.

Yes

No, but LoRA or QLoRA fits

No, full tuning needed

Yes

No

Do weights, gradients,
optimiser state and activations
fit on one GPU?

Plain data parallel:
replicate and split the data

Use LoRA or QLoRA
on one or a few GPUs

Shard the states:
ZeRO-3 or FSDP full shard

Still too big
or too slow?

Offload to CPU or NVMe,
or split layers across GPUs

Done: check tokens/s
and memory

Diagram summary: Start by asking whether everything fits on one GPU; if so, plain data parallelism is simplest and avoids sharding traffic. If only an adapter method fits, use LoRA or QLoRA; if full tuning is needed, shard the states, and only offload or split layers when that is still not enough.

Offloading is the last resort because it is slower. DeepSpeed’s ZeRO-Offload moves optimiser and gradient states to CPU memory within ZeRO-2, and ZeRO-Infinity, with ZeRO-3, can move the model state to CPU or NVMe. Tensor parallelism splits a single layer across devices. Those tools matter for models too large for one node, and are beyond this lesson.

Reading the loss curve

Plot training loss, validation loss and the task metric together. Then read the pattern before changing anything.

What you seeCommon causeFirst action
Loss starts very lowLoss includes prompt text, or the targets leak, or data is duplicated across splitsDecode labels; audit the split
Flat from step 0Labels all masked, adapter not training, learning rate far too lowCount trainable parameters; decode labels
Spikes or NaNLearning rate too high, bad batch, no gradient clipping, overflowLower the rate; check gradient norm; inspect the batch
Train falls, validation risesOverfittingFewer epochs, restore an earlier checkpoint, more varied data
Validation loss falls, task metric fallsLoss is not the taskChoose the checkpoint by task metric
Model never stops generatingEnd token missing or mismatchedFix template and targets

These are the common causes, not proofs. Each one is a hypothesis you check by looking at the data or by changing one thing.

Overfitting and forgettingForgetting (catastrophic forgetting)The loss of general abilities a model was not trained to keep after fine-tuning. Mix in general data and re-run regression tests.Open the glossary entry are not the same problem. Overfitting is visible as the gap between training and validation. Forgetting is the loss of something the model used to do; validation loss on your own data will not show it, and the evaluation in lesson 6 must include it.

The debugging order

When a run misbehaves, work from the cheapest, most informative check to the most expensive. This is practice advice, not a documented standard, but it matches how most pipeline faults are found.

  1. Decode what the model sees. Print one training example after templating, masking and truncation: the input ids and the labels. Check that the answer is there, that the prompt is masked, and that the end token is present.
  2. Overfit a tiny batch. Train on eight to sixteen examples until the loss goes near zero. If it cannot, the pipeline is broken, and more data will not fix it.
  3. Compare training and serving prompts character by character. A template that differs at serve time makes a fine model look bad.
  4. Run the base model on the evaluation set to get the true baseline (lesson 1’s gate).
  5. Change one variable at a time, and pin the seed, library versions and a hash of the data.
Diagram: Debug in order of cheapest and most informative first.

no

yes

Run misbehaves

1 Decode one templated example:
answer present, prompt masked, end token present

2 Overfit a tiny batch of 8 to 16

Loss near zero?

Pipeline is broken: more data will not fix it

3 Compare training and serving prompts character by character

4 Run the base model on the eval set for the true baseline

5 Change one variable at a time, pin seed, versions, data hash

Diagram summary: Debug in order of cheapest and most informative first. Decode what the model sees, check that it can overfit a tiny batch, compare training and serving prompts, get the real baseline, then change one variable at a time with the seed, versions and data hash pinned.

Python

# Illustrative: the knobs this lesson names, as TRL SFTConfig arguments.
# Values are examples, not recommendations; defaults differ between versions.
from trl import SFTConfig

args = SFTConfig(
    per_device_train_batch_size=4,   # sequences per pass, per GPU
    gradient_accumulation_steps=8,   # effective batch = 4 x 8 x number of GPUs
    gradient_checkpointing=True,     # recompute activations to save memory
    max_length=2048,                 # choose from your length distribution
    assistant_only_loss=True,        # loss on assistant text (chat data)
    learning_rate=1e-4,              # adapters usually take a higher rate
    bf16=True,
    packing=False,                   # check how your stack separates examples
)

Keep with each run the base model revision, tokenizer and template, data hash, configuration, seed and code commit. A run you cannot reproduce is a run you cannot debug. Budget more than one clean run’s cost for iteration, since the first run rarely works.

Real-World Application

Take a hypothetical team tuning a 13B model on 40,000 chat transcripts. The first run goes out of memory on one GPU. They compute 208 GB of states, move to 8 GPUs with full sharding (26 GB of states each by the formula), and use a small batch per pass with accumulation. Suppose training loss then falls smoothly but the model ignores the output schema in production. The debugging order says to decode a batch first. Two plausible findings: the loss included user turns, and the longest transcripts were cut off before the answer. Each is a setup fault that leaves a clean curve, which is why decoding comes before any change to the learning rate or the model size.

Interview Perspective

Expect: “What is gradient checkpointing and how does it differ from accumulation?”, “How much memory per GPU for full fine-tuning of a 13B model on 8 GPUs, with and without ZeRO-3?”, “Loss is flat, what do you do?”, “Why not always shard?”.

A strong answer states which tokens carry the loss, gives the effective batch formula, separates activation levers from state levers, uses the 16P, 4P + 12P/N, 2P + 14P/N and 16P/N formulas, notes sharding’s communication cost, and describes the debugging order. Common mistakes: believing accumulation or checkpointing shrinks model states, picking checkpoints by validation loss alone, and reaching for sharding when the model already fits.

Provenance: Common industry pattern. These are questions this topic tends to draw; none is verified for a named company.

Practice Questions

Provenance: generated practice.

  • Basic: What are gradient accumulation and gradient checkpointing, and how do they differ in what they save and cost?
  • Intermediate: Per-GPU model-state memory for a 30B-parameter full fine-tune on 16 GPUs under plain data parallelism and under ZeRO-3.
  • Advanced: Loss decreases smoothly but the tuned model ignores the JSON schema in production. List causes in the order you would check them.
  • Product: A teammate wants to buy more GPUs because a run is out of memory. What do you ask first?

Activity

Do, notice, apply.

  1. Do. Using the formulas, compute per-GPU states for a 7B model on 4 GPUs under data parallelism and ZeRO-1, 2 and 3.
  2. Notice. Which strategy first fits on a 40 GB card, and what did the formulas leave out?
  3. Apply. Take a training script you know, or a TRL example. Write down which tokens carry the loss, the effective batch size, and what you would log, then say what a flat loss would make you check first.

Homework

Write a run card for a LoRA or full fine-tune of your choice: objective and masking, effective batch size, the memory plan (what you would turn on and the price of each), the sharding decision with the per-GPU state estimate, the metrics you would log, and the three curve patterns you would act on and what you would do.

Quick Revision

  • SFT is next-token cross-entropy, usually on response tokens only; check masking, the end token and truncation.
  • Pick checkpoints by a held-out task metric, not validation loss alone.
  • effective batch=sequences per pass×accumulation steps×GPUs\text{effective batch} = \text{sequences per pass} \times \text{accumulation steps} \times \text{GPUs}. Accumulation saves activations and costs time.
  • Checkpointing saves activations and costs recompute; neither lever shrinks model states.
  • Per-GPU states: 16P replicated; 4P + 12P/N; 2P + 14P/N; 16P/N (ZeRO-1, 2, 3).
  • Full sharding costs extra communication (3 units against 2 in the ZeRO paper). If it fits, do not shard.
  • Debug in order: decode labels, overfit a tiny batch, compare prompts, check the baseline, change one thing.

Check yourself

  • Checkpoint (answer aloud, no notes): Give your SFT setup for a 7B LoRA run, then say what you do when the loss is flat from the first step.
  • Re-test (nearby variant): Full fine-tune of a 13B model on 8 GPUs: which strategy, what per-GPU state memory, and what does it cost in communication?
  • Misconception to avoid: “A lower validation loss always means a better model.”

Resources & Further Reading

Checked sources to go deeper. The essential ones come first in each group.

Official documentation

Further reading

Research papers

More for this module: Fine-tuning resources

Practice

Test what you just read. Quizzes and cards are grouped by module: Fine-tuning.

Check yourself11 questions on what this lesson set out to teach

Checking answers needs JavaScript. You can still read every question and option below.

0 of 11 answered

Keyboard: arrow keys move between options. Space or Enter selects the focused option.

ObjectiveExplain what an SFT run optimises and which tokens carry the loss, and say why validation loss alone should not pick the checkpoint.

  1. Question 1 of 11In an SFT run with the loss restricted to the response, what does the logged training loss report?

    Choose one answer.

  2. Question 2 of 11Validation loss is lowest at step 400, while the held-out JSON-valid rate peaks at step 700 and validation loss there is only slightly higher. Which checkpoint should ship?

    Choose one answer.

ObjectiveCompute the effective batch size, and choose among gradient accumulation, gradient checkpointing, LoRA and sequence limits for a run that runs out of memory, stating what each saves and costs.

  1. Question 3 of 11A full fine-tune runs out of memory at 16 sequences per pass on one GPU, and the profile shows activations are the bulk. The team wants updates equivalent to 64 sequences. Which change fits?

    Choose one answer.

  2. Question 4 of 11Each of 4 GPUs runs 6 sequences per pass and accumulates over 5 passes before the optimiser steps. How many sequences contribute to one update?

    Choose one answer.

  3. Question 5 of 11A team enables gradient checkpointing, yet a 30B full fine-tune on one 80 GB GPU still runs out of memory. Why did it not help?

    Choose one answer.

  4. Question 11 of 11A full fine-tune runs out of memory in gradients and optimiser state, not in activations. Transcripts are long, but each answer sits near the start. Which lever addresses the problem, and what does it cost?

    Choose one answer.

ObjectiveCompute per-GPU model-state memory for plain data parallelism and ZeRO stages 1 to 3 from the 16-bytes-per-parameter rule, and say what full sharding pays for its saving.

  1. Question 6 of 11A 20B-parameter full fine-tune uses Adam in mixed precision on 16 GPUs with ZeRO-2. What are the model states per GPU, before activations?

    Choose one answer.

  2. Question 7 of 11A 3B-parameter full fine-tune with short sequences runs on 8 GPUs of 80 GB each. Which setup is the best default?

    Choose one answer.

  3. Question 8 of 11Compared with plain data parallelism, what does ZeRO-3 or FSDP full sharding pay in return for its memory saving?

    Choose one answer.

ObjectiveDiagnose a run from its loss curves and task metric, and apply the debugging order: decode the labels, overfit a tiny batch, change one thing at a time.

  1. Question 9 of 11On a 3,000-example set, training loss keeps falling through epoch 5. Validation loss bottomed after epoch 2 and has risen since, and the task metric fell with it. What is the best reading and response?

    Choose one answer.

  2. Question 10 of 11A new LoRA run shows a loss that does not move from step 0. Which first check is cheapest and most informative?

    Choose one answer.