Skip to content

PyTorch adapter

PyTorchHyperParameterAdapter

PyTorchHyperParameterAdapter(torch_optimizer: Optimizer, autotune_optimizer: BayesianOptimizer | None = None, tune_n_steps: int = 1, warmup_epochs: int = DEFAULT_WARMUP_EPOCHS, warmup_metric_threshold: float | None = None, max_delta: float | None = DEFAULT_MAX_DELTA, *, tune: tuple[str, ...] | list[str] | None = None, seed: int | None = None, score: str = 'level', spike_factor: float | None = None, model: Module | None = None, keep_best: bool = False)

Tunes the hyperparameters of a PyTorch optimizer while it trains.

Call one of the hooks (usually on_epoch_end) with a higher-is-better metric such as -val_loss. Each tuning call:

  1. scores the configuration that ran since the previous tuning call, using the BayesianOptimizer and its stability guard; if it is rejected, the last good configuration is restored exactly and the call ends there;
  2. otherwise asks for the next configuration and writes it into optimizer.param_groups, clipped to current * (1 +/- max_delta).

Values refer to the first param group; other groups keep their original ratio to it, so layer-wise settings (e.g. a lower backbone learning rate) survive tuning. Categorical values are applied without clipping.

Every call is recorded in history, with what ran, its score and what was decided.

Attributes:

Name Type Description
autotune_optimizer

The BayesianOptimizer that proposes and judges configurations.

history list[dict[str, Any]]

One dict per hook call and divergence cut; see history_columns.

last_rollback

Whether the latest hook call rolled back.

last_instability

Same as last_rollback.

batch_cuts

How many times the divergence guard cut the learning rate.

Examples:

>>> optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
>>> tuner = PyTorchHyperParameterAdapter(optimizer)     # tunes lr in [1e-5, 1e-2]
>>> for epoch in range(20):
...     train_one_epoch(model, optimizer)
...     tuner.on_epoch_end(metric=-evaluate(model))

Parameters:

Name Type Description Default
torch_optimizer Optimizer

The torch.optim.Optimizer to tune (Adam, SGD, ...).

required
autotune_optimizer BayesianOptimizer | None

The BayesianOptimizer that proposes and judges configurations. If None, one is built over infer_space(torch_optimizer, tune).

None
tune_n_steps int

Tune on every n-th hook call (1 = every call).

1
warmup_epochs int

Number of hook calls ignored before tuning starts.

DEFAULT_WARMUP_EPOCHS
warmup_metric_threshold float | None

Start tuning once the loss is at or below this value, i.e. once metric >= -warmup_metric_threshold. Must be > 0. Once passed, the warmup is not checked again.

None
max_delta float | None

Maximum relative change per tuning step, in (0, 1); 0.5 allows +/-50%. None applies proposals unclipped. From a value of 0, a step may move by max_delta * (high - low).

DEFAULT_MAX_DELTA
tune tuple[str, ...] | list[str] | None

Settings to tune when autotune_optimizer is None (default ("lr",)); see infer_space.

None
seed int | None

Seed for the TPE sampler when autotune_optimizer is None.

None
score str

What TPE learns from. "level": the metric reached. "progress": its relative improvement during the interval, which does not reward a configuration for running late in training. The stability guard always judges the level.

'level'
spike_factor float | None

Enables the divergence guard in on_batch_end: a batch loss that is NaN/Inf or above spike_factor times the median of the last 20 cuts the learning rate at once.

None
model Module | None

The model being trained; needed for keep_best.

None
keep_best bool

Keep a copy (on the CPU) of the model and optimizer state with the best metric so far; see restore_best(). It is restored automatically when training diverges (a NaN/Inf metric or batch loss).

False

Raises:

Type Description
ValueError

An argument is out of range, or a name in the search space is not a setting of every param group (the message lists the settings that exist).

Source code in src/autotunenet/adapters/pytorch/adapter.py
def __init__(self,
             torch_optimizer: torch.optim.Optimizer,
             autotune_optimizer: BayesianOptimizer | None = None,
             tune_n_steps: int = 1,
             warmup_epochs: int = DEFAULT_WARMUP_EPOCHS,
             warmup_metric_threshold: float | None = None,
             max_delta: float | None = DEFAULT_MAX_DELTA,
             *,
             tune: tuple[str, ...] | list[str] | None = None,
             seed: int | None = None,
             score: str = "level",
             spike_factor: float | None = None,
             model: torch.nn.Module | None = None,
             keep_best: bool = False):
    """
    Args:
        torch_optimizer: The `torch.optim.Optimizer` to tune (Adam, SGD, ...).
        autotune_optimizer: The `BayesianOptimizer` that proposes and judges
            configurations. If `None`, one is built over `infer_space(torch_optimizer, tune)`.
        tune_n_steps: Tune on every n-th hook call (1 = every call).
        warmup_epochs: Number of hook calls ignored before tuning starts.
        warmup_metric_threshold: Start tuning once the loss is at or below this
            value, i.e. once metric >= -warmup_metric_threshold. Must be > 0.
            Once passed, the warmup is not checked again.
        max_delta: Maximum relative change per tuning step, in (0, 1);
            0.5 allows +/-50%. `None` applies proposals unclipped. From a
            value of 0, a step may move by `max_delta * (high - low)`.
        tune: Settings to tune when `autotune_optimizer` is `None`
            (default `("lr",)`); see `infer_space`.
        seed: Seed for the TPE sampler when `autotune_optimizer` is `None`.
        score: What TPE learns from. `"level"`: the metric reached.
            `"progress"`: its relative improvement during the interval,
            which does not reward a configuration for running late in
            training. The stability guard always judges the level.
        spike_factor: Enables the divergence guard in `on_batch_end`: a
            batch loss that is NaN/Inf or above `spike_factor` times the
            median of the last 20 cuts the learning rate at once.
        model: The model being trained; needed for `keep_best`.
        keep_best: Keep a copy (on the CPU) of the model and optimizer
            state with the best metric so far; see `restore_best()`. It is
            restored automatically when training diverges (a NaN/Inf metric
            or batch loss).

    Raises:
        ValueError: An argument is out of range, or a name in the search
            space is not a setting of every param group (the message lists
            the settings that exist).
    """
    if isinstance(tune_n_steps, bool) or not isinstance(tune_n_steps, int) or tune_n_steps <= 0:
        raise ValueError(
            "tune_n_steps must be a positive integer "
            "(e.g. 1 = every step/epoch, 5 = every 5 steps/epochs)"
        )

    if isinstance(warmup_epochs, bool) or not isinstance(warmup_epochs, int) or warmup_epochs < 0:
        raise ValueError("warmup_epochs must be a non-negative integer")

    if warmup_metric_threshold is not None and warmup_metric_threshold <= 0:
        raise ValueError(
            "warmup_metric_threshold must be > 0: tuning starts once the loss "
            "is at or below it (metric >= -warmup_metric_threshold)"
        )

    if max_delta is not None and (max_delta <=0 or max_delta >= 1):
        raise ValueError("max_delta must be in the range (0,1)")
    if score not in SCORES:
        raise ValueError(f"score must be one of {SCORES}")
    if spike_factor is not None and spike_factor <= 1:
        raise ValueError("spike_factor must be above 1 (e.g. 3: a loss 3x the recent median)")
    if keep_best and model is None:
        raise ValueError("keep_best needs the model: pass model=...")
    if autotune_optimizer is None:
        autotune_optimizer = BayesianOptimizer(infer_space(torch_optimizer, tuple(tune or ("lr",))), seed=seed)
    elif tune is not None:
        raise ValueError("tune applies only when no autotune_optimizer is given; "
                         "its ParameterSpace decides what is tuned")

    self.torch_optimizer = torch_optimizer
    self.autotune_optimizer = autotune_optimizer
    self.tune_n_steps = tune_n_steps
    self.max_delta = max_delta
    self.score = score
    self.spike_factor = spike_factor
    self.model = model
    self.keep_best = keep_best

    self.rollback = Rollback()
    self.tracker = Tracker()

    self._validate_tuned_keys()

    self._epoch = 0
    self._step = 0
    self._batch = 0
    # Each param group keeps its ratio to the first (reference) group, so
    # layer-wise settings such as a lower backbone LR survive tuning.
    self._group_ratios = self._compute_group_ratios()
    self._last_good_params: dict[str, float] = self._read_current_params()
    # Fallback rollback target when nothing has been accepted yet
    # (e.g. the first tuned epoch diverges).
    self._initial_params: dict[str, float] = dict(self._last_good_params)

    self.warmup_epochs = warmup_epochs
    self.warmup_metric_threshold = warmup_metric_threshold
    self._tuning_enabled = warmup_epochs == 0 and warmup_metric_threshold is None

    self._pending_observation = False
    self._interval_start: float | None = None      # metric when the running configuration was applied
    self._recent_losses: deque[float] = deque(maxlen=SPIKE_WINDOW)
    self._start_loss: float | None = None             # median of the first batch losses
    self._best_metric: float | None = None
    self._best_state: dict[str, Any] | None = None

    self.history: list[dict[str, Any]] = []
    self.batch_cuts = 0
    self.last_instability = False
    self.last_rollback = False

best_metric property

best_metric: float | None

The best metric passed to a hook so far (kept with its weights when keep_best is on).

on_epoch_end

on_epoch_end(metric: float)

Tuning hook for the end of an epoch.

Parameters:

Name Type Description Default
metric float

Higher-is-better metric measured with the hyperparameters in effect since the previous call, e.g. -val_loss. A float, NumPy scalar or one-element tensor.

required

Raises:

Type Description
ValueError

metric is not a single number.

Source code in src/autotunenet/adapters/pytorch/adapter.py
def on_epoch_end(self, metric: float):
    """
    Tuning hook for the end of an epoch.

    Args:
        metric: Higher-is-better metric measured with the hyperparameters in
            effect since the previous call, e.g. `-val_loss`. A float, NumPy
            scalar or one-element tensor.

    Raises:
        ValueError: `metric` is not a single number.
    """
    self._epoch += 1
    self._tuning_call(metric)

on_step_end

on_step_end(metric: float)

Tuning hook for the end of a training step; same behaviour as on_epoch_end.

Source code in src/autotunenet/adapters/pytorch/adapter.py
def on_step_end(self, metric: float):
    """Tuning hook for the end of a training step; same behaviour as `on_epoch_end`."""
    self._tuning_call(metric)

on_validation_end

on_validation_end(metric: float)

Tuning hook for the end of a validation pass; same behaviour as on_epoch_end.

Source code in src/autotunenet/adapters/pytorch/adapter.py
def on_validation_end(self, metric: float):
    """Tuning hook for the end of a validation pass; same behaviour as `on_epoch_end`."""
    self._tuning_call(metric)

step

step(metric: float)

Generic tuning call, for loops that are not epoch-based; same behaviour as on_epoch_end.

Source code in src/autotunenet/adapters/pytorch/adapter.py
def step(self, metric: float):
    """Generic tuning call, for loops that are not epoch-based; same behaviour as `on_epoch_end`."""
    self._tuning_call(metric)

step_tuning_metric

step_tuning_metric(metric: float)

Deprecated alias of step(); kept for backward compatibility.

Source code in src/autotunenet/adapters/pytorch/adapter.py
def step_tuning_metric(self, metric: float):
    """Deprecated alias of step(); kept for backward compatibility."""
    self._tuning_call(metric)

on_batch_end

on_batch_end(loss: float) -> bool

Divergence guard, called after each training batch with its loss (lower is better).

Does nothing unless spike_factor is set. A loss that is NaN/Inf, or a spike, halves the learning rate at once (by 1 - max_delta if set), without waiting for the next tuning call. A spike is a loss above both spike_factor times the median of the last 20 batch losses and the loss training started from (the median of its first 10 batches): late in training, small losses vary by large ratios without diverging. The learning rate is never cut below the bottom of its search range. A NaN/Inf loss also restores the best weights when keep_best is on. Costs a few comparisons per batch.

Parameters:

Name Type Description Default
loss float

The batch's training loss.

required

Returns:

Type Description
bool

Whether the learning rate was cut.

Source code in src/autotunenet/adapters/pytorch/adapter.py
def on_batch_end(self, loss: float) -> bool:
    """
    Divergence guard, called after each training batch with its loss (lower is better).

    Does nothing unless `spike_factor` is set. A loss that is NaN/Inf, or a
    spike, halves the learning rate at once (by `1 - max_delta` if set),
    without waiting for the next tuning call. A spike is a loss above both
    `spike_factor` times the median of the last 20 batch losses and the
    loss training started from (the median of its first 10 batches): late
    in training, small losses vary by large ratios without diverging. The
    learning rate is never cut below the bottom of its search range. A
    NaN/Inf loss also restores the best weights when `keep_best` is on.
    Costs a few comparisons per batch.

    Args:
        loss: The batch's training loss.

    Returns:
        Whether the learning rate was cut.
    """
    if self.spike_factor is None:
        return False
    self._batch += 1
    loss = to_score(loss)
    finite = math.isfinite(loss)
    spike = (finite and self._start_loss is not None and len(self._recent_losses) >= SPIKE_WINDOW // 2
             and loss > self.spike_factor * statistics.median(self._recent_losses)
             and loss > self._start_loss)
    if finite and not spike:
        self._recent_losses.append(loss)
        if self._start_loss is None and len(self._recent_losses) == SPIKE_WINDOW // 2:
            self._start_loss = statistics.median(self._recent_losses)
        return False

    before = self._read_current_params()
    floor = self._lr_floor()
    if "lr" not in before or before["lr"] <= floor:
        return False                     # nothing left to cut
    factor = 1 - (self.max_delta if self.max_delta is not None else DEFAULT_MAX_DELTA)
    self._apply_params({"lr": max(floor, before["lr"] * factor)}, bounded=False)
    if not finite:
        self._restore_best_if_kept()
    self._recent_losses.clear()          # the loss level changes after a cut
    self.batch_cuts += 1
    self._log(action="cut", reason="nan" if not finite else "spike", metric=loss, ran=before,
              next=self._read_current_params())
    return True

restore_best

restore_best() -> bool

Load the kept best model and optimizer state, keeping the current hyperparameters.

Returns:

Type Description
bool

Whether a kept state was restored (False if keep_best is off or

bool

nothing has been kept yet).

Source code in src/autotunenet/adapters/pytorch/adapter.py
def restore_best(self) -> bool:
    """
    Load the kept best model and optimizer state, keeping the current hyperparameters.

    Returns:
        Whether a kept state was restored (`False` if `keep_best` is off or
        nothing has been kept yet).
    """
    if self._best_state is None:
        return False
    settings = [{k: v for k, v in g.items() if k != "params"} for g in self.torch_optimizer.param_groups]
    self.model.load_state_dict(self._best_state["model"])
    self.torch_optimizer.load_state_dict(self._best_state["optimizer"])
    for group, kept in zip(self.torch_optimizer.param_groups, settings):
        group.update(kept)
    return True

history_to_csv

history_to_csv(path) -> None

Write history to a CSV file: one row per decision, one column per tuned setting.

ran_<name> is the value that produced the row's metric, next_<name> the value in effect afterwards.

Source code in src/autotunenet/adapters/pytorch/adapter.py
def history_to_csv(self, path) -> None:
    """
    Write `history` to a CSV file: one row per decision, one column per tuned setting.

    `ran_<name>` is the value that produced the row's metric, `next_<name>` the
    value in effect afterwards.
    """
    names = sorted({k for row in self.history for k in (*row["ran"], *row["next"])})
    fields = [c for c in self.history_columns if c not in ("ran", "next")]
    fields += [f"ran_{n}" for n in names] + [f"next_{n}" for n in names]
    with open(path, "w", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=fields)
        writer.writeheader()
        for row in self.history:
            out = {k: row[k] for k in fields if k in row}
            out.update({f"ran_{n}": row["ran"].get(n) for n in names})
            out.update({f"next_{n}": row["next"].get(n) for n in names})
            writer.writerow(out)

state_dict

state_dict() -> dict[str, Any]

The tuner's state, to save next to the model and optimizer checkpoints.

Holds plain Python values only (torch.save and torch.load(weights_only=True) both work). The kept best weights are not included; save the model for that.

Examples:

>>> torch.save({"model": model.state_dict(), "optimizer": optimizer.state_dict(),
...             "tuner": tuner.state_dict()}, "checkpoint.pt")
Source code in src/autotunenet/adapters/pytorch/adapter.py
def state_dict(self) -> dict[str, Any]:
    """
    The tuner's state, to save next to the model and optimizer checkpoints.

    Holds plain Python values only (`torch.save` and `torch.load(weights_only=True)`
    both work). The kept best weights are not included; save the model for that.

    Examples:
        >>> torch.save({"model": model.state_dict(), "optimizer": optimizer.state_dict(),
        ...             "tuner": tuner.state_dict()}, "checkpoint.pt")
    """
    space = self.autotune_optimizer.param_space
    return {
        "version": 1,
        "space": {n: (list(v) if isinstance(v, list) else {"low": v[0], "high": v[1], "log": space.is_log(n)})
                  for n, v in space.space.items()},
        "epoch": self._epoch, "step": self._step, "batch": self._batch,
        "tuning_enabled": self._tuning_enabled, "pending_observation": self._pending_observation,
        "interval_start": self._interval_start, "initial_params": dict(self._initial_params),
        "last_good_params": dict(self._last_good_params), "group_ratios": [dict(r) for r in self._group_ratios],
        "recent_losses": list(self._recent_losses), "start_loss": self._start_loss,
        "batch_cuts": self.batch_cuts,
        "best_metric": self._best_metric if self._best_state is not None or not self.keep_best else None,
        "history": copy.deepcopy(self.history),
        "optimizer": self.autotune_optimizer.state_dict(),
    }

load_state_dict

load_state_dict(state: dict[str, Any]) -> None

Continue from a state_dict().

Build the tuner as before (same arguments) around the restored PyTorch optimizer, then call this. The search space of the saved run is restored too, so an inferred range does not move with the resumed learning rate.

Source code in src/autotunenet/adapters/pytorch/adapter.py
def load_state_dict(self, state: dict[str, Any]) -> None:
    """
    Continue from a `state_dict()`.

    Build the tuner as before (same arguments) around the restored PyTorch
    optimizer, then call this. The search space of the saved run is restored
    too, so an inferred range does not move with the resumed learning rate.
    """
    self.autotune_optimizer.param_space = ParameterSpace(
        {n: v if isinstance(v, list) else dict(v) for n, v in state["space"].items()})
    self._epoch, self._step, self._batch = state["epoch"], state["step"], state["batch"]
    self._tuning_enabled = state["tuning_enabled"]
    self._pending_observation = state["pending_observation"]
    self._interval_start = state["interval_start"]
    self._initial_params = dict(state["initial_params"])
    self._last_good_params = dict(state["last_good_params"])
    self._group_ratios = [dict(r) for r in state["group_ratios"]]
    self._recent_losses = deque(state["recent_losses"], maxlen=SPIKE_WINDOW)
    self._start_loss = state.get("start_loss")
    self.batch_cuts = state["batch_cuts"]
    self._best_metric = state["best_metric"]
    self._best_state = None
    self.history = copy.deepcopy(state["history"])
    self.autotune_optimizer.load_state_dict(state["optimizer"])

from_config classmethod

from_config(torch_optimizer: Optimizer, config_path: str, seed: int | None = None) -> PyTorchHyperParameterAdapter

Build an adapter from a YAML config file.

Uses the same schema and defaults as build_pytorch_autotunenet.

Parameters:

Name Type Description Default
torch_optimizer Optimizer

The torch.optim.Optimizer to tune.

required
config_path str

Path to the YAML file.

required
seed int | None

Seed for the TPE sampler.

None

Returns:

Type Description
PyTorchHyperParameterAdapter

A configured PyTorchHyperParameterAdapter.

Raises:

Type Description
ValueError

The configuration is invalid.

Examples:

>>> adapter = PyTorchHyperParameterAdapter.from_config(optimizer, "autotune.yaml", seed=42)
Source code in src/autotunenet/adapters/pytorch/adapter.py
@classmethod
def from_config(cls, torch_optimizer: torch.optim.Optimizer, config_path: str,
                seed: int | None = None) -> "PyTorchHyperParameterAdapter":
    """
    Build an adapter from a YAML config file.

    Uses the same schema and defaults as `build_pytorch_autotunenet`.

    Args:
        torch_optimizer: The `torch.optim.Optimizer` to tune.
        config_path: Path to the YAML file.
        seed: Seed for the TPE sampler.

    Returns:
        A configured `PyTorchHyperParameterAdapter`.

    Raises:
        ValueError: The configuration is invalid.

    Examples:
        >>> adapter = PyTorchHyperParameterAdapter.from_config(optimizer, "autotune.yaml", seed=42)
    """
    # Local import: factory imports this module.
    from autotunenet.factory import build_pytorch_autotunenet

    config = load_config(config_path)
    return build_pytorch_autotunenet(
        torch_optimizer=torch_optimizer,
        raw_config=config.raw_config,
        seed=seed,
    )

infer_space

infer_space(torch_optimizer: Optimizer, tune=('lr',)) -> ParameterSpace

A search space around the optimizer's current settings.

Each name in tune gets the log range [v / 100, v * 10], where v is its value in the first param group. Supported: lr, and weight_decay when it is above 0. Anything else needs an explicit ParameterSpace.

Raises:

Type Description
ValueError

A name is not a setting of the optimizer, cannot be inferred, or its value is 0.

Examples:

>>> opt = torch.optim.Adam(model.parameters(), lr=1e-3)
>>> infer_space(opt).space
{'lr': {'low': 1e-05, 'high': 0.01, 'log': True}}
Source code in src/autotunenet/adapters/pytorch/adapter.py
def infer_space(torch_optimizer: torch.optim.Optimizer, tune=("lr",)) -> ParameterSpace:
    """
    A search space around the optimizer's current settings.

    Each name in `tune` gets the log range `[v / 100, v * 10]`, where `v` is its
    value in the first param group. Supported: `lr`, and `weight_decay` when it
    is above 0. Anything else needs an explicit `ParameterSpace`.

    Raises:
        ValueError: A name is not a setting of the optimizer, cannot be inferred,
            or its value is 0.

    Examples:
        >>> opt = torch.optim.Adam(model.parameters(), lr=1e-3)
        >>> infer_space(opt).space
        {'lr': {'low': 1e-05, 'high': 0.01, 'log': True}}
    """
    group = torch_optimizer.param_groups[0]
    space = {}
    for name in tune:
        if name not in ("lr", "weight_decay"):
            raise ValueError(f"Cannot infer a range for '{name}'; pass a ParameterSpace with its range")
        value = group.get(name)
        if not isinstance(value, (int, float)) or isinstance(value, bool):
            raise ValueError(f"'{name}' is not a setting of {type(torch_optimizer).__name__}")
        if value <= 0:
            raise ValueError(f"'{name}' is {value}; a range cannot be inferred from it. "
                             f"Set a starting value above 0, or pass a ParameterSpace with its range")
        space[name] = {"low": value / INFER_BELOW, "high": value * INFER_ABOVE, "log": True}
    return ParameterSpace(space)