Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Path: blob/master/utils/autobatch.py
Views: 475
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license1"""2Auto-batch utils3"""45from copy import deepcopy67import numpy as np8import torch9from torch.cuda import amp1011from utils.general import LOGGER, colorstr12from utils.torch_utils import profile131415def check_train_batch_size(model, imgsz=640):16# Check YOLOv5 training batch size17with amp.autocast():18return autobatch(deepcopy(model).train(), imgsz) # compute optimal batch size192021def autobatch(model, imgsz=640, fraction=0.9, batch_size=16):22# Automatically estimate best batch size to use `fraction` of available CUDA memory23# Usage:24# import torch25# from utils.autobatch import autobatch26# model = torch.hub.load('ultralytics/yolov5', 'yolov5s', autoshape=False)27# print(autobatch(model))2829prefix = colorstr('AutoBatch: ')30LOGGER.info(f'{prefix}Computing optimal batch size for --imgsz {imgsz}')31device = next(model.parameters()).device # get model device32if device.type == 'cpu':33LOGGER.info(f'{prefix}CUDA not detected, using default CPU batch-size {batch_size}')34return batch_size3536d = str(device).upper() # 'CUDA:0'37properties = torch.cuda.get_device_properties(device) # device properties38t = properties.total_memory / 1024 ** 3 # (GiB)39r = torch.cuda.memory_reserved(device) / 1024 ** 3 # (GiB)40a = torch.cuda.memory_allocated(device) / 1024 ** 3 # (GiB)41f = t - (r + a) # free inside reserved42LOGGER.info(f'{prefix}{d} ({properties.name}) {t:.2f}G total, {r:.2f}G reserved, {a:.2f}G allocated, {f:.2f}G free')4344batch_sizes = [1, 2, 4, 8, 16]45try:46img = [torch.zeros(b, 3, imgsz, imgsz) for b in batch_sizes]47y = profile(img, model, n=3, device=device)48except Exception as e:49LOGGER.warning(f'{prefix}{e}')5051y = [x[2] for x in y if x] # memory [2]52batch_sizes = batch_sizes[:len(y)]53p = np.polyfit(batch_sizes, y, deg=1) # first degree polynomial fit54b = int((f * fraction - p[1]) / p[0]) # y intercept (optimal batch size)55LOGGER.info(f'{prefix}Using batch-size {b} for {d} {t * fraction:.2f}G/{t:.2f}G ({fraction * 100:.0f}%)')56return b575859