async_hyperband_example.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #!/usr/bin/env python
  2. import argparse
  3. import time
  4. from typing import Any, Dict
  5. from ray import tune
  6. from ray.tune.schedulers import AsyncHyperBandScheduler
  7. def evaluation_fn(step, width, height) -> float:
  8. # simulate model evaluation
  9. time.sleep(0.1)
  10. return (0.1 + width * step / 100) ** (-1) + height * 0.1
  11. def easy_objective(config: Dict[str, Any]) -> None:
  12. # Config contains the hyperparameters to tune
  13. width, height = config["width"], config["height"]
  14. for step in range(config["steps"]):
  15. # Iterative training function - can be an arbitrary training procedure
  16. intermediate_score = evaluation_fn(step, width, height)
  17. # Feed the score back back to Tune.
  18. tune.report({"iterations": step, "mean_loss": intermediate_score})
  19. if __name__ == "__main__":
  20. parser = argparse.ArgumentParser(description="AsyncHyperBand optimization example")
  21. parser.add_argument(
  22. "--smoke-test", action="store_true", help="Finish quickly for testing"
  23. )
  24. args, _ = parser.parse_known_args()
  25. # AsyncHyperBand enables aggressive early stopping of poorly performing trials
  26. scheduler = AsyncHyperBandScheduler(
  27. grace_period=5, # Minimum training iterations before stopping
  28. max_t=100, # Maximum training iterations
  29. )
  30. tuner = tune.Tuner(
  31. tune.with_resources(easy_objective, {"cpu": 1, "gpu": 0}),
  32. run_config=tune.RunConfig(
  33. name="asynchyperband_test",
  34. stop={"training_iteration": 1 if args.smoke_test else 9999},
  35. verbose=1,
  36. ),
  37. tune_config=tune.TuneConfig(
  38. metric="mean_loss",
  39. mode="min",
  40. scheduler=scheduler,
  41. num_samples=20, # Number of trials to run
  42. ),
  43. param_space={
  44. "steps": 100,
  45. "width": tune.uniform(10, 100),
  46. "height": tune.uniform(0, 100),
  47. },
  48. )
  49. # Run the hyperparameter optimization
  50. results = tuner.fit()
  51. print(f"Best hyperparameters found: {results.get_best_result().config}")