CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
hukaixuan19970627

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

GitHub Repository: hukaixuan19970627/yolov5_obb
Path: blob/master/utils/autobatch.py
Views: 475
1
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
"""
3
Auto-batch utils
4
"""
5
6
from copy import deepcopy
7
8
import numpy as np
9
import torch
10
from torch.cuda import amp
11
12
from utils.general import LOGGER, colorstr
13
from utils.torch_utils import profile
14
15
16
def check_train_batch_size(model, imgsz=640):
17
# Check YOLOv5 training batch size
18
with amp.autocast():
19
return autobatch(deepcopy(model).train(), imgsz) # compute optimal batch size
20
21
22
def autobatch(model, imgsz=640, fraction=0.9, batch_size=16):
23
# Automatically estimate best batch size to use `fraction` of available CUDA memory
24
# Usage:
25
# import torch
26
# from utils.autobatch import autobatch
27
# model = torch.hub.load('ultralytics/yolov5', 'yolov5s', autoshape=False)
28
# print(autobatch(model))
29
30
prefix = colorstr('AutoBatch: ')
31
LOGGER.info(f'{prefix}Computing optimal batch size for --imgsz {imgsz}')
32
device = next(model.parameters()).device # get model device
33
if device.type == 'cpu':
34
LOGGER.info(f'{prefix}CUDA not detected, using default CPU batch-size {batch_size}')
35
return batch_size
36
37
d = str(device).upper() # 'CUDA:0'
38
properties = torch.cuda.get_device_properties(device) # device properties
39
t = properties.total_memory / 1024 ** 3 # (GiB)
40
r = torch.cuda.memory_reserved(device) / 1024 ** 3 # (GiB)
41
a = torch.cuda.memory_allocated(device) / 1024 ** 3 # (GiB)
42
f = t - (r + a) # free inside reserved
43
LOGGER.info(f'{prefix}{d} ({properties.name}) {t:.2f}G total, {r:.2f}G reserved, {a:.2f}G allocated, {f:.2f}G free')
44
45
batch_sizes = [1, 2, 4, 8, 16]
46
try:
47
img = [torch.zeros(b, 3, imgsz, imgsz) for b in batch_sizes]
48
y = profile(img, model, n=3, device=device)
49
except Exception as e:
50
LOGGER.warning(f'{prefix}{e}')
51
52
y = [x[2] for x in y if x] # memory [2]
53
batch_sizes = batch_sizes[:len(y)]
54
p = np.polyfit(batch_sizes, y, deg=1) # first degree polynomial fit
55
b = int((f * fraction - p[1]) / p[0]) # y intercept (optimal batch size)
56
LOGGER.info(f'{prefix}Using batch-size {b} for {d} {t * fraction:.2f}G/{t:.2f}G ({fraction * 100:.0f}%)')
57
return b
58
59