tuner.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. from ultralytics.cfg import TASK2DATA, TASK2METRIC
  3. from ultralytics.utils import DEFAULT_CFG_DICT, LOGGER, NUM_THREADS
  4. def run_ray_tune(model,
  5. space: dict = None,
  6. grace_period: int = 10,
  7. gpu_per_trial: int = None,
  8. max_samples: int = 10,
  9. **train_args):
  10. """
  11. Runs hyperparameter tuning using Ray Tune.
  12. Args:
  13. model (YOLO): Model to run the tuner on.
  14. space (dict, optional): The hyperparameter search space. Defaults to None.
  15. grace_period (int, optional): The grace period in epochs of the ASHA scheduler. Defaults to 10.
  16. gpu_per_trial (int, optional): The number of GPUs to allocate per trial. Defaults to None.
  17. max_samples (int, optional): The maximum number of trials to run. Defaults to 10.
  18. train_args (dict, optional): Additional arguments to pass to the `train()` method. Defaults to {}.
  19. Returns:
  20. (dict): A dictionary containing the results of the hyperparameter search.
  21. Raises:
  22. ModuleNotFoundError: If Ray Tune is not installed.
  23. """
  24. if train_args is None:
  25. train_args = {}
  26. try:
  27. from ray import tune
  28. from ray.air import RunConfig
  29. from ray.air.integrations.wandb import WandbLoggerCallback
  30. from ray.tune.schedulers import ASHAScheduler
  31. except ImportError:
  32. raise ModuleNotFoundError('Tuning hyperparameters requires Ray Tune. Install with: pip install "ray[tune]"')
  33. try:
  34. import wandb
  35. assert hasattr(wandb, '__version__')
  36. except (ImportError, AssertionError):
  37. wandb = False
  38. default_space = {
  39. # 'optimizer': tune.choice(['SGD', 'Adam', 'AdamW', 'NAdam', 'RAdam', 'RMSProp']),
  40. 'lr0': tune.uniform(1e-5, 1e-1),
  41. 'lrf': tune.uniform(0.01, 1.0), # final OneCycleLR learning rate (lr0 * lrf)
  42. 'momentum': tune.uniform(0.6, 0.98), # SGD momentum/Adam beta1
  43. 'weight_decay': tune.uniform(0.0, 0.001), # optimizer weight decay 5e-4
  44. 'warmup_epochs': tune.uniform(0.0, 5.0), # warmup epochs (fractions ok)
  45. 'warmup_momentum': tune.uniform(0.0, 0.95), # warmup initial momentum
  46. 'box': tune.uniform(0.02, 0.2), # box loss gain
  47. 'cls': tune.uniform(0.2, 4.0), # cls loss gain (scale with pixels)
  48. 'hsv_h': tune.uniform(0.0, 0.1), # image HSV-Hue augmentation (fraction)
  49. 'hsv_s': tune.uniform(0.0, 0.9), # image HSV-Saturation augmentation (fraction)
  50. 'hsv_v': tune.uniform(0.0, 0.9), # image HSV-Value augmentation (fraction)
  51. 'degrees': tune.uniform(0.0, 45.0), # image rotation (+/- deg)
  52. 'translate': tune.uniform(0.0, 0.9), # image translation (+/- fraction)
  53. 'scale': tune.uniform(0.0, 0.9), # image scale (+/- gain)
  54. 'shear': tune.uniform(0.0, 10.0), # image shear (+/- deg)
  55. 'perspective': tune.uniform(0.0, 0.001), # image perspective (+/- fraction), range 0-0.001
  56. 'flipud': tune.uniform(0.0, 1.0), # image flip up-down (probability)
  57. 'fliplr': tune.uniform(0.0, 1.0), # image flip left-right (probability)
  58. 'mosaic': tune.uniform(0.0, 1.0), # image mixup (probability)
  59. 'mixup': tune.uniform(0.0, 1.0), # image mixup (probability)
  60. 'copy_paste': tune.uniform(0.0, 1.0)} # segment copy-paste (probability)
  61. def _tune(config):
  62. """
  63. Trains the YOLO model with the specified hyperparameters and additional arguments.
  64. Args:
  65. config (dict): A dictionary of hyperparameters to use for training.
  66. Returns:
  67. None.
  68. """
  69. model._reset_callbacks()
  70. config.update(train_args)
  71. model.train(**config)
  72. # Get search space
  73. if not space:
  74. space = default_space
  75. LOGGER.warning('WARNING ⚠️ search space not provided, using default search space.')
  76. # Get dataset
  77. data = train_args.get('data', TASK2DATA[model.task])
  78. space['data'] = data
  79. if 'data' not in train_args:
  80. LOGGER.warning(f'WARNING ⚠️ data not provided, using default "data={data}".')
  81. # Define the trainable function with allocated resources
  82. trainable_with_resources = tune.with_resources(_tune, {'cpu': NUM_THREADS, 'gpu': gpu_per_trial or 0})
  83. # Define the ASHA scheduler for hyperparameter search
  84. asha_scheduler = ASHAScheduler(time_attr='epoch',
  85. metric=TASK2METRIC[model.task],
  86. mode='max',
  87. max_t=train_args.get('epochs') or DEFAULT_CFG_DICT['epochs'] or 100,
  88. grace_period=grace_period,
  89. reduction_factor=3)
  90. # Define the callbacks for the hyperparameter search
  91. tuner_callbacks = [WandbLoggerCallback(project='YOLOv8-tune')] if wandb else []
  92. # Create the Ray Tune hyperparameter search tuner
  93. tuner = tune.Tuner(trainable_with_resources,
  94. param_space=space,
  95. tune_config=tune.TuneConfig(scheduler=asha_scheduler, num_samples=max_samples),
  96. run_config=RunConfig(callbacks=tuner_callbacks, storage_path='./runs/tune'))
  97. # Run the hyperparameter search
  98. tuner.fit()
  99. # Return the results of the hyperparameter search
  100. return tuner.get_results()