Skip to content

Configuration

build_pytorch_autotunenet

build_pytorch_autotunenet(torch_optimizer: Optimizer, raw_config: dict, seed: int | None = None) -> PyTorchHyperParameterAdapter

Validate a configuration and build the adapter, optimizer and stability guard from it.

Every section except parameter_space is optional; missing keys take the defaults below.

Section Key Default Meaning
parameter_space name required [low, high] (linear range), {low, high, log: true} (log range) or {choices: [...]}
tuning tune_n_steps 1 tune every n calls
tuning warmup_epochs 2 calls before tuning starts
tuning warmup_metric_threshold None start tuning once the loss (-metric) is at or below this value
tuning max_delta 0.5 maximum relative change per step, in (0, 1); null = unclipped
tuning score level what TPE learns from: level (metric reached) or progress (improvement during the interval)
tuning spike_factor None divergence guard in on_batch_end: cut the LR when a batch loss exceeds this × the recent median
metrics smoothing_window 3 moving-average window
search n_startup_trials 3 random TPE trials before the model is used
search history_window None TPE learns only from the last n scored configurations
stability max_regression 0.2 relative drop from the best score counted as a regression
stability patience 2 consecutive regressions before rollback
stability cooldown 3 steps with rollback suppressed after one

Parameters:

Name Type Description Default
torch_optimizer Optimizer

The torch.optim.Optimizer whose hyperparameters are tuned.

required
raw_config dict

The configuration as a dictionary (e.g. loaded from YAML).

required
seed int | None

Seed for the TPE sampler.

None

Returns:

Type Description
PyTorchHyperParameterAdapter

A PyTorchHyperParameterAdapter; call its on_epoch_end(metric) once per epoch.

Raises:

Type Description
ValueError

The configuration is invalid (see AutoTuneConfig), or a tuned name is not a setting of the optimizer's param groups.

Examples:

>>> adapter = build_pytorch_autotunenet(
...     optimizer,
...     raw_config={
...         "parameter_space": {"lr": {"low": 1e-4, "high": 1e-2, "log": True}},
...         "tuning": {"warmup_epochs": 2, "max_delta": 0.5},
...         "stability": {"patience": 2, "cooldown": 3},
...     },
...     seed=42,
... )
Source code in src/autotunenet/factory.py
def build_pytorch_autotunenet(
    torch_optimizer: torch.optim.Optimizer,
    raw_config: dict,
    seed: int | None = None,
) -> PyTorchHyperParameterAdapter:
    """
    Validate a configuration and build the adapter, optimizer and stability guard from it.

    Every section except `parameter_space` is optional; missing keys take the
    defaults below.

    | Section | Key | Default | Meaning |
    |---|---|---|---|
    | `parameter_space` | *name* | required | `[low, high]` (linear range), `{low, high, log: true}` (log range) or `{choices: [...]}` |
    | `tuning` | `tune_n_steps` | `1` | tune every n calls |
    | `tuning` | `warmup_epochs` | `2` | calls before tuning starts |
    | `tuning` | `warmup_metric_threshold` | `None` | start tuning once the loss (`-metric`) is at or below this value |
    | `tuning` | `max_delta` | `0.5` | maximum relative change per step, in (0, 1); `null` = unclipped |
    | `tuning` | `score` | `level` | what TPE learns from: `level` (metric reached) or `progress` (improvement during the interval) |
    | `tuning` | `spike_factor` | `None` | divergence guard in `on_batch_end`: cut the LR when a batch loss exceeds this × the recent median |
    | `metrics` | `smoothing_window` | `3` | moving-average window |
    | `search` | `n_startup_trials` | `3` | random TPE trials before the model is used |
    | `search` | `history_window` | `None` | TPE learns only from the last n scored configurations |
    | `stability` | `max_regression` | `0.2` | relative drop from the best score counted as a regression |
    | `stability` | `patience` | `2` | consecutive regressions before rollback |
    | `stability` | `cooldown` | `3` | steps with rollback suppressed after one |

    Args:
        torch_optimizer: The `torch.optim.Optimizer` whose hyperparameters are tuned.
        raw_config: The configuration as a dictionary (e.g. loaded from YAML).
        seed: Seed for the TPE sampler.

    Returns:
        A `PyTorchHyperParameterAdapter`; call its `on_epoch_end(metric)` once per epoch.

    Raises:
        ValueError: The configuration is invalid (see `AutoTuneConfig`), or a
            tuned name is not a setting of the optimizer's param groups.

    Examples:
        >>> adapter = build_pytorch_autotunenet(
        ...     optimizer,
        ...     raw_config={
        ...         "parameter_space": {"lr": {"low": 1e-4, "high": 1e-2, "log": True}},
        ...         "tuning": {"warmup_epochs": 2, "max_delta": 0.5},
        ...         "stability": {"patience": 2, "cooldown": 3},
        ...     },
        ...     seed=42,
        ... )
    """

    config = AutoTuneConfig(raw_config)

    param_space = ParameterSpace(config.parameter_space)

    autotune_optimizer = BayesianOptimizer(
        param_space=param_space,
        seed=seed,
        smoothing_window=config.metrics.get("smoothing_window", DEFAULT_SMOOTHING_WINDOW),
        n_startup_trials=config.search.get("n_startup_trials", DEFAULT_STARTUP_TRIALS),
        history_window=config.search.get("history_window"),
    )

    autotune_optimizer.guard = StabilityMonitor(
        max_regression=config.stability.get("max_regression", 0.2),
        patience=config.stability.get("patience", 2),
        cooldown=config.stability.get("cooldown", 3),
    )

    tuning_cfg = config.tuning

    tune_n_steps = tuning_cfg.get("tune_n_steps", 1)
    warmup_epochs = tuning_cfg.get("warmup_epochs", DEFAULT_WARMUP_EPOCHS)
    warmup_metric_threshold = tuning_cfg.get(
        "warmup_metric_threshold"
    )
    max_delta = tuning_cfg.get("max_delta", DEFAULT_MAX_DELTA)       # explicit null: unclipped


    adapter = PyTorchHyperParameterAdapter(
        torch_optimizer=torch_optimizer,
        autotune_optimizer=autotune_optimizer,
        tune_n_steps=tune_n_steps,
        warmup_epochs=warmup_epochs,
        warmup_metric_threshold=warmup_metric_threshold,
        max_delta=max_delta,
        score=tuning_cfg.get("score", "level"),
        spike_factor=tuning_cfg.get("spike_factor"),
    )

    return adapter

load_config

load_config(path: str) -> AutoTuneConfig

Load and validate a configuration from a YAML file.

Parameters:

Name Type Description Default
path str

Path to the YAML file.

required

Returns:

Type Description
AutoTuneConfig

The validated AutoTuneConfig.

Raises:

Type Description
FileNotFoundError

The file does not exist.

ValueError

The configuration is invalid.

Source code in src/autotunenet/config/loader.py
def load_config(path: str) -> AutoTuneConfig:
    """
    Load and validate a configuration from a YAML file.

    Args:
        path: Path to the YAML file.

    Returns:
        The validated `AutoTuneConfig`.

    Raises:
        FileNotFoundError: The file does not exist.
        ValueError: The configuration is invalid.
    """
    with open(path) as file:
        raw_config = yaml.safe_load(file)

    return AutoTuneConfig(raw_config)

load_config_from_dict

load_config_from_dict(raw_config: dict[str, Any]) -> AutoTuneConfig

Validate a configuration given as a dictionary.

Parameters:

Name Type Description Default
raw_config dict[str, Any]

The configuration, with the same sections as the YAML file.

required

Returns:

Type Description
AutoTuneConfig

The validated AutoTuneConfig.

Raises:

Type Description
ValueError

The configuration is invalid.

Source code in src/autotunenet/config/loader.py
def load_config_from_dict(raw_config: dict[str, Any]) -> AutoTuneConfig:
    """
    Validate a configuration given as a dictionary.

    Args:
        raw_config: The configuration, with the same sections as the YAML file.

    Returns:
        The validated `AutoTuneConfig`.

    Raises:
        ValueError: The configuration is invalid.
    """
    return AutoTuneConfig(raw_config)

AutoTuneConfig

AutoTuneConfig(raw_config: dict[str, Any])

A validated AutoTuneNet configuration.

Sections: parameter_space (required), tuning, metrics, search and stability; see build_pytorch_autotunenet for every key and its default. Missing sections become empty dictionaries.

Attributes:

Name Type Description
raw_config

The configuration as given.

parameter_space

The normalized parameter space.

tuning

tune_n_steps, warmup_epochs, warmup_metric_threshold, max_delta, score, spike_factor.

metrics

smoothing_window.

search

n_startup_trials, history_window.

stability

max_regression, patience, cooldown.

Parameters:

Name Type Description Default
raw_config dict[str, Any]

The configuration dictionary.

required

Raises:

Type Description
KeyError

parameter_space is missing.

ValueError

A value has the wrong type or is out of range (e.g. max_delta outside (0, 1), patience not a positive integer).

Source code in src/autotunenet/config/schema.py
def __init__(self, raw_config: dict[str, Any]):
    """
    Args:
        raw_config: The configuration dictionary.

    Raises:
        KeyError: `parameter_space` is missing.
        ValueError: A value has the wrong type or is out of range
            (e.g. `max_delta` outside (0, 1), `patience` not a positive integer).
    """
    self.raw_config = raw_config

    self.parameter_space = normalize_parameter_space(raw_config["parameter_space"])
    self.tuning = raw_config.get("tuning", {}) or {}
    self.stability = raw_config.get("stability", {}) or {}
    self.metrics = raw_config.get("metrics", {}) or {}
    self.search = raw_config.get("search", {}) or {}

    self._validate()

normalize_parameter_space

normalize_parameter_space(raw_space: dict[str, Any]) -> dict[str, tuple[float, float] | dict[str, Any] | list[Any]]

Convert a config-style parameter space into the form ParameterSpace expects.

Config files (YAML/JSON) have no tuple type, so the config syntax is: lr: [1e-4, 1e-1] -> continuous range (low, high), linear lr: {low: 1e-4, high: 1e-1} -> continuous range, linear lr: {low: 1e-4, high: 1e-1, log: true} -> continuous range, log scale batch_size: {choices: [32, 64]} -> categorical choices

Tuples are passed through unchanged as ranges. Numeric strings (such as 1e-4, which PyYAML reads as a string) are converted to floats.

Parameters:

Name Type Description Default
raw_space dict[str, Any]

Name to range or choices, in config syntax.

required

Returns:

Type Description
dict[str, tuple[float, float] | dict[str, Any] | list[Any]]

Name to (low, high) tuple, {"low", "high", "log": True} mapping or list.

Raises:

Type Description
ValueError

The space is not a dictionary, a range does not have exactly two bounds, a bound is not numeric, low > high, a log range has low <= 0, choices is empty, or an entry has another form.

Source code in src/autotunenet/config/schema.py
def normalize_parameter_space(
    raw_space: dict[str, Any],
) -> dict[str, tuple[float, float] | dict[str, Any] | list[Any]]:
    """
    Convert a config-style parameter space into the form ParameterSpace expects.

    Config files (YAML/JSON) have no tuple type, so the config syntax is:
        lr: [1e-4, 1e-1]                        -> continuous range (low, high), linear
        lr: {low: 1e-4, high: 1e-1}             -> continuous range, linear
        lr: {low: 1e-4, high: 1e-1, log: true}  -> continuous range, log scale
        batch_size: {choices: [32, 64]}         -> categorical choices

    Tuples are passed through unchanged as ranges. Numeric strings (such as
    `1e-4`, which PyYAML reads as a string) are converted to floats.

    Args:
        raw_space: Name to range or choices, in config syntax.

    Returns:
        Name to `(low, high)` tuple, `{"low", "high", "log": True}` mapping or list.

    Raises:
        ValueError: The space is not a dictionary, a range does not have
            exactly two bounds, a bound is not numeric, `low > high`, a log
            range has `low <= 0`, `choices` is empty, or an entry has another form.
    """
    if not isinstance(raw_space, dict):
        raise ValueError("parameter_space must be a dictionary")

    normalized: dict[str, tuple[float, float] | dict[str, Any] | list[Any]] = {}

    for name, spec in raw_space.items():
        log = False
        if isinstance(spec, dict):
            if "choices" in spec:
                choices = spec["choices"]
                if not isinstance(choices, (list, tuple)) or len(choices) == 0:
                    raise ValueError(f"Parameter '{name}': 'choices' must be a non-empty list")
                normalized[name] = list(choices)
                continue
            if "low" in spec and "high" in spec:
                log = spec.get("log", False)
                if not isinstance(log, bool):
                    raise ValueError(f"Parameter '{name}': 'log' must be true or false")
                spec = [spec["low"], spec["high"]]
            else:
                raise ValueError(
                    f"Parameter '{name}': mapping must define either 'choices' or both 'low' and 'high'"
                )

        if isinstance(spec, (list, tuple)):
            if len(spec) != 2:
                raise ValueError(
                    f"Parameter '{name}': a range must be [low, high]; "
                    f"use {{choices: [...]}} for categorical values"
                )
            low, high = (_to_number(v, name) for v in spec)
            if low > high:
                raise ValueError(f"Parameter '{name}': low ({low}) must be <= high ({high})")
            if log:
                if low <= 0:
                    raise ValueError(f"Parameter '{name}': a log-scale range needs low > 0")
                normalized[name] = {"low": low, "high": high, "log": True}
            else:
                normalized[name] = (low, high)
            continue

        raise ValueError(f"invalid parameter definition for {name}")

    return normalized