autobatch.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. """
  3. Functions for estimating the best YOLO batch size to use a fraction of the available CUDA memory in PyTorch.
  4. """
  5. from copy import deepcopy
  6. import numpy as np
  7. import torch
  8. from ultralytics.utils import DEFAULT_CFG, LOGGER, colorstr
  9. from ultralytics.utils.torch_utils import profile
  10. def check_train_batch_size(model, imgsz=640, amp=True):
  11. """
  12. Check YOLO training batch size using the autobatch() function.
  13. Args:
  14. model (torch.nn.Module): YOLO model to check batch size for.
  15. imgsz (int): Image size used for training.
  16. amp (bool): If True, use automatic mixed precision (AMP) for training.
  17. Returns:
  18. (int): Optimal batch size computed using the autobatch() function.
  19. """
  20. with torch.cuda.amp.autocast(amp):
  21. return autobatch(deepcopy(model).train(), imgsz) # compute optimal batch size
  22. def autobatch(model, imgsz=640, fraction=0.67, batch_size=DEFAULT_CFG.batch):
  23. """
  24. Automatically estimate the best YOLO batch size to use a fraction of the available CUDA memory.
  25. Args:
  26. model (torch.nn.module): YOLO model to compute batch size for.
  27. imgsz (int, optional): The image size used as input for the YOLO model. Defaults to 640.
  28. fraction (float, optional): The fraction of available CUDA memory to use. Defaults to 0.67.
  29. batch_size (int, optional): The default batch size to use if an error is detected. Defaults to 16.
  30. Returns:
  31. (int): The optimal batch size.
  32. """
  33. # Check device
  34. prefix = colorstr('AutoBatch: ')
  35. LOGGER.info(f'{prefix}Computing optimal batch size for imgsz={imgsz}')
  36. device = next(model.parameters()).device # get model device
  37. if device.type == 'cpu':
  38. LOGGER.info(f'{prefix}CUDA not detected, using default CPU batch-size {batch_size}')
  39. return batch_size
  40. if torch.backends.cudnn.benchmark:
  41. LOGGER.info(f'{prefix} ⚠️ Requires torch.backends.cudnn.benchmark=False, using default batch-size {batch_size}')
  42. return batch_size
  43. # Inspect CUDA memory
  44. gb = 1 << 30 # bytes to GiB (1024 ** 3)
  45. d = str(device).upper() # 'CUDA:0'
  46. properties = torch.cuda.get_device_properties(device) # device properties
  47. t = properties.total_memory / gb # GiB total
  48. r = torch.cuda.memory_reserved(device) / gb # GiB reserved
  49. a = torch.cuda.memory_allocated(device) / gb # GiB allocated
  50. f = t - (r + a) # GiB free
  51. LOGGER.info(f'{prefix}{d} ({properties.name}) {t:.2f}G total, {r:.2f}G reserved, {a:.2f}G allocated, {f:.2f}G free')
  52. # Profile batch sizes
  53. batch_sizes = [1, 2, 4, 8, 16]
  54. try:
  55. img = [torch.empty(b, 3, imgsz, imgsz) for b in batch_sizes]
  56. results = profile(img, model, n=3, device=device)
  57. # Fit a solution
  58. y = [x[2] for x in results if x] # memory [2]
  59. p = np.polyfit(batch_sizes[:len(y)], y, deg=1) # first degree polynomial fit
  60. b = int((f * fraction - p[1]) / p[0]) # y intercept (optimal batch size)
  61. if None in results: # some sizes failed
  62. i = results.index(None) # first fail index
  63. if b >= batch_sizes[i]: # y intercept above failure point
  64. b = batch_sizes[max(i - 1, 0)] # select prior safe point
  65. if b < 1 or b > 1024: # b outside of safe range
  66. b = batch_size
  67. LOGGER.info(f'{prefix}WARNING ⚠️ CUDA anomaly detected, using default batch-size {batch_size}.')
  68. fraction = (np.polyval(p, b) + r + a) / t # actual fraction predicted
  69. LOGGER.info(f'{prefix}Using batch-size {b} for {d} {t * fraction:.2f}G/{t:.2f}G ({fraction * 100:.0f}%) ✅')
  70. return b
  71. except Exception as e:
  72. LOGGER.warning(f'{prefix}WARNING ⚠️ error detected: {e}, using default batch-size {batch_size}.')
  73. return batch_size