Skip to content

Benchmark extension points

The classes you use to add tasks, scenarios, methods and runtimes. See Extending the benchmark for worked examples.

Tasks

TaskSpec dataclass

TaskSpec(name: str, build_loaders: Callable[[int, int], tuple[DataLoader, DataLoader]], build_test_loader: Callable[[int], DataLoader], build_model: Callable[[], Module], batch_size: int, lr: float, lr_range: tuple[float, float], data_paths: tuple[str, ...] = (), prepare_data: Callable[[], None] | None = None)

A dataset and model pair, with its training defaults.

Register one with TASKS.add(name, TaskSpec(...)), in a plugin file or in autotunenet.bench.tasks.

Attributes:

Name Type Description
name str

Task name, as used in experiment files.

build_loaders Callable[[int, int], tuple[DataLoader, DataLoader]]

(batch_size, seed) -> (train_loader, val_loader). The train/validation split must depend only on seed, so every method sees the same split.

build_test_loader Callable[[int], DataLoader]

(batch_size) -> test_loader, the held-out split, used once to report the final model.

build_model Callable[[], Module]

() -> nn.Module, a freshly initialised model.

batch_size int

Batch size used by every method.

lr float

Default initial learning rate.

lr_range tuple[float, float]

(low, high) learning-rate range searched (log scale) by every tuning method.

data_paths tuple[str, ...]

Files or folders the task reads, relative to the data directory (autotunenet.bench.paths.data_dir()). Hosted runtimes upload these, e.g. ("MNIST/raw",).

prepare_data Callable[[], None] | None

() -> None, downloads the data into the data directory if missing; used by autotunenet data.

Examples:

>>> TASKS.add("my_task", TaskSpec(
...     name="my_task", build_loaders=my_loaders, build_test_loader=my_test_loader,
...     build_model=MyModel, batch_size=64, lr=0.01, lr_range=(1e-4, 1e-1),
...     data_paths=("my_task",), prepare_data=download_my_task,
... ))

Scenarios

Scenario

What happens to a training run besides the method's own decisions.

Examples are label noise or gradient noise starting mid-run, or a bad initial learning rate. Register a subclass with @SCENARIOS.register("name"); its constructor keyword arguments come from the experiment file, and a seed argument receives the run's seed.

Attributes:

Name Type Description
shift_epoch int | None

First epoch trained under a shift, or None if there is none.

overrides_initial_lr bool

True if every method, including population methods, must start from initial_lr(task).

initial_lr

initial_lr(task) -> float

Learning rate every method starts from (default: the task's lr).

Source code in src/autotunenet/bench/scenarios/base.py
def initial_lr(self, task) -> float:
    """Learning rate every method starts from (default: the task's `lr`)."""
    return task.lr

on_epoch_start

on_epoch_start(epoch: int, trainer) -> None

Called before each training epoch; may change the trainer's data or add hooks.

Source code in src/autotunenet/bench/scenarios/base.py
def on_epoch_start(self, epoch: int, trainer) -> None:
    """Called before each training epoch; may change the trainer's data or add hooks."""
    pass

Methods

Method

Bases: ABC

A way of choosing the learning rate, compared by the benchmarks.

Register a subclass with @METHODS.register("name"). Its constructor keyword arguments come from the method's entry in the experiment file. Subclass SingleRunMethod instead when the method trains one model.

run abstractmethod

run(ctx: RunContext, ledger: ComputeLedger) -> RunOutcome

Train for one cell and report the chosen model.

Create models with ctx.new_trainer() and ctx.new_scenario(), record every epoch of every model in ledger, and evaluate the test split only once, for the reported model.

Parameters:

Name Type Description Default
ctx RunContext

The cell to run.

required
ledger ComputeLedger

Compute accounting to update.

required

Returns:

Type Description
RunOutcome

The reported model's test metrics and per-epoch history.

Source code in src/autotunenet/bench/core/method.py
@abstractmethod
def run(self, ctx: RunContext, ledger: ComputeLedger) -> RunOutcome:
    """
    Train for one cell and report the chosen model.

    Create models with `ctx.new_trainer()` and `ctx.new_scenario()`, record
    every epoch of every model in `ledger`, and evaluate the test split
    only once, for the reported model.

    Args:
        ctx: The cell to run.
        ledger: Compute accounting to update.

    Returns:
        The reported model's test metrics and per-epoch history.
    """
    ...

SingleRunMethod

Bases: Method

A method that trains one model and adjusts it after each epoch.

The model is trained with Adam from the scenario's initial learning rate for ctx.epochs epochs; the Controller from make_controller runs after every epoch, and the test split is evaluated once at the end.

make_controller abstractmethod

make_controller(optimizer: Optimizer, ctx: RunContext) -> Controller

Build the controller for one run.

Parameters:

Name Type Description Default
optimizer Optimizer

The Adam optimizer training the model; the controller may change its param_groups.

required
ctx RunContext

The cell being run.

required
Source code in src/autotunenet/bench/core/method.py
@abstractmethod
def make_controller(self, optimizer: torch.optim.Optimizer, ctx: RunContext) -> Controller:
    """
    Build the controller for one run.

    Args:
        optimizer: The Adam optimizer training the model; the controller may
            change its `param_groups`.
        ctx: The cell being run.
    """
    ...

Controller

Bases: ABC

Per-epoch decision logic of a single-run method (e.g. a scheduler step).

Only on_epoch_end is required; the other hooks do nothing unless overridden.

on_train_start

on_train_start(model: Module) -> None

Called once before training, with the model being trained.

Source code in src/autotunenet/bench/core/method.py
def on_train_start(self, model: torch.nn.Module) -> None:
    """Called once before training, with the model being trained."""

on_batch_end

on_batch_end(loss: float) -> None

Called after every optimizer step with the batch's training loss.

Source code in src/autotunenet/bench/core/method.py
def on_batch_end(self, loss: float) -> None:
    """Called after every optimizer step with the batch's training loss."""

on_train_end

on_train_end() -> None

Called after the last epoch, before the test split is evaluated.

Source code in src/autotunenet/bench/core/method.py
def on_train_end(self) -> None:
    """Called after the last epoch, before the test split is evaluated."""

on_epoch_end abstractmethod

on_epoch_end(epoch: int, val_loss: float) -> None

Called after each epoch's validation.

Parameters:

Name Type Description Default
epoch int

Index of the epoch just trained (from 0).

required
val_loss float

Validation loss after that epoch.

required
Source code in src/autotunenet/bench/core/method.py
@abstractmethod
def on_epoch_end(self, epoch: int, val_loss: float) -> None:
    """
    Called after each epoch's validation.

    Args:
        epoch: Index of the epoch just trained (from 0).
        val_loss: Validation loss after that epoch.
    """
    ...

extra

extra() -> dict[str, Any]

Method-specific details to store with the result.

Source code in src/autotunenet/bench/core/method.py
def extra(self) -> dict[str, Any]:
    """Method-specific details to store with the result."""
    return {}

RunContext dataclass

RunContext(task: Any, scenario_name: str, scenario_params: dict[str, Any], seed: int, device: device, epochs: int, options: dict[str, Any] = dict())

Everything a method needs to train one cell (method x task x scenario x seed).

Attributes:

Name Type Description
task Any

The TaskSpec.

scenario_name str

Registered name of the scenario.

scenario_params dict[str, Any]

Scenario arguments from the experiment file.

seed int

The run's seed; fixes the data split and initial weights.

device device

Torch device to train on.

epochs int

Epochs per trained model (the experiment's epochs).

options dict[str, Any]

Extra options.

new_scenario

new_scenario()

A fresh scenario instance (each trained model needs its own).

Scenarios that take a seed get the run seed unless the experiment pins one, so noise differs across seeds but is reproducible.

Source code in src/autotunenet/bench/core/method.py
def new_scenario(self):
    """
    A fresh scenario instance (each trained model needs its own).

    Scenarios that take a `seed` get the run seed unless the experiment
    pins one, so noise differs across seeds but is reproducible.
    """
    cls = SCENARIOS.get(self.scenario_name)
    params = dict(self.scenario_params)
    if "seed" in inspect.signature(cls).parameters and "seed" not in params:
        params["seed"] = self.seed
    return cls(**params)

new_trainer

new_trainer(init_seed: int | None = None) -> Trainer

A Trainer on the run's split; init_seed varies the initial weights and data order.

Source code in src/autotunenet/bench/core/method.py
def new_trainer(self, init_seed: int | None = None) -> Trainer:
    """A Trainer on the run's split; `init_seed` varies the initial weights and data order."""
    return Trainer(self.task, self.seed, self.device, init_seed=init_seed)

train_single_run

train_single_run(ctx: RunContext, ledger: ComputeLedger, make_controller) -> RunOutcome

One model from the scenario's initial learning rate, then the test split once.

Source code in src/autotunenet/bench/core/method.py
def train_single_run(ctx: RunContext, ledger: ComputeLedger, make_controller) -> RunOutcome:
    """One model from the scenario's initial learning rate, then the test split once."""
    scenario = ctx.new_scenario()
    trainer = ctx.new_trainer()
    optimizer = torch.optim.Adam(trainer.model.parameters(), lr=scenario.initial_lr(ctx.task))
    controller = make_controller(optimizer, ctx)
    history = train_epochs(ctx, ledger, trainer, optimizer, scenario, controller)
    test_loss, test_accuracy = trainer.test()
    return RunOutcome(test_loss, test_accuracy, history, controller.extra())

train_epochs

train_epochs(ctx: RunContext, ledger: ComputeLedger, trainer: Trainer, optimizer, scenario, controller: Controller) -> list[dict[str, Any]]

Train trainer.model for ctx.epochs, calling the scenario before and the controller after every epoch. Returns the per-epoch history. The test split is not touched here.

Source code in src/autotunenet/bench/core/method.py
def train_epochs(ctx: RunContext, ledger: ComputeLedger, trainer: Trainer, optimizer,
                 scenario, controller: Controller) -> list[dict[str, Any]]:
    """
    Train `trainer.model` for ctx.epochs, calling the scenario before and the
    controller after every epoch. Returns the per-epoch history. The test
    split is not touched here.
    """
    history = []
    controller.on_train_start(trainer.model)
    # Only controllers that override on_batch_end pay for a call per batch.
    batch_hook = controller.on_batch_end if type(controller).on_batch_end is not Controller.on_batch_end else None
    for epoch in range(ctx.epochs):
        scenario.on_epoch_start(epoch, trainer)
        lr = optimizer.param_groups[0]["lr"]
        train_loss = trainer.train_epoch(optimizer, on_batch_end=batch_hook)
        ledger.add_epochs(1)
        val_loss, val_accuracy = trainer.evaluate()
        history.append({"epoch": epoch, "lr": lr, "train_loss": train_loss,
                        "val_loss": val_loss, "val_accuracy": val_accuracy})
        with ledger.time_controller():
            controller.on_epoch_end(epoch, val_loss)
    controller.on_train_end()
    return history

ComputeLedger dataclass

ComputeLedger(epochs_trained: int = 0, max_parallel_models: int = 1, trials: int = 1, restarts: int = 0, wall_time_sec: float = 0.0, controller_time_sec: float = 0.0)

Registries

METHODS, TASKS and SCENARIOS in autotunenet.bench.core.registry are instances of Registry.

Registry

Registry(kind: str)

Bases: Generic[T]

A name-to-object table for one kind of component (method, task or scenario).

Attributes:

Name Type Description
kind

The kind, used in error messages.

Source code in src/autotunenet/bench/core/registry.py
def __init__(self, kind: str):
    self.kind = kind
    self._items: dict[str, T] = {}

register

register(name: str)

Decorator that registers a class or function under name.

Raises:

Type Description
ValueError

name is already registered.

Source code in src/autotunenet/bench/core/registry.py
def register(self, name: str):
    """
    Decorator that registers a class or function under `name`.

    Raises:
        ValueError: `name` is already registered.
    """
    def decorator(obj: T) -> T:
        if name in self._items:
            raise ValueError(f"{self.kind} '{name}' is already registered")
        self._items[name] = obj
        return obj
    return decorator

add

add(name: str, obj: T) -> T

Register obj under name and return it.

Raises:

Type Description
ValueError

name is already registered.

Source code in src/autotunenet/bench/core/registry.py
def add(self, name: str, obj: T) -> T:
    """
    Register `obj` under `name` and return it.

    Raises:
        ValueError: `name` is already registered.
    """
    return self.register(name)(obj)

get

get(name: str) -> T

Return what is registered under name.

Raises:

Type Description
KeyError

Unknown name; the message lists the registered names.

Source code in src/autotunenet/bench/core/registry.py
def get(self, name: str) -> T:
    """
    Return what is registered under `name`.

    Raises:
        KeyError: Unknown name; the message lists the registered names.
    """
    try:
        return self._items[name]
    except KeyError:
        raise KeyError(
            f"Unknown {self.kind} '{name}'. Available: {', '.join(self.names()) or 'none'}"
        ) from None

names

names() -> list[str]

Registered names, sorted.

Source code in src/autotunenet/bench/core/registry.py
def names(self) -> list[str]:
    """Registered names, sorted."""
    return sorted(self._items)

Results

RunOutcome dataclass

RunOutcome(test_loss: float, test_accuracy: float, history: list[dict[str, Any]], extra: dict[str, Any] = dict())

What a method returns: test metrics, per-epoch history, method extras.

RunResult dataclass

RunResult(experiment: str, method: str, task: str, scenario: str, seed: int, test_loss: float, test_accuracy: float, history: list[dict[str, Any]], shift_epoch: int | None, compute: dict[str, Any], environment: dict[str, Any], config: dict[str, Any], extra: dict[str, Any] = dict(), schema_version: int = SCHEMA_VERSION)

The result of one cell, stored as JSON at <results>/<experiment>/<method>/<task>/<scenario>/seed_<seed>.json.

Attributes:

Name Type Description
experiment str

Experiment name.

method str

Method name.

task str

Task name.

scenario str

Scenario name.

seed int

Seed of the run.

test_loss float

Test loss of the reported model.

test_accuracy float

Test accuracy of the reported model, in [0, 1].

history list[dict[str, Any]]

One entry per epoch: epoch, lr, train_loss, val_loss, val_accuracy.

shift_epoch int | None

First epoch under the scenario's shift, or None.

compute dict[str, Any]

ComputeLedger fields: epochs_trained, max_parallel_models, trials, restarts, wall_time_sec, controller_time_sec.

environment dict[str, Any]

Device, accelerator, library versions, platform and git commit.

config dict[str, Any]

Epochs, method and scenario arguments, and task settings.

extra dict[str, Any]

Method-specific details (e.g. rollbacks, exploits).

schema_version int

Version of this format.

save

save(path: Path) -> None

Write atomically, so an interrupted run never leaves a half-written file.

Source code in src/autotunenet/bench/core/result.py
def save(self, path: Path) -> None:
    """Write atomically, so an interrupted run never leaves a half-written file."""
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_suffix(".json.tmp")
    with open(tmp, "w") as f:
        json.dump(asdict(self), f, indent=2)
    os.replace(tmp, path)

load classmethod

load(path: Path) -> RunResult

Read a result file written by save.

Source code in src/autotunenet/bench/core/result.py
@classmethod
def load(cls, path: Path) -> "RunResult":
    """Read a result file written by `save`."""
    with open(path) as f:
        return cls(**json.load(f))

Runtimes

Runtime

Bases: ABC

A place where cells are trained, such as this machine or Kaggle.

Each method is one stage of autotunenet run and one CLI command. Only run is required; the other stages default to doing nothing. Register a new runtime in autotunenet.bench.runtimes.RUNTIMES.

Attributes:

Name Type Description
name str

The value of --runtime that selects it.

setup

setup() -> list[str]

Check what this runtime needs.

Returns:

Type Description
list[str]

Problems found, each a sentence saying what to fix; empty when ready.

Source code in src/autotunenet/bench/runtimes/base.py
def setup(self) -> list[str]:
    """
    Check what this runtime needs.

    Returns:
        Problems found, each a sentence saying what to fix; empty when ready.
    """
    return []

data

data(tasks: Sequence, force: bool = False) -> None

Make each task's data available to this runtime.

Parameters:

Name Type Description Default
tasks Sequence

TaskSpecs whose data is needed.

required
force bool

Upload or fetch again even if already available.

False
Source code in src/autotunenet/bench/runtimes/base.py
def data(self, tasks: Sequence, force: bool = False) -> None:
    """
    Make each task's data available to this runtime.

    Args:
        tasks: `TaskSpec`s whose data is needed.
        force: Upload or fetch again even if already available.
    """

prepare

prepare(exp: Experiment, exp_path: Path, cells: Sequence[Cell], results_dir: Path, plugins: Sequence[str], parallel: int) -> None

Plan the cells that have no result yet; keep a round that is still running.

Parameters:

Name Type Description Default
exp Experiment

The experiment.

required
exp_path Path

Its YAML file (shipped to hosted runtimes).

required
cells Sequence[Cell]

Cells to consider; those with results are skipped.

required
results_dir Path

Root results folder.

required
plugins Sequence[str]

Plugin files to ship with the work.

required
parallel int

How many workers (e.g. notebooks) to use at once.

required
Source code in src/autotunenet/bench/runtimes/base.py
def prepare(self, exp: Experiment, exp_path: Path, cells: Sequence[Cell], results_dir: Path,
            plugins: Sequence[str], parallel: int) -> None:
    """
    Plan the cells that have no result yet; keep a round that is still running.

    Args:
        exp: The experiment.
        exp_path: Its YAML file (shipped to hosted runtimes).
        cells: Cells to consider; those with results are skipped.
        results_dir: Root results folder.
        plugins: Plugin files to ship with the work.
        parallel: How many workers (e.g. notebooks) to use at once.
    """

start

start(exp: Experiment, results_dir: Path) -> None

Start whatever prepare planned; work already started is skipped.

Source code in src/autotunenet/bench/runtimes/base.py
def start(self, exp: Experiment, results_dir: Path) -> None:
    """Start whatever `prepare` planned; work already started is skipped."""

pull

pull(exp: Experiment, results_dir: Path) -> int

Collect finished results into results_dir without overwriting existing ones.

Returns:

Type Description
int

The number of new result files.

Source code in src/autotunenet/bench/runtimes/base.py
def pull(self, exp: Experiment, results_dir: Path) -> int:
    """
    Collect finished results into `results_dir` without overwriting existing ones.

    Returns:
        The number of new result files.
    """
    return 0

in_progress

in_progress(exp: Experiment, results_dir: Path) -> bool

Whether started work is still running.

Source code in src/autotunenet/bench/runtimes/base.py
def in_progress(self, exp: Experiment, results_dir: Path) -> bool:
    """Whether started work is still running."""
    return False

describe

describe(exp: Experiment, results_dir: Path) -> list[str]

Status lines for autotunenet status.

Source code in src/autotunenet/bench/runtimes/base.py
def describe(self, exp: Experiment, results_dir: Path) -> list[str]:
    """Status lines for `autotunenet status`."""
    return []

run abstractmethod

run(exp: Experiment, exp_path: Path, cells: Sequence[Cell], results_dir: Path, plugins: Sequence[str], parallel: int, device: str) -> list[Cell]

Run every stage until the cells are done or the work stops.

Parameters:

Name Type Description Default
exp Experiment

The experiment.

required
exp_path Path

Its YAML file.

required
cells Sequence[Cell]

Cells to run; those with results are skipped.

required
results_dir Path

Root results folder.

required
plugins Sequence[str]

Plugin files or modules.

required
parallel int

Workers to use at once (hosted runtimes).

required
device str

auto, cpu, cuda or mps (this machine).

required

Returns:

Type Description
list[Cell]

The cells that still have no result.

Source code in src/autotunenet/bench/runtimes/base.py
@abstractmethod
def run(self, exp: Experiment, exp_path: Path, cells: Sequence[Cell], results_dir: Path,
        plugins: Sequence[str], parallel: int, device: str) -> list[Cell]:
    """
    Run every stage until the cells are done or the work stops.

    Args:
        exp: The experiment.
        exp_path: Its YAML file.
        cells: Cells to run; those with results are skipped.
        results_dir: Root results folder.
        plugins: Plugin files or modules.
        parallel: Workers to use at once (hosted runtimes).
        device: `auto`, `cpu`, `cuda` or `mps` (this machine).

    Returns:
        The cells that still have no result.
    """