To achieve your requirements, you can use the optuna library for hyperparameter optimization. It is actively maintained, allows for specifying ranges in a config file, and supports parallel execution. Below is a simple implementation that meets your criteria:
Step 1: Install Optuna
First, install the optuna library if you haven't already:
pip install optuna
Step 2: Create a YAML Config File
Create a YAML file (config.yaml) to specify the hyperparameter ranges, GPU to use, number of parallel jobs, and total number of experiments:
env_id: "my_env"
logger_tag: "my_tag"
gpu: 0
n_jobs: 4
n_trials: 100
hyperparameters:
learning_rate:
type: float
low: 0.0001
high: 0.1
batch_size:
type: int
low: 32
high: 256
hidden_units:
type: int
low: 64
high: 512
Step 3: Create a Launcher Function
Create a Python script (launcher.py) to read the config, launch the experiments, and handle the hyperparameter optimization:
import yaml
import optuna
import multiprocessing
import os
from run_experiment import train
def read_config(config_path):
with open(config_path, 'r') as file:
return yaml.safe_load(file)
def objective(trial, cfg):
params = {}
for key, param in cfg['hyperparameters'].items():
if param['type'] == 'float':
params[key] = trial.suggest_float(key, param['low'], param['high'])
elif param['type'] == 'int':
params[key] = trial.suggest_int(key, param['low'], param['high'])
cfg.update(params)
return train(cfg)
def launch_experiments(config_path, override_params=None):
cfg = read_config(config_path)
if override_params:
cfg.update(override_params)
study = optuna.create_study(direction='minimize', storage=f'sqlite:///{cfg["env_id"]}_{cfg["logger_tag"]}.db', study_name='hparam_optimization', load_if_exists=True)
def run_trial(trial):
return objective(trial, cfg)
optuna.logging.set_verbosity(optuna.logging.INFO)
study.optimize(run_trial, n_trials=cfg['n_trials'], n_jobs=cfg['n_jobs'])
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description='Launch hyperparameter optimization experiments.')
parser.add_argument('config', type=str, help='Path to config file')
parser.add_argument('--overrides', type=str, help='Override parameters in JSON format', default=None)
args = parser.parse_args()
override_params = yaml.safe_load(args.overrides) if args.overrides else None
launch_experiments(args.config, override_params)
Step 4: Run the Launcher
You can now run the launcher script with your YAML config file:
python launcher.py config.yaml
If you want to override some parameters, you can pass them as a JSON string:
python launcher.py config.yaml --overrides '{"n_trials": 200, "n_jobs": 2}'
Explanation
- Optuna: Used for hyperparameter optimization.
- YAML Config: Specifies hyperparameter ranges and other settings.
- Isolated Runs: Optuna supports parallel execution with
n_jobs parameter.
- Simple Code: The code is straightforward and easy to understand.
- No Hydra: The config is read using the
yaml library.
- Launcher Function:
launch_experiments function to start the optimization.
- Local File: Optuna uses a SQLite database to store trial results.
- Stochasticity: Optuna handles stochasticity by running multiple trials.
This setup should meet all your requirements effectively.