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

> Write shards to a new step prefix, then a checksummed manifest, then a latest pointer. A crash test shows why that order is the commit.

Source: https://www.nodus-compute.ai/blog/save-checkpoints-to-s3-or-gcs/
Build revision: 3fccd4ded8808679191cba88c5898ae387742862

<!-- vale Nodus.Providers = NO -->

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](https://www.nodus-compute.ai/blog/save-and-resume-pytorch-checkpoints/). For how often to save on interruptible machines, see [how to make spot GPU training survive preemption](https://www.nodus-compute.ai/blog/resume-training-after-spot-preemption/).

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

They guarantee one object at a time. The [Amazon S3 consistency model](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html#ConsistencyModel) 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](https://cloud.google.com/storage/docs/consistency) 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](https://docs.aws.amazon.com/AmazonS3/latest/userguide/mpuoverview.html) for objects of 100 MB or more, with 5 MiB to 5 GiB parts and at most 10,000 of them ([limits](https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html)). The object does not exist until `CompleteMultipartUpload` succeeds. Cloud Storage has [resumable uploads](https://cloud.google.com/storage/docs/uploads-downloads) 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.](https://www.nodus-compute.ai/blog-charts/save-checkpoints-to-s3-or-gcs/crash-outcomes.svg) *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](https://docs.aws.amazon.com/AmazonS3/latest/userguide/mpu-abort-incomplete-mpu-lifecycle-config.html), 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.

```python
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
```

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](https://docs.aws.amazon.com/AmazonS3/latest/userguide/conditional-writes.html) 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](https://cloud.google.com/storage/docs/request-preconditions), 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](https://docs.ray.io/en/latest/train/user-guides/checkpoints.html) 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](https://github.com/awslabs/s3-connector-for-pytorch) (`pip install s3torchconnector`) gives `S3Checkpoint` writers that `torch.save` can write into. [PyTorch Lightning](https://lightning.ai/docs/pytorch/stable/common/remote_fs.html) 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`](https://docs.pytorch.org/docs/stable/distributed.checkpoint.html) 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](https://aws.amazon.com/s3/pricing/). [Cloud Storage](https://cloud.google.com/storage/pricing) 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.](https://www.nodus-compute.ai/blog-charts/save-checkpoints-to-s3-or-gcs/storage-cost.svg) *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](https://www.nodus-compute.ai/docs/guides/checkpoints/) 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.

Terminal window

```console
$ nodus run --name checkpoints-resume --cpu 2 --memory 4Gi --checkpoint /nodus/state --max-cost 0.50 -d -- python train.py
```

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](https://www.nodus-compute.ai/pricing/), and [this comparison](https://www.nodus-compute.ai/blog/automatic-checkpointing-and-resume-for-training/) 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](https://aws.amazon.com/s3/pricing/) 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.
