|
| 1 | +import ray |
| 2 | +from ray import tune |
| 3 | +import os |
| 4 | +import argparse |
| 5 | +import yaml |
| 6 | + |
| 7 | +from bootstrap.run import run |
| 8 | + |
| 9 | + |
| 10 | +def train_func(config): |
| 11 | + # change exp dir |
| 12 | + |
| 13 | + option_path = config.pop("option_file") |
| 14 | + os.chdir(config.pop("run_dir")) |
| 15 | + exp_dir = config.pop("exp_dir_prefix") |
| 16 | + |
| 17 | + override_options = { |
| 18 | + "resume": "last", |
| 19 | + } |
| 20 | + |
| 21 | + for name, value in config.items(): |
| 22 | + override_options[name] = value |
| 23 | + if type(value) == list: |
| 24 | + value_str = ",".join(str(x) for x in value) |
| 25 | + else: |
| 26 | + value_str = str(value) |
| 27 | + exp_dir += f"--{name.split('.')[-1]}_{value_str}" |
| 28 | + |
| 29 | + override_options["exp.dir"] = exp_dir |
| 30 | + run(path_opts=option_path, override_options=override_options, run_parser=False) |
| 31 | + |
| 32 | + |
| 33 | +def build_tune_config(option_path): |
| 34 | + with open(option_path, "r") as yaml_file: |
| 35 | + options = yaml.load(yaml_file) |
| 36 | + config = {} |
| 37 | + for key, values in options["gridsearch"].items(): |
| 38 | + config[key] = tune.grid_search(values) |
| 39 | + config["exp_dir_prefix"] = options["exp"]["dir"] |
| 40 | + config["option_file"] = option_path |
| 41 | + config["run_dir"] = os.getcwd() |
| 42 | + return config, config["exp_dir_prefix"] |
| 43 | + |
| 44 | + |
| 45 | +def grid(path_opts, cpu_per_trial=2, gpu_per_trial=0.5): |
| 46 | + config, name = build_tune_config(path_opts) |
| 47 | + ray.init() |
| 48 | + tune.run( |
| 49 | + train_func, |
| 50 | + name=name, |
| 51 | + # stop={"avg_inc_acc": 100}, |
| 52 | + config=config, |
| 53 | + resources_per_trial={"cpu": cpu_per_trial, "gpu": gpu_per_trial}, |
| 54 | + local_dir="ray_results", |
| 55 | + ) |
| 56 | + |
| 57 | + # TODO: tune analysis to get best results. |
| 58 | + # For this, we need to extract the best score for each experiment. |
| 59 | + # analysis = tune.run( |
| 60 | + # train_mnist, config={"lr": tune.grid_search([0.001, 0.01, 0.1])}) |
| 61 | + # print("Best config: ", analysis.get_best_config(metric="mean_accuracy")) |
| 62 | + |
| 63 | + |
| 64 | +def main(): |
| 65 | + parser = argparse.ArgumentParser() |
| 66 | + parser.add_argument("-o", "--path_opts", required=True, help="Main file") |
| 67 | + parser.add_argument( |
| 68 | + "-g", |
| 69 | + "--gpu", |
| 70 | + type=float, |
| 71 | + default=0.5, |
| 72 | + help="Percentage of gpu needed for one training", |
| 73 | + ) |
| 74 | + parser.add_argument( |
| 75 | + "-c", |
| 76 | + "--cpu", |
| 77 | + type=float, |
| 78 | + default=2, |
| 79 | + help="Percentage of gpu needed for one training", |
| 80 | + ) |
| 81 | + args = parser.parse_args() |
| 82 | + grid(args.path_opts, args.cpu, args.gpu) |
| 83 | + |
| 84 | + |
| 85 | +if __name__ == "__main__": |
| 86 | + main() |
0 commit comments