# Checkpointing long training runs so you never lose progress



Learn how to implement robust checkpointing in PyTorch to prevent data loss and optimize costs during long-running GPU jobs on Podstack.



Training · 2026-10-18 · 3 min read



When training large-scale models, the primary threat to your budget and timeline isn't just a loss of accuracy—it's a loss of state. Whether it's an unexpected node failure, a network hiccup, or a preemptible instance reaching its time limit, an uncheckpointed training run can result in hours of wasted compute and hundreds of dollars down the drain.

On a high-performance GPU cloud like Podstack, where resources are billed per second, every moment of lost progress is literal money off the table. Implementing a robust checkpointing strategy ensures that your jobs are resilient, resumeable, and reliable.

## Why Checkpointing Matters in Modern ML

Checkpointing is the process of saving the current state of your model—including weights, optimizer states, and epoch counters—to persistent storage during training. 

In a serverless or job-based environment, this serves two critical functions:
1.  **Fault Tolerance:** If a hardware error occurs, you can restart from the last saved state rather than starting from zero.
2.  **Elasticity:** You can stop a job to switch to a different GPU tier or scale down, then resume seamlessly when resources are available.

## The Anatomy of a Proper Checkpoint

A common mistake is saving only the model weights. To truly resume a training run without a "jump" in the loss curve, you must save the entire state dictionary. This includes:
*   **Model state:** The `state_dict` containing learned weights.
*   **Optimizer state:** Gradients, momentums, and learning rate schedules.
*   **Metadata:** Current epoch, global step, and best loss recorded so far.

## Implementing Checkpoints in PyTorch

Here is a practical pattern for saving and loading checkpoints that integrates easily with Podstack jobs.

```python
import torch
import os

def save_checkpoint(state, filename="checkpoint.pth.tar"):
    """Saves the training state to a file."""
    print(f"=> Saving checkpoint to {filename}")
    torch.save(state, filename)

def load_checkpoint(model, optimizer, filename="checkpoint.pth.tar"):
    """Loads the training state from a file if it exists."""
    if os.path.isfile(filename):
        print(f"=> Loading checkpoint '{filename}'")
        checkpoint = torch.load(filename)
        
        model.load_state_dict(checkpoint['state_dict'])
        optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
        epoch = checkpoint['epoch']
        loss = checkpoint['loss']
        
        print(f"=> Loaded checkpoint (epoch {epoch})")
        return epoch, loss
    else:
        print(f"=> No checkpoint found at '{filename}'")
        return 0, float('inf')

# --- Inside your training loop ---
# 1. Initialize
model = MyModel().to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)

# 2. Check for existing progress
start_epoch, best_loss = load_checkpoint(model, optimizer)

for epoch in range(start_epoch, num_epochs):
    train_one_epoch(model, optimizer)
    
    # 3. Save periodically (e.g., every epoch or 1000 steps)
    checkpoint_data = {
        'epoch': epoch + 1,
        'state_dict': model.state_dict(),
        'optimizer_state_dict': optimizer.state_dict(),
        'loss': current_loss,
    }
    save_checkpoint(checkpoint_data)
```

## Best Practices for Long Runs

### 1. The "Two-File" Strategy
Always maintain a `latest_checkpoint.pth` and a `best_model.pth`. The latest checkpoint allows for resumption, while the best model ensures you don't keep a version that began to overfit or diverge.

### 2. Frequency vs. Overhead
Saving a 5GB model every 60 seconds will throttle your training due to I/O overhead. Aim for a frequency that balances risk: if your job runs for 24 hours, checkpointing every 15–30 minutes is usually the "sweet spot" to minimize data loss without impacting performance.

### 3. Verification
Before starting a long-running job, run a 2-epoch test. Ensure the checkpoint saves, stop the process, restart it, and verify that the loss at the start of epoch 3 matches the end of epoch 2.

## Automating with Podstack

Podstack is designed for high-throughput GPU workflows. When you deploy a job using the Podstack API, your environment is provisioned instantly. To ensure your checkpoints survive between job restarts, you should leverage Podstack’s persistent volumes or remote storage hooks.

When launching a job, you can pass your `PODSTACK_API_KEY` to your environment to allow your script to programmatically interact with Podstack’s storage layer or to trigger alerts if a checkpoint hasn't been updated in a specified window.

Using the API, you can monitor your job’s output to ensure checkpoints are being written successfully:

```text
Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key.
```

If a job is interrupted, Podstack’s per-second billing ensures you only paid for the work done. By simply resubmitting the job, your `load_checkpoint` logic will pull the state from your persistent volume, and you’ll pick up right where the hardware left off.

## Conclusion

Checkpointing isn't just a safety net; it's a fundamental part of the machine learning lifecycle. By implementing a standardized save/load pattern and utilizing Podstack’s robust job infrastructure, you turn potential disasters into minor hiccups. Your models train faster, your costs stay predictable, and your progress is never lost.
