I have a python code to run a ML experiment given a set of parameters. I'm looking for a way to do hparams search so that:
The library is used, active and mantained
I can specify the range of hparams to tune in a yaml file and then use something to read it
Each run should be completely isolated. An independent process spawned
Write the simples, most understandable code possible.
Don't use hydra.
I want to call a function (maybe a launcher) in which I specify: the yaml config file and some (variable number) override parameters. The yaml file should contain also the gpu to use, the number of parallel jobs to launch, the total number of experiments to make
It should be created a local file (bulid from the yaml variables env_id and logger_tag) of "tried hparams" so that each new run that is spawned reads that file to decide the new set of hparams to try.
The hparams selection should account for stocasticity in the final return value.
I already have run_experiment.py where there is a train(cfg) function that runs a full experiments and returns the final loss.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Below is one possible solution. In our example we use Optuna for the hyper‐parameter selection (it’s an active and well‐maintained library), PyYAML to read a YAML file, and we spawn each trial as a new process by calling your existing experiment script via Python’s subprocess API. (The final loss is returned via stdout as JSON.) You’ll need to adapt your experiment script (here assumed to be named run_experiment.py) so that when it’s called with a command‐line argument like this it runs the experiment (using its internal train(cfg) function) and then prints a JSON string to stdout containing the final loss (for example, { "loss": <value> }).
Below is a minimal example that meets your requirements:
python
# launcher.py
import argparse
import json
import os
import subprocess
import yaml
import optuna
def load_config(yaml_file):
"""Load YAML configuration from a file."""
with open(yaml_file, "r") as f:
config = yaml.safe_load(f)
return config
def merge_overrides(config, overrides):
"""
Merge override parameters (in key=value syntax) from the command line
into the main config. (Only at the top level.)
"""
for override in overrides:
if "=" not in override:
continue
key, value = override.split("=", 1)
# Convert the value to int/float/bool if possible.
if value.lower() in ["true", "false"]:
value = value.lower() == "true"
else:
try:
if "." in value:
value = float(value)
else:
value = int(value)
except ValueError:
pass # leave as string if you can’t convert
config[key] = value
return config
def update_tried_file(tried_file, trial_info):
"""Append the new trial configuration and its outcome into a local file."""
tried = []
if os.path.exists(tried_file):
with open(tried_file, "r") as f:
tried = json.load(f)
tried.append(trial_info)
with open(tried_file, "w") as f:
json.dump(tried, f, indent=4)
def objective(trial, config, tried_file):
# Determine hparams: the YAML is expected to have an "hparams" dict.
# Example YAML snippet:
# hparams:
# lr:
# type: float
# low: 0.0001
# high: 0.01
# log: true
# batch_size:
# type: int
# low: 32
# high: 128
# step: 32
hparams = {}
if "hparams" in config:
for name, spec in config["hparams"].items():
ptype = spec.get("type", "float")
if ptype == "float":
low = spec["low"]
high = spec["high"]
log = spec.get("log", False)
hparams[name] = trial.suggest_float(name, low, high, log=log)
elif ptype == "int":
low = spec["low"]
high = spec["high"]
step = spec.get("step", 1)
hparams[name] = trial.suggest_int(name, low, high, step=step)
elif ptype == "categorical":
choices = spec["choices"]
hparams[name] = trial.suggest_categorical(name, choices)
else:
raise ValueError(f"Unsupported type {ptype} for hyperparameter {name}")
# Create a trial-specific config.
trial_config = config.copy() # shallow copy is sufficient if YAML has only primitives.
trial_config.update(hparams)
# (Optional) You might want to print or log hparams for debugging:
print(f"Trial {trial.number}: {hparams}")
# Call the experiment code (run_experiment.py) as an independent process.
# We pass the trial configuration (with hyperparameter settings) as a JSON string.
# It is assumed that run_experiment.py, when given --config "json_string" runs
# the experiment (using train(cfg)) and writes a JSON object to stdout containing "loss".
python_exec = os.environ.get("PYTHON_EXEC", "python")
cmd = [python_exec, "run_experiment.py", "--config", json.dumps(trial_config)]
print("Running:", " ".join(cmd))
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
print("Error in trial:", result.stderr)
raise RuntimeError("Experiment failed on trial {}".format(trial.number))
try:
output = json.loads(result.stdout)
loss = output["loss"]
except Exception as e:
print("Could not parse experiment output:", result.stdout)
raise e
# Save the hparams and outcome in our log file.
trial_info = {"trial": trial.number, "params": hparams, "loss": loss}
update_tried_file(tried_file, trial_info)
return loss
def main():
parser = argparse.ArgumentParser(
description="Launch hyperparameter search experiments."
)
parser.add_argument(
"--config",
type=str,
required=True,
help="Path to the YAML configuration file (specify ranges, GPU, etc.)",
)
parser.add_argument(
"overrides",
nargs="*",
help="Override parameters in key=value format (e.g., gpu=1 total_experiments=50)",
)
args = parser.parse_args()
# Load YAML configuration and merge any command line overrides.
config = load_config(args.config)
config = merge_overrides(config, args.overrides)
# Get search parameters from the config.
total_experiments = config.get("total_experiments", 10)
parallel_jobs = config.get("parallel_jobs", 1)
# Create the local file to track tried hyperparameters.
# The file name is built from the provided env_id and logger_tag.
env_id = config.get("env_id", "default")
logger_tag = config.get("logger_tag", "default")
tried_file = f"tried_hparams_{env_id}_{logger_tag}.json"
# Create an Optuna study.
study = optuna.create_study(direction="minimize")
study.optimize(
lambda trial: objective(trial, config, tried_file),
n_trials=total_experiments,
n_jobs=parallel_jobs,
)
print("== Best Trial ==")
best = study.best_trial
print("Loss:", best.value)
print("Params:")
for key, value in best.params.items():
print(f" {key}: {value}")
if __name__ == "__main__":
main()
How This Works
Config File & Overrides:
– The launcher reads a YAML file that contains settings such as which GPU to use, the number of parallel jobs, total experiments, and the hyperparameter ranges.
– Additional command-line overrides (using key=value syntax) can override YAML settings.
Trial Logging:
– A file named tried_hparams_{env_id}_{logger_tag}.json is maintained. For each new trial run the script reads (and appends to) this file with the tried hyperparameters and the final loss.
Trials as Isolated Processes:
– The objective() function uses Python’s subprocess.run() to spawn a new process for each trial. It calls run_experiment.py with a JSON‐encoded configuration. This guarantees each run is completely isolated.
Stochasticity:
– By using Optuna’s sampling (and running full experiments that may return slightly different loss values each run), the hparams search naturally “accounts for stochasticity” in the final loss.
Simplicity & Clarity:
– The code is commented and uses only a few libraries (PyYAML, Optuna, and Python standard libraries), keeping it simple and understandable.
No Hydra:
– Hydra is not used at all in this implementation.
A Note on run_experiment.py
Your existing run_experiment.py should be adapted so that when executed from the command line it does roughly the following:
Parse a command-line argument (e.g., --config) that is a JSON string.
Convert that JSON into a configuration dictionary.
Call your train(cfg) function.
Print the final loss as JSON to stdout.
For example, a minimal version of run_experiment.py might look like this:
python
# run_experiment.py
import argparse
import json
from my_training_module import train # your train function
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--config", type=str, required=True, help="Experiment configuration in JSON format")
args = parser.parse_args()
cfg = json.loads(args.config)
loss = train(cfg) # run your experiment
# Print result as JSON so that the launcher can parse it.
print(json.dumps({"loss": loss}))
if __name__ == "__main__":
main()
Running the Launcher
Assuming the launcher is saved as launcher.py and your YAML config is in my_config.yaml, you would run:
This command uses the settings from the YAML file, overrides the GPU setting to 1 and total experiments to 50, and then launches the hyperparameter search over multiple independent processes.
This solution meets your requirements:
Active & maintained libraries: Optuna and PyYAML.
YAML‐based hparams ranges: Specified in the YAML file.
Isolated runs: Each trial is run in its own process.
Simple & understandable code: The launcher and its comments illustrate the flow clearly.
No Hydra: Hydra is not used.
Custom launcher interface: You call the launcher with a config file and variable overrides.
Local “tried hparams” file: A file is created (named from env_id and logger_tag) and shared between runs.
Stochastic tuning: Each trial’s loss (which may be stochastic) is used by Optuna for optimization.
Feel free to modify the details (such as how the new configuration is merged or how the subprocess is invoked) to best suit your project.