Skip to content

Tuning

ParameterSpace

ParameterSpace(space: dict[str, Any])

Search space for the tuned hyperparameters.

Each entry maps a hyperparameter name (a key of the optimizer's param_groups, such as lr) to one of:

Form Meaning
(low, high) continuous range, linear scale
{"low": a, "high": b, "log": True} continuous range; log=True samples evenly across orders of magnitude (log defaults to False)
[v1, v2, ...] categorical choices

Numeric strings such as "1e-4" are converted to floats.

Attributes:

Name Type Description
space dict[str, Any]

Name to (low, high) tuple (ranges) or list (choices).

log dict[str, bool]

Name to True if that range uses a log scale.

Examples:

>>> space = ParameterSpace({
...     "lr": {"low": 1e-4, "high": 1e-1, "log": True},
...     "momentum": (0.8, 0.99),
...     "nesterov_like": [0.0, 1.0],
... })
>>> space.is_log("lr")
True

Parameters:

Name Type Description Default
space dict[str, Any]

Mapping from hyperparameter name to its range or choices (see the class description).

required

Raises:

Type Description
ValueError

A range mapping lacks low or high, log is not a bool, a tuple does not have two elements, low > high, a log range has low <= 0, a list is empty, or a value is a string that is not a number.

TypeError

An entry is not a tuple, mapping or list, or a value is not numeric.

Warns:

Type Description
UserWarning

A linear range with low > 0 spans 100x or more; use log=True for such ranges.

Source code in src/autotunenet/parameters.py
def __init__(self, space: dict[str, Any]):
    """
    Args:
        space: Mapping from hyperparameter name to its range or choices
            (see the class description).

    Raises:
        ValueError: A range mapping lacks `low` or `high`, `log` is not a
            bool, a tuple does not have two elements, `low > high`, a log
            range has `low <= 0`, a list is empty, or a value is a string
            that is not a number.
        TypeError: An entry is not a tuple, mapping or list, or a value is
            not numeric.

    Warns:
        UserWarning: A linear range with `low > 0` spans 100x or more;
            use `log=True` for such ranges.
    """
    self.space: dict[str, Any] = dict(space)
    self.log: dict[str, bool] = {}
    self._validate_space()

is_log

is_log(name: str) -> bool

Return whether name is a log-scale range (False for choices and unknown names).

Source code in src/autotunenet/parameters.py
def is_log(self, name: str) -> bool:
    """Return whether `name` is a log-scale range (`False` for choices and unknown names)."""
    return self.log.get(name, False)

sample

sample() -> dict[str, Any]

Draw one random configuration (uniform, or log-uniform for log ranges).

Uses Python's random module, so seed it with random.seed for repeatable samples. BayesianOptimizer does not use this method; it samples through Optuna.

Returns:

Type Description
dict[str, Any]

Name to sampled value, for every entry in the space.

Source code in src/autotunenet/parameters.py
def sample(self) -> dict[str, Any]:
    """
    Draw one random configuration (uniform, or log-uniform for log ranges).

    Uses Python's `random` module, so seed it with `random.seed` for
    repeatable samples. `BayesianOptimizer` does not use this method; it
    samples through Optuna.

    Returns:
        Name to sampled value, for every entry in the space.
    """
    params = {}
    for name, values in self.space.items():
        if isinstance(values, tuple):
            low, high = values
            if self.is_log(name):
                params[name] = math.exp(random.uniform(math.log(low), math.log(high)))
            else:
                params[name] = random.uniform(low, high)
        elif isinstance(values, list):
            params[name] = random.choice(values)

    return params

BayesianOptimizer

BayesianOptimizer(param_space: ParameterSpace, seed: int | None = None, smoothing_window: int = DEFAULT_SMOOTHING_WINDOW, n_startup_trials: int = DEFAULT_STARTUP_TRIALS, history_window: int | None = None)

Bases: Optimizer

Proposes hyperparameters with Optuna's TPE sampler and guards against harmful ones.

Each tuning step is one ask/tell pair: suggest() asks TPE for a configuration, and observe() reports the score it produced. In observe() the score is smoothed (moving average) and passed to the StabilityMonitor:

  • stable: the configuration is accepted. TPE is told its raw score, the smoothed score goes into history, and, unless the step was a tolerated regression, it becomes the rollback target.
  • unstable (a regression for patience steps, or a NaN/Inf score at once): the configuration is rejected, TPE is still told its real score (or the worst score seen, for NaN/Inf) so it learns to avoid that region, and rollback_params holds the last good configuration.

Usually driven by PyTorchHyperParameterAdapter, which also applies the proposals and rollbacks to the PyTorch optimizer.

Attributes:

Name Type Description
study

The underlying Optuna study (direction "maximize").

smoother

The MetricSmoother applied to scores.

guard

The StabilityMonitor; replace it to change its settings.

rollback

The Rollback store of the last good configuration.

last_rollback

Whether the latest observe() rejected its configuration.

last_instability

Same as last_rollback.

Examples:

>>> space = ParameterSpace({"lr": {"low": 1e-4, "high": 1e-1, "log": True}})
>>> opt = BayesianOptimizer(space, seed=0, n_startup_trials=3)
>>> params = opt.suggest()            # {"lr": ...}
>>> accepted = opt.observe(params, score=-0.42)   # higher is better

Parameters:

Name Type Description Default
param_space ParameterSpace

ParameterSpace to search.

required
seed int | None

Seed for the TPE sampler (None for a random seed).

None
smoothing_window int

Moving-average window used by the stability check.

DEFAULT_SMOOTHING_WINDOW
n_startup_trials int

Number of completed trials TPE samples at random before it starts using its model. Optuna's default is 10, but an online run has few tuning steps, so the default here is 3.

DEFAULT_STARTUP_TRIALS
history_window int | None

If set, TPE learns only from the last history_window scored configurations. Early-training scores describe a different phase of training; forgetting them keeps the model current. Must exceed n_startup_trials. None keeps every observation.

None

Raises:

Type Description
ValueError

n_startup_trials is not a non-negative integer, or history_window is not an integer above n_startup_trials.

Source code in src/autotunenet/bayesian_optimizer.py
def __init__(
    self,
    param_space: ParameterSpace,
    seed: int | None = None,
    smoothing_window: int = DEFAULT_SMOOTHING_WINDOW,
    n_startup_trials: int = DEFAULT_STARTUP_TRIALS,
    history_window: int | None = None,
):
    """
    Args:
        param_space: `ParameterSpace` to search.
        seed: Seed for the TPE sampler (`None` for a random seed).
        smoothing_window: Moving-average window used by the stability check.
        n_startup_trials: Number of completed trials TPE samples at random
            before it starts using its model. Optuna's default is 10, but an
            online run has few tuning steps, so the default here is 3.
        history_window: If set, TPE learns only from the last
            `history_window` scored configurations. Early-training scores
            describe a different phase of training; forgetting them keeps
            the model current. Must exceed `n_startup_trials`. `None` keeps
            every observation.

    Raises:
        ValueError: `n_startup_trials` is not a non-negative integer, or
            `history_window` is not an integer above `n_startup_trials`.
    """
    super().__init__(param_space)

    if not isinstance(n_startup_trials, int) or isinstance(n_startup_trials, bool) or n_startup_trials < 0:
        raise ValueError("n_startup_trials must be a non-negative integer")
    if history_window is not None and (not isinstance(history_window, int) or isinstance(history_window, bool)
                                       or history_window <= n_startup_trials):
        raise ValueError(f"history_window must be an integer above n_startup_trials ({n_startup_trials}), "
                         "or None to keep every observation")
    self.seed = seed
    self.n_startup_trials = n_startup_trials
    self.history_window = history_window

    self.study = optuna.create_study(
        direction="maximize",
        sampler=optuna.samplers.TPESampler(seed=seed, n_startup_trials=n_startup_trials)
    )

    self._active_trial = None

    self.smoother = MetricSmoother(window_size=smoothing_window)
    self.guard = StabilityMonitor()
    self.rollback = Rollback()
    self.tracker = Tracker()
    self.last_instability = False
    self.last_rollback = False
    self._rollback_params = None

rollback_params property

rollback_params

The last good configuration, set when observe() rejects a configuration; None until then.

suggest

suggest() -> dict[str, Any]

Ask TPE for the next configuration.

Each call starts a new trial; the next observe() call reports its score.

Returns:

Type Description
dict[str, Any]

Hyperparameter name to proposed value, one entry per item in the space.

Source code in src/autotunenet/bayesian_optimizer.py
def suggest(self) -> dict[str, Any]:
    """
    Ask TPE for the next configuration.

    Each call starts a new trial; the next `observe()` call reports its score.

    Returns:
        Hyperparameter name to proposed value, one entry per item in the space.
    """
    if self.history_window is not None:
        self._forget_old_trials()
    self._active_trial = self.study.ask()
    params = {}

    for name, values in self.param_space.space.items():
        if isinstance(values, tuple):
            low, high = values
            params[name] = self._active_trial.suggest_float(
                name, low, high, log=self.param_space.is_log(name)
            )

        elif isinstance(values, list):
            params[name] = self._active_trial.suggest_categorical(
                name, values
            )

    return params

observe

observe(params: dict[str, Any], score: float, objective: float | None = None) -> bool

Report the score of the configuration from the last suggest().

Parameters:

Name Type Description Default
params dict[str, Any]

The hyperparameters that actually ran. They may differ from the proposal (for example after max_delta clipping); TPE records these values.

required
score float

Higher-is-better metric, e.g. -val_loss. NaN or infinity triggers an immediate rollback. The stability guard judges it.

required
objective float | None

What TPE is told about this configuration, if not score; e.g. the improvement during the interval rather than the level reached. The guard still judges score.

None

Returns:

Type Description
bool

True if the configuration was accepted, False if it was

bool

rejected; then rollback_params holds the configuration to restore

bool

(or None if no configuration has been accepted yet).

Raises:

Type Description
RuntimeError

There is no pending suggest().

ValueError

score is not a single number.

Source code in src/autotunenet/bayesian_optimizer.py
@log_errors(context="BayesianOptimizer.observe")
def observe(self, params: dict[str, Any], score: float, objective: float | None = None) -> bool:
    """
    Report the score of the configuration from the last `suggest()`.

    Args:
        params: The hyperparameters that actually ran. They may differ
            from the proposal (for example after `max_delta` clipping);
            TPE records these values.
        score: Higher-is-better metric, e.g. `-val_loss`. NaN or infinity
            triggers an immediate rollback. The stability guard judges it.
        objective: What TPE is told about this configuration, if not
            `score`; e.g. the improvement during the interval rather than
            the level reached. The guard still judges `score`.

    Returns:
        `True` if the configuration was accepted, `False` if it was
        rejected; then `rollback_params` holds the configuration to restore
        (or `None` if no configuration has been accepted yet).

    Raises:
        RuntimeError: There is no pending `suggest()`.
        ValueError: `score` is not a single number.
    """
    if self._active_trial is None:
        raise RuntimeError("No active trial to observe")

    self.last_instability = False
    self.last_rollback = False

    score = to_score(score)
    told = score if objective is None else to_score(objective)

    if math.isfinite(score):
        smoothed_score = self.smoother.add(score)
        best_score = self.best_score() if self.history else None
        is_stable = self.guard.update(smoothed_score, best_score)
    else:
        # A NaN/Inf score means training has diverged. Roll back at once
        # (no patience, even during cooldown) and keep the value out of the
        # smoother and history, where it would poison every later comparison.
        self.tracker.logger.warning(f"Non-finite score {score}; rolling back immediately.")
        smoothed_score = None
        self.guard.force_rollback()
        is_stable = False

    trial = self._active_trial
    self._active_trial = None

    if is_stable:
        if self.guard.in_rollback:
            self.guard.exit_rollback()
            self.tracker.log_rollback_end()

        # The smoothed score drives the stability check and history; TPE gets
        # the raw score, which belongs to this config alone (the smoothing
        # window also contains epochs that ran under earlier configs).
        super().observe(params, smoothed_score)
        self._record_observation(trial, params, told)
        # Only a non-regressing step becomes the rollback target. A step
        # accepted during cooldown, or one still within the patience
        # allowance, may be a bad config.
        if not getattr(self.guard, "last_step_regressed", False):
            self.rollback.update(params)

        self.tracker.log_step(
            step=self._step,
            params=params,
            score=smoothed_score,
            best_score=best_score
        )
        return True
    else:
        self.last_instability = True
        self.last_rollback = True
        # Report the rejected config with the score it actually produced, so
        # TPE learns that this region is harmful (a FAIL would be ignored).
        if math.isfinite(score) and math.isfinite(told):
            self._record_observation(trial, params, told)
        else:
            worst = self._worst_completed_value()
            if worst is None:
                self.study.tell(trial, state=TrialState.FAIL)
            else:
                self._record_observation(trial, params, worst)
        # Store rollback params for adapter to apply
        if self.rollback._last_good_params is not None:
            self._rollback_params = self.rollback.rollback()
        self.tracker.log_rollback_start()
        return False

state_dict

state_dict() -> dict[str, Any]

Everything needed to continue this optimizer in a new process.

Holds only plain Python values, so it can be saved with torch.save (and loaded with weights_only=True) or as JSON.

Source code in src/autotunenet/bayesian_optimizer.py
def state_dict(self) -> dict[str, Any]:
    """
    Everything needed to continue this optimizer in a new process.

    Holds only plain Python values, so it can be saved with `torch.save`
    (and loaded with `weights_only=True`) or as JSON.
    """
    completed = [t for t in self.study.trials if t.state == TrialState.COMPLETE]
    active = self._active_trial
    return {
        "trials": [{"params": dict(t.params), "value": t.value,
                    "distributions": {k: optuna.distributions.distribution_to_json(d)
                                      for k, d in t.distributions.items()}} for t in completed],
        "active_params": dict(active.params) if active is not None else None,
        "sampler_rng": _rng_states(self.study.sampler),
        "history": [[dict(p), s] for p, s in self.history],
        "step": self._step,
        "smoother": list(self.smoother._values),
        "guard": {"patience": self.guard._patience, "cooldown": self.guard._cooldown_remaining,
                  "in_rollback": self.guard._in_rollback, "last_step_regressed": self.guard.last_step_regressed},
        "rollback_target": self.rollback._last_good_params,
        "rollback_params": self._rollback_params,
    }

load_state_dict

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

Restore a state_dict() into an optimizer built with the same space and settings.

Source code in src/autotunenet/bayesian_optimizer.py
def load_state_dict(self, state: dict[str, Any]) -> None:
    """Restore a `state_dict()` into an optimizer built with the same space and settings."""
    study = optuna.create_study(direction="maximize", sampler=self.study.sampler)
    for t in state["trials"]:
        study.add_trial(optuna.trial.create_trial(
            params=t["params"], value=t["value"],
            distributions={k: optuna.distributions.json_to_distribution(d)
                           for k, d in t["distributions"].items()}))
    self.study = study
    _set_rng_states(self.study.sampler, state["sampler_rng"])
    self._active_trial = None
    if state["active_params"] is not None:
        # Re-open the pending trial with the same values, so the next observe() completes it.
        self.study.enqueue_trial(state["active_params"])
        rng = _rng_states(self.study.sampler)
        self.suggest()
        _set_rng_states(self.study.sampler, rng)
    self.history = [(dict(p), s) for p, s in state["history"]]
    self._step = state["step"]
    self.smoother.reset()
    for value in state["smoother"]:
        self.smoother.add(value)
    g = state["guard"]
    self.guard._patience, self.guard._cooldown_remaining = g["patience"], g["cooldown"]
    self.guard._in_rollback, self.guard.last_step_regressed = g["in_rollback"], g["last_step_regressed"]
    self.rollback._last_good_params = state["rollback_target"]
    self._rollback_params = state["rollback_params"]

Optimizer

Optimizer(param_space: ParameterSpace)

Bases: ABC

Abstract base class for optimizers that propose hyperparameters and learn from scores.

Subclasses implement suggest(). Scores are higher-is-better (pass -val_loss, not val_loss).

Attributes:

Name Type Description
param_space

The search space.

history list[tuple[dict[str, Any], float]]

(params, score) pairs accepted so far, in order.

Parameters:

Name Type Description Default
param_space ParameterSpace

The search space, usually a ParameterSpace.

required
Source code in src/autotunenet/optimizer.py
def __init__(self, param_space: "ParameterSpace"):
    '''
    Args:
        param_space: The search space, usually a `ParameterSpace`.
    '''
    self.param_space = param_space
    self.history: list[tuple[dict[str, Any], float]] = []
    self._step = 0

suggest abstractmethod

suggest() -> dict[str, Any]

Propose the next configuration to try.

Returns:

Type Description
dict[str, Any]

Hyperparameter name to value.

Source code in src/autotunenet/optimizer.py
@abstractmethod
def suggest(self) -> dict[str, Any]:
    '''
    Propose the next configuration to try.

    Returns:
        Hyperparameter name to value.
    '''
    pass

observe

observe(params: dict[str, Any], score: float) -> None

Record the score of a configuration.

Parameters:

Name Type Description Default
params dict[str, Any]

The hyperparameters that produced the score.

required
score float

Higher-is-better metric (e.g. -val_loss); converted with to_score.

required

Raises:

Type Description
ValueError

score is not a single number.

Source code in src/autotunenet/optimizer.py
def observe(self, params: dict[str, Any], score: float) -> None:
    '''
    Record the score of a configuration.

    Args:
        params: The hyperparameters that produced the score.
        score: Higher-is-better metric (e.g. `-val_loss`); converted with `to_score`.

    Raises:
        ValueError: `score` is not a single number.
    '''
    score = to_score(score)

    self._step += 1
    self.history.append((params, score))

best_result

best_result() -> tuple[dict[str, Any], float]

Return the best (params, score) in history, ignoring non-finite scores.

Raises:

Type Description
RuntimeError

No finite observation has been recorded yet.

Source code in src/autotunenet/optimizer.py
def best_result(self) -> tuple[dict[str, Any], float]:
    """
    Return the best `(params, score)` in `history`, ignoring non-finite scores.

    Raises:
        RuntimeError: No finite observation has been recorded yet.
    """
    # Non-finite scores never count as "best": NaN compares False with
    # everything, so a NaN entry would otherwise stick as the maximum.
    finite = [item for item in self.history if math.isfinite(item[1])]
    if not finite:
        raise RuntimeError("No observations available yet")
    return max(finite, key=lambda item: item[1])

best_params

best_params() -> dict[str, Any]

Return the hyperparameters of best_result().

Source code in src/autotunenet/optimizer.py
def best_params(self) -> dict[str, Any]:
    """Return the hyperparameters of `best_result()`."""
    return self.best_result()[0]

best_score

best_score() -> float

Return the score of best_result().

Source code in src/autotunenet/optimizer.py
def best_score(self) -> float:
    """Return the score of `best_result()`."""
    return self.best_result()[1]

num_observations

num_observations() -> int

Return the number of entries in history.

Source code in src/autotunenet/optimizer.py
def num_observations(self) -> int:
    """Return the number of entries in `history`."""
    return len(self.history)

to_score

to_score(value: Any) -> float

Convert a metric to a Python float.

Accepts int/float, NumPy scalars (e.g. np.float32) and one-element tensors (e.g. torch.tensor(-0.1) or -loss.detach()).

Parameters:

Name Type Description Default
value Any

The metric to convert.

required

Returns:

Type Description
float

The value as a float (NaN and infinity are passed through).

Raises:

Type Description
ValueError

value is a bool, or is not a single number.

Source code in src/autotunenet/optimizer.py
def to_score(value: Any) -> float:
    """
    Convert a metric to a Python float.

    Accepts int/float, NumPy scalars (e.g. np.float32) and one-element
    tensors (e.g. torch.tensor(-0.1) or -loss.detach()).

    Args:
        value: The metric to convert.

    Returns:
        The value as a float (NaN and infinity are passed through).

    Raises:
        ValueError: `value` is a bool, or is not a single number.
    """
    if isinstance(value, bool):
        raise ValueError("Score must be a numeric value, not a bool")
    try:
        return float(value)
    except (TypeError, ValueError, RuntimeError):
        raise ValueError(
            f"Score must be a single numeric value (got {type(value).__name__})"
        ) from None

MetricSmoother

MetricSmoother(window_size: int = DEFAULT_SMOOTHING_WINDOW)

Mean of the last window_size values added.

Examples:

>>> s = MetricSmoother(window_size=2)
>>> s.add(1.0), s.add(3.0), s.add(5.0)
(1.0, 2.0, 4.0)

Parameters:

Name Type Description Default
window_size int

Number of most recent values averaged (default 3).

DEFAULT_SMOOTHING_WINDOW
Source code in src/autotunenet/metrics.py
def __init__(self, window_size: int = DEFAULT_SMOOTHING_WINDOW):
    """
    Args:
        window_size: Number of most recent values averaged (default 3).
    """
    self.window_size = window_size
    self._values: deque[float] = deque(maxlen = window_size)

value property

value: float | None

The current moving average, or None before any value is added.

add

add(value: float) -> float

Add a value and return the new moving average.

Source code in src/autotunenet/metrics.py
def add(self, value: float) -> float:
    """Add a value and return the new moving average."""
    self._values.append(value)
    return self.value

reset

reset() -> None

Forget all values.

Source code in src/autotunenet/metrics.py
def reset(self) -> None:
    """Forget all values."""
    self._values.clear()