nevergrad_example.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. """This example demonstrates the usage of Nevergrad with Ray Tune.
  2. It also checks that it is usable with a separate scheduler.
  3. Requires the Nevergrad library to be installed (`pip install nevergrad`).
  4. """
  5. import time
  6. from ray import tune
  7. from ray.tune.schedulers import AsyncHyperBandScheduler
  8. from ray.tune.search import ConcurrencyLimiter
  9. from ray.tune.search.nevergrad import NevergradSearch
  10. def evaluation_fn(step, width, height):
  11. return (0.1 + width * step / 100) ** (-1) + height * 0.1
  12. def easy_objective(config):
  13. # Hyperparameters
  14. width, height = config["width"], config["height"]
  15. for step in range(config["steps"]):
  16. # Iterative training function - can be any arbitrary training procedure
  17. intermediate_score = evaluation_fn(step, width, height)
  18. # Feed the score back back to Tune.
  19. tune.report({"iterations": step, "mean_loss": intermediate_score})
  20. time.sleep(0.1)
  21. if __name__ == "__main__":
  22. import argparse
  23. import nevergrad as ng
  24. parser = argparse.ArgumentParser()
  25. parser.add_argument(
  26. "--smoke-test", action="store_true", help="Finish quickly for testing"
  27. )
  28. args, _ = parser.parse_known_args()
  29. # Optional: Pass the parameter space yourself
  30. # space = ng.p.Dict(
  31. # width=ng.p.Scalar(lower=0, upper=20),
  32. # height=ng.p.Scalar(lower=-100, upper=100),
  33. # activation=ng.p.Choice(choices=["relu", "tanh"])
  34. # )
  35. algo = NevergradSearch(
  36. optimizer=ng.optimizers.OnePlusOne,
  37. # space=space, # If you want to set the space manually
  38. )
  39. algo = ConcurrencyLimiter(algo, max_concurrent=4)
  40. scheduler = AsyncHyperBandScheduler()
  41. tuner = tune.Tuner(
  42. easy_objective,
  43. tune_config=tune.TuneConfig(
  44. metric="mean_loss",
  45. mode="min",
  46. search_alg=algo,
  47. scheduler=scheduler,
  48. num_samples=10 if args.smoke_test else 50,
  49. ),
  50. run_config=tune.RunConfig(name="nevergrad"),
  51. param_space={
  52. "steps": 100,
  53. "width": tune.uniform(0, 20),
  54. "height": tune.uniform(-100, 100),
  55. "activation": tune.choice(["relu", "tanh"]),
  56. },
  57. )
  58. results = tuner.fit()
  59. print("Best hyperparameters found were: ", results.get_best_result().config)