Skip to content

workflows

sweep

sweep(fn)

Turn a plain task(**params) -> dict function into a runnable Sweep.

mushin.multirun

multirun(values) wraps a list (of ints, floats, bools, or strings) to mark it as a sweep axis: Hydra runs one job per value and the values become an xarray dimension. It behaves like a list (multirun([1, 2, 3])).

mushin.hydra_list

hydra_list(values) wraps a list to pass it as a single argument value to one job (no sweep); use it when the task parameter itself takes a list.

Both are mushin's own, also importable from mushin.workflows. They were hydra-zen's multirun and hydra_list, re-exported, until mushin stopped importing hydra-zen. run() still takes hydra-zen's, as mushin's, with a DeprecationWarning; pass mushin's.

BaseWorkflow

Provides an interface for creating a reusable workflow: encapsulated "boilerplate" for running, aggregating, and analyzing one or more Hydra jobs.

Attributes:

Name Type Description
cfgs List[Any]

List of configurations for each Hydra job.

metrics Dict[str, List[Any]]

Dictionary of metrics for across all jobs.

workflow_overrides Dict[str, Any]

Present for backward compatibility; not populated. The swept parameters of the last run are exposed by the multirun_task_overrides property.

jobs List[Any]

List of jobs returned for each experiment within the workflow.

working_dir Optional[Path]

The working directory of the experiment defined by Hydra's sweep directory (hydra.sweep.dir).

multirun_task_overrides property

multirun_task_overrides

Returns override param-name -> value.

A sequence of overrides associated with a multirun will be stored in a mushin.multirun list. This enables one to distinguish this from an override whose sole value was a list of values.

Returns:

Name Type Description
multirun_task_overrides Dict[str, LoadedValue | Sequence[LoadedValue]]

Examples:

>>> from mushin import multirun, hydra_list
>>>
>>> class WorkFlow(MultiRunMetricsWorkflow):
...     @staticmethod
...     def task(*args, **kwargs):
...         return None
>>>
>>> wf = WorkFlow()
>>> wf.run(foo=hydra_list(["val"]), bar=multirun(["a", "b"]), apple=1)
>>> wf.multirun_task_overrides
{'foo': ['val'], 'bar': multirun(['a', 'b']), 'apple': 1}

__init__

__init__(eval_task_cfg=None)

Workflows and experiments using Hydra.

Parameters:

Name Type Description Default
eval_task_cfg

The workflow configuration object.

None

pre_task staticmethod

pre_task(*args, **kwargs)

Called prior to task

This can be useful for doing things like setting random seeds, which must occur prior to instantiating objects for the evaluation task.

Notes

This function is automatically wrapped by zen, which is responsible for parsing the function's signature and then extracting and instantiating the corresponding fields from a Hydra config object – passing them to the function. This behavior can be modified by self.run(pre_task_fn_wrapper=...)

task staticmethod

task(*args, **kwargs)

User-defined task that is run by the workflow. This should be a static method.

Arguments will be instantiated configuration variables. For example, if the the workflow configuration is structured as::

├── eval_task_cfg
│    ├── trainer
|    ├── module
|    ├── another_config

The inputs to task can be any of the three configurations: trainer, module, or another_config such as::

@staticmethod
def task(trainer: Trainer, module: LightningModule) -> None:
    trainer.fit(module)
Notes

This function is automatically wrapped by zen, which is responsible for parsing the function's signature and then extracting and instantiating the corresponding fields from a Hydra config object – passing them to the function. This behavior can be modified by self.run(task_fn_wrapper=...)

validate

validate(include_pre_task=True)

Validates that the configuration will execute with the user-defined evaluation task

Raises:

Type Description
ConfigValidationError

The config lacks a field that task (or pre_task) requires, or a signature cannot be read. While hydra-zen is imported, it is also hydra-zen's HydraZenValidationError, which this raised before mushin had a zen of its own.

run

run(
    *,
    working_dir=None,
    sweeper=None,
    launcher=None,
    launcher_config=None,
    overrides=None,
    task_fn_wrapper=zen,
    pre_task_fn_wrapper=zen,
    version_base=_VERSION_BASE_DEFAULT,
    to_dictconfig=False,
    config_name="mushin_workflow",
    job_name="mushin_workflow",
    with_log_configuration=True,
    on_error="raise",
    resume=False,
    capture_env=False,
    dry_run=False,
    confirm_above=None,
    max_total_seconds=None,
    sample=None,
    sample_seed=0,
    cache_dir=None,
    wait=_WAIT_DEFAULT,
    **workflow_overrides,
)

Run the experiment.

Individual workflows can explicitly define workflow_overrides to improve readability and undstanding of what parameters are expected for a particular workflow.

Parameters:

Name Type Description Default
task_fn_wrapper Callable[[Callable[..., T1]], Callable[[Any], T1]] | None

A wrapper applied to self.task prior to launching the task. The default is mushin's own zen (mushin.workflows.zen), which behaves as hydra-zen's zen did as this default: it resolves the job's config in place, then calls the task with the config fields its signature names, each config among them instantiated. hydra-zen's zen may still be passed. Specify None for no wrapper to be applied.

zen
working_dir str | None

The directory to run the experiment in. This value is used for setting hydra.sweep.dir. A run refuses a working_dir whose earlier jobs, submitted by launcher="submitit_slurm" or "submitit_local", may still be queued or running, whatever launcher it uses: a ValueError, or a RuntimeError when scontrol gives no answer it can read. Where those jobs cannot be checked (no scontrol), it warns and runs.

None
sweeper str | None

The configuration name of the Hydra Sweeper to use (i.e., the override for hydra/sweeper=sweeper)

None
launcher str | None

The configuration name of the Hydra Launcher to use (i.e., the override for hydra/launcher=launcher)

None
launcher_config Mapping[str, Any] | None

Fields for the selected launcher, applied as hydra.launcher.<key>=<value> overrides: no hand-rolled strings. Pair with mushin.slurm for cells that each run as one SLURM job, e.g. run(launcher="submitit_slurm", launcher_config=mushin.slurm(gpus=1, partition="gpu")), or with mushin.submitit_slurm_config for DDP cells, a task per GPU. cells_per_job (mushin.slurm(..., cells_per_job=20)) has each job run several cells, one after another, on "submitit_slurm" or "submitit_local" only. Requires launcher=.

None
overrides list[str] | None

Parameter overrides not considered part of the swept workflow parameter set (which are exposed via multirun_task_overrides).

None
version_base (Optional[str], optional(default=1.3))

The Hydra compatibility version governing default behaviors. - An explicit version string like "1.3" selects the defaults of that Hydra version. - None selects the defaults of the installed Hydra version. On Hydra 1.4 and later, which deprecate the parameter, the default and None are not passed to Hydra (1.4 has only its own defaults); an explicit version is, so Hydra warns, and raises for one it no longer supports, such as "1.1". Regardless of version_base, run sets hydra.job.chdir=True (unless you override it); each job runs in its own working directory, which the workflow's metrics sidecars depend on.

VERSION_BASE_DEFAULT
to_dictconfig bool

If True, convert a dataclasses.dataclass to a omegaconf.DictConfig. Note, this will remove Hydra's capability for validation with structured configurations.

False
config_name str (default: "mushin_workflow")

Name of the stored configuration in Hydra's ConfigStore API.

'mushin_workflow'
job_name str (default: "mushin_workflow")

Name of job for logging.

'mushin_workflow'
with_log_configuration bool (default: True)

If True, enables the configuration of the logging subsystem from the loaded config.

True
**workflow_overrides str | int | float | bool | multirun | hydra_list

These parameters represent the values for configurations to use for the experiment.

Passing param=multirun([1, 2, 3]) will perform a multirun over those three param values, whereas passing param=hydra_list([1, 2, 3]) will pass the entire list as a single input. Both are mushin's own (mushin.multirun, mushin.hydra_list); hydra-zen's are taken as mushin's, with a DeprecationWarning.

These values will be appended to the overrides for the Hydra job.

{}
dry_run bool (default: False)

Preview the grid (cell count + per-axis values) and return a summary dict without launching any job.

False
confirm_above int | None (default: None)

Refuse to launch a sweep with more than this many cells (raising a ValueError). MUSHIN_MAX_CELLS supplies a default ceiling.

None
max_total_seconds float | None (default: None)

Graceful wall-clock budget: once exhausted, remaining cells are skipped (NaN, self.skipped) and a later resume=True finishes them. One deadline for the whole sweep, timed from its first computed cell: under a parallel launcher (joblib, submitit) every worker stops starting cells once it passes. Disabled (with a warning in the cell's own process) for a cell run as one of several ranks or tasks (a multi-rank DDP launch, or a submitit job with tasks_per_node > 1, submitit_local included), because each checks it at its own moment: DDP could hang, or a late task record the cell skipped. When launcher_config gives each cell several tasks, run() also warns before it submits anything.

None
sample int | None (default: None)

Run a random sample-cell subset of the grid (rest NaN) for fast exploration; deterministic and resume-safe. sample_seed varies the subset.

None
cache_dir str | None (default: None)

Content-addressed cache of completed cells shared across working_dir\ s: a cell whose config, task source and the project code the task can run match a cached entry reuses it instead of recomputing.

None
on_error str (default: "raise")

Failure policy for the sweep. "raise" (the default) preserves the existing behavior: a failing job aborts the sweep and the exception propagates. "nan" enables fail-soft: a failing job is recorded (in self.failures and the on-disk sweep manifest), its grid cell becomes NaN, a UserWarning is emitted, and the sweep completes.

'raise'
wait bool (default: True)

False submits the sweep's jobs and returns without waiting on them, a summary dict in place of the result; once they have ended, mushin.collect (or collect()) builds the result. Needs launcher="submitit_slurm" or "submitit_local", a working_dir, and Hydra's basic sweeper. See MultiRunMetricsWorkflow.run.

_WAIT_DEFAULT

jobs_post_process

jobs_post_process()

Method to extract attributes and metrics relevant to the workflow.

plot

plot(**kwargs)

Plot workflow metrics.

to_xarray

to_xarray()

Convert workflow data to xArray Dataset or DataArray.

MultiRunMetricsWorkflow

Bases: BaseWorkflow

Abstract class for workflows that record metrics using Hydra multirun.

This workflow creates subdirectories of multirun experiments using Hydra. These directories contain the Hydra YAML configuration and any saved metrics file (defined by the evaluationf task)::

├── working_dir
│    ├── <experiment directory name: 0>
│    |    ├── <hydra output subdirectory: (default: .hydra)>
|    |    |    ├── config.yaml
|    |    |    ├── hydra.yaml
|    |    |    ├── overrides.yaml
│    |    ├── <metrics_filename>
│    ├── <experiment directory name: 1>
|    |    ...

The evaluation task is expected to return a dictionary that maps metric-name (str) -> value (number | Sequence[number])

Examples:

Let's create a simple workflow where we perform a multirun over a parameter, epsilon, and evaluate a task function that computes an accuracy and loss based on that epsilon value and a specified scale.

>>> from mushin.workflows import MultiRunMetricsWorkflow
>>> from mushin import multirun
>>> class LocalRobustness(MultiRunMetricsWorkflow):
...     @staticmethod
...     def task(epsilon: float, scale: float) -> dict:
...         epsilon *= scale
...         val = 100 - epsilon**2
...         result = dict(accuracies=val+2, loss=epsilon**2)
...         tr.save(result, "test_metrics.pt")
...         return result

We'll run this workflow for six total configurations of three epsilon values and two scale values. This will launch a Hydra multirun job and aggregate the results.

>>> wf = LocalRobustness()
>>> wf.run(epsilon=multirun([1.0, 2.0, 3.0]), scale=multirun([0.1, 1.0]))
[2022-05-02 11:57:59,219][HYDRA] Launching 6 jobs locally
[2022-05-02 11:57:59,220][HYDRA]    #0 : +epsilon=1.0 +scale=0.1
[2022-05-02 11:57:59,312][HYDRA]    #1 : +epsilon=1.0 +scale=1.0
[2022-05-02 11:57:59,405][HYDRA]    #2 : +epsilon=2.0 +scale=0.1
[2022-05-02 11:57:59,498][HYDRA]    #3 : +epsilon=2.0 +scale=1.0
[2022-05-02 11:57:59,590][HYDRA]    #4 : +epsilon=3.0 +scale=0.1
[2022-05-02 11:57:59,683][HYDRA]    #5 : +epsilon=3.0 +scale=1.0

Now that this workflow has run, we can view the results as an xarray-dataset whose coordinates reflect the multirun parameters that were varied, and whose data-variables are our recorded metrics: "accuracies" and "loss".

>>> ds = wf.to_xarray()
>>> ds
<xarray.Dataset>
Dimensions:     (epsilon: 3, scale: 2)
Coordinates:
* epsilon     (epsilon) float64 1.0 2.0 3.0
* scale       (scale) float64 0.1 1.0
Data variables:
    accuracies  (epsilon, scale) float64 102.0 101.0 102.0 98.0 101.9 93.0
    loss        (epsilon, scale) float64 0.01 1.0 0.04 4.0 0.09 9.0

We can also load this workflow by providing the working directory where it was run.

>>> loaded = LocalRobustness().load_from_dir(wf.working_dir)
>>> loaded.to_xarray()
<xarray.Dataset>
Dimensions:     (epsilon: 3, scale: 2)
Coordinates:
* epsilon     (epsilon) float64 1.0 2.0 3.0
* scale       (scale) float64 0.1 1.0
Data variables:
    accuracies  (epsilon, scale) float64 102.0 101.0 102.0 98.0 101.9 93.0
    loss        (epsilon, scale) float64 0.01 1.0 0.04 4.0 0.09 9.0

is_complete property

is_complete

Whether every requested grid cell completed. For a workflow loaded from disk, whether its record (failures, skipped) is empty: the record is rebuilt on each load, from the cells' statuses and, once metrics are loaded, their metrics. True for a workflow that has neither swept nor loaded. False for a run submitted with wait=False until it is collected.

notes property

notes

Free-form note recorded for this sweep via run(notes=...) (or read from the manifest of a loaded sweep); None if none was set.

tags property

tags

Tags recorded for this sweep via run(tags=[...]) (or read from the manifest of a loaded sweep); an empty list if none were set.

provenance property

provenance

Best-effort per-run provenance (git/versions/config) read from one job's mushin_provenance.json: the first that has an accelerator, else the first. None if no record is found.

target_dir_multirun_overrides property

target_dir_multirun_overrides

For a multirun that sweeps over the target directories of a previous multirun, target_dir_multirun_overrides provides the flattened overrides for that previous run.

Examples:

>>> class A(MultiRunMetricsWorkflow):
...     @staticmethod
...     def task(value: float, scale: float):
...         pass
...
>>> class B(MultiRunMetricsWorkflow):
...     @staticmethod
...     def task():
...         pass
>>> a = A()
>>> a.run(value=multirun([-1.0, 0.0, 1.0]), scale=multirun([11.0, 9.0]))
[2022-05-13 17:19:51,497][HYDRA] Launching 6 jobs locally
[2022-05-13 17:19:51,497][HYDRA]        #0 : +value=-1.0 +scale=11.0
[2022-05-13 17:19:51,555][HYDRA]        #1 : +value=-1.0 +scale=9.0
[2022-05-13 17:19:51,729][HYDRA]        #2 : +value=1.0 +scale=11.0
[2022-05-13 17:19:51,787][HYDRA]        #3 : +value=1.0 +scale=9.0
>>> b = B()
>>> b.run(target_job_dirs=a.multirun_working_dirs)
[2022-05-13 17:19:59,900][HYDRA] Launching 6 jobs locally
[2022-05-13 17:19:59,900][HYDRA]        #0 : +job_dir=/home/scratch/multirun/0
[2022-05-13 17:19:59,958][HYDRA]        #1 : +job_dir=/home/scratch/multirun/1
[2022-05-13 17:20:00,015][HYDRA]        #2 : +job_dir=/home/scratch/multirun/2
[2022-05-13 17:20:00,073][HYDRA]        #3 : +job_dir=/home/scratch/multirun/3
>>> b.target_dir_multirun_overrides
{'value': [-1.0, -1.0, 1.0, 1.0],
 'scale': [11.0, 9.0, 11.0, 9.0]}

task staticmethod

task(*args, **kwargs)

Abstract staticmethod for users to define the task that is configured and launched by the workflow

metric_load_fn staticmethod

metric_load_fn(file_path)

Loads a metric file and returns a dictionary of metric-name -> metric-value mappings.

The default loader sniffs the file: a JSON metrics sidecar (the mushin_metrics.json a task writes by returning a dict) is read with json; anything else with torch.load (the MetricsCallback .pt path). Override this method for a custom format.

Parameters:

Name Type Description Default
file_path Path
required

Returns:

Name Type Description
named_metrics Mapping[str, Any]

metric-name -> metric-value(s)

Examples:

Designing a workflow that uses the pickle module to save and load metrics

>>> from mushin import MultiRunMetricsWorkflow, multirun
>>> import pickle
>>>
>>> class PickledWorkFlow(MultiRunMetricsWorkflow):
...     @staticmethod
...     def metric_load_fn(file_path: Path):
...         with file_path.open("rb") as f:
...             return pickle.load(f)
...
...     @staticmethod
...     def task(a, b):
...         with open("./metrics.pkl", "wb") as f:
...             pickle.dump(dict(a=a, b=b), f)
>>>
>>> wf = PickledWorkFlow()
>>> wf.run(a=multirun([1, 2, 3]), b=False)
>>> wf.load_metrics("metrics.pkl")
>>> wf.metrics
dict(a=[1, 2, 3], b=[False, False, False])

run

run(
    *,
    task_fn_wrapper=zen,
    pre_task_fn_wrapper=zen,
    working_dir=None,
    sweeper=None,
    launcher=None,
    launcher_config=None,
    overrides=None,
    version_base=_VERSION_BASE_DEFAULT,
    target_job_dirs=None,
    to_dictconfig=False,
    config_name="mushin_workflow",
    job_name="mushin_workflow",
    with_log_configuration=True,
    on_error="raise",
    resume=False,
    capture_env=False,
    dry_run=False,
    confirm_above=None,
    max_total_seconds=None,
    sample=None,
    sample_seed=0,
    cache_dir=None,
    notes=None,
    tags=None,
    wait=_WAIT_DEFAULT,
    **workflow_overrides,
)

Run the sweep: one Hydra job per grid cell, metrics collected per cell.

Extends BaseWorkflow.run (see it for the launcher/sweeper/ Hydra parameters) with metrics-workflow behavior:

Parameters:

Name Type Description Default
target_job_dirs Sequence[str | Path] | None (default: None)

Existing job directories to evaluate over: each directory becomes one cell of a job_dir sweep dimension, and the task receives that cell's directory as its job_dir argument. Use this to post-process completed runs (e.g. evaluate saved checkpoints) instead of sweeping parameter values.

None
on_error str (default: "raise")

"raise" propagates the first failing cell. "nan" records the failure (self.failures, the sweep manifest, and a mushin_error.txt traceback in the cell dir), fills that cell's metrics with NaN, and keeps sweeping. On the submitit launchers, a cell whose job ends without returning (an out-of-memory kill, a failed node, scancel, or an error outside the task, such as the job failing to import it) fails the same way, and its mushin_error.txt names the job's log. A time limit usually reaches the task as an error submitit raises in it, which fails the cell as any task error does.

'raise'
resume bool (default: False)

Skip cells already recorded as completed in working_dir (their metrics are read from the sidecar) and re-run the rest. A completed cell is reused only if its swept-parameter combination AND fingerprints of its resolved config, its task source and the project code the task can run still match. That project code is every project file the task's module imports (and pre_task's), directly or through other project files, at any depth (imports inside functions included), and the modules of the classes the cell's config names (_target_, or hydra-zen's just() and zen_meta), each with the __init__.py of the packages it is in, which importing it runs. Each file is compared as a whole, by its syntax tree without its main block and docstrings: an edit anywhere in it re-runs the cells, and a comment, a docstring or formatting does not (so neither does a prompt a decorator reads from a docstring). The task function's own source is compared as text, as before, so any edit to it re-runs its cells, a comment included. A task defined in the driver script is compared by what its definition can reach by name in the script (a helper, a constant, a star import, a definition a project decorator registers, in the main block too), not by the run call, other top-level calls or prints, or what only they read (GRID = dict(...)), so extending the grid or adding a print is not an edit. The script is read when the run starts (a _target_ defined in it, when the first cell naming it runs), so editing it while the sweep runs does not change what its cells record. A task defined in a notebook is compared by the definitions its code reaches by name in the kernel as the run starts (each function and class its cells define, through decorators, a partial, a bound method or an instance) and by every project module its cells import, so re-running an edited cell and resuming re-runs the cells; with cache_dir, importing another project module in a cell can make them compute again. A class whose class statement cannot be told from another kept version of its cell (or, on 3.11/3.12, from another statement of it its cell runs) can make a resume re-run them, and cache_dir compute them, 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, but re-runs them 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. No value is compared (a number, a string, a dict config): pass one as a swept parameter, or use a new working_dir after editing it. A re-run warns, naming the file (helpers (file)) or the notebook name (helper (notebook)). Files are compared as they are on disk: if one changes after this process loaded it and is not reloaded, the old code keeps running while the cells computed now are recorded as the new code's, so reload it (or restart) before resuming. mushin warns when it had recorded that file earlier in the same process. A run can import a module loaded through importlib.util.LazyLoader that has not run yet, even one the task does not use, so import such a module yourself before run(). Not covered: installed packages other than editable ones, data files, the environment, in a notebook its values, a function reached only through a container (a registry), a closure or a default, a name one of its functions rebinds (global helper), a class's attribute values beyond its text, possibly a module loaded other than by a cell's import statement (importlib.import_module, a plugin loader that fills a registry, an import in a %%time cell), possibly a class no class statement makes (type(...), make_dataclass) or one of which a cell holds more than one version (two class statements run, or a statement and a class bound from elsewhere), a _target_ defined in the notebook, code whose text the kernel does not keep (a %%time cell, exec, a %run file; a class it makes re-runs instead), possibly a cell holding a form feed, a vertical tab or another character that ends a line for 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 %run runs from a notebook or an .ipy file, a silent one, or one run inside another cell before import mushin; a cell holding one can re-run the cells instead), what an IPython input transformer changes in a cell, possibly a class a background thread or a callback makes while a cell runs (taken for that cell's), a top-level statement of the driver script that changes an object in place (CFG["x"] = 2, parser.add_argument(...)) or a call in its main block that rebinds a global (setup()), a script definition reached only through an __init_subclass__ or metaclass registry, a definition registered inside a block (if ENABLED: @register class ...), a class body reading the module's name it shadows (SCALE = SCALE), and code reached only through some other string. The script rule follows names, so state reached another way (globals(), exec) can hide an edit: keep helpers in an imported module, which is compared as a whole file, when that matters. In a notebook, a name rebound through globals() or exec, or by a function the notebook's names do not lead to (one kept only in an object's attributes), is still compared, so once a run rebinds it in the kernel, a resume re-runs the cells; the resilience guide lists where mushin looks. A very large project is covered up to a fixed number of files (with a warning). After upgrading a dependency, changing the data or editing such code, re-run from a fresh working_dir rather than resuming.

False
capture_env bool (default: False)

After the sweep, snapshot the environment (uv export, falling back to uv pip freeze then an importlib.metadata dump) to working_dir/mushin_env.txt, or mushin_env.<n>.txt if a snapshot already exists there (a resume never overwrites the original run's snapshot).

False
dry_run bool (default: False)

Preview the sweep instead of running it: print the cell count and each swept axis with its values (a range typo shows up as an unexpectedly wide axis), then return a summary dict (num_cells/axes/fixed/working_dir) without launching any job.

False
confirm_above int | None (default: None)

Refuse to launch a sweep with more than this many grid cells, raising a ValueError instead: a guard against an accidentally huge grid. The MUSHIN_MAX_CELLS environment variable supplies a default ceiling when this is not set (an explicit value wins). Use dry_run=True to preview an over-limit sweep. sample= does not lower this gate: every grid cell is still composed, and launched, but on mushin's submitit launchers, which usually submit jobs only for the sampled cells (not when the sweep has Hydra callbacks).

None
max_total_seconds float | None (default: None)

A graceful wall-clock budget. Once it is exhausted the remaining cells are skipped (recorded 'skipped', NaN in the dataset, surfaced in self.skipped) instead of the sweep running to the end. The clock starts when the sweep's first computed cell starts, so at least one cell always runs and resume cache hits do not consume it; a cell already running is never interrupted, so the sweep can end up to one cell's duration past the deadline (a cell that a scheduler preempts and requeues after the deadline still runs, since it started before it). Skipped cells are not completed, so a later resume=True with more time finishes them; pass max_total_seconds again to time-box that run too, and its clock starts afresh. The budget is one deadline for the whole sweep, whatever the launcher, as long as every worker sees the same sweep directory (a filesystem they share, as submitit needs anyway) and, on several nodes, synchronized clocks: under a parallel launcher (launcher="joblib", submitit) no worker starts a cell after it passes, so it bounds elapsed time, not compute summed over the workers, and each worker can finish one cell it started just before it. The default sequential launcher keeps the deadline in memory; a parallel launcher's workers share the start through a hidden file in the sweep directory (.mushin_budget_start.<id>), compared across processes on the wall clock. run removes the file when its launch returns normally; a launch that raises leaves it, so jobs a scheduler still holds keep the same deadline, and it is inert afterwards because each run has its own id. If no start can be shared (the file cannot be created, or is gone when read) or the budget step fails, each worker process times the budget from its own first cell, which runs, with a warning raised in that worker (on its stderr, not through the caller's warning filters). Disabled (with a warning) for a cell run as one of several ranks or tasks (submitit DDP/FSDP, or a submitit job with tasks_per_node > 1): each checks the deadline at its own moment, so DDP could hang at rendezvous, or a late task record the cell skipped; use the scheduler's time limit for those jobs instead.

None
sample int | None (default: None)

Run only a random subset of sample cells from the full grid for fast exploration; the remaining cells are skipped (NaN, and self.skipped). The subset is chosen deterministically (see sample_seed) so it is reproducible and identical across a resume; resuming WITHOUT sample fills in the remaining cells. The full grid is still composed by Hydra, and launched too (only the sampled cells run), but on mushin's submitit launchers, which usually submit jobs only for the sampled cells (not when the sweep has Hydra callbacks). sample >= n_cells runs everything. A sampled sweep is intentionally incomplete (is_complete is False).

None
sample_seed int (default: 0)

Seeds the sample selection; change it to draw a different reproducible subset of the same grid.

0
cache_dir str | None (default: None)

A content-addressed cache of completed cells, shared across working_dir\ s. A cell whose resolved config, task source and the project code the task reaches match a cached entry (keyed on the same fingerprints as resume) reuses that result instead of recomputing, so a cell computed in one sweep is free in another. Newly-computed cells are stored there. Complements resume (which reuses within a single working_dir); a changed config value, an edited task body or an edited project file is a cache miss. An entry an earlier mushin wrote is recomputed once. Files are read as they are on disk (see resume): after editing a module in a running process, reload it (or restart) before using the cache, or the old code's results are stored under the new code's key. When the project code cannot be fingerprinted (a warning says so), the cache is not used for that cell, and a partial task never uses the cache, as on main: the key cannot see into the data it binds.

None
notes str | None (default: None)

A free-form note recorded for the sweep, in the manifest, on wf.notes, and as the dataset attr mushin_notes. Lineage for "why did I run this?". A resume that does not re-pass it keeps the original run's note.

None
tags list[str] | None (default: None)

Tags recorded for the sweep, in the manifest, on wf.tags, and as the dataset attr mushin_tags (preserved across a resume).

None
wait bool (default: True)

False submits the sweep's jobs and returns at once, without waiting on them, so a login node need not stay connected. It returns a dict: working_dir (absolute), run_id, submitted (the cells left to jobs) and job_ids (one per SLURM job array, as squeue and sbatch --dependency take them). Once the jobs have ended, mushin.collect(working_dir) (or this workflow's collect()) builds the result; until then to_xarray raises and is_complete is False. A run with nothing to submit (a resume reusing every cell) finishes at once and returns the dict with submitted=0. Needs launcher="submitit_slurm" or "submitit_local", a working_dir, and Hydra's basic sweeper (a ValueError otherwise, before anything is written). Every batch of a max_batch_size sweep is submitted at once, and a Hydra on_multirun_end callback runs at submission. A wait= for a task, pre_task or config field of that name is refused (it was the task's before wait was run()'s): pass it as overrides=["++wait=..."].

_WAIT_DEFAULT
**workflow_overrides str | int | float | bool | multirun | hydra_list

The sweep itself: param=value fixes a value, param=multirun([...]) makes a grid dimension. Nested config paths (**{"model.width": multirun([4, 8])}) and config groups are supported; see the workflows guide's "Sweep-axis support" section.

{}

collect

collect(
    working_dir=None, metrics_filename="mushin_metrics.json"
)

Finish a run submitted with run(..., wait=False), once its jobs have ended, as run() would have finished it, and return self. mushin.collect does the same and returns the dataset.

Parameters:

Name Type Description Default
working_dir str | Path | None (default: None)

The run's working_dir; None for the one this workflow last ran in.

None
metrics_filename str | Sequence[str] (default: "mushin_metrics.json")

For a run with nothing left to collect (collected already, run with wait=True, or its jobs cancelled): the metrics files load_from_dir reads.

'mushin_metrics.json'

Returns:

Type Description
Self

Raises:

Type Description
RuntimeError

A job of the run has not ended (nothing is written), or cannot be read here; or, under on_error="raise", a cell failed, which is raised as a waited run raises it.

Notes

See mushin.collect.

load_from_dir

load_from_dir(working_dir, metrics_filename)

Loading workflow job data from a given working directory. The workflow is loaded in-place and "self" is returned by this method.

Parameters:

Name Type Description Default
working_dir Path | str

The base working directory of the experiment. It is expected that subdirectories within this working directory will contain individual Hydra jobs data (yaml configurations) and saved metrics files.

required
metrics_filename str | Sequence[str] | None

The filename(s) or glob-pattern(s) uses to load the metrics. If None, the metrics stored in self.metrics is used.

required

Returns:

Name Type Description
loaded_workflow Self

load_metrics

load_metrics(metrics_filename)

Loads and aggregates across all multirun working dirs, and stores the metrics in self.metrics.

self.metric_load_fn is used to load each job's metric file(s).

Parameters:

Name Type Description Default
metrics_filename str | Sequence[str]

The filename(s) or glob-pattern(s) used to load the metrics. Required (unlike to_xarray/load_from_dir, this method does not accept None).

required

Returns:

Name Type Description
metrics Dict[str, List[Any]]

Examples:

Creating a workflow that saves named metrics using torch.save

>>> from mushin.workflows import MultiRunMetricsWorkflow, multirun
>>> import torch as tr
>>>
... class TorchWorkFlow(MultiRunMetricsWorkflow):
...     @staticmethod
...     def task(a, b):
...         tr.save(dict(a=a, b=b), "metrics.pt")
...
>>> wf = TorchWorkFlow()
>>> wf.run(a=multirun([1, 2, 3]), b=False)
[2022-06-01 12:35:51,650][HYDRA] Launching 3 jobs locally
[2022-06-01 12:35:51,650][HYDRA]        #0 : +a=1 +b=False
[2022-06-01 12:35:51,715][HYDRA]        #1 : +a=2 +b=False
[2022-06-01 12:35:51,780][HYDRA]        #2 : +a=3 +b=False

~MultiRunMetricsWorkflow.metric_load_fn reads the JSON metrics sidecar or a torch file by default (refer to it to change this behavior).

>>> wf.load_metrics("metrics.pt")
defaultdict(list, {'a': [1, 2, 3], 'b': [False, False, False]})
>>> wf.metrics
defaultdict(list, {'a': [1, 2, 3], 'b': [False, False, False]})

to_dataframe

to_dataframe(**to_xarray_kwargs)

The sweep results as a tidy long-form pandas.DataFrame.

One row per sweep cell (times any extra metric dimensions), with the sweep parameters and metrics as plain columns: the pandas view of to_xarray (to_xarray(...).to_dataframe().reset_index()), for when you'd rather not touch xarray at all. Keyword arguments forward to to_xarray. Dataset-level attrs (provenance, failure records) live only on the xarray form.

to_xarray

to_xarray(
    include_working_subdirs_as_data_var=False,
    coord_from_metrics=None,
    non_multirun_params_as_singleton_dims=False,
    metrics_filename=None,
)

Convert workflow data to xarray Dataset.

Parameters:

Name Type Description Default
include_working_subdirs_as_data_var (bool, optional(default=False))

If True then the data-variable "working_subdir" will be included in the xarray. This data variable is used to lookup the working sub-dir path (a string) by multirun coordinate.

False
coord_from_metrics str | None (default: None)

If not None defines the metric key to use as a coordinate in the Dataset. This function assumes that this coordinate represents the leading dimension for all data-variables.

None
non_multirun_params_as_singleton_dims (bool, optional(default=False))

If True then non-multirun entries from workflow_overrides will be included as length-1 dimensions in the xarray. Useful for merging/ concatenation with other Datasets

False
metrics_filename str | Sequence[str] | None

The filename or glob-pattern uses to load the metrics. If None, the metrics stored in self.metrics is used.

None

Returns:

Name Type Description
results Dataset

A dataset whose dimensions and coordinate-values are determined by the quantities over which the multi-run was performed. The data variables correspond to the named results returned by the jobs.

RobustnessCurve

Bases: MultiRunMetricsWorkflow

Abstract class for workflows that measure performance for different perturbation values.

This workflow requires and uses parameter epsilon as the configuration option for varying the perturbation.

See Also

MultiRunMetricsWorkflow

run

run(
    *,
    epsilon,
    task_fn_wrapper=zen,
    pre_task_fn_wrapper=zen,
    target_job_dirs=None,
    version_base=_VERSION_BASE_DEFAULT,
    working_dir=None,
    sweeper=None,
    launcher=None,
    launcher_config=None,
    overrides=None,
    to_dictconfig=False,
    config_name="mushin_workflow",
    job_name="mushin_workflow",
    with_log_configuration=True,
    on_error="raise",
    resume=False,
    capture_env=False,
    **workflow_overrides,
)

Run the experiment for varying value epsilon.

Parameters:

Name Type Description Default
epsilon str | Sequence[float]

The configuration parameter for the perturbation. Unlike Hydra overrides, this parameter can be a list of floats that will be converted into a multirun sequence override for Hydra.

required
task_fn_wrapper Callable[[Callable[..., T1]], Callable[[Any], T1]] | None

A wrapper applied to self.task prior to launching the task. The default is mushin's own zen (mushin.workflows.zen), which behaves as hydra-zen's zen did as this default: it resolves the job's config in place, then calls the task with the config fields its signature names, each config among them instantiated. hydra-zen's zen may still be passed. Specify None for no wrapper to be applied.

zen
working_dir str | None

The directory to run the experiment in. This value is used for setting hydra.sweep.dir. A run refuses a working_dir whose earlier jobs, submitted by launcher="submitit_slurm" or "submitit_local", may still be queued or running, whatever launcher it uses: a ValueError, or a RuntimeError when scontrol gives no answer it can read. Where those jobs cannot be checked (no scontrol), it warns and runs.

None
sweeper str | None

The configuration name of the Hydra Sweeper to use (i.e., the override for hydra/sweeper=sweeper)

None
launcher str | None

The configuration name of the Hydra Launcher to use (i.e., the override for hydra/launcher=launcher)

None
launcher_config Mapping[str, Any] | None

Fields for the selected launcher, applied as hydra.launcher.<key>=<value> overrides: no hand-rolled strings. Pair with mushin.slurm for cells that each run as one SLURM job, e.g. run(launcher="submitit_slurm", launcher_config=mushin.slurm(gpus=1, partition="gpu")), or with mushin.submitit_slurm_config for DDP cells, a task per GPU. cells_per_job (mushin.slurm(..., cells_per_job=20)) has each job run several cells, one after another, on "submitit_slurm" or "submitit_local" only. Requires launcher=.

None
overrides list[str] | None

Parameter overrides not considered part of the swept workflow parameter set (which are exposed via multirun_task_overrides).

None
**workflow_overrides str | int | float | bool | multirun | hydra_list

These parameters represent the values for configurations to use for the experiment.

These values will be appended to the overrides for the Hydra job.

{}

to_xarray

to_xarray(
    include_working_subdirs_as_data_var=False,
    coord_from_metrics=None,
    non_multirun_params_as_singleton_dims=False,
    metrics_filename=None,
)

Convert workflow data to xarray Dataset.

Parameters:

Name Type Description Default
include_working_subdirs_as_data_var (bool, optional(default=False))

If True then the data-variable "working_subdir" will be included in the xarray. This data variable is used to lookup the working sub-dir path (a string) by multirun coordinate.

False
coord_from_metrics str | None (default: None)

If not None defines the metric key to use as a coordinate in the Dataset. This function assumes that this coordinate represents the leading dimension for all data-variables.

None
non_multirun_params_as_singleton_dims (bool, optional(default=False))

If True then non-multirun entries from workflow_overrides will be included as length-1 dimensions in the xarray. Useful for merging/ concatenation with other Datasets

False
metrics_filename str | Sequence[str] | None

The filename or glob-pattern uses to load the metrics. If None, the metrics stored in self.metrics is used.

None

Returns:

Name Type Description
results Dataset

A dataset whose dimensions and coordinate-values are determined by the quantities over which the multi-run was performed. The data variables correspond to the named results returned by the jobs.

plot

plot(
    metric,
    ax=None,
    group=None,
    save_filename=None,
    non_multirun_params_as_singleton_dims=False,
    **kwargs,
)

Plot metrics versus epsilon.

Using the xarray.Dataset from to_xarray, plot the metrics against the workflow perturbation parameters.

Parameters:

Name Type Description Default
metric str

The metric saved

required
ax Any

If not None, the matplotlib.Axes to use for plotting.

None
group str | None

Needed if other parameters besides epsilon were varied.

None
save_filename str | None

If not None save figure to the filename provided.

None
non_multirun_params_as_singleton_dims (bool, optional(default=False))

If True then non-multirun entries from workflow_overrides will be included as length-1 dimensions in the xarray. Useful for merging/ concatenation with other Datasets

False
**kwargs

Additional arguments passed to xarray.plot.

{}

ConfigValidationError

Bases: ValueError

A config a task cannot be called with: one that lacks a field the task requires, or a task whose signature cannot be read. BaseWorkflow.validate() raises it.

A ValueError, as is the error run() raises before it launches for a parameter no config field or override provides. While hydra-zen is imported, the error raised is also hydra-zen's HydraZenValidationError, which validate() raised before mushin had a zen of its own, so an except written for that one still catches it. Catch this one: hydra-zen leaves mushin's dependencies in the next release.

Running on SLURM

The resources of a sweep whose cells each run as one SLURM job, for run(launcher="submitit_slurm", launcher_config=...); the way to collect a sweep submitted with wait=False once its jobs have ended; and the way to cancel the jobs such a sweep left queued or running. For a cell trained with DDP, a task per GPU, see submitit_slurm_config.

slurm

slurm(
    *,
    gpus=0,
    cpus=None,
    mem_gb=None,
    timeout_min=None,
    partition=None,
    account=None,
    qos=None,
    setup=None,
    cells_per_job=1,
    check=True,
    **extra,
)

The launcher_config of a sweep that runs its cells as SLURM jobs of one task.

Pass it with launcher="submitit_slurm" (the slurm extra)::

experiment.run(
    lr=mushin.multirun([0.01, 0.1]),
    launcher="submitit_slurm",
    launcher_config=mushin.slurm(gpus=1, timeout_min=120, partition="gpu"),
)

Each job runs one task, with gpus GPUs and cpus CPUs, so a cell runs once (a job of several tasks runs the cell once per task). A cell that trains with DDP, on one node or several, runs a task per GPU: build its config with mushin.submitit_slurm_config instead. Each job runs one cell, or cells_per_job of them, for a sweep of many short cells.

Parameters:

Name Type Description Default
gpus int

GPUs per job (--gpus-per-node); 0, the default, requests none.

0
cpus int

CPUs for the job's task (--cpus-per-task); unset leaves SLURM's default (which can depend on the GPUs asked for).

None
mem_gb int

Memory per job, in whole GB (--mem); unset leaves SLURM's default.

None
timeout_min int

The job's time limit, in minutes (--time); 60 when unset, as in hydra-submitit-launcher.

None
partition str

Written into each job's script; unset leaves SLURM's defaults. An SBATCH_PARTITION, SBATCH_ACCOUNT, SBATCH_QOS or SBATCH_TIMELIMIT in the environment that submits the jobs overrides the script (sbatch reads them first); one that overrides an argument given here warns.

None
account str

Written into each job's script; unset leaves SLURM's defaults. An SBATCH_PARTITION, SBATCH_ACCOUNT, SBATCH_QOS or SBATCH_TIMELIMIT in the environment that submits the jobs overrides the script (sbatch reads them first); one that overrides an argument given here warns.

None
qos str

Written into each job's script; unset leaves SLURM's defaults. An SBATCH_PARTITION, SBATCH_ACCOUNT, SBATCH_QOS or SBATCH_TIMELIMIT in the environment that submits the jobs overrides the script (sbatch reads them first); one that overrides an argument given here warns.

None
setup list of str

Shell lines each job runs before the cell, such as module load cuda or export OMP_NUM_THREADS=8, run as written. They cannot choose the Python: each job runs the driver's own interpreter, by its path. A shell variable is written $HOME, not ${HOME}: Hydra reads every ${...} as its own interpolation, so no line may hold one.

None
cells_per_job int

The cells each job runs, one after another, in one Python process; 1, the default, gives each cell a job of its own. The cells a sweep submits are grouped in order, so a job runs up to this many. timeout_min is the job's, for all of them, and array_parallelism counts jobs, not cells. What a cell leaves in the process (module state, GPU memory it still references) is there for the next.

1
check bool

Check the request against the cluster when this is called: see below.

True
**extra Any

Other fields of hydra-submitit-launcher's SLURM config, passed through unchecked (array_parallelism, constraint, gres, additional_parameters, ...), except one the helper has already written (nodes, tasks_per_node, and the field of each argument given). What they ask of SLURM, including more tasks, is yours.

{}

Returns:

Type Description
dict

The launcher config; nothing is submitted.

Notes

With check=True, on a machine with scontrol (where run() will submit from), it refuses a request SLURM would reject or never start, as scontrol states it: a partition that does not exist, or a time limit past the partition's MaxTime. It names the partitions whose time limit fits, and never picks one for you. It judges only a partition named here or in SBATCH_PARTITION (a job that names none can be routed by the cluster), and no time limit under a QoS, which can lift it (one that the account's default QoS lifts is not seen: pass check=False). GPUs and accounts are not judged: scontrol lists a partition's GPUs only where the cluster accounts for them, and an account may run in a partition through its parent account. Nothing is judged when scontrol is missing, slow or unreadable, when additional_parameters sets the partition, time, QoS or cluster (or SBATCH_CLUSTERS is set), or inside a job. The answer is kept for five minutes.

collect

collect(
    working_dir, metrics_filename="mushin_metrics.json"
)

Build the dataset of a sweep submitted with run(..., wait=False), once its jobs have ended.

run(launcher="submitit_slurm", wait=False, working_dir=...) submits the sweep's jobs and returns at once, so the driver need not stay connected while they queue and run. Collect then finishes the run as a waited run() would have: each cell whose job ended without a result (out of memory, scancel, a time limit) is recorded failed, the sweep manifest is written, the run's launch files and budget start file are removed, and the dataset is returned. Call it from a new Python session if you like: it needs no import of the script that ran the sweep. For a relative working_dir, call it from the directory run() was called in.

Parameters:

Name Type Description Default
working_dir str or PathLike

The run's working_dir.

required
metrics_filename str or Sequence[str]

For a run with nothing left to collect (collected already, run with wait=True, or its jobs cancelled with mushin.cancel): the metrics files load_from_dir reads. Collecting such a run reloads it and writes nothing.

'mushin_metrics.json'

Returns:

Type Description
Dataset

The sweep's dataset, as run() returns it.

Raises:

Type Description
FileNotFoundError

working_dir is not a sweep's directory.

RuntimeError

A job of the run has not ended: queued, running, or requeued after preemption (nothing is written; collect again later). Or a job's end cannot be read here: sacct gives no answer (the state reads UNKNOWN), or a submitit_local run was submitted from another host. Or the jobs' files cannot be loaded here: their submissions, or a result whose type does not import here (nothing is written; collect where it does). Or working_dir is not the dir the run was submitted in, but a copy or a move of it (nothing is written). Or, under on_error="raise", a cell failed: its own error is raised, once every cell is recorded, as a waited run raises it.

ImportError

The slurm extra is not installed.

Notes

A SLURM job's end is read from sacct, as submitit reads it; a submitit_local job's from its process, on the host that submitted it.

Collect unpickles the jobs' submission and result files under the sweep's .submitit/ folder, which hold the task and what it returned, so collect a working_dir you trust, with the task's code and the types it returns importable as in the jobs, and keep .submitit/ until the run is collected. While it waits on the jobs, collect sets Hydra's process-wide state to the driver's, and restores it after.

A job that died gives no result: collect waits for those files once, as long as submitit waits for one (15 seconds), then records the cells.

Examples:

>>> summary = sweep.run(seed=mushin.multirun([0, 1, 2]),
...                     launcher="submitit_slurm", working_dir="runs/a",
...                     wait=False)
>>> # later, perhaps from a new session
>>> ds = mushin.collect("runs/a")

cancel

cancel(working_dir, *, dry_run=False)

Cancel a sweep's SLURM jobs that are still queued or running.

Each submission of run(launcher="submitit_slurm") names the jobs it sent in a file under <working_dir>/mushin_jobs/, which its driver removes once it has waited on them, so the files that remain name jobs that may not have ended: a running sweep's, or those of a driver killed mid-sweep (Ctrl-C, a lost login session). cancel asks SLURM about each of their job arrays and runs scancel once, for those still queued or running. Call it where scontrol and scancel reach the cluster, such as a login node, with the driver running or not.

Parameters:

Name Type Description Default
working_dir str or PathLike

The sweep's working_dir.

required
dry_run bool

Return the ids it would cancel, and cancel and remove nothing.

False

Returns:

Type Description
list of str

The ids cancelled, one per job array (or per job, for a submission of one cell); with dry_run, the ids it would cancel.

Raises:

Type Description
FileNotFoundError

working_dir is not a directory.

RuntimeError

scontrol or scancel is not found, SLURM's answer about a job cannot be read (it took too long, failed, or is not in the expected form), or scancel fails. In the first two cases nothing is cancelled, and the message names the scancel command to run by hand.

Notes

A job is cancelled only while SLURM lists it as not ended and its script or log paths lie under the sweep's submitit folder. A job id SLURM has since given another job is left alone, with a warning. A job SLURM no longer lists (it forgets one some minutes after it ends) is over.

Once a submission's jobs are cancelled or over, its file is removed, so mushin.show no longer lists its cells as queued: a cell whose job never started shows its dir's earlier record, or no row. A driver still running records the cancelled cells as failed, and a later resume=True runs them again.

Two kinds of submission are not checked. A launcher="submitit_local" job's id is a process id on the machine that submitted it, not SLURM's: it is skipped with a warning, and its file is removed only on that machine, once none of its processes runs. A submission sent to other clusters (--clusters) is out of plain scontrol's sight: the warning names the scancel --clusters=... command to run, and its file is removed.

Resuming

A task that declares a mushin_resume parameter receives one of these per cell; the resilience guide shows the pattern.

ResumeContext dataclass

Handed to a task that declares a mushin_resume parameter.

Attributes:

Name Type Description
dir Path | None

The cell's working directory (already the cwd when the task runs).

is_resume bool

True when a prior attempt of the SAME combo left artifacts here.

last_ckpt Path | None

The newest checkpoint in dir that is this cell's own, or None. One another cell left in dir before this cell took it over (a sweep over another grid in the same working_dir) is not, nor is one this cell wrote under another config or task code (a resume after either changed): is_resume can then be True while this is None.

attempt int

1 on the first run; increments on each re-execution of this combo.