|
| 1 | +""" |
| 2 | +Multiple Optimizers on SVMSurrogate |
| 3 | +======================================= |
| 4 | +
|
| 5 | +This example shows how to run SMAC-HB and SMAC-random-search on SVMSurrogate |
| 6 | +
|
| 7 | +Please install the necessary dependencies via ``pip install .`` and singularity (v3.5). |
| 8 | +https://sylabs.io/guides/3.5/user-guide/quick_start.html#quick-installation-steps |
| 9 | +""" |
| 10 | +import logging |
| 11 | +from pathlib import Path |
| 12 | +from time import time |
| 13 | + |
| 14 | +import numpy as np |
| 15 | +from smac.facade.smac_mf_facade import SMAC4MF |
| 16 | +from smac.facade.roar_facade import ROAR |
| 17 | +from smac.intensification.hyperband import Hyperband |
| 18 | +from smac.scenario.scenario import Scenario |
| 19 | +from smac.callbacks import IncorporateRunResultCallback |
| 20 | + |
| 21 | +from hpobench.container.benchmarks.surrogates.svm_benchmark import SurrogateSVMBenchmark |
| 22 | +from hpobench.abstract_benchmark import AbstractBenchmark |
| 23 | +from hpobench.util.example_utils import set_env_variables_to_use_only_one_core |
| 24 | + |
| 25 | +logger = logging.getLogger("minicomp") |
| 26 | +logging.basicConfig(level=logging.INFO) |
| 27 | +set_env_variables_to_use_only_one_core() |
| 28 | + |
| 29 | + |
| 30 | +class Callback(IncorporateRunResultCallback): |
| 31 | + def __init__(self): |
| 32 | + self.budget = 10 |
| 33 | + |
| 34 | + def __call__(self, smbo, run_info, result, time_left) -> None: |
| 35 | + self.budget -= run_info.budget |
| 36 | + if self.budget < 0: |
| 37 | + # No budget left |
| 38 | + raise ValueError |
| 39 | + |
| 40 | +def create_smac_rs(benchmark, output_dir: Path, seed: int): |
| 41 | + # Set up SMAC-HB |
| 42 | + cs = benchmark.get_configuration_space(seed=seed) |
| 43 | + |
| 44 | + scenario_dict = {"run_obj": "quality", # we optimize quality (alternative to runtime) |
| 45 | + "wallclock-limit": 60, |
| 46 | + "cs": cs, |
| 47 | + "deterministic": "true", |
| 48 | + "runcount-limit": 200, |
| 49 | + "limit_resources": True, # Uses pynisher to limit memory and runtime |
| 50 | + "cutoff": 1800, # runtime limit for target algorithm |
| 51 | + "memory_limit": 10000, # adapt this to reasonable value for your hardware |
| 52 | + "output_dir": output_dir, |
| 53 | + "abort_on_first_run_crash": True, |
| 54 | + } |
| 55 | + |
| 56 | + scenario = Scenario(scenario_dict) |
| 57 | + def optimization_function_wrapper(cfg, seed, **kwargs): |
| 58 | + """ Helper-function: simple wrapper to use the benchmark with smac """ |
| 59 | + result_dict = benchmark.objective_function(cfg, rng=seed) |
| 60 | + cs.sample_configuration() |
| 61 | + return result_dict['function_value'] |
| 62 | + |
| 63 | + smac = ROAR(scenario=scenario, |
| 64 | + rng=np.random.RandomState(seed), |
| 65 | + tae_runner=optimization_function_wrapper, |
| 66 | + ) |
| 67 | + return smac |
| 68 | + |
| 69 | +def create_smac_hb(benchmark, output_dir: Path, seed: int): |
| 70 | + # Set up SMAC-HB |
| 71 | + cs = benchmark.get_configuration_space(seed=seed) |
| 72 | + |
| 73 | + scenario_dict = {"run_obj": "quality", # we optimize quality (alternative to runtime) |
| 74 | + "wallclock-limit": 60, |
| 75 | + "cs": cs, |
| 76 | + "deterministic": "true", |
| 77 | + "runcount-limit": 200, |
| 78 | + "limit_resources": True, # Uses pynisher to limit memory and runtime |
| 79 | + "cutoff": 1800, # runtime limit for target algorithm |
| 80 | + "memory_limit": 10000, # adapt this to reasonable value for your hardware |
| 81 | + "output_dir": output_dir, |
| 82 | + "abort_on_first_run_crash": True, |
| 83 | + } |
| 84 | + |
| 85 | + scenario = Scenario(scenario_dict) |
| 86 | + def optimization_function_wrapper(cfg, seed, instance, budget): |
| 87 | + """ Helper-function: simple wrapper to use the benchmark with smac """ |
| 88 | + result_dict = benchmark.objective_function(cfg, rng=seed, |
| 89 | + fidelity={"dataset_fraction": budget}) |
| 90 | + cs.sample_configuration() |
| 91 | + return result_dict['function_value'] |
| 92 | + |
| 93 | + smac = SMAC4MF(scenario=scenario, |
| 94 | + rng=np.random.RandomState(seed), |
| 95 | + tae_runner=optimization_function_wrapper, |
| 96 | + intensifier=Hyperband, |
| 97 | + intensifier_kwargs={'initial_budget': 0.1, 'max_budget': 1, 'eta': 3} |
| 98 | + ) |
| 99 | + return smac |
| 100 | + |
| 101 | + |
| 102 | +def run_experiment(out_path: str, on_travis: bool = False): |
| 103 | + |
| 104 | + out_path = Path(out_path) |
| 105 | + out_path.mkdir(exist_ok=True) |
| 106 | + |
| 107 | + hb_res = [] |
| 108 | + rs_res = [] |
| 109 | + for i in range(4): |
| 110 | + benchmark = SurrogateSVMBenchmark(rng=i) |
| 111 | + smac = create_smac_hb(benchmark=benchmark, seed=i, output_dir=out_path) |
| 112 | + callback = Callback() |
| 113 | + smac.register_callback(callback) |
| 114 | + try: |
| 115 | + smac.optimize() |
| 116 | + except ValueError: |
| 117 | + print("Done") |
| 118 | + incumbent = smac.solver.incumbent |
| 119 | + inc_res = benchmark.objective_function(configuration=incumbent) |
| 120 | + hb_res.append(inc_res["function_value"]) |
| 121 | + |
| 122 | + benchmark = SurrogateSVMBenchmark(rng=i) |
| 123 | + smac = create_smac_rs(benchmark=benchmark, seed=i, output_dir=out_path) |
| 124 | + callback = Callback() |
| 125 | + smac.register_callback(callback) |
| 126 | + try: |
| 127 | + smac.optimize() |
| 128 | + except ValueError: |
| 129 | + print("Done") |
| 130 | + incumbent = smac.solver.incumbent |
| 131 | + inc_res = benchmark.objective_function(configuration=incumbent) |
| 132 | + rs_res.append(inc_res["function_value"]) |
| 133 | + |
| 134 | + print("SMAC-HB", hb_res, np.median(hb_res)) |
| 135 | + print("SMAC-RS", rs_res, np.median(rs_res)) |
| 136 | + |
| 137 | + |
| 138 | +if __name__ == "__main__": |
| 139 | + import argparse |
| 140 | + parser = argparse.ArgumentParser(prog='HPOBench - SVM comp', |
| 141 | + description='Run different opts on SVM Surrogate', |
| 142 | + usage='%(prog)s --out_path <string>') |
| 143 | + parser.add_argument('--out_path', default='./svm_comp', type=str) |
| 144 | + parser.add_argument('--on_travis', action='store_true', |
| 145 | + help='Flag to speed up the run on the continuous integration tool \"travis\". This flag can be' |
| 146 | + 'ignored by the user') |
| 147 | + args = parser.parse_args() |
| 148 | + |
| 149 | + run_experiment(out_path=args.out_path, on_travis=args.on_travis) |
0 commit comments