# mushin > Boilerplate-free, reproducible machine-learning experiment sweeps: a framework-agnostic sweep engine built on Hydra, with first-class PyTorch Lightning integration. Decorate an experiment, sweep its parameters, and get the results back as a labeled `xarray.Dataset`. Facts to get right when writing code that uses mushin: - Install with `pip install mushin-py`, import with `import mushin`. The PyPI name is not `mushin`. - The core install is the sweep -> dataset workflow. `compare`, the metric batteries, LLM evaluation (`mushin.llm`) and `Study` need the `eval` extra: `pip install "mushin-py[eval]"`. Other extras: `viz`, `netcdf`, `detection`, `image`, `audio`, `mcp`, `slurm`, `zen`. - mushin no longer imports hydra-zen; `mushin.multirun`, `mushin.hydra_list` and `run()`'s default task wrapper are mushin's own. hydra-zen is still installed with mushin, and from the next release only with the `zen` extra: code that imports hydra-zen (`builds`, `make_config`) should depend on `mushin-py[zen]`. - Supported Python: 3.11 to 3.15. - The public API is the top-level `mushin` namespace plus the documented `mushin.workflows`, `mushin.benchmark` and `mushin.llm` symbols. Modules whose names start with an underscore are internal. - A task returns a `dict` of metrics; each key becomes a data variable. Each `mushin.multirun([...])` argument becomes a dimension of the dataset. Use `mushin.hydra_list([...])` to pass a list as one value instead of sweeping it. - `pip install mushin-py` also installs torch (>= 2.4; >= 2.15 on Python 3.15) and pytorch-lightning, even for a task that never imports them. Intel macOS is not supported: PyTorch publishes no x86_64 macOS wheels after torch 2.2. - The sweep layer is framework-agnostic (scikit-learn, XGBoost, plain NumPy). `HydraDDP`, `MetricsCallback`, auto-tuning, `compare` and the batteries assume PyTorch / Lightning. - To set up, run and report an experiment, read the [agent guide](https://raw.githubusercontent.com/martinez-hub/mushin/main/src/mushin/agent_guide.md) first. On mushin 0.16 or later, `python -m mushin guide` prints the copy for the installed version; the web copy applies from mushin 0.10 on. ```python import mushin @mushin.sweep def experiment(lr, seed): accuracy = 0.9 - abs(lr - 0.1) + 0.001 * seed # train and evaluate here return dict(accuracy=accuracy) ds = experiment.run( lr=mushin.multirun([0.01, 0.1, 1.0]), seed=mushin.multirun([0, 1, 2]) ) ds["accuracy"].mean("seed") # dims (lr, seed); average over seeds experiment.workflow.to_dataframe() # the same results as a tidy pandas table ``` --- Source: https://martinez-hub.github.io/mushin/ # mushin Boilerplate-free, reproducible machine-learning experiment sweeps: a framework-agnostic sweep engine built on [Hydra](https://hydra.cc), with first-class [PyTorch Lightning](https://lightning.ai/) integration. `mushin` is the evaluate-and-report layer sitting on top of Hydra and, for deep learning, Lightning. Define your experiment as a function, sweep over parameters with Hydra, and get results back as a labeled `xarray.Dataset`, not rows in a dashboard you have to export. !!! tip "Highlights" - **`@mushin.sweep`.** The boilerplate-free core: decorate a function and `experiment.run(...)` returns the labeled dataset. See the [quickstart](https://martinez-hub.github.io/mushin/quickstart/). - **Resilient & resumable sweeps:** `on_error="nan"` fail-soft plus a durable `resume=True` that survives a hard process kill or SLURM preemption without recomputing finished cells. See [resilience](https://martinez-hub.github.io/mushin/guides/resilience/). - **Laptop → cluster, one code path:** out-of-process launchers (`launcher="joblib"` / submitit) and multi-GPU / multi-node training (`HydraDDP` / `HydraFSDP`, GPU packing), validated on real cluster hardware. See [multi-node training](https://martinez-hub.github.io/mushin/guides/multinode/). - **Lean core, opt-in eval:** the evaluation layer (`compare`, the batteries, LLM eval, `Study`) is the optional [`eval` extra](https://martinez-hub.github.io/mushin/install/#optional-extras); a plain install is just the sweep → dataset core. See the full [changelog](https://martinez-hub.github.io/mushin/changelog/) for every release. ## Three pillars **Sweeps → datasets.** `MultiRunMetricsWorkflow` runs a Hydra multirun, collects your returned metrics, and assembles them into a labeled `xarray.Dataset` keyed by the swept parameters. **`compare` with statistics.** *(optional [`eval` extra](https://martinez-hub.github.io/mushin/install/#optional-extras): `pip install "mushin-py[eval]"`)* `benchmark.compare` evaluates a set of trained models on a standard metric battery (torchmetrics), then runs pairwise significance tests (scipy) with multiple-comparison correction (Holm by default; also Bonferroni/FDR/none). The result is a `BenchmarkResult` with a paper-ready `.summary()`, tidy `.comparisons` DataFrame, and a labeled `.data` dataset. **`Study`.** `Study` orchestrates the full pipeline (multi-seed training sweep via Hydra, then straight into `compare`) in one call. `Study.from_checkpoints` handles the eval-only case when you already have checkpoints. ## Quick example ```python import torch as tr from mushin import multirun from mushin.workflows import MultiRunMetricsWorkflow class LRSweep(MultiRunMetricsWorkflow): @staticmethod def task(lr: float, seed: int) -> dict: tr.manual_seed(seed) # ... train a model, then evaluate it ... acc = ... # your validation accuracy return dict(accuracy=acc) wf = LRSweep() wf.run(lr=multirun([0.01, 0.1, 1.0]), seed=multirun([0, 1, 2])) # 9 runs ds = wf.to_xarray() # Dimensions: (lr: 3, seed: 3) # Data variables: accuracy (lr, seed) ds["accuracy"].mean("seed") # average over seeds, per learning rate ``` ## Get started - [Install](https://martinez-hub.github.io/mushin/install/): pip, extras, and the support matrix - [Quickstart](https://martinez-hub.github.io/mushin/quickstart/): run the flagship sweep example end-to-end - [Tutorial](https://martinez-hub.github.io/mushin/tutorial/): a longer guided pass through a real sweep - [Core concepts](https://martinez-hub.github.io/mushin/concepts/): the mental model behind workflows and datasets - [Example notebooks](https://martinez-hub.github.io/mushin/notebooks/01_sweep_to_dataset/): seven runnable notebooks, executed in CI: sweeps → datasets, compare & batteries, studies, resilient sweeps, LLM eval, scikit-learn, and analyzing results - [Guides](https://martinez-hub.github.io/mushin/guides/workflows/): workflows, compare, Study, segmentation, MCP - [API Reference](https://martinez-hub.github.io/mushin/reference/benchmark/): full auto-generated docs --- Source: https://martinez-hub.github.io/mushin/install/ # Install ## Basic install ```bash pip install mushin-py ``` Already use [uv](https://docs.astral.sh/uv/)? ```bash uv pip install mushin-py # or, inside a uv project: uv add mushin-py ``` !!! note "Install name vs. import name" The PyPI distribution is **`mushin-py`**, but you `import mushin`: the same pattern as `scikit-learn` → `sklearn`. ## Optional extras The core install is the sweep → dataset workflow. The **evaluation layer** (`compare`, the metric batteries, LLM evaluation, and `Study`) is the `eval` extra. Accessing those features without it raises a clear install hint. | Extra | What it adds | Install | |---|---|---| | `eval` | `compare`, metric batteries, LLM eval, `Study` (adds torchmetrics, scipy) | `pip install "mushin-py[eval]"` | | `viz` | matplotlib (for plotting results) | `pip install "mushin-py[viz]"` | | `netcdf` | netCDF4 (save/load datasets as `.nc` files) | `pip install "mushin-py[netcdf]"` | | `mcp` | MCP server (`mushin-mcp`) for Claude Code integration | `pip install "mushin-py[mcp]"` | | `slurm` | the Hydra launcher behind `launcher="submitit_slurm"`, which submits each cell to a SLURM cluster (adds hydra-submitit-launcher) | `pip install "mushin-py[slurm]"` | | `zen` | hydra-zen, to build configs with `builds` and `make_config` (installed with mushin until the next release; see below) | `pip install "mushin-py[zen]"` | | `detection` / `image` / `audio` | extra metric batteries (imply `eval`) | `pip install "mushin-py[detection]"` | Combine extras with commas, e.g. `pip install "mushin-py[eval,viz]"`. !!! note "hydra-zen becomes the `zen` extra" mushin no longer imports hydra-zen: the task wrapper and the `multirun`/`hydra_list` markers it used from hydra-zen are its own. This release still installs hydra-zen with mushin; the next one installs it only with the `zen` extra. If your code imports hydra-zen (`builds`, `make_config`, as the guides' examples do), add `mushin-py[zen]`, or hydra-zen itself, to your dependencies now. See [hydra-zen](https://martinez-hub.github.io/mushin/guides/workflows/#hydra-zen) in the workflows guide. ## Support matrix | Platform | Python | torch | NumPy | |---|---|---|---| | Linux / Windows / macOS (Apple Silicon) | 3.11 – 3.15 | ≥ 2.4 (≥ 2.15 on 3.15) | ≥ 2 | A few notes: - **pytorch-lightning ≥ 2.4** is required on all platforms. - **Apple Silicon (M-series)**: fully supported. The CI suite runs on Apple Silicon on every pull request. The sweep engine has no device code, and training on the M-series GPU goes through Lightning's MPS accelerator: build your `Trainer` with `accelerator="mps"` (or `"auto"`, which selects MPS) inside your task. Auto-tuning and the eval layer follow your model's device, and provenance records the MPS chip. The multi-GPU / cluster features (`HydraDDP`/`HydraFSDP`, `pin_gpu_round_robin`, `submitit_slurm_config`) are simply not applicable on a single-chip Mac; `launcher="joblib"` still parallelizes sweep *cells* across CPU cores as usual. - **Intel macOS (x86_64)** is not supported: PyTorch publishes no x86_64 macOS wheels after torch 2.2, and `mushin` requires torch ≥ 2.4 and NumPy 2. The last release series that supports Intel Macs is 0.14.x, which supports them on Python 3.10 and 3.11 (newer Pythons are unsupported there, and torch 2.2 has no wheels for Python 3.13+): `python3.11 -m pip install "mushin-py<0.15"`. - **Python 3.10** is not supported: it reached end-of-life on 2026-10-01, and `mushin` requires Python ≥ 3.11. - **Python 3.15** needs torch 2.15 or later, the first release with 3.15 wheels, and on a Mac those wheels need macOS 14 or later. PyYAML has no 3.15 wheel yet, so pip builds it from source. Without libyaml's headers that build has no C parser, and mushin reads each run's `hydra.yaml` through OmegaConf instead: the same results, more slowly when you reload a large sweep. - These floors are enforced by the `min-versions` CI job on every pull request. --- Source: https://martinez-hub.github.io/mushin/quickstart/ # Quickstart This page walks through the flagship example: run a parameter sweep and get the results back as a labeled `xarray.Dataset`. The decorator flow below runs as `examples/parallel_sweep.py` in the repository; `examples/sweep_to_dataset.py` is the same flow written with the class API (`MultiRunMetricsWorkflow`), which this page introduces further down. Decorate a function with `@mushin.sweep`, sweep it over a grid, and get results back as a labeled `xarray.Dataset`: no subclassing, no callbacks. Whatever the function returns as a `dict` becomes data variables in the output dataset. ```python import mushin @mushin.sweep def experiment(lr, seed): ... # train, evaluate return dict(accuracy=acc) # returned dict -> dataset variables ds = experiment.run( lr=mushin.multirun([0.01, 0.1, 1.0]), seed=mushin.multirun([0, 1, 2]), ) ``` **Prefer pandas?** You never have to touch xarray: one call turns the sweep into a tidy long-form table (one row per cell, params and metrics as columns): ```python df = experiment.workflow.to_dataframe() # or ds.to_dataframe().reset_index() # lr seed accuracy # 0 0.01 0 0.914 # 1 0.01 1 0.907 # ... df.groupby("lr")["accuracy"].mean() # plain pandas from here on ``` The labeled dataset is still the richer object (`.sel`, `.mean("seed")`, provenance in `attrs`, netCDF round-trip), but it's an option, not a prerequisite. Need the full tool (`.failures`, `.plot()`, provenance, custom `to_xarray`)? Drop to `experiment.workflow` (the last-run instance), or use the `MultiRunMetricsWorkflow` class directly (shown next). ## Going deeper: the workflow class For advanced control (custom `pre_task`, `jobs_post_process`, subclassing like `mushin.workflows.RobustnessCurve`), subclass `MultiRunMetricsWorkflow` and implement a static `task` method. This is exactly what `@mushin.sweep` builds for you: ```python import torch as tr from mushin import multirun from mushin.workflows import MultiRunMetricsWorkflow LEARNING_RATES = [0.01, 0.1, 1.0] SEEDS = [0, 1, 2] POINTS_PER_CLASS = 256 def _make_data(seed: int, n: int = POINTS_PER_CLASS) -> tuple[tr.Tensor, tr.Tensor]: g = tr.Generator().manual_seed(seed) x0 = tr.randn(n, 2, generator=g) + tr.tensor([2.0, 2.0]) x1 = tr.randn(n, 2, generator=g) + tr.tensor([-2.0, -2.0]) x = tr.cat([x0, x1]) y = tr.cat([tr.zeros(n), tr.ones(n)]) return x, y class LRSweep(MultiRunMetricsWorkflow): @staticmethod def task(lr: float, seed: int) -> dict: tr.manual_seed(seed) x, y = _make_data(seed) model = tr.nn.Linear(2, 1) opt = tr.optim.SGD(model.parameters(), lr=lr) for _ in range(100): opt.zero_grad() logits = model(x).squeeze(1) loss = tr.nn.functional.binary_cross_entropy_with_logits(logits, y) loss.backward() opt.step() with tr.no_grad(): preds = (model(x).squeeze(1) > 0).float() acc = (preds == y).float().mean().item() # returning the dict is what populates the dataset; saving is optional result = dict(accuracy=acc) tr.save(result, "metrics.pt") return result ``` ## Run the sweep Call `wf.run(...)` with `multirun(...)` wrapped arguments. Hydra launches one job per combination: 3 learning rates × 3 seeds = 9 runs total. ```python wf = LRSweep() wf.run( lr=multirun(LEARNING_RATES), seed=multirun(SEEDS), ) ``` > **Heads up:** your `task()` runs in a per-job directory. If it reads or writes > files by relative path, wrap them with `mushin.original_cwd() / "..."`. See > [Concepts](https://martinez-hub.github.io/mushin/concepts/#working-directories). ## Get results as a dataset ```python ds = wf.to_xarray() print(ds) ``` Expected output: ``` Dimensions: (lr: 3, seed: 3) Coordinates: * lr (lr) float64 0.01 0.1 1.0 * seed (seed) int64 0 1 2 Data variables: accuracy (lr, seed) float64 ... ``` From there, standard xarray/pandas operations apply: ```python # average accuracy across seeds, per learning rate mean_acc = ds["accuracy"].mean("seed") print(mean_acc) # plot import matplotlib.pyplot as plt mean_acc.plot.line(x="lr", marker="o") plt.xscale("log") plt.savefig("sweep_accuracy.png", dpi=120, bbox_inches="tight") ``` ## Run the full example ```bash uv run python examples/sweep_to_dataset.py ``` ## Next steps - [Workflows & sweeps guide](https://martinez-hub.github.io/mushin/guides/workflows/): more on `BaseWorkflow` and `MultiRunMetricsWorkflow` - [Comparing methods guide](https://martinez-hub.github.io/mushin/guides/compare/): evaluate trained models with statistics - [Studies guide](https://martinez-hub.github.io/mushin/guides/study/): combine training + compare in one call - [API Reference: workflows](https://martinez-hub.github.io/mushin/reference/workflows/) --- Source: https://martinez-hub.github.io/mushin/for-agents/ # For AI agents mushin ships a usage guide for AI coding agents (Claude Code, Codex, Cursor and the like) that set up experiments for scientists and engineers. It covers which API to use for which job, a tested template, the pitfalls that give wrong results, how to run long sweeps from an agent, and what to check before reporting. This page shows the guide from the main branch; from mushin 0.16, `python -m mushin guide` prints the copy that matches the installed version. ## Claude Code Install the guide as a skill from this repository's plugin marketplace, then load it with `/mushin:guide` before writing or changing an experiment: ```text /plugin marketplace add martinez-hub/mushin /plugin install mushin@mushin ``` On Claude Code 2.1.275 or later, one command does both: `/plugin install mushin --marketplace martinez-hub/mushin`. The skill runs `python -m mushin guide` in your project, so it always shows the guide for the installed mushin (0.16 or later; install it first with `pip install "mushin-py[eval]"`). With `mushin-mcp` connected (see [Analyzing from Claude Code](https://martinez-hub.github.io/mushin/guides/mcp/)), the guide is also the `/mushin:guide (MCP)` prompt and the `@mushin:mushin://guide` resource. ## Point your agent at it For any agent, add this to your project's `AGENTS.md` or `CLAUDE.md`: ```text This project uses mushin. Install it with `pip install "mushin-py[eval]"` (the `eval` extra adds the statistics; not `pip install mushin`, a PyPI name that is not this project). Before writing or changing an experiment, run `python -m mushin guide` and follow it. On mushin 0.10 to 0.15, read https://raw.githubusercontent.com/martinez-hub/mushin/main/src/mushin/agent_guide.md instead; before 0.10, upgrade first. ``` To give an agent the whole site at once, point it at [llms-full.txt](https://martinez-hub.github.io/mushin/llms-full.txt): every page but the contributing guide and the changelog, as one Markdown file, with the example code and the API reference inlined. [llms.txt](https://martinez-hub.github.io/mushin/llms.txt) is the short index of the same pages. To let an agent inspect finished runs, see [Analyzing from Claude Code](https://martinez-hub.github.io/mushin/guides/mcp/): `mushin-mcp` is a read-only MCP server over a directory of runs. --- This guide is for a coding agent setting up an experiment for a scientist or engineer. The copy that `python -m mushin guide` prints matches the installed mushin, whose version is its first line. A copy read from the web describes the newest mushin; most of it applies from 0.10 on. For exact signatures, use `help(obj)`. ## What mushin is mushin runs a Python function over a grid of parameters and seeds, and returns the results as a labeled `xarray.Dataset` (or a pandas table), with each run's provenance and paired statistics across seeds. The function can use any framework: scikit-learn, XGBoost, plain NumPy or PyTorch. torch and pytorch-lightning are installed with mushin either way; they also power the optional evaluation layer (metric batteries, `compare`, `Study`). ## Install The PyPI name is `mushin-py`, and the import is `import mushin`. The PyPI package named `mushin` is not this project. | Install | Adds | |---|---| | `pip install mushin-py` | sweeps to datasets, provenance, resume | | `pip install "mushin-py[eval]"` | `compare_methods` (needs scipy), `compare`, metric batteries, `mushin.llm`, `Study` | | `pip install "mushin-py[viz]"` | matplotlib, for plots | | `pip install "mushin-py[netcdf]"` | saving datasets as `.nc` files | | `pip install "mushin-py[mcp]"` | `mushin-mcp`, a read-only MCP server over finished runs | | `pip install "mushin-py[detection]"` (or `image`, `audio`) | more metric batteries | | `pip install "mushin-py[slurm]"` | `launcher="submitit_slurm"`, to submit cells to a SLURM cluster (adds hydra-submitit-launcher) | | `pip install "mushin-py[zen]"` | hydra-zen, for configs built with `builds` or `make_config`. mushin itself no longer imports it; it is installed with mushin until the next release, then only with this extra | | `pip install hydra-joblib-launcher` | `launcher="joblib"`, to run cells in parallel (a Hydra plugin, not an extra) | | `pip install hydra-ray-launcher` | the Ray launcher, to pack several jobs onto each GPU (a Hydra plugin, not an extra) | Python 3.11 to 3.15 is supported. Intel macOS is not. ## Choosing an entry point | Job | Use | |---|---| | Run a function over a grid of parameters and seeds | `@mushin.sweep` | | Collect results yourself, or train with Lightning | `mushin.MultiRunMetricsWorkflow` | | Compare methods across seeds, with significance | `mushin.benchmark.compare_methods` | | Score torch models on a metric battery | `mushin.compare` | | Train several methods, then compare them | `mushin.Study` | | Compare LLM systems | `mushin.llm` | | Inspect finished runs | `mushin.show`, `mushin.best`, `mushin.diff`, or the MCP server | | Run cells in parallel on one machine | `launcher="joblib"` | | Run several jobs on each GPU | Ray; see the GPU packing guide (Going further). `pin_gpu_round_robin` needs a fresh process per job, which joblib stops giving once cells outnumber `n_jobs` | | Run each cell as a SLURM job | `launcher="submitit_slurm"` with `launcher_config=mushin.slurm(...)`; for many short cells, `mushin.slurm(..., cells_per_job=20)` runs 20 cells per job; add `wait=False` to submit and return at once, then `mushin.collect(working_dir)` once the jobs have ended. See the SLURM guide (Going further) | | Train one cell across several GPUs or nodes | the multi-node guide (see Going further) | ## A template experiment Write the experiment as one script in the scientist's project. Leave their code where it is: the sweep task is a new module-level function that calls it and returns a dict of numbers. Do not put `@mushin.sweep` on their function. It replaces the function with a sweep handle, which cannot be called, so their other call sites break. The template's statistics need the `eval` extra: `pip install "mushin-py[eval]"`. ```python import random import mushin from mushin.benchmark import compare_methods # The scientist's code. Import theirs; this stub stands in for it. def train_and_evaluate(method: str, lr: float, seed: int) -> float: rng = random.Random(seed) base = {"baseline": 0.70, "new": 0.75}[method] return base - abs(lr - 0.01) + rng.gauss(0, 0.005) # The sweep task: a new module-level function that calls their code and # returns a dict of numbers. Never decorate their function itself. @mushin.sweep def experiment(method: str, lr: float, seed: int): return {"score": float(train_and_evaluate(method, lr, seed))} GRID = dict( method=mushin.multirun(["baseline", "new"]), lr=mushin.multirun([0.001, 0.01]), seed=mushin.multirun(list(range(6))), # 6 seeds: the floor for 2 methods ) RUN_DIR = "runs/compare-v1" # under a gitignored runs/; one per sweep if __name__ == "__main__": plan = experiment.run(**GRID, working_dir=RUN_DIR, dry_run=True) assert plan["num_cells"] == 24, plan ds = experiment.run(**GRID, working_dir=RUN_DIR, on_error="nan") print(experiment.workflow.to_dataframe().head()) # compare_methods needs exactly the dims (method, seed): select lr away. table = compare_methods(ds.sel(lr=0.01)) print(table) # mean_diff = method_a - method_b print("results in", experiment.workflow.working_dir) ``` What it does: - `dry_run=True` prints the grid and returns `{"num_cells", "axes", "fixed", "working_dir"}` without running anything. Check `num_cells` before every expensive run. - Each `mushin.multirun([...])` argument becomes a dimension of `ds`, here `(method, lr, seed)`. A plain value, such as `lr=0.01`, is fixed for every cell. - `experiment.workflow` is the `MultiRunMetricsWorkflow` of the latest `run()` call, a dry run included: read its `failures`, `skipped`, `working_dir` and `to_dataframe()` right after the run you care about. - `compare_methods` runs a paired test (Wilcoxon by default) for each pair of methods across seeds, and corrects the p-values for the number of pairs (Holm). Its table has `mean_diff` and `effect_size`, the raw and corrected p-values, and `significant`. `mean_diff` is `method_a - method_b`, so a negative value means `method_b` scored higher. ## Rules that prevent wrong results and wasted compute Sweep a value with `mushin.multirun([...])`. A bare list raises: ```python try: experiment.run(method=["baseline", "new"], lr=0.01, seed=0, dry_run=True) except TypeError as e: print(e) # ... wrap them: `method=mushin.multirun(['baseline', 'new'])` ... ``` To pass a list as one value instead, use `mushin.hydra_list([...])`. The other rules: - **Return a dict of numbers.** The values are converted to JSON into each cell's `mushin_metrics.json`. - **Each cell runs in its own directory**, so a relative path in the task resolves there, not in the project. Build input paths from `mushin.original_cwd()`, for example `mushin.original_cwd() / "data" / "train.csv"`. - **Check the size first.** Run with `dry_run=True` before anything expensive. `confirm_above=N`, or the `MUSHIN_MAX_CELLS` environment variable, refuses a grid of more than `N` cells. `max_total_seconds=T` stops starting cells `T` seconds after the first cell that computes, and records the rest as skipped. A later `resume=True` runs them, with no time limit unless it passes `max_total_seconds` again, which starts a new clock. Under `launcher="joblib"` every worker honors the same deadline, so `T` bounds the elapsed time, not the compute summed over the workers, and each worker can finish a cell it started just before the deadline: the sweep can run past `T` by up to one cell per worker. - **Failures.** With `on_error="nan"`, the sweep goes on when a cell raises: the cell becomes NaN, `experiment.workflow.failures` lists it, and its traceback is in `mushin_error.txt` in the cell's directory (for a SLURM job that ended without returning, killed or unable to import the task, submitit's message and the path to the job's log). `compare_methods` then refuses the incomplete grid with `IncompleteSweepError`, unless you pass `allow_incomplete=True`. Fix the cause, then rerun the same script with `resume=True`. - **Explore with `sample=N`.** It runs N cells of the grid and records the rest as skipped; a later run with `resume=True` and no `sample` fills them in. - **Resume.** `resume=True` with the same `working_dir` reruns the cells that are incomplete or whose config, task function or project code changed: every project file the task's module (and `pre_task`'s) imports, directly or through other project files, and the modules of the classes the config names as `_target_`, each with its packages' `__init__.py`. An edit anywhere in such a file re-runs the cells; a comment, a docstring or formatting does not (any edit to the task function's own source does, a comment included). In the driver script, only what the task's definition can reach by name counts, not the `run(...)` call, top-level calls, `print` calls or what only they read, so extending the grid is not an edit. In a notebook, the functions and classes its cells define that the task reaches by name, or that an annotation of that code names (a string one too; not through a type alias such as `Opt = Optional[Helper]`), count, by their definitions, as the kernel holds them when the run starts; no value does (a number, a model name, a dict config), so pass values as swept parameters. On Python 3.13 and earlier, after editing a class an annotation that is not a string names, re-run the cell that annotates with it too. For such a task, every project module a cell imports counts too, so with `cache_dir=`, importing another one in a cell can make the cells compute again. Re-running a class's cell when mushin cannot tell its version apart from another kept one (a class a function makes, or on 3.11/3.12 a cell stating it twice) can make a resume re-run the cells too. 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 the cells 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 a cell's `import` statement (`importlib.import_module`, a plugin loader, an import in a `%%time` cell) may not be compared, nor may a module named only in a string annotation (`"pkg.sub.Model"`), nor may a class no `class` statement makes (`type(...)`, `make_dataclass`), or a class of which one cell holds more than one version (two `class` statements run, or a statement and a class bound from elsewhere), nor what an IPython input transformer changes in a cell, nor 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 also re-run the cells), and a class a background thread or a callback makes while a cell runs may be taken for that cell's: after editing one, use a new `working_dir`. `run()` can import an `importlib.util.LazyLoader` module that has not run yet, even one the task does not use: import such modules before `run()`. Resume does not see an installed package, data files, or code reached only through some other string. After such a change, use a new `working_dir`. `cache_dir=` keys on the same fingerprints. Hydra still lists every cell when a resume launches; the completed ones return their saved metrics without running. - **`compare_methods` needs exactly two dims, `method` and `seed`,** and string `method` values. Select or average away other dims on the Dataset first: `ds.sel(lr=0.01)`, or `ds.mean("lr", keep_attrs=True)` (older xarray drops attrs in a reduction unless asked). The record of failed cells lives in `ds.attrs`, and `compare_methods` checks it there: `ds["score"]`, and anything built from it, has lost it, so an incomplete sweep would be compared without a word. Check `wf.is_complete` before comparing. Rename yours if needed (`ds.rename({"model": "method"})`). To pick one method, use `ds.sel({"method": "new"})`: `ds.sel(method="new")` does not select, since `method` is also a keyword of `sel`. A method whose score is the same for every seed gets NaN for its pairs, with a warning. - **Seeds.** With `k` methods there are `m = k * (k - 1) / 2` pairs, and with Wilcoxon a pair can only be significant at 0.05 if `m * 2 ** (1 - n) < 0.05` for `n` seeds. So use at least 6 seeds for 2 methods, 7 for 3 and 8 for 4; `compare_methods` warns when the seed count cannot reach significance for the pairs it corrects over. These are floors, not enough power: a real but small difference needs more seeds. - **Make each seed an independent repeat.** The statistics treat seeds as independent. If each seed only re-splits one small dataset into train and validation, the runs share most of their data and the p-values come out too small. Prefer a fixed held-out test set, with the seed varying only the model's own randomness (initialization, data order, subsampling). Otherwise say so in the report: `compare_methods` has no correction for overlapping splits. - **Choose on some seeds, test on others.** Pick settings (a learning rate, a regularization strength) on exploration seeds, then run the comparison on fresh seeds: choosing and testing on the same seeds overstates the winner. If a knob means something different for each method, sweep a level (`level=mushin.multirun(["low", "high"])`) and map it to each method's value inside the task. Then select each method at its own level on the Dataset, for example `ds.sel(level=xr.DataArray(["high", "low"], dims="method"))` (in the order of `ds["method"]`), which keeps the record of failed cells. - **Commit before the final runs.** Each cell's `mushin_provenance.json` records the git commit and whether the tree was dirty, and untracked files count. Add `runs/`, `__pycache__/` and any logs to `.gitignore`, commit, and check that `git status --porcelain` prints nothing before the final run. - **Record the environment of the final run** with `capture_env=True`: it writes the full package list to `mushin_env.txt` in the sweep directory. Each cell's provenance lists only mushin's own stack (torch, numpy, Lightning, Hydra), not, for example, scikit-learn. - **`best()` is per cell unless you pass `over=`.** `mushin.best(root, "score")` returns the single best cell, which is one seed. To pick a configuration, average over seeds: `mushin.best(root, "score", over="seed")` returns the configuration with the best mean, counting only configurations with a result at every seed another has (older versions: `ds["score"].mean("seed")`). - **On Windows, set `PYTHONUTF8=1`** (or run `python -X utf8`) when output is captured: a pipe then writes in the ANSI code page (cp1252 on Western systems), and printing a character it lacks fails. mushin's own console output does not fail there (except `python -m mushin guide --path`, which exits with an error rather than print a path the code page cannot show), but the rest of a run (your code, the libraries it calls, their logs) still can, so set it anyway. ## Running long sweeps from an agent An agent's shell commands time out, and a sweep can take hours. Put the sweep in a script, like the template, with a fixed `working_dir` under the gitignored `runs/`, and start it in the background, with its log under `runs/` too: ```bash mkdir -p runs date -u "+%Y-%m-%d %H:%M" # note when it started, in UTC nohup python experiment.py > runs/compare-v1.log 2>&1 & ``` Then poll it: ```bash python -c "import mushin; mushin.show('runs/compare-v1')" ``` `show` prints one row per cell that has started, with its status (`running`, `completed`, `failed` or `skipped`) and metrics; on the submitit launchers, a cell whose job is submitted but has not started is `queued`. After the rows it prints the latest run's progress, for example `run 3f2a9c1e, started 2026-11-29 10:02 UTC: 12 of 24 cells done (11 completed, 1 failed), 2 running, 10 not started; not finished`, and returns it as `.progress`. Go by that line, not by counting rows: a reused `working_dir` keeps an earlier run's rows, `completed` ones included, until this run reaches each cell, and the line counts them as rows from an earlier run, not as done. The line describes the run your script started only once its `started` time is no earlier than the time you noted. Before the script launches its cells (while it imports and checks its arguments), the line is still the previous run's, which may read `finished`; with a fresh `working_dir` there is no line yet, and `.progress` is `None`. If the script exits before its run appears, it failed before launching: its log says why. The run has finished once it has written its manifest: ```bash python -c "import mushin; p = mushin.show('runs/compare-v1').progress; print(p and (p.started.isoformat(), p.finished))" ``` If the process has exited and `finished` is `False`, the run stopped early: it raised (under the default `on_error="raise"`, a failed cell makes the run raise, and the log ends with the traceback) or it was killed. Fix the cause, then rerun with `resume=True`. In mushin 0.20 and earlier, `show` prints no progress line: there, count the `completed` rows against the dry run's `num_cells`, in a `working_dir` no earlier run used. Use the default launcher for a sweep you run this way. If the process died with cells still `running`, check that nothing from that run is still alive before you relaunch the same script with `resume=True`: with `launcher="joblib"`, the worker processes outlive the main one and keep computing cells. On SLURM the jobs keep running too, and a `run()` on that `working_dir` refuses to start while it finds them queued or running; `mushin.cancel(working_dir)` cancels them and returns their ids (with `dry_run=True` it only lists them). To leave a SLURM sweep running without a live process, pass `wait=False`: `run()` submits the jobs and returns a dict (`working_dir`, `run_id`, `submitted`, `job_ids`) instead of the result. Once the jobs have ended, `mushin.collect(working_dir)` returns the dataset, from any session (for a relative `working_dir`, one in the directory `run()` was called in); it raises, writing nothing, while any job is queued or running. A `run()` on that `working_dir` is refused until the run is collected or its jobs have ended. ## Where results go, and how to reload them A sweep writes to its `working_dir`, or by default to `multirun//