I'll create a simple hyperparameter search solution that meets your requirements. Here's a straightforward implementation using Ray Tune, which is actively maintained and designed for distributed hyperparameter tuning:
import os
import yaml
import json
import random
import numpy as np
from typing import Dict, Any, Optional, List
import ray
from ray import tune
from ray.tune.search.basic_variant import BasicVariantGenerator
from ray.tune.search import Searcher
import subprocess
from pathlib import Path
# Import your existing experiment code
from run_experiment import train
class TriedParamsTracker:
"""Tracks previously tried parameter combinations and suggests new ones."""
def __init__(self, file_path: str):
self.file_path = file_path
self.tried_params = self._load_tried_params()
def _load_tried_params(self) -> List[Dict[str, Any]]:
"""Load previously tried parameters from file."""
if os.path.exists(self.file_path):
with open(self.file_path, 'r') as f:
return json.load(f)
return []
def save_params(self, params: Dict[str, Any], result: float):
"""Save tried parameters and their results."""
params_with_result = params.copy()
params_with_result['result'] = result
self.tried_params.append(params_with_result)
with open(self.file_path, 'w') as f:
json.dump(self.tried_params, f, indent=2)
def get_tried_configs(self) -> List[Dict[str, Any]]:
"""Get all previously tried configurations."""
return self.tried_params
class CustomSearcher(Searcher):
"""Custom searcher that accounts for stochasticity in results."""
def __init__(self, space: Dict[str, Any], tracker: TriedParamsTracker, metric: str, mode: str):
super().__init__(metric=metric, mode=mode)
self.space = space
self.tracker = tracker
self.rng = random.Random(42) # Fixed seed for reproducibility
self._tried_configs = set()
self._load_tried_configs()
def _load_tried_configs(self):
"""Load previously tried configurations from tracker."""
for config in self.tracker.get_tried_configs():
# Remove result from config for comparison
config_copy = config.copy()
if 'result' in config_copy:
del config_copy['result']
self._tried_configs.add(self._hash_config(config_copy))
def _hash_config(self, config: Dict[str, Any]) -> str:
"""Create a unique hash for a configuration."""
return json.dumps(config, sort_keys=True)
def suggest(self, trial_id: str) -> Optional[Dict[str, Any]]:
"""Suggest a new configuration to try."""
# Try to find a configuration that hasn't been tried yet
for _ in range(100): # Limit attempts to avoid infinite loop
config = {}
for param, space_def in self.space.items():
if isinstance(space_def, list):
config[param] = self.rng.choice(space_def)
elif isinstance(space_def, dict) and 'min' in space_def and 'max' in space_def:
if space_def.get('type', 'float') == 'int':
config[param] = self.rng.randint(space_def['min'], space_def['max'])
else:
config[param] = self.rng.uniform(space_def['min'], space_def['max'])
else:
config[param] = space_def # Fixed parameter
config_hash = self._hash_config(config)
if config_hash not in self._tried_configs:
self._tried_configs.add(config_hash)
return config
return None # No new configuration found
def on_trial_complete(self, trial_id: str, result: Optional[Dict] = None, **kwargs):
"""Process completed trial results."""
if result:
# Update tracker with the new result
self.tracker.save_params(
self._trial_configs[trial_id],
result.get(self.metric, float('nan'))
)
def run_isolated_experiment(config: Dict[str, Any]) -> Dict[str, float]:
"""Run experiment in an isolated process and return results."""
# Create a temporary config file for this run
tmp_config_path = f"/tmp/config_{os.getpid()}.yaml"
with open(tmp_config_path, 'w') as f:
yaml.dump(config, f)
# Run the experiment in a separate process
cmd = ["python", "run_experiment.py", "--config", tmp_config_path]
result = subprocess.run(cmd, capture_output=True, text=True)
# Parse the output to get the final loss
# Assuming the train function prints the final loss in a specific format
loss = None
for line in result.stdout.split('\n'):
if line.startswith("FINAL_LOSS:"):
loss = float(line.split(":")[1].strip())
# Clean up
os.remove(tmp_config_path)
return {"loss": loss if loss is not None else float('inf')}
def launch_hparam_search(config_file: str, **overrides):
"""Launch hyperparameter search based on config file and overrides."""
# Load the configuration
with open(config_file, 'r') as f:
config = yaml.safe_load(f)
# Apply overrides
for key, value in overrides.items():
config[key] = value
# Extract search-specific parameters
gpu_id = config.pop('gpu_id', 0)
num_parallel = config.pop('num_parallel', 1)
num_experiments = config.pop('num_experiments', 10)
env_id = config.get('env_id', 'default')
logger_tag = config.get('logger_tag', 'experiment')
# Set up environment variables for GPU
os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_id)
# Create tracker file path
tracker_file = f"{env_id}_{logger_tag}_hparam_history.json"
tracker = TriedParamsTracker(tracker_file)
# Extract search space from config
search_space = {}
fixed_params = {}
for key, value in config.items():
if isinstance(value, dict) and ('min' in value or 'values' in value):
if 'values' in value:
search_space[key] = value['values']
else:
search_space[key] = value
else:
fixed_params[key] = value
# Initialize Ray
if not ray.is_initialized():
ray.init(num_cpus=num_parallel)
# Create custom searcher
searcher = CustomSearcher(
space=search_space,
tracker=tracker,
metric="loss",
mode="min"
)
# Run the hyperparameter search
analysis = tune.run(
run_isolated_experiment,
config=fixed_params,
search_alg=searcher,
num_samples=num_experiments,
resources_per_trial={"cpu": 1, "gpu": 1/num_parallel},
verbose=1
)
# Print the best configuration
best_config = analysis.get_best_config(metric="loss", mode="min")
best_result = analysis.get_best_trial(metric="loss", mode="min").last_result
print(f"Best configuration: {best_config}")
print(f"Best result: {best_result['loss']}")
return best_config, best_result
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Hyperparameter search")
parser.add_argument("--config", type=str, required=True, help="Path to YAML config file")
parser.add_argument("--overrides", nargs="*", default=[], help="Override parameters in format key=value")
args = parser.parse_args()
# Parse overrides
override_dict = {}
for override in args.overrides:
key, value = override.split("=")
# Try to convert to appropriate type
try:
value = eval(value)
except:
pass
override_dict[key] = value
launch_hparam_search(args.config, **override_dict)
Would you like me to explain or break down this code?