Skip to content

Quick start

This page adds AutoTuneNet to an existing PyTorch training loop. You need a model, an optimizer and a validation metric; nothing else in the loop changes.

1. Create the tuner

from autotunenet import PyTorchHyperParameterAdapter

tuner = PyTorchHyperParameterAdapter(optimizer)

With nothing else given, it tunes the learning rate within [lr / 100, lr * 10] on a log scale, around the value your optimizer starts with. It leaves the first 2 epochs alone, and changes the learning rate by at most ±50% per tuning step. These are the settings used in the benchmarks.

To tune weight decay as well, pass tune=["lr", "weight_decay"] (it must start above 0). Pass seed=0 for repeatable runs.

2. Report a metric once per epoch

for epoch in range(epochs):
    train_one_epoch(model, optimizer)
    val_loss = evaluate(model)
    tuner.on_epoch_end(metric=-val_loss)     # higher is better

The tuner writes the next configuration into optimizer.param_groups before the next epoch starts. tuner.last_rollback is True after a call that rolled back, and tuner.history lists every decision (decision log).

3. Choose the range yourself (optional)

For other settings (momentum, betas, ...) or a range of your own, give a ParameterSpace and the BayesianOptimizer that searches it:

from autotunenet import BayesianOptimizer, ParameterSpace, PyTorchHyperParameterAdapter

space = ParameterSpace({"lr": {"low": 1e-4, "high": 1e-1, "log": True}, "momentum": (0.8, 0.99)})
tuner = PyTorchHyperParameterAdapter(optimizer, BayesianOptimizer(space, seed=0))

Every name must be a numeric setting of your optimizer's param groups.

Python form Meaning
(low, high) continuous, linear scale
{"low": a, "high": b, "log": True} continuous, log scale (low > 0)
[a, b, c] categorical choices

A complete, runnable example

examples/quickstart.py trains a linear model on synthetic data and runs on a CPU in about a second:

"""Minimal AutoTuneNet loop: tune the learning rate of a linear model, once per epoch.

    python examples/quickstart.py
"""
import torch
from torch import nn

from autotunenet import PyTorchHyperParameterAdapter

torch.manual_seed(0)

# Toy data: y = 3x + noise. Replace with your own DataLoaders.
x = torch.randn(1024, 1)
y = 3 * x + 0.1 * torch.randn(1024, 1)
x_train, y_train, x_val, y_val = x[:800], y[:800], x[800:], y[800:]

model = nn.Linear(1, 1)
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
loss_fn = nn.MSELoss()

# Tunes lr within [0.01 / 100, 0.01 * 10] (log scale), leaves the first 2 epochs
# alone and changes lr by at most ±50% per epoch.
tuner = PyTorchHyperParameterAdapter(optimizer, seed=0)

for epoch in range(15):
    model.train()
    for i in range(0, len(x_train), 32):
        optimizer.zero_grad()
        loss_fn(model(x_train[i:i + 32]), y_train[i:i + 32]).backward()
        optimizer.step()

    model.eval()
    with torch.no_grad():
        val_loss = loss_fn(model(x_val), y_val).item()

    tuner.on_epoch_end(metric=-val_loss)            # higher is better
    print(f"epoch {epoch:2d}  val_loss={val_loss:.4f}  lr={optimizer.param_groups[0]['lr']:.5f}"
          f"{'  rollback' if tuner.last_rollback else ''}")

Output (abridged):

epoch  1  val_loss=1.6608  lr=0.01000      # warmup: untouched
epoch  2  val_loss=0.5898  lr=0.00500      # first proposal, clipped to -50%
epoch  5  val_loss=0.0922  lr=0.00322
epoch  9  val_loss=0.0545  lr=0.00020      # TPE moved to small steps as the loss flattened
epoch 14  val_loss=0.0440  lr=0.00153

Logging

Each accepted step and each rollback is logged to the AutoTuneNet logger at INFO level. To silence it:

import logging
logging.getLogger("AutoTuneNet").setLevel(logging.WARNING)

To also write the log to a file, call autotunenet.logging.logger.enable_file_logging("autotune.log") or set the AUTOTUNENET_LOG_FILE environment variable.

Next