Training practice and distributed training
- Production
- 40 min
- Lesson 4 of 7 in Fine-tuning
- Last verified
Select text in the lesson first to keep it with your note. With the keyboard, move focus here and press the button: the note goes with the section you are reading.
In this module
On this page
Before you start
- Completed:PEFT, LoRA and QLoRA in depth
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.
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_lossfor prompt-completion data (by default the loss is on the completion for those datasets, and on the full sequence for plain text datasets) and asassistant_only_lossfor chat data, which needs a chat template that marks the assistant text. Padding is excluded by an ignore index,-100by 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_lengthare 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.
| Lever | What it saves | What it costs |
|---|---|---|
| Gradient accumulation | Activation memory, by using a smaller batch per pass | More passes per update; slower wall-clock; same update |
| Gradient checkpointing | Activation memory, by not storing them all | Extra compute, as the forward pass is partly re-run |
| LoRA or QLoRA | Gradients and optimiser state for the frozen base | Limited adapter capacity |
| Shorter sequences, truncation | Activations, directly | Cut-off text may hold the answer |
| Packing or padding-free batches | Wasted padding | Needs supported attention kernels; packing mixes examples in a row |
| Activation offloading to CPU | GPU memory | Slightly more training time (TRL docs) |
| Sharding or offloading states | Model-state memory | Communication 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:
Illustrative: 4 sequences per pass, 8 accumulation steps and 8 GPUs give sequences per update.
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 parameters, Adam and mixed precision, plain data parallelism keeps bytes per GPU. With GPUs:
| Strategy | What is split across GPUs | Model-state bytes per GPU |
|---|---|---|
| Data parallel (replicated) | Nothing | |
| ZeRO-1 | Optimiser states | |
| ZeRO-2 | Optimiser states and gradients | |
| ZeRO-3 | Optimiser states, gradients and parameters |
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 GB of states per GPU: it cannot fit. Under the formulas:
- ZeRO-1: .
- ZeRO-2: .
- ZeRO-3: .
| Strategy | Formula (, ) | Model-state memory per GPU | Fits in 80 GB? |
|---|---|---|---|
| Data parallel | 208 GB | No | |
| ZeRO-1 | 71.5 GB | Barely, little room for activations | |
| ZeRO-2 | 48.75 GB | Yes | |
| ZeRO-3 | 26 GB | Yes, 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 ( units against ). 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:
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 see | Common cause | First action |
|---|---|---|
| Loss starts very low | Loss includes prompt text, or the targets leak, or data is duplicated across splits | Decode labels; audit the split |
| Flat from step 0 | Labels all masked, adapter not training, learning rate far too low | Count trainable parameters; decode labels |
| Spikes or NaN | Learning rate too high, bad batch, no gradient clipping, overflow | Lower the rate; check gradient norm; inspect the batch |
| Train falls, validation rises | Overfitting | Fewer epochs, restore an earlier checkpoint, more varied data |
| Validation loss falls, task metric falls | Loss is not the task | Choose the checkpoint by task metric |
| Model never stops generating | End token missing or mismatched | Fix 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.
- 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.
- 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.
- Compare training and serving prompts character by character. A template that differs at serve time makes a fine model look bad.
- Run the base model on the evaluation set to get the true baseline (lesson 1’s gate).
- Change one variable at a time, and pin the seed, library versions and a hash of the data.
# 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.
- Do. Using the formulas, compute per-GPU states for a 7B model on 4 GPUs under data parallelism and ZeRO-1, 2 and 3.
- Notice. Which strategy first fits on a 40 GB card, and what did the formulas leave out?
- 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.
- . 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.”
Related
Resources & Further Reading
Checked sources to go deeper. The essential ones come first in each group.
Official documentation
FullyShardedDataParallel (PyTorch 2.14 documentation) (opens in a new tab)
The reference for the sharding strategies, to read before choosing one in a real run.
Reducing Memory Usage (TRL documentation) (opens in a new tab)
A practical list of memory levers in one trainer library, each with its code switch.
Further reading
A Recipe for Training Neural Networks (opens in a new tab)
A habit-forming checklist for debugging training runs, written for general neural networks.
Research papers
ZeRO: Memory Optimizations Toward Training Trillion Parameter Models (opens in a new tab)Essential
The memory analysis behind the per-GPU formulas, with the communication argument for each stage.
The tensor-parallel layer split that this lesson only names, for models too large for one node.
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.
Keyboard: arrow keys move between options. Space or Enter selects the focused option.