Search space for different types of optimizers and schedulers#
Different optimizers have different update rules and behavior, and they may perform better or worse depending on the specific dataset and model architecture. Hence, trying out different optimizers and learning rate schedulers can be beneficial for ablation studies/ HPO.
To work with different optimizers effectively in the ablator, it is necessary to create custom config class from
OptimizerConfigobjects that can handle passing either torch-defined or custom optimizers to the ablator.This is similar to schedulers.
Let us first import necessary modules:
[ ]:
try:
import ablator
except:
!pip install ablator
print("Stopping RUNTIME! Please run again") # This script automatically restart runtime (if ablator is not found and installing is needed) so changes are applied
import os
os.kill(os.getpid(), 9)
[ ]:
from ablator import (ModelConfig, TrainConfig, ParallelConfig, SchedulerConfig, ModelWrapper,
ParallelTrainer, configclass, ConfigBase, Literal, Optional)
from ablator.config.hpo import SearchSpace
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
from torch.optim.lr_scheduler import OneCycleLR, ReduceLROnPlateau, StepLR
import os
import shutil
from sklearn.metrics import accuracy_score
Search space for optimizers#
We define a function called create_optimizer that creates an optimizer object based on the given inputs (optimizer name, model to optimize, and learning rate). In this example, we will use three optimizers: Adam, AdamW, and SGD. In specific, the function does the following:
Creates a list of model parameters
parameter_groupsfrom the model modulemodel.named_parameters().Defines dictionaries with specific parameters for each optimizer.
Create the optimizer using the model parameters, learning rate, and the defined dictionaries for each optimizer parameters.
Returns the optimizer object.
[2]:
def create_optimizer(optimizer_name: str, model: nn.Module, lr: float):
parameter_groups = [v for k, v in model.named_parameters()]
adamw_parameters = {
"betas": (0.0, 0.1),
"eps": 0.001,
"weight_decay": 0.1
}
adam_parameters = {
"betas" : (0.0, 0.1),
"weight_decay": 0.0
}
sgd_parameters = {
"momentum": 0.9,
"weight_decay": 0.1
}
Optimizer = None
if optimizer_name == "adam":
Optimizer = optim.Adam(parameter_groups, lr = lr, **adam_parameters)
elif optimizer_name == "adamw":
Optimizer = optim.AdamW(parameter_groups, lr = lr, **adamw_parameters)
elif optimizer_name == "sgd":
Optimizer = optim.SGD(parameter_groups, lr = lr, **sgd_parameters)
return Optimizer
Finally, we create an Optimizer configuration CustomOptimizerConfig. Internally, Ablator requires that the optimizer config has function make_optimizer with input as a model module:
[4]:
@configclass
class CustomOptimizerConfig(ConfigBase):
name: Literal["adam", "adamw", "sgd"] = "adam"
lr: float = 0.001
def make_optimizer(self, model: nn.Module):
return create_optimizer(self.name, model, self.lr)
optimizer_config = CustomOptimizerConfig(name = "adam", lr = 0.001)
optimizer_config
[4]:
CustomOptimizerConfig(name='adam', lr=0.001)
Here the configuration attribute
namewill be used in the search space, and we’re allowing search space to be["adam", "adamw", "sgd"].Inside
make_optimizer, we callcreate_optimizerwith the model, the name and lr attributes of the config object, and this function will return the corresponding optimizer.
Search space for different schedulers#
We define a function called create_scheduler that creates a scheduler object based on the given inputs (scheduler name, the model to optimize, the optimizer used). In this example, we will use three schedulers: StepLR, OneCycleLR, and ReduceLROnPlateau. In specific, the function does the following:
Defines dictionaries with specific parameters for each scheduler.
Create the scheduler using the optimizer and the defined dictionaries for each scheduler parameters.
Return the scheduler object.
We also define a second function called scheduler_arguments that returns the arguments of the scheduler
[5]:
def create_scheduler(scheduler_name: str, model: nn.Module, optimizer: torch.optim):
parameters = scheduler_arguments(scheduler_name)
del parameters["step_when"]
Scheduler = None
if scheduler_name == "step":
Scheduler = StepLR(optimizer, **parameters)
elif scheduler_name == "cycle":
Scheduler = OneCycleLR(optimizer, **parameters)
elif scheduler_name == "plateau":
Scheduler = ReduceLROnPlateau(optimizer, **parameters)
return Scheduler
def scheduler_arguments(scheduler_name):
if scheduler_name == "step":
return {
"step_size" : 1,
"gamma" : 0.99,
"step_when": "epoch"
}
elif scheduler_name == "plateau":
return {
"patience": 10,
"min_lr": 1e-5,
"mode": "min",
"factor": 0.0,
"threshold": 1e-4,
"step_when": "val"
}
elif scheduler_name == "cycle":
return {
"max_lr": 1e-3,
"total_steps": 10 * 1875, # number of training epochs * number of step per epoch len(train_loader)
"step_when": "train"
}
Assigning values to these arguments should be done with careful consideration, compromising requirements of the schedulers and ablator configurations.
One factor that might affect this is the step_when argument. step_when is solely for ablator to determine when to run scheduler.step() (hence it gets removed when creating the schedulers in create_scheduler function, as no schedulers uses it). If it’s "train", the learning rate is scheduled after every batch in the training loop, if it’s "val", scheduling takes place in the validation loop, and if it’s "epoch", scheduling takes place at the end of each epoch.
Another factor is the configuration TrainConfig.eval_epoch, which decides how often the validation loop is run. If eval_epoch is 1, the validation loop is run after every epoch, if it’s 2, the validation loop is run after every two epochs, and so on.
For example, OneCycleLR requires total_steps to be epochs * steps_per_epoch, and this value is dependent on which value we’re assigning to step_when:
step_when="epoch": learning rate scheduled every epochs, sototal_steps = epochs * 1 = epochsstep_when="val": learning rate scheduled in validation loop, sototal_steps = epochs * len(val_loader)if validation loop is run after every epoch (akaeval_epoch=1), andtotal_steps = epochs * len(val_loader) / 2if validation loop is run after every two epochs (akaeval_epoch=2), etc.step_when="train": learning rate scheduled in training loop, sototal_steps = epochs * len(train_loader)(this is what we’re using in the example above)
Similarly, we also create a custom config CustomSchedulerConfig, defining the required method make_scheduler with shceduler name, the model, and the optimizer as inputs.
[7]:
@configclass
class CustomSchedulerConfig(SchedulerConfig):
def __init__(self, name, arguments=None):
arguments = scheduler_arguments(name)
super(CustomSchedulerConfig, self).__init__(name=name, arguments=arguments)
def make_scheduler(self, model: torch.nn.Module, optimizer: torch.optim):
return create_scheduler(self.name, model, optimizer)
scheduler_config = CustomSchedulerConfig(name = "step")
scheduler_config
[7]:
CustomSchedulerConfig(name='step', arguments={'step_size': 1, 'gamma': 0.99, 'step_when': 'epoch'})
Here the configuration attribute
namewill be used in the search space, and we’re allowing search space to be["step", "cycle", "plateau"].In the constructor, we pass the parameter names and the dictionary arguments (constructed by
scheduler_argumentsfunction, corresponding to the scheduler) to the parent class constructor. The parent class constructor will accordingly initialize 2 attributes:nameandarguments.Inside
make_scheduler, we callcreate_scheduler, passing the optimizer, the name, and and the model, and it will return the matching scheduler.
Note
Remember to redefine the TrainConfig config class, hence the ParallelConfig, before creating the training config to pass in the optimizer and scheduler config objects. E.g:
@configclass
class CustomTrainConfig(TrainConfig):
optimizer_config: CustomOptimizerConfig
scheduler_config: CustomSchedulerConfig
@configclass
class CustomParallelConfig(ParallelConfig):
model_config: CustomModelConfig
train_config: CustomTrainConfig
Create search space for optimizers and schedulers#
Now, we can try out different optimizers and schedulers by providing a search space to the ablator.
[8]:
search_space = {
"train_config.optimizer_config.lr": SearchSpace(value_range = [0.001, 0.01], value_type = 'float'),
"train_config.optimizer_config.name": SearchSpace(categorical_values = ["adam", "sgd", "adamw"]),
"train_config.scheduler_config.name": SearchSpace(categorical_values = ["step", "cycle", "plateau"])
}
Note:
In the default OptimizerConfig, providing the name of the optimizer in the config will create an object of the associated optimizer class. Changing the name in the search space will result in a mismatch in the class type, causing an error. Hence, we have to define custom configs in this way.
One benefit this method offers is that we can define our custom optimizers or schedulers as a class and pass them to their respective configs for the ablator to manage training.
Conclusion#
Finally, with this, we can now test different optimizers and schedulers for our model. You can go to for a complete example of an experiment.