惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Schneier on Security
A
About on SuperTechFans
V
Visual Studio Blog
美团技术团队
雷峰网
雷峰网
J
Java Code Geeks
L
LINUX DO - 最新话题
T
Threatpost
I
Intezer
Simon Willison's Weblog
Simon Willison's Weblog
月光博客
月光博客
博客园 - Franky
The Cloudflare Blog
AWS News Blog
AWS News Blog
T
Tor Project blog
IT之家
IT之家
S
SegmentFault 最新的问题
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园_首页
T
The Exploit Database - CXSecurity.com
L
LINUX DO - 热门话题
S
Securelist
V
V2EX
C
CERT Recently Published Vulnerability Notes
T
Threat Research - Cisco Blogs
Attack and Defense Labs
Attack and Defense Labs
人人都是产品经理
人人都是产品经理
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
量子位
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Cyberwarzone
Cyberwarzone
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
大猫的无限游戏
大猫的无限游戏
T
Tenable Blog
爱范儿
爱范儿
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Hacker News: Ask HN
Hacker News: Ask HN
小众软件
小众软件
Spread Privacy
Spread Privacy
S
Security Affairs
NISL@THU
NISL@THU
Blog — PlanetScale
Blog — PlanetScale
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
MongoDB | Blog
MongoDB | Blog
AI
AI
Cisco Talos Blog
Cisco Talos Blog
N
Netflix TechBlog - Medium
博客园 - 司徒正美

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Never lose a training run again: a checkpoint-and-resume playbook for ephemeral GPUs
Tanay Joshi · 2026-06-23 · via DEV Community

▶ Prefer to play with it? There's an interactive version of this article
where you can break things yourself: https://resumable-ml-training.vercel.app

I train a lot of models on compute that can disappear at any second — free notebooks, pre-emptible instances, whatever I can get. Early on, a single disconnect could wipe out hours of work. So I built a pattern that makes a dropped session cost seconds instead. This is that pattern, written up generically so you can drop it into any training loop.

The 2 a.m. disconnect

If you have ever trained a model on a free GPU, you know the feeling. You kick off a long run, check back later, and the session is gone. The notebook is disconnected, the runtime recycled, and every epoch since the last time you looked has evaporated. You start again from zero.

Free and pre-emptible compute is one of the best deals in machine learning — but it is ephemeral. The machine can vanish at any moment: idle timeouts, usage caps, spot-instance reclamation. Fighting this with keep-alive hacks treats the symptom. The real fix is to make your training resumable and your pipeline idempotent, so an interruption simply doesn't matter.

Here is the pattern I now use for every long run. It rests on five ideas.

1. Checkpoint the whole state — not just the weights

The most common mistake is saving only model.state_dict(). That is not enough to resume training. If you reload only the weights and start a fresh optimizer, you lose:

  • the optimizer state (Adam's moment estimates — momentum and variance),
  • the learning-rate scheduler position (so the LR jumps back to its starting value),
  • the epoch counter (so you re-run epochs you already finished),
  • the best-so-far tracking and early-stopping counter,
  • the RNG state (so the run is no longer reproducible across the break).

A resumable checkpoint captures all of it:

def make_checkpoint(epoch, model, optimizer, scheduler, best, rng):
    return {
        "epochs_done": epoch + 1,
        "model":       model.state_dict(),
        "optimizer":   optimizer.state_dict(),
        "scheduler":   scheduler.state_dict(),
        "best_metric": best,
        "rng": {
            "torch":  torch.get_rng_state(),
            "cuda":   torch.cuda.get_rng_state_all() if torch.cuda.is_available() else None,
            "numpy":  np.random.get_state(),
            "python": random.getstate(),
        },
    }

Save this every epoch. The cost is milliseconds; the payoff is never losing more than one epoch of work.

2. Write atomically — or risk a corrupted checkpoint

Here is a subtle trap: if the machine dies while you are writing the checkpoint, you get a half-written, unreadable file — and now you have lost everything, including the good checkpoint you just overwrote.

The fix is the write-temp-then-rename trick. A rename on the same filesystem is atomic: the checkpoint file is either the complete old version or the complete new version, never a torn mix.

import os

def save_atomic(path, state):
    tmp = path + ".tmp"
    torch.save(state, tmp)
    os.replace(tmp, path)   # atomic on the same filesystem

This one helper has saved me more than once.

3. A "done marker" makes the entire job idempotent

Resuming one run is good. Resuming a sweep of many runs is better. If you train across several configurations, seeds, or datasets, you want to re-launch the whole batch and have it automatically skip everything already finished and resume only the one that was interrupted.

The trick is a done marker: write the final results file (metrics, summary) only when a run fully completes. Then the launcher logic is trivial:

def run_one(run_dir, cfg):
    if (run_dir / "results.json").exists():           # done marker
        print(f"[skip] already complete: {run_dir.name}")
        return load(run_dir / "results.json")
    # ... train (resuming from checkpoint if present) ...
    save_atomic(run_dir / "results.json", results)    # write marker LAST
    (run_dir / "checkpoint.pt").unlink(missing_ok=True)  # done -> drop checkpoint

Now your orchestration loop is fully restartable:

for seed in SEEDS:
    for config in CONFIGS:
        run_one(run_dir_for(seed, config), config)

Re-run it after any disconnect. Finished work is skipped, interrupted work resumes, nothing is ever duplicated. This is the same principle build tools like make use: declare the output, and only do the work if the output is missing.

4. Put the state where it outlives the machine

A checkpoint is only useful if it survives the thing that died. The number-one mistake on ephemeral compute is writing checkpoints to the node's local scratch disk — which is wiped the instant the runtime is recycled. Your checkpoints must live on storage that is external to the compute.

You have two families of options.

Cloud / network storage (best for ephemeral cloud GPUs):

  • A mounted cloud drive (Google Drive, Dropbox, OneDrive, iCloud Drive).
  • An object-store bucket (S3, GCS, R2, Azure Blob) you sync to after each epoch.
  • A network filesystem (NFS/SMB) on a persistent volume.

Local / self-hosted storage (best when you own the machine, or for hybrid setups):

  • An external SSD/HDD, or a second internal disk that is not part of the ephemeral root.
  • A home server or NAS the training box can reach over the LAN.
  • Your laptop: periodically rsync/scp the checkpoint directory back from a remote box, so a copy always exists on hardware you control.

A clean trick that works in both worlds: keep your code on the fast local disk but symlink the checkpoint/output directory to persistent storage. You get local-disk speed for reads and durable state for writes.

# code stays on fast local disk; outputs live on durable storage
ln -s /mnt/persistent/my_project/outputs  ./outputs

The principle is storage-agnostic: the checkpoint must outlive the compute node. Cloud bucket, mounted drive, NAS, or an external SSD on your desk — any of them works, as long as it is not the disk that gets wiped.

5. Resume means continue, not restart

With state saved durably, the training loop just checks for a checkpoint on startup and continues:

start_epoch = 0
if checkpoint_path.exists():
    ck = torch.load(checkpoint_path, map_location=device, weights_only=False)
    model.load_state_dict(ck["model"])
    optimizer.load_state_dict(ck["optimizer"])
    scheduler.load_state_dict(ck["scheduler"])
    best_metric = ck["best_metric"]
    start_epoch = ck["epochs_done"]
    restore_rng(ck["rng"])
    print(f"[resume] continuing from epoch {start_epoch + 1}")

for epoch in range(start_epoch, num_epochs):   # note: start_epoch, not 0
    train_one_epoch(...)
    save_atomic(checkpoint_path, make_checkpoint(epoch, ...))

A good smoke test: start a run, kill it mid-training, restart it, and confirm the log shows [resume] continuing from epoch N — with the learning rate picking up smoothly where it left off, not jumping back to its initial value. If the LR is continuous, your optimizer and scheduler state survived correctly.

Gotchas I hit (so you don't have to)

  • The weights_only pickle trap. Recent PyTorch (2.6+) defaults torch.load(..., weights_only=True), which refuses to load checkpoints containing non-tensor objects — like the NumPy/Python RNG state above. For your own trusted checkpoint files, pass weights_only=False. (Never do this for files from untrusted sources — it runs arbitrary pickle code.)
  • Append your logs, don't truncate. On resume, open the log file in append mode so you keep the full history across restarts instead of overwriting it.
  • Mind early-stopping state. If you track "epochs since last improvement," checkpoint that counter too — otherwise a resume silently resets your patience.
  • Setup cells will re-run, and that's fine. When a runtime is recycled, the interpreter's memory is gone — you cannot avoid re-importing libraries or re-mounting storage. Make those steps cheap and idempotent (mount only if not mounted; install only if missing; cache any preprocessed data to durable storage). The goal is not to skip setup; it is to make the expensive work resumable.

The payoff

Once this is in place, the disconnect stops being a disaster and becomes a shrug. You reconnect, re-run the cheap setup, hit "go," and watch it print [resume] continuing from epoch …. No lost epochs. No duplicate runs. No keep-alive browser hacks.

A quick checklist to make any training job bulletproof:

  • [ ] Checkpoint model + optimizer + scheduler + epoch + RNG, every epoch
  • [ ] Write checkpoints atomically (temp file → rename)
  • [ ] Write a done marker only on full completion; skip finished runs
  • [ ] Store state on something that outlives the compute node (cloud or local)
  • [ ] On startup, resume from the saved epoch, not from zero
  • [ ] Test it: interrupt, restart, confirm a clean resume

Ephemeral compute is one of the best deals in machine learning. With a resumable, idempotent pipeline, you get all of its upside and almost none of its fragility.


Found this useful?

I write about the unglamorous engineering that makes ML actually ship.

If this saved you a training run, a ⭐ on the repo or a follow means a lot.