Guides & Tutorials4 min read

Checkpoint Your Training So a Spot GPU Can't Cost You Work

A spot GPU can be reclaimed with two minutes' notice and its disk is wiped when the rental ends. Here's a PyTorch training loop that checkpoints off the machine and reacts to the notice, so a reclaim costs minutes, not the run.

A training curve resuming from a checkpoint after an interruption

A spot GPU is cheaper because its owner can take it back. On ParalonCloud that comes with two minutes' notice. Two facts decide how you write a training job for it:

  1. The rental can end before your job does.
  2. The disk is wiped when the rental ends. A checkpoint saved only to the machine's disk is lost with it.

So a spot-proof job does two things: it saves state off the machine on a regular schedule, and it resumes from the latest save when it starts. Reacting to the two-minute notice is a bonus on top, not the plan.

1. Save everything you need to resume

A checkpoint has to restore the exact point of training, not just the weights:

import torch

def save_checkpoint(path, model, optimizer, scheduler, step, epoch):
    torch.save({
        "model": model.state_dict(),
        "optimizer": optimizer.state_dict(),
        "scheduler": scheduler.state_dict() if scheduler else None,
        "step": step,
        "epoch": epoch,
        "rng": {
            "torch": torch.get_rng_state(),
            "cuda": torch.cuda.get_rng_state_all(),
        },
    }, path)

def load_checkpoint(path, model, optimizer, scheduler):
    ckpt = torch.load(path, map_location="cuda", weights_only=False)
    model.load_state_dict(ckpt["model"])
    optimizer.load_state_dict(ckpt["optimizer"])
    if scheduler and ckpt["scheduler"]:
        scheduler.load_state_dict(ckpt["scheduler"])
    torch.set_rng_state(ckpt["rng"]["torch"])
    torch.cuda.set_rng_state_all(ckpt["rng"]["cuda"])
    return ckpt["step"], ckpt["epoch"]

Write to a temporary file and rename it, so a save interrupted halfway never replaces a good checkpoint with a broken one.

2. Get it off the machine

Any storage outside the rental works: an S3-compatible bucket, the Hugging Face Hub, your own server. With an S3-compatible bucket:

import os, boto3

s3 = boto3.client("s3", endpoint_url=os.environ.get("S3_ENDPOINT"))
BUCKET, KEY = os.environ["CKPT_BUCKET"], os.environ["CKPT_KEY"]  # e.g. "runs/llm-ft/latest.pt"

def upload(local_path):
    s3.upload_file(local_path, BUCKET, KEY)

def download(local_path):
    try:
        s3.download_file(BUCKET, KEY, local_path)
        return True
    except s3.exceptions.ClientError:
        return False

Upload time is the real limit on how often you save. A checkpoint that takes longer to upload than the notice period can only be saved on a schedule, never at the last moment.

3. The training loop: resume, save on a schedule

import os, time

LOCAL = "/tmp/ckpt.pt"
SAVE_EVERY_S = 10 * 60   # how much work you're willing to redo after a reclaim

step, epoch = 0, 0
if download(LOCAL):
    step, epoch = load_checkpoint(LOCAL, model, optimizer, scheduler)
    print(f"resumed at step {step}, epoch {epoch}")

last_save = time.time()

def checkpoint_now():
    save_checkpoint(LOCAL + ".tmp", model, optimizer, scheduler, step, epoch)
    os.replace(LOCAL + ".tmp", LOCAL)
    upload(LOCAL)

for epoch in range(epoch, num_epochs):
    for batch in train_loader_from(step):   # skip batches already seen this epoch
        loss = train_step(model, optimizer, batch)
        scheduler.step()
        step += 1
        if time.time() - last_save > SAVE_EVERY_S or reclaim_requested():
            checkpoint_now()
            last_save = time.time()
            if reclaim_requested():
                raise SystemExit("reclaimed: checkpoint saved, exiting")

train_loader_from(step) stands for whatever your data pipeline needs to skip ahead: a sampler seeded per epoch and an offset, or a dataset you can index into. Resuming at the right batch matters as much as restoring the weights.

4. React to the two-minute notice

When a spot machine is reclaimed, the Rental API sets reclaim_at on your rental. A background thread can watch for it and flip a flag the loop checks:

import os, threading, time, requests

RENTAL_ID = os.environ["PARALON_RENTAL_ID"]   # rental_id from POST /rentals, or from GET /api/v1/rentals
API_KEY = os.environ["PARALON_API_KEY"]      # a key with the rental scope
_reclaim = threading.Event()

def _watch():
    url = f"https://paraloncloud.com/api/v1/rentals/{RENTAL_ID}"
    headers = {"Authorization": f"Bearer {API_KEY}"}
    while not _reclaim.is_set():
        try:
            r = requests.get(url, headers=headers, timeout=10)
            if r.ok and r.json().get("reclaim_at"):
                _reclaim.set()
        except requests.RequestException:
            pass
        time.sleep(15)

threading.Thread(target=_watch, daemon=True).start()

def reclaim_requested():
    return _reclaim.is_set()

Keep the API key in an environment variable, never in the notebook, and use a key that only has the rental scope.

Poll often enough that the notice leaves time to save and upload. If your checkpoint takes longer than that to write, rely on the schedule in step 3 and treat the notice as a chance to stop cleanly.

5. Resuming on another GPU

When a rental is reclaimed, start a new one (spot or on-demand) and run the same script. It downloads the latest checkpoint and carries on. Two things make that painless:

  • Pin your environment. Install from a requirements file with exact versions, so the new machine runs the same code.
  • Don't assume the same card. A different GPU may need a different batch size to fit; keep the effective batch size the same with gradient accumulation if it matters to your results.

Is spot worth it for your run?

If a reclaim costs you at most one save interval of work plus the time to start a new rental, and that's a fair trade for the discount, use spot. If the run can't checkpoint, rent on-demand.

Next

On the network

A GPU with JupyterLab on it, in about a minute

Billed for the minutes it runs, on a machine we benchmarked before listing it. Or call open models through an OpenAI-compatible API.

Keep reading

Related articles