PyTorch guide¶
How the adapter (tuner in the examples) interacts with a PyTorch training loop: hooks, param groups, schedulers, checkpoints, the decision log, the divergence guard and best-weight restore.
Hooks¶
| Method | Call it | Typical metric |
|---|---|---|
on_epoch_end(metric) |
after validating at the end of an epoch | -val_loss |
on_validation_end(metric) |
after any validation pass (e.g. every N steps) | -val_loss |
on_step_end(metric) |
after an optimizer step | -train_loss of a smoothed window (noisy) |
step(metric) |
any loop that is not epoch-based | any higher-is-better score |
All four run the same logic (see How it works). Choose the one that names your call site. warmup_epochs and tune_n_steps count calls, whichever hook you use.
The metric must have been measured with the hyperparameters in effect since the previous call: it is credited to them. Validate first, then call the hook.
for epoch in range(epochs):
train_one_epoch(model, optimizer)
val_loss = evaluate(model) # measured with this epoch's lr
tuner.on_epoch_end(metric=-val_loss) # credits it, then sets next epoch's lr
Pass a loss as -loss, or a higher-is-better metric (accuracy, F1) as it is. Floats, NumPy scalars and one-element tensors are accepted; loss.item() is not required.
Tuning more often than once per epoch¶
For long epochs, validate on a held-out subset every few hundred steps and call on_validation_end:
for step, batch in enumerate(loader):
train_step(batch)
if step % 500 == 499:
tuner.on_validation_end(metric=-quick_val_loss(model))
More calls give TPE more observations per run. Keep the validation subset fixed, so scores are comparable between calls.
Optimizers¶
Any torch.optim.Optimizer works: AutoTuneNet only reads and writes optimizer.param_groups. You can tune any numeric setting the optimizer has:
| Optimizer | Tunable settings (examples) |
|---|---|
SGD |
lr, momentum, weight_decay, dampening |
Adam, AdamW |
lr, weight_decay, eps |
RMSprop |
lr, alpha, momentum, weight_decay |
A name the optimizer does not have, such as momentum with Adam, raises ValueError at construction and lists the available settings. Tuple-valued settings such as Adam's betas cannot be tuned.
Param groups¶
Values refer to the first group. Other groups keep their ratio to it:
optimizer = torch.optim.SGD([
{"params": backbone.parameters(), "lr": 1e-4},
{"params": head.parameters(), "lr": 1e-3},
], momentum=0.9)
# The controller sets lr = 2e-4 on the backbone -> head gets 2e-3.
Every tuned name must exist in every group. Runnable: examples/multi_param.py.
Learning-rate schedulers¶
Don't tune lr and run a scheduler on it at the same time: both write lr, and the adapter's credit assignment assumes it set the value that ran. Choose one of these:
- Tune
lrwith AutoTuneNet and drop the scheduler. This is what the benchmarks do. - Keep the scheduler for
lrand tune other settings (weight_decay,momentum).
Warmup schedules are covered by warmup_epochs: AutoTuneNet leaves the optimizer untouched until warmup ends, so a scheduler can own the first epochs, as long as it stops writing lr before tuning starts.
Mixed precision, gradient clipping, DDP¶
- AMP /
GradScaler: unaffected. The scaler wrapsoptimizer.step(); AutoTuneNet changesparam_groupsbetween steps. - Gradient clipping: unaffected.
- DistributedDataParallel: every rank must apply the same hyperparameters. Compute the validation metric on all ranks (all-reduce it), seed the
BayesianOptimizeridentically on every rank, and call the hook on every rank. The ranks then make identical decisions.
Checkpoints¶
Save the tuner's state next to the model and optimizer. state_dict() holds plain values only, so torch.load(..., weights_only=True) reads it:
torch.save({"model": model.state_dict(), "optimizer": optimizer.state_dict(),
"tuner": tuner.state_dict()}, "ckpt.pt")
To resume, restore the optimizer first, build the tuner with the same arguments as before, then load its state:
ckpt = torch.load("ckpt.pt", weights_only=True)
model.load_state_dict(ckpt["model"])
optimizer.load_state_dict(ckpt["optimizer"])
tuner = PyTorchHyperParameterAdapter(optimizer, seed=0)
tuner.load_state_dict(ckpt["tuner"])
The resumed run makes the same decisions as one that was never interrupted: TPE's trials and random state, the warmup, the stability guard and the search range all continue. The range is restored rather than inferred again, so it does not move with the resumed learning rate. The weights kept by keep_best are not part of the state; your model checkpoint covers them.
Decision log¶
tuner.history has one entry per hook call (and per divergence cut):
| Key | Meaning |
|---|---|
call, epoch, batch |
When: hook call number, epoch count, batch count (cuts only) |
action |
warmup (not tuning yet), skip (tune_n_steps), start (first proposal), accept, rollback, cut |
reason |
For rollback and cut: regression, nan or spike |
metric, smoothed, best |
The metric passed in, its moving average, and the best accepted score |
objective |
What TPE was told, when score="progress" |
ran, next |
The values that produced metric, and the values in effect afterwards |
tuner.history_to_csv("decisions.csv") writes it with one column per setting (ran_lr, next_lr, ...).
Divergence guard¶
A learning rate that is far too high can wreck the weights within an epoch, before the next tuning call. With spike_factor, call on_batch_end after each optimizer step:
tuner = PyTorchHyperParameterAdapter(optimizer, spike_factor=3)
for x, y in loader:
loss = loss_fn(model(x), y)
loss.backward(); optimizer.step(); optimizer.zero_grad()
tuner.on_batch_end(loss.item())
A loss that is NaN/Inf, or a spike, halves the learning rate at once (by 1 - max_delta). A spike is a loss more than 3× the median of the last 20 batches and above the loss training started from: late in training, small losses vary by large ratios without anything going wrong. Cuts never take the learning rate below the bottom of its search range. The cut is logged as a cut decision, and the next tuning call scores the reduced value. It costs a few comparisons per batch.
Keeping the best weights¶
A rollback restores hyperparameters, not weights. To also keep the weights of the best epoch, pass the model:
tuner = PyTorchHyperParameterAdapter(optimizer, model=model, keep_best=True)
...
tuner.restore_best() # e.g. after the last epoch, before testing
The tuner copies the model and optimizer state to the CPU whenever the metric beats its best so far, and restores it automatically when training diverges (a NaN/Inf metric or batch loss). restore_best() keeps the current hyperparameters. The copy costs one model's worth of CPU memory and a device-to-host transfer per improving epoch.
Rollback scope¶
A rollback restores hyperparameters only. Model weights and optimizer moments are left as they are, unless keep_best=True and training diverged (above). To restore weights on every rollback, check tuner.last_rollback after each call: