DEV Community

Viswaretas Kotra
Viswaretas Kotra

Posted on Originally published at nodus-compute.ai

How do you save training checkpoints to S3 or GCS safely?

Amazon S3 and Google Cloud Storage make each upload atomic but not a checkpoint made of several files, so save safely by uploading the files under a new step prefix, then a manifest of their sizes and SHA-256 hashes, then a latest pointer last. Resume by following the pointer and verifying the hashes; on Nodus, a Job writes to /nodus/state and Nodus stores, commits and restores the checkpoint for you. In our crash test, that order resumed a verified checkpoint at all 9 crash points, while overwriting fixed keys silently paired a new model with an old optimizer at 5 of 7.

This post is about the storage layer: getting the bytes into a bucket and finding the last good checkpoint after a crash. For what goes inside the checkpoint (model, optimizer, scheduler, RNG, data position), see how to save and resume PyTorch checkpoints. For how often to save on interruptible machines, see how to make spot GPU training survive preemption.

What do S3 and GCS guarantee when you upload a checkpoint?

They guarantee one object at a time. The Amazon S3 consistency model says updates to a single key are atomic and reads after a PUT or DELETE are strongly consistent. The same page says "there is no way to make atomic updates across keys." Cloud Storage says an interrupted upload leaves no partial data, and the object only appears once the whole upload succeeds.

So a reader never sees half of optim.pt, but it can see a new model.pt next to an old optim.pt, or a step folder with a file missing. Checkpoints are almost always several files, and sharded runs write at least one per rank.

AWS recommends multipart upload for objects of 100 MB or more, with 5 MiB to 5 GiB parts and at most 10,000 of them (limits). The object does not exist until CompleteMultipartUpload succeeds. Cloud Storage has resumable uploads for objects up to 5 TiB.

What happens if the job dies halfway through an upload?

We tested it. A Python script saves a checkpoint for step 100 to a bucket, then starts saving step 200 and crashes right before each S3 write in turn. After every crash it runs that strategy's resume code and checks whether the loaded tensors exactly match a real saved step. Each checkpoint has a small model.pt (one PUT) and an 11.4 MiB optim.pt sent as a three-part multipart upload.

We ran it on CPU against moto 5.2.6, an in-process S3 emulator, with boto3 1.44.12 and PyTorch 2.15. No real bucket was involved, and we did not run the GCS side, which has the same single-object guarantee.

Strategy Crash points Resumed step 200 Resumed step 100 Resume crashed Loaded mixed state
Overwrite the same two keys 7 1 1 0 5
Pick the highest step prefix 7 1 1 5 0
Update latest first, then shards 8 1 1 6 0
Shards, manifest, latest last 9 1 8 0 0

Overwriting fixed keys is the dangerous one: at 5 of 7 crash points it loaded a step-200 model with a step-100 optimizer and raised no error. Picking the newest folder and writing the pointer first both fail loudly with NoSuchKey, which stops the run but leaves you hand-editing a bucket. The manifest-then-pointer order resumed a verified checkpoint at all 9 of its crash points.

Crash test results: overwriting the same keys loaded mixed state at 5 of 7 crash points; highest-prefix and pointer-first resume crashed at 5 of 7 and 6 of 8; manifest then pointer last resumed a verified checkpoint at all 9.
Only the write order with the pointer last never needed a human after a crash.

Every crash inside the multipart upload also left one incomplete upload behind. It is invisible to a normal listing and, per the AWS lifecycle docs, keeps costing storage until it is aborted.

What does the safe write order look like in code?

This is the save and resume logic from our test, unchanged apart from comments. put() sends a single PUT for small files and a multipart upload above 5 MiB.

def save_safe(s3, step, state):
    manifest = {"step": step, "files": {}}
    for name, obj in state.items():
        data = to_bytes(obj)                       # torch.save into memory
        put(s3, step_prefix(step) + name, data)    # e.g. run1/step-00000200/optim.pt
        manifest["files"][name] = {"bytes": len(data), "sha256": hashlib.sha256(data).hexdigest()}
    # IfNoneMatch="*": never overwrite a manifest another writer already committed
    s3.put_object(Bucket=BUCKET, Key=step_prefix(step) + "manifest.json",
                  Body=json.dumps(manifest).encode(), IfNoneMatch="*")
    s3.put_object(Bucket=BUCKET, Key=f"{PREFIX}/latest", Body=str(step).encode())


def load_verified(s3, step):
    m = json.loads(s3.get_object(Bucket=BUCKET, Key=step_prefix(step) + "manifest.json")["Body"].read())
    out = {}
    for name, meta in m["files"].items():
        body = s3.get_object(Bucket=BUCKET, Key=step_prefix(step) + name)["Body"].read()
        if len(body) != meta["bytes"] or hashlib.sha256(body).hexdigest() != meta["sha256"]:
            raise ValueError(f"{name} failed verification")
        out[name] = torch.load(io.BytesIO(body), weights_only=True)
    return out


def resume_safe(s3):
    try:
        step = int(s3.get_object(Bucket=BUCKET, Key=f"{PREFIX}/latest")["Body"].read())
        return step, load_verified(s3, step)
    except (s3.exceptions.NoSuchKey, ValueError):
        pass
    # fallback: newest step whose manifest exists and verifies
    keys = [o["Key"] for o in s3.list_objects_v2(Bucket=BUCKET, Prefix=PREFIX + "/").get("Contents", [])]
    for step in sorted({int(k.split("step-")[1][:8]) for k in keys if k.endswith("manifest.json")}, reverse=True):
        try:
            return step, load_verified(s3, step)
        except Exception:
            continue
    return None, None
Enter fullscreen mode Exit fullscreen mode

The manifest is the commit marker and the pointer is a shortcut to it. A step folder without a manifest is garbage by definition, so cleanup can delete it. The fallback scan matters when retention deleted the step the pointer names, or a file fails its checksum.

A machine you thought was dead can come back and write too. S3 conditional writes with If-None-Match refuse to create a key that already exists; in our test the second manifest PUT came back PreconditionFailed. On Cloud Storage the equivalent is the ifGenerationMatch=0 precondition, which only proceeds if no live object has that name.

Should you write to local disk first or stream straight to the bucket?

Write to local disk first when it fits. Training resumes as soon as the local write finishes, and a failed upload can be retried from the file. Ray Train works this way: report() copies a local checkpoint directory to storage_path, synchronously by default or with an async upload mode.

Stream directly when local disk is small or the checkpoint is huge. The S3 Connector for PyTorch (pip install s3torchconnector) gives S3Checkpoint writers that torch.save can write into. PyTorch Lightning accepts s3:// paths for default_root_dir and ckpt_path through fsspec.

Either way, the pointer rule still holds. With async uploads, update latest only after the upload has finished, not when the local copy is done. PyTorch's async_save makes that explicit: it returns a staging_completion future for the local copy and an upload_completion future for the saved checkpoint.

How do sharded multi-GPU runs fit in?

Use torch.distributed.checkpoint (DCP) and let each rank write its own shards. The S3 connector ships S3StorageWriter and S3StorageReader for DCP (pip install s3torchconnector[dcp]). In the PyTorch 2.15 source we read, DCP's file system writer writes the .metadata file in its final step, after the shard files, so a DCP folder without .metadata is unfinished. Treat it like the manifest above, and write your own latest pointer once DCP.save has returned on every rank.

How much does keeping checkpoints in S3 or GCS cost?

Less than people fear if you delete old ones, a lot if you don't. A full mixed-precision checkpoint with the Adam optimizer is about 14 bytes per parameter: 2 for bf16 weights, 4 for fp32 master weights and 8 for Adam's two moments. That makes a 7B model about 98 GB and a 70B model about 980 GB per checkpoint.

We priced S3 Standard at its first-tier $0.023 per GB-month. Cloud Storage lists Standard storage in Iowa (us-central1) at $0.000027397 per GiB-hour, which is $0.020 per GiB-month over 730 hours. As a worked line, 294 GB is 273.8 GiB, and 273.8 x $0.020 is $5.48.

What you keep for a month Stored S3 Standard GCS Standard (us-central1)
7B, last 3 checkpoints 294 GB $6.76 $5.48
70B, last 3 checkpoints 2,940 GB $67.62 $54.76
70B, last 10 checkpoints 9,800 GB $225.40 $182.54
7B, hourly for 7 days, nothing deleted 16,464 GB $378.67 $306.67

Prices checked November 26, 2026. Storage only; request and network charges are extra and listed on the same pages.

Monthly storage cost: 7B keeping 3 checkpoints costs $6.76 on S3 and $5.48 on GCS; 70B keeping 3 costs $67.62 and $54.76; 70B keeping 10 costs $225.40 and $182.54; 7B hourly for 7 days costs $378.67 and $306.67.
A week of undeleted hourly 7B checkpoints costs more to store than keeping the last three of a 70B run.

Keep rolling checkpoints in the Standard class. S3 Standard-IA bills a 30-day minimum, and Cloud Storage Nearline has a 30-day minimum storage duration, so a checkpoint you delete after a day is billed as if kept a month. Add an AbortIncompleteMultipartUpload lifecycle rule too, because every crashed upload in our test left parts behind.

Which approach should you use?

The rule we use, from the test above and the providers' own docs:

  1. Single process and files under a few GB: torch.save to local disk, upload each file under a new step prefix, then the manifest, then latest.
  2. Any file of 100 MB or more: multipart upload on S3, resumable upload on GCS, plus a lifecycle rule that aborts incomplete uploads.
  3. Sharded across GPUs: DCP with a storage writer, treating .metadata as the commit and writing latest after DCP.save returns everywhere.
  4. Always: verify sizes and checksums before loading, keep the last two or three plus any milestones, and delete old steps only after a newer latest is committed.

How does Nodus handle checkpoint storage?

On Nodus you skip the bucket protocol for recovery state. A Job writes what it needs under /nodus/state (also NODUS_STATE_DIR). The checkpoints guide says "Nodus decides when to checkpoint and where to store it." Your program should still write a temporary file and rename it, so a checkpoint never captures a half-written file.

$ nodus run --name checkpoints-resume --cpu 2 --memory 4Gi --checkpoint /nodus/state --max-cost 0.50 -d -- python train.py
Enter fullscreen mode Exit fullscreen mode

Several of the guarantees above are built in. A program can subscribe to a checkpoint request and acknowledge it once its files are complete, the same job our manifest does. An empty state directory never replaces an earlier checkpoint that had files in it. Per the recovery docs, Nodus accepts checkpoints only from the current attempt's epoch, so a machine that comes back after being replaced cannot overwrite its successor's work.

Multi-node Jobs (Beta) use recovery.checkpoint.format: Dcp, and Nodus publishes the collective checkpoint only after its metadata is durable. The default maxSize is 1Ti, and after a Job finishes only the final checkpoint is kept once retainAfterFinish (seven days by default) passes. Downloadable results go to /nodus/outputs, and nodus cp checks each file's SHA-256 before writing it.

GPU rates are on the pricing page, and this comparison covers which other platforms checkpoint for you.

FAQ

Does Nodus copy my checkpoints into my own S3 bucket?

The checkpoints guide says Nodus chooses where checkpoints are stored, and S3 Connections are documented for Job inputs and Volume imports. If you also want an archive in your own bucket, upload from your code with the manifest-then-pointer order above.

Can I just rename a temporary key to the final key, like on a local disk?

Not in one step. The S3 pricing page lists S3 Express One Zone as the only storage class with the RenameObject API, so elsewhere a rename is a copy plus a delete. The manifest-last pattern gives you the same safety without needing rename.

Do I need my own checksums if S3 already checks uploads?

The upload checksum proves the bytes that arrived match the bytes sent. Your manifest proves the files on resume are the exact set from one completed save, which also catches a file overwritten by another run or a missing shard.

What should I keep forever?

Usually the final checkpoint and a few milestones you might branch from, such as the end of each training phase. Everything else is recovery state, and keeping the last two or three covers a bad save plus one fallback.

Originally published on the Nodus blog.

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

The crash-test table is the part that makes this post worth bookmarking. Overwriting the same two keys loading a step-200 model with a step-100 optimizer at 5 of 7 crash points is exactly the silent-corruption failure that never shows up in happy-path testing — the run resumes, the loss looks plausible, and you've quietly wasted a training budget. And the highest-step-prefix strategy failing differently (5 of 7 resume crashes on NoSuchKey) is a useful reminder that a failure you can see beats a failure you can't. The one detail I'd add from experience with the same pattern: the manifest-as-commit-marker only holds if the reader verifies it — a step folder with a manifest but a truncated shard is still a trap if resume trusts the manifest alone, which is why the hash check before load matters as much as the write order. One question: in the DCP case, you write your own latest pointer after DCP.save returns on every rank — how do you handle a rank that returns successfully but whose shards are still being flushed asynchronously, or does DCP.save guarantee durability on return?