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:
- scores the configuration that ran since the previous tuning call,
using the
BayesianOptimizerand its stability guard; if it is rejected, the last good configuration is restored exactly and the call ends there; - otherwise asks for the next configuration and writes it into
optimizer.param_groups, clipped tocurrent * (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 |
|
history |
list[dict[str, Any]]
|
One dict per hook call and divergence cut; see |
last_rollback |
Whether the latest hook call rolled back. |
|
last_instability |
Same as |
|
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 |
required |
autotune_optimizer
|
BayesianOptimizer | None
|
The |
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%. |
DEFAULT_MAX_DELTA
|
tune
|
tuple[str, ...] | list[str] | None
|
Settings to tune when |
None
|
seed
|
int | None
|
Seed for the TPE sampler when |
None
|
score
|
str
|
What TPE learns from. |
'level'
|
spike_factor
|
float | None
|
Enables the divergence guard in |
None
|
model
|
Module | None
|
The model being trained; needed for |
None
|
keep_best
|
bool
|
Keep a copy (on the CPU) of the model and optimizer
state with the best metric so far; see |
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
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 | |
best_metric
property
¶
The best metric passed to a hook so far (kept with its weights when keep_best is on).
on_epoch_end ¶
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. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
|
Source code in src/autotunenet/adapters/pytorch/adapter.py
on_step_end ¶
on_validation_end ¶
Tuning hook for the end of a validation pass; same behaviour as on_epoch_end.
step ¶
Generic tuning call, for loops that are not epoch-based; same behaviour as on_epoch_end.
step_tuning_metric ¶
on_batch_end ¶
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
restore_best ¶
Load the kept best model and optimizer state, keeping the current hyperparameters.
Returns:
| Type | Description |
|---|---|
bool
|
Whether a kept state was restored ( |
bool
|
nothing has been kept yet). |
Source code in src/autotunenet/adapters/pytorch/adapter.py
history_to_csv ¶
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
state_dict ¶
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
load_state_dict ¶
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
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 |
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
The configuration is invalid. |
Examples:
Source code in src/autotunenet/adapters/pytorch/adapter.py
infer_space ¶
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}}