Skip to content

Resilient & resumable sweeps

A long method x seed sweep is only as reliable as its flakiest cell. One OOM, a corrupt data shard, or a transient cluster hiccup should not throw away the hours already spent on the runs that did succeed, and it must never let you quietly compute statistics on a half-finished grid. mushin gives you three tools for this: fail-soft runs, resume, and provenance.

Prefer to follow along? Notebook 04: Resilient sweeps runs this whole fail-soft → resume loop end to end with live output.

Fail-soft: on_error="nan"

By default a failing job aborts the whole sweep and re-raises the exception (on_error="raise"). Pass on_error="nan" instead and mushin keeps going: the failing cell is recorded, its grid position becomes NaN, a UserWarning is emitted, and every other cell completes normally.

from mushin import multirun
from mushin.workflows import MultiRunMetricsWorkflow

wf = MyWorkflow()
wf.run(
    method=multirun(["cnn", "mlp"]),
    seed=multirun([0, 1, 2, 3, 4]),
    working_dir="runs/experiment",
    on_error="nan",
)

After the run you can inspect what happened:

wf.is_complete  # False — at least one cell failed
wf.failures  # [{"combo": "method=mlp,seed=3", "exception": "...", "working_dir": "..."}]
ds = wf.to_xarray()
ds["accuracy"].sel({"method": "mlp", "seed": 3})  # nan
ds.attrs["mushin_failures"]  # JSON list: ["method=mlp,seed=3"]

To debug a failed cell, look inside its working_dir: mushin writes the full stack trace to mushin_error.txt there (the one-line exception above is just the repr), alongside Hydra's own .hydra/ config snapshot and job log for that cell. When the cell's submitit job (submitit_slurm or submitit_local) ended without returning, the file starts with a one-line summary naming the job's log, then holds submitit's message: for a job killed out of memory, say, the job's error output (its start and end, when it is long); for one that could not import the task, its traceback.

The failed cells are also written to a sweep manifest, <working_dir>/mushin_sweep_manifest.json, which records every requested cell's status (completed / failed) and the job directory it ran in. This manifest is what makes a resume possible.

Statistics refuse an incomplete sweep

You cannot compare methods on a grid that has holes in it: the missing cells are missing data, not measurements. Both compare (compare_methods) and Study detect the completeness signal and refuse:

from mushin.benchmark import compare_methods, IncompleteSweepError

try:
    compare_methods(ds)
except IncompleteSweepError as e:
    print(e)  # "1 run(s) failed (method=mlp,seed=3); fix the cause and re-run
    #  with resume=True to complete the sweep before comparing."

This is keyed purely on ds.attrs["mushin_failures"]: a plain user dataset, or a metric that is legitimately NaN for some other reason, is unaffected. Only a sweep that actually recorded failures triggers the guard.

A sweep reloaded from disk carries the same signal. MultiRunMetricsWorkflow().load_from_dir(working_dir, "mushin_metrics.json") records every cell of the sweep's grid that has no result: as failed if its status says so, otherwise as skipped (not run), which covers a cell still running and one a killed sweep never started. A completed cell whose task returned None has a result with no metrics (NaN), as it does in the run. Its to_xarray() then has the same attrs, is_complete is False, and compare_methods refuses it too. Give each sweep its own working_dir (resuming it is fine): job dirs that an earlier sweep left in a reused one can stand in for cells the new sweep has not run yet.

Resume: fill only the failed cells

Fix the underlying cause, then re-run against the same working_dir with resume=True. mushin reads the prior manifest and short-circuits every cell that already completed (reusing its cached metrics from disk); only the failed and missing cells actually re-execute:

wf = MyWorkflow()
wf.run(
    method=multirun(["cnn", "mlp"]),
    seed=multirun([0, 1, 2, 3, 4]),
    working_dir="runs/experiment",  # same directory as before
    resume=True,
)

wf.is_complete  # True — every cell now present
compare_methods(wf.to_xarray())  # no longer raises

resume=True requires working_dir to be set (there is nothing to resume from without a stable location). The completed cells are not recomputed, so a resume of a mostly-successful sweep is cheap.

That holds when the cause was outside your code: a full disk, a lost node, a flaky download. If the fix is an edit to the task or to a project file its module imports (a helper, a constant), the completed cells were computed by the old code, so the resume re-runs them as well, with a warning naming the file. An edit anywhere in such a file counts; a comment, a docstring or formatting does not. In the driver script, only what the task's definition can reach by name counts (its helpers and constants), not the run(...) call, other top-level calls, print calls or what only they read, so extending the grid and resuming reuses the completed cells. The task function's own source is compared as text, so a comment inside its body is an edit. If you edit a module and resume in the same Python process without reloading it, the old code still runs: reload it (or restart) first. The script rule follows names, so a statement that changes an object in place (CFG["lr"] = 0.1), a function that rebinds a global when called, a definition registered inside a block, or a registry filled by __init_subclass__ can hide an edit there; helpers kept in an imported module are compared as a whole file.

In a notebook, what counts is the definitions the task's code reaches by name in the kernel when the run starts: each function and class defined in a cell, through decorators, a partial, a bound method or an instance. A function or class named in an annotation of that code counts as well (a parameter's, a return's, a class attribute's or a type parameter's, a string one too), since a reader of the hints (typing.get_type_hints, pydantic) resolves it. On Python 3.13 and earlier, an annotation that is not a string holds the class its name meant when its cell ran, so after editing such a class, re-run the cell that annotates with it too (the task's, or the dataclass's). Re-run the edited cell, then resume, and the cells re-run with a warning naming it (helper (notebook)). No value is compared: not a number, a string or a dict config. A value is only safe to compare when every writer of it is known, and in a notebook a writer can sit anywhere a value can. So pass a value the results depend on (a model name, a scale) to the task as a swept parameter, or use a new working_dir after editing one. A function reached only through a container (a registry), a closure or a default, a class an annotation reaches only through a value such as a type alias (Opt = Optional[Helper]), a definition only a class body's value names (field(default_factory=make)), a name one of the notebook's functions rebinds (global helper), a _target_ defined in the notebook, and code whose text the kernel does not keep (a %%time cell, exec, a %run file) are not compared either, and a class no class statement makes (type(...), namedtuple(...), make_dataclass) may not be. For such a task, every project module that a cell whose text the kernel keeps imports counts too, whether or not the task names it, so an edit to it re-runs the cells. cache_dir= keys on the same record, so importing another project module in a cell, or a restart after removing one's import, can make the cells compute again. A class whose class statement cannot be told from another kept version of its cell (one a function makes, or one edited before import mushin), or on Python 3.11 and 3.12 from another statement of it that its cell runs too, can also make a resume re-run the cells, and cache_dir= compute them again, when its cell runs again or after a restart. A class that a cell run after import mushin makes without stating it (in a %%time cell, by exec, %run or a global factory, or a copy such as dataclass(slots=True)(C)) is not read either, but it makes a resume re-run the cells, and cache_dir= compute them again, whenever that cell runs again and after a restart. A resume on another Python version can also re-run the cells of a class stated more than once in its cell. A module loaded other than by an import statement of such a cell (importlib.import_module, a plugin loader that fills a registry, an import in a %%time cell) may not be compared, as in a script, nor may one named only in a string annotation (x: "pkg.sub.Model"); nor may a class be told apart by its statement when one cell holds more than one version of it (two class statements of it run, or a statement and a class bound from elsewhere). Nor may what an IPython input transformer changes in a cell be compared, nor a cell holding a form feed, a vertical tab or another character that ends a line for Python's str.splitlines (not a newline or a carriage return) that the shell's history does not hold and mushin did not see run, such as one that %run runs from a notebook or an .ipy file, one run silently, or one run inside another cell (%%capture) before import mushin. A cell holding one can also make a resume re-run the cells, and cache_dir= compute them again. A class a background thread or a callback makes while a cell runs may be taken for one that cell made. After editing such a module, class or cell, use a new working_dir.

mushin finds those functions by looking through the notebook's names: the functions they hold, and what those reach through decorators, partials, bound methods, classes, closures, defaults and small lists, tuples, sets and dicts. A name rebound some other way is still compared, so once a run rebinds it in the kernel, the next resume re-runs the cells. That covers globals() and exec, and a global statement in a function kept only somewhere that look-through does not go: an object's attributes, a dict's keys, a container of more than 256 items, more than three steps from a name (each container, class, base class, instance, closure, default, decorator, partial and bound method is a step), a subclass of a container, a metaclass, or a class from outside the notebook.

run() can import a module loaded through importlib.util.LazyLoader (as lazy_loader.load does) that has not run yet, even one the task does not use, and one that fails to import can make run() raise its error. If such a module has side effects or can fail to import, import it yourself before calling run().

The full loop

run(on_error="nan")  ──►  inspect wf.failures  ──►  fix the cause
        ▲                                                │
        │                                                ▼
   compare / Study  ◄── run(working_dir=…, resume=True) ◄┘
   (once is_complete)

Surviving a hard kill & resuming mid-training

resume=True is durable across a hard process kill (OOM, SLURM preemption, node death), not just handled Python exceptions. Each cell records its status (running → completed/failed) from inside its own job, so a mid-sweep kill never loses the cells that already finished; resuming re-runs only the unfinished ones.

A long-running cell can also resume its own training. Declare a mushin_resume parameter on your task; mushin injects a ResumeContext:

from mushin.workflows import MultiRunMetricsWorkflow


class Train(MultiRunMetricsWorkflow):
    @staticmethod
    def task(lr, seed, mushin_resume=None):
        # mushin_resume.dir       -> this cell's directory (write your checkpoint here)
        # mushin_resume.is_resume -> True when a prior attempt of THIS cell ran here
        # mushin_resume.last_ckpt -> newest checkpoint in dir written under this
        #                            config and task code, or None
        ckpt = mushin_resume.last_ckpt  # None on a first attempt, or a changed config
        # Lightning: save last.ckpt at the top of the cell's directory
        trainer = Trainer(
            callbacks=[ModelCheckpoint(dirpath=mushin_resume.dir, save_last=True)]
        )
        trainer.fit(model, ckpt_path=ckpt)
        return dict(accuracy=...)

Write your checkpoint at the top of mushin_resume.dir, where last_ckpt looks (Lightning: ModelCheckpoint(dirpath=mushin_resume.dir, save_last=True)). With only default_root_dir set, Lightning writes it under lightning_logs/version_<n>/checkpoints/, which last_ckpt does not search. Re-running the same sweep (same grid) reuses each cell's directory, so a resumed cell finds its own checkpoint. The directories are named by job number, so a sweep over another grid in the same working_dir runs its cells in directories earlier cells used, and a cell there can be handed an earlier cell's checkpoint: run another grid in a new working_dir. Tasks that don't declare mushin_resume are unaffected.

A checkpoint goes only to an attempt under the config and task code that wrote it. When either has changed since, last_ckpt is None and the cell trains from scratch, though is_resume is still True. To continue from the old checkpoint on purpose (a raised max_epochs, say), load it from mushin_resume.dir yourself before the task writes its own there.

Provenance

Every run (fail-soft or not) writes a per-job provenance record, mushin_provenance.json, into each job directory before the task executes, so even a failing cell leaves its lineage behind. It captures the git SHA, key package versions, the config as written (an interpolation such as ${oc.env:DB_URL} is kept as its text, so the value it reads never reaches the file, and a secret-looking value is redacted) and, once the task has returned, the accelerator as the cell's process saw it (CUDA and cuDNN build, and the device once the task initialized CUDA or when MPS is available). It is null when that process never imported torch. With torch loaded, cuda and cudnn are the wheel's build (null on a CPU-only build) and device is null until the task initializes CUDA; records from before 0.17 named a present GPU even for a task that stayed on the CPU, so diff against such a sweep reports a device change once. A cell killed during its task keeps the view its process had before the task:

wf.provenance  # dict: {"git": {"sha": ...}, "packages": {...}, "config": {...}, ...}
ds.attrs[
    "provenance"
]  # the same record, JSON-encoded, so a saved dataset carries its lineage

For a fuller record, pass capture_env=True to write a complete dependency snapshot (mushin_env.txt, via uv export/pip freeze, falling back to an importlib.metadata dump) alongside the sweep:

wf.run(..., working_dir="runs/experiment", capture_env=True)

Using it from Study

Study threads the same options through to its training sweep, so you get fail-soft, resumable training runs with the same guarantees: an incomplete training sweep raises IncompleteSweepError from Study.run rather than comparing partially-trained checkpoints:

from mushin import Study

study = Study(
    methods={"cnn": train_cnn, "mlp": train_mlp},
    load_fn=load_model,
    seeds=[0, 1, 2, 3, 4],
    data=test_loader,
    num_classes=10,
    working_dir="runs/study",
    on_error="nan",  # fail-soft training
    capture_env=True,  # snapshot the environment
)
study.run()  # raises IncompleteSweepError if any (method, seed) failed
# ...fix the cause, then re-run with resume=True on the same working_dir:
study = Study(..., working_dir="runs/study", resume=True)
result = study.run()

See also