Skip to content

Checkpointing a Deterministic Forecast

Basic inference workflow checkpointing.

This example shows how to use earth2studio.utils.checkpoint.Checkpoint to restart a deterministic forecast after it stops partway through a run. See the checkpointing user guide for more information on checkpoint catalogs and restart policies.

The example uses earth2studio.data.Random and earth2studio.models.px.FCN, the FourCastNet AFNO prognostic model.

In this example you will learn:

  • Creating a persistent checkpoint
  • Running a forecast that stops before the requested final horizon
  • Re-opening the IO backend and checkpoint
  • Resuming the deterministic workflow from the latest completed lead time

Set Up

A restartable forecast needs two persistent locations: one for forecast fields and one for the checkpoint. The IO backend owns the forecast arrays. The checkpoint owns restart metadata plus any model state required to continue the rollout. Model weights and forecast fields are not copied into the checkpoint.

Warning

Model checkpoint state is opt-in. Before relying on restartable inference, verify that the model you plan to use documents checkpoint support. If a model does not support checkpointing yet, open a feature request on the Earth2Studio GitHub.

import os
import shutil
from collections import OrderedDict
from pathlib import Path

import numpy as np
import torch

import earth2studio.run as run
from earth2studio.data import Random
from earth2studio.io import ZarrBackend
from earth2studio.io.utils import output_template
from earth2studio.models.px import FCN
from earth2studio.utils.checkpoint import Checkpoint
from earth2studio.utils.time import to_time_array

os.makedirs("outputs", exist_ok=True)

forecast_store = Path("outputs/04_checkpoint_restart.zarr")
checkpoint_store = Path("outputs/04_checkpoint_restart_checkpoint")

# Clean up any left over checkpoints
for path in (forecast_store, checkpoint_store):
    if path.exists():
        shutil.rmtree(path)

Load the packaged FCN/AFNO forecast model package. The default package points at the FourCastNet model artifacts. Instantiate FCN inside checkpoint contexts so its restart state binds to the active checkpoint session.

Rollout checkpoint state can be staged on the same device used for inference. Setting device to the current CUDA device can reduce CPU/GPU transfers for restart tensors during a run. Set it to torch.device("cpu") for CPU-only development. Since FCN level 2 checkpoints store the complete autoregressive state, keep history_size small when using mode="append".

compute_device = torch.device(
    f"cuda:{torch.cuda.current_device()}" if torch.cuda.is_available() else "cpu"
)

model_package = FCN.load_default_package()

output_variables = np.array(["t2m", "u10m"])
time = ["2024-01-01T00:00:00"]
final_nsteps = 3
first_attempt_nsteps = 1

Preallocate the full output store. A real full-length deterministic run does this before the first model step. We do it explicitly here because this example simulates a mid-run stop by intentionally running only the first forecast step. The IO store writes only two variables, while the checkpoint keeps FCN's complete restart state internally when level=2 is used.

def deterministic_template(model, time, nsteps, variables):
    """Concrete IO template for an entire roll out

    The model's output signature declares one forecast step and leads with a dynamic
    `batch` dimension. `output_template` replaces that prefix with the run's times,
    extends the lead times over the whole roll out and narrows the variables to the
    ones being stored.
    """
    signature = model.output_coords(model.input_coords())
    leads = signature.coords["lead_time"].values
    return output_template(
        signature,
        leading={"time": to_time_array(time)},
        coords={
            "lead_time": np.concatenate(
                [
                    np.zeros(1, dtype=leads.dtype),
                    *(leads + leads[-1] * i for i in range(nsteps)),
                ]
            ),
            "variable": variables,
        },
    )


def model_domain_coords(model):
    """Small helper"""
    signature = model.input_coords()
    return OrderedDict(
        (dim, signature.coords[dim].values)
        for dim in signature.dims
        if dim not in ("batch", "time", "lead_time", "variable")
    )

First Attempt

Every restartable run should be performed inside a checkpoint context. On an empty checkpoint, with checkpoint opens a new session for future writes. Construct restart-aware components inside that context so their state binds to the active checkpoint session. The workflow records a checkpoint row after each successful IO write because flush_interval=1 and mode="append" keeps each row in the printed checkpoint table.

checkpoint = Checkpoint(
    "restart-demo",
    path=checkpoint_store,
    mode="append",
    flush_interval=1,
    history_size=4,
    level=2,
    device=compute_device,
)

with checkpoint as ckpt:
    model = FCN.load_model(model_package)
    domain_coords = model_domain_coords(model)
    io = ZarrBackend(str(forecast_store), backend_kwargs={"overwrite": True})
    template = deterministic_template(model, time, final_nsteps, output_variables)
    io.add_array(template)
    data = Random(domain_coords=domain_coords)
    # A store's extent is fixed when its arrays are created, so this shorter first
    # attempt declares the full roll out's lead times and writes a subset of them.
    restart_coords = OrderedDict(
        {
            "variable": output_variables,
            "lead_time": template.coords["lead_time"].values,
        }
    )
    run.deterministic(
        time=time,
        nsteps=first_attempt_nsteps,
        prognostic=model,
        data=data,
        io=io,
        output_coords=restart_coords,
        device=compute_device,
        verbose=False,
        checkpoint=ckpt,
    )

print("Checkpoint after the stopped run:")
print(checkpoint)
Console output16 lines
2026-11-19 17:27:26.259 | INFO     | earth2studio.run:deterministic:132 - Running simple workflow!
2026-11-19 17:27:26.260 | INFO     | earth2studio.run:deterministic:140 - Inference device: cuda:0
2026-11-19 17:27:27.100 | SUCCESS  | earth2studio.run:deterministic:181 - Fetched data from Random
2026-11-19 17:27:27.101 | INFO     | earth2studio.run:deterministic:189 - Inference starting!
2026-11-19 17:27:27.563 | SUCCESS  | earth2studio.run:deterministic:218 - 
Inference complete
Checkpoint after the stopped run:
Checkpoint("restart-demo")
path: outputs/04_checkpoint_restart_checkpoint
mode: append
level: 2
rank: 0/1

id  lead_time  write_count  saved_at                        
0   0 hours    1            2026-11-19T17:27:27.276412+00:00
1   6 hours    2            2026-11-19T17:27:27.556405+00:00

Resume

In a new process, re-open the same IO store and checkpoint. The printout above shows the available row ids. Select -1 to resume from the latest row.

The selected checkpoint session is used as a context manager so the chosen row is the active restart state while components are constructed and while the workflow runs. FCN restores its restart state during construction. Its iterator consumes the selected checkpoint boundary internally and yields the next forecast state, while the workflow still fetches the normal initial condition and feeds it to the iterator.

io = ZarrBackend(str(forecast_store))
checkpoint = Checkpoint(
    "restart-demo",
    path=checkpoint_store,
    mode="append",
    history_size=4,
    level=2,
    device=compute_device,
)

with checkpoint.select(-1) as ckpt:
    model = FCN.load_model(model_package)
    domain_coords = model_domain_coords(model)
    data = Random(domain_coords=domain_coords)
    run.deterministic(
        time=time,
        nsteps=final_nsteps,
        prognostic=model,
        data=data,
        io=io,
        output_coords=restart_coords,
        device=compute_device,
        verbose=False,
        checkpoint=ckpt,
    )

print("Checkpoint after resume:")
print(checkpoint)
print(io.root.tree())
Console output25 lines
2026-11-19 17:27:29.693 | INFO     | earth2studio.run:deterministic:132 - Running simple workflow!
2026-11-19 17:27:29.693 | INFO     | earth2studio.run:deterministic:140 - Inference device: cuda:0
2026-11-19 17:27:30.413 | SUCCESS  | earth2studio.run:deterministic:181 - Fetched data from Random
2026-11-19 17:27:30.414 | INFO     | earth2studio.run:deterministic:189 - Inference starting!
2026-11-19 17:27:30.569 | SUCCESS  | earth2studio.run:deterministic:218 - 
Inference complete
Checkpoint after resume:
Checkpoint("restart-demo")
path: outputs/04_checkpoint_restart_checkpoint
mode: append
level: 2
rank: 0/1

id  lead_time  write_count  saved_at                        
0   0 hours    1            2026-11-19T17:27:27.276412+00:00
1   6 hours    2            2026-11-19T17:27:27.556405+00:00
2   6 hours    3            2026-11-19T17:27:30.486663+00:00
3   12 hours   4            2026-11-19T17:27:30.561267+00:00
/
โ”œโ”€โ”€ lat (720,) float64
โ”œโ”€โ”€ lead_time (4,) timedelta64[ns]
โ”œโ”€โ”€ lon (1440,) float64
โ”œโ”€โ”€ t2m (1, 4, 720, 1440) float32
โ”œโ”€โ”€ time (1,) datetime64[ns]
โ””โ”€โ”€ u10m (1, 4, 720, 1440) float32

Execution profile

Runtime telemetry

Total runtime32.4 s

Execution environment

CPUAMD EPYC 7313P 16-Core Processor
GPUNVIDIA H100 PCIe ยท 79.6 GiB
System RAM58.5 GiB
PlatformLinux 6.8.0-147-generic
Python3.13.13
GPU driver / CUDADriver 595.99.02 ยท CUDA support 13.2