Single logo
  • Courses
  • Blog
  • About
Join for freeJoin free
Learning pathDeep Learning for Production: Transformers, Fine-Tuning and Serving
  1. 1
    Dropout, Early Stopping and Batch Norm: Judge Each One by the Validation Curve
  2. 2
    Transfer Learning on Images: A Frozen ResNet-18, a Small Head and an Honest Baseline
  3. 3
    Attention Explained Without the Maths: Query, Key, Value and the Word "it"
  4. 4
    Transformer Building Blocks in PyTorch: Follow the Shapes Through Attention and a Block
  5. 5
    Pretrained Models from Hugging Face: A Sentiment Pipeline and Sentence Embeddings on a CPU
  6. 6
    Loading a Language Model and Running Inference: Download, Load, Tokenize, Generate
  7. 7
    Model Size and Memory: Parameters x Bytes, Quantization, and Where to Run a Model
  8. 8
    Training on a GPU: Mixed Precision, Gradient Accumulation and Checkpoints That Really Resume
  9. 9
    When NOT to Fine-Tune: A Decision Tree of Prompt, RAG, Tools, Then Fine-Tuning
  10. 10
    Full Fine-Tuning vs LoRA vs QLoRA: What Each One Changes and What It Costs
  11. 11
    LoRA Fine-Tune of a Tiny Model: Teach SmolLM2-135M Your House Style on a CPU
  12. 12
    Knowledge Distillation: Teach a Model 100 Times Smaller From a Teacher's Soft Labels
  13. 13
    Serving Open Models: Continuous Batching, vLLM and Cold Starts
  1. Blog
  2. /
  3. Machine Learning
  4. /
  5. Deep Learning

Learning path: Deep Learning for Production: Transformers, Fine-Tuning and Serving · Step 8 of 13

Training on a GPU: Mixed Precision, Gradient Accumulation and Checkpoints That Really Resume

Make long training runs faster and safer: measured CPU vs GPU vs 16-bit step times on an RTX 4070 Laptop GPU, gradient accumulation that trades time for memory, and a checkpoint that resumes a crashed run to a max weight difference of zero, plus the silent resume that doesn't.

Chaand Sheikh

·27 November 2026Deep Learning

What you will learn

  • Move training to a GPU and read measured step times for CPU, GPU and 16-bit
  • Explain mixed precision (autocast and GradScaler) and gradient accumulation at a high level
  • Save a checkpoint with weights, optimizer state, random state and step
  • Resume a crashed run and prove it matches by comparing weights

Before you start

  • The Same Network in PyTorch
  • Loading a Language Model and Running Inference

Think about a long video game. You've played for two hours and you reach the boss. You lose, and with no save you're back at the very beginning. So you save before the fight, and losing only costs you the last few minutes. A good save holds more than your position: your health, your items, the level you're on.

Training is the same. A checkpoint is your save, and it needs more than just the model. This article makes long runs faster (GPU, mixed precision, gradient accumulation) and safer (checkpoints), and shows the one small mistake that gives you no error at all, only a different model.

The project

We fine-tune SmolLM2-135M-Instruct on 50 support questions, each with a short reply signed "Team Kestrel". Only a small set of added weights trains (a LoRA adapter; see LoRA Fine-Tune of a Tiny Model for how that works), in batches of 5, for 40 steps:

trainable 921,600 of 135,436,608

On a CPU the full 40 steps took 72.5 seconds.

Result first: two resumes, no errors

At step 25 the run stops. That's a crash we added on purpose (--stop-at 25), with exit code 1. The last save was at step 20, so steps 21 to 25 are lost.

  • Resume A picks up from step 20 and finishes at a final loss of 1.897, the same as a run that never crashed. Comparing every weight, the biggest difference is zero.
  • Resume B leaves out one thing. It also resumes, also finishes, exit code 0. Final loss 1.868.

Both look fine. The second one is a different model. We'll see why after the speed tools.

Speed: GPU and mixed precision

These numbers were measured on an NVIDIA RTX 4070 Laptop GPU with 8 GB, on the same model and data: 23 training steps each (3 warm-up, 20 timed), median of three runs.

A GPU does many small sums at once, and that's what training is. You move the model and each batch to the device:

m.to(dev)
ids, mask, lab = (x.to(dev) for x in batch)

Mixed precision is the next step. Many of those sums don't need 32 bits, so they run in 16. torch.autocast picks which ones, and a GradScaler stops tiny gradients from rounding down to zero. These lines are taken from the script that timed the GPU runs, trimmed to the training step:

scaler = torch.amp.GradScaler('cuda')

with torch.autocast('cuda', dtype=torch.float16):
    loss = m(input_ids=ids, labels=lab, attention_mask=mask).loss
scaler.scale(loss).backward()
scaler.step(opt)
scaler.update()
opt.zero_grad()
Milliseconds per training step on CPU and GPU CPU fp32 1,784.5 ms GPU fp32 384.9 ms GPU fp16 (autocast) 451.4 ms RTX 4070 Laptop GPU, measured, median of 3 runs. Final loss 2.427 for all three.
Median milliseconds per training step, measured on this model and data. The GPU was several times faster than the CPU. 16-bit was slower than 32-bit here.
Runms per stepPeak GPU memoryFinal loss
CPU fp321,784.5n/a2.427
GPU fp32384.91,222 MB2.427
GPU fp16 autocast + GradScaler451.41,285 MB2.427

So what did 16 bits give us? Nothing here. 451 ms a step, slower than 385 at 32 bits, and a little more peak memory. All three ended at the same loss, 2.427. Our model is small, so launch overhead matters: the GPU spends much of its time waiting to be told what to do next. While it ran, nvidia-smi showed the GPU at most 75% busy. Mixed precision is built for bigger models, so time it on yours.

Gradient accumulation: a big batch in small pieces

What if you want 20 examples per step and only 5 fit on your GPU? Run a batch of 5, compute the loss, call backward, and don't step yet. The gradients pile up. Do that four times, then take one optimizer step with all four batches behind it. Dividing each loss by 4 keeps the scale right:

(loss / 4).backward()
if (step + 1) % 4 == 0:
    opt.step()
    opt.zero_grad()

Measured on the same GPU, model and data:

20 examples per step asFirst-step lossms per stepPeak GPU memory
One batch of 204.617394.92,851 MB
4 batches of 5, accumulated4.6271,467.31,131 MB

Close losses, not identical. You pay with time instead of memory: peak memory fell by more than half, and each step took almost four times as long.

save_ckpt: what a save holds

Back to the CPU run with the crash. Here's the save function from train.py:

def save_ckpt(model, opt, step, path):
    path.mkdir(parents=True, exist_ok=True)
    model.save_pretrained(path)
    state = {"step": step, "opt": opt.state_dict(),
             "rng": torch.get_rng_state()}
    torch.save(state, path / "state.pt")
  • model.save_pretrained writes the trained weights: adapter_model.safetensors, 3.72 MB.
  • state.pt holds the step number,
  • the optimizer's state dict. AdamW keeps running averages for every weight it trains, a memory of how each weight has been moving. That's why state.pt is 7.54 MB, about twice the weights,
  • and the random number state, so the dice roll the same way after a resume.

In the loop it runs every 10 steps (STEPS, EVERY, LR = 40, 10, 5e-4), so there are saves at 10 and 20 before the crash. The batches are picked by step number, so a resumed run sees exactly the batches it would have seen.

load_ckpt: pick up the game

def load_ckpt(make_base, path, keep_opt=True):
    base = make_base()
    model = load_adapter(base, path, trainable=True)
    opt = make_opt(model)
    state = torch.load(path / "state.pt",
                       weights_only=False)
    if keep_opt:
        opt.load_state_dict(state["opt"])
    torch.set_rng_state(state["rng"])
    return model, opt, state["step"]

Load the base model, then the trained weights with trainable=True. load_state_dict puts the optimizer's averages back. set_rng_state puts the dice back, and the step counter jumps to 20.

python train.py --out runs/a --stop-at 25
python train.py --out runs/a --resume
step 20  loss 2.653
saved checkpoint at step 20
step 25  loss 2.398
crashed at step 25
resumed from step 20
step 25  loss 2.398
step 30  loss 2.042
saved checkpoint at step 30
step 35  loss 2.033
step 40  loss 1.897
saved checkpoint at step 40
final loss 1.897

Step 25 shows 2.398 again, the very number we saw before the crash, and it goes on to 1.897. Now compare.py checks every weight against the run that never crashed:

from safetensors.torch import load_file


def max_diff(path_a, path_b):
    a = load_file(path_a + "/adapter_model.safetensors")
    b = load_file(path_b + "/adapter_model.safetensors")
    gaps = [(a[k] - b[k]).abs().max().item() for k in a]
    return max(gaps)
max weight difference: 0.00e+00

Zero. That isn't a similar model, it's the same model.

Same spot, zero speed

Now resume B, with --no-optimizer. The opt.load_state_dict line is skipped. The weights come back and nothing complains. It's like saving your position but not your speed: you're in the same spot, starting from a standstill.

python train.py --out runs/b --resume --no-optimizer
resumed from step 20
step 25  loss 2.380
step 30  loss 1.999
saved checkpoint at step 30
step 35  loss 2.025
step 40  loss 1.868
saved checkpoint at step 40
final loss 1.868
Loss per step: straight run, resumed run, and resume without optimizer state 0 1 2 3 4 5 1 10 20 25 30 40 step loss checkpoint at 20 1.868 1.897 straight and resumed (same) resumed without optimizer
Loss per step. The straight run and resume A are identical at every step. Resume B (no optimizer state) matches at step 21, 2.514, splits at step 22 (2.403 vs 2.409) and ends at 1.868. Drawn from the run's loss logs.

It finishes at 1.868, which is lower. So is it better? We can't say. Each loss is just one batch of 5, and the straight run itself jumped from 1.418 at step 38 to 1.897 at step 40. What we did measure is the weights:

max weight difference: 1.16e-02

A different model, with exit code 0. Later on, you couldn't tell whether your code change moved the result or your resume did. Compare the weights, don't trust the loss.

Common mistakes

  • Saving only the model. Without optimizer state, random state and step, the resume runs but trains a different model.
  • Trusting a lower loss after a resume. One-batch losses jump around; compare weights against a straight run.
  • Assuming 16-bit is always faster. On this small model it was 451 ms vs 385 ms per step. Measure on yours.
  • Accumulating without dividing the loss. Four un-divided backward passes give gradients four times too big.
  • Forgetting to move the batch to the GPU. The model and every batch must be on the same device.

Quick recap

ToolWhat it givesMeasured here
GPUMany sums at once385 ms vs 1,784.5 ms per step on CPU
Mixed precision16-bit sums with autocast and GradScalerNot faster on this small model (451 ms)
Gradient accumulationA big batch in small piecesPeak 1,131 MB vs 2,851 MB, at 1,467 ms vs 395 ms
CheckpointWeights, optimizer state, RNG state, stepResume: max weight difference 0
Missing optimizer stateNo error, different modelMax weight difference 1.16e-02

Try it yourself

In train.py, change EVERY from 10 to 5, crash at step 25 again, and resume. Which step does it pick up from, and does compare.py still print zero?

Built this? Share your solution in the StudyEasy AI Community.

Join free on Skool →
← Previous
Model Size and Memory: Parameters x Bytes, Quantization, and Where to Run a Model
Next →
When NOT to Fine-Tune: A Decision Tree of Prompt, RAG, Tools, Then Fine-Tuning
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Related articles
Why Neural Networks: Pixels, One Neuron and Layers

Why pictures need neural networks: a handwritten digit is 784 numbers, one neuron is a weighted sum plus a bias and one small rule, and neurons stack into layers. Worked out on MNIST with NumPy.

The Forward Pass and Activation Functions: ReLU, Sigmoid, Tanh and Softmax

Follow numbers through a tiny 3-2-3 network in NumPy: one matrix product per layer, ReLU inside, softmax at the end, and a count of every weight and bias.

Loss and Backpropagation: How Wrong, and Who Is to Blame

The loss says how wrong the network was; backpropagation says how much each weight is to blame. MSE and cross-entropy, the chain rule by hand on a two-weight chain, then the same gradients from PyTorch autograd.

The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers

How training is organised: shuffle, cut into mini-batches, take one step per batch, repeat per epoch. Real MNIST runs compare three learning rates, SGD against Adam, and show the overfitting signal in the validation loss.

On this page
  • The project
  • Result first: two resumes, no errors
  • Speed: GPU and mixed precision
  • Gradient accumulation: a big batch in small pieces
  • save_ckpt: what a save holds
  • load_ckpt: pick up the game
  • Same spot, zero speed
  • Common mistakes
  • Quick recap
  • Try it yourself
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool
Go deeper with a course

Machine Learning Engineer: From First Model to ML Engineer

Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.