Diff of /utils/autobatch.py [000000] .. [190ca4]

Switch to unified view

a b/utils/autobatch.py
1
# YOLOv5 🚀 by Ultralytics, AGPL-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
11
from utils.general import LOGGER, colorstr
12
from utils.torch_utils import profile
13
14
15
def check_train_batch_size(model, imgsz=640, amp=True):
16
    # Check YOLOv5 training batch size
17
    with torch.cuda.amp.autocast(amp):
18
        return autobatch(deepcopy(model).train(), imgsz)  # compute optimal batch size
19
20
21
def autobatch(model, imgsz=640, fraction=0.8, batch_size=16):
22
    # Automatically estimate best YOLOv5 batch size to use `fraction` of available CUDA memory
23
    # Usage:
24
    #     import torch
25
    #     from utils.autobatch import autobatch
26
    #     model = torch.hub.load('ultralytics/yolov5', 'yolov5s', autoshape=False)
27
    #     print(autobatch(model))
28
29
    # Check device
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
    if torch.backends.cudnn.benchmark:
37
        LOGGER.info(f'{prefix} ⚠️ Requires torch.backends.cudnn.benchmark=False, using default batch-size {batch_size}')
38
        return batch_size
39
40
    # Inspect CUDA memory
41
    gb = 1 << 30  # bytes to GiB (1024 ** 3)
42
    d = str(device).upper()  # 'CUDA:0'
43
    properties = torch.cuda.get_device_properties(device)  # device properties
44
    t = properties.total_memory / gb  # GiB total
45
    r = torch.cuda.memory_reserved(device) / gb  # GiB reserved
46
    a = torch.cuda.memory_allocated(device) / gb  # GiB allocated
47
    f = t - (r + a)  # GiB free
48
    LOGGER.info(f'{prefix}{d} ({properties.name}) {t:.2f}G total, {r:.2f}G reserved, {a:.2f}G allocated, {f:.2f}G free')
49
50
    # Profile batch sizes
51
    batch_sizes = [1, 2, 4, 8, 16]
52
    try:
53
        img = [torch.empty(b, 3, imgsz, imgsz) for b in batch_sizes]
54
        results = profile(img, model, n=3, device=device)
55
    except Exception as e:
56
        LOGGER.warning(f'{prefix}{e}')
57
58
    # Fit a solution
59
    y = [x[2] for x in results if x]  # memory [2]
60
    p = np.polyfit(batch_sizes[:len(y)], y, deg=1)  # first degree polynomial fit
61
    b = int((f * fraction - p[1]) / p[0])  # y intercept (optimal batch size)
62
    if None in results:  # some sizes failed
63
        i = results.index(None)  # first fail index
64
        if b >= batch_sizes[i]:  # y intercept above failure point
65
            b = batch_sizes[max(i - 1, 0)]  # select prior safe point
66
    if b < 1 or b > 1024:  # b outside of safe range
67
        b = batch_size
68
        LOGGER.warning(f'{prefix}WARNING ⚠️ CUDA anomaly detected, recommend restart environment and retry command.')
69
70
    fraction = (np.polyval(p, b) + r + a) / t  # actual fraction predicted
71
    LOGGER.info(f'{prefix}Using batch-size {b} for {d} {t * fraction:.2f}G/{t:.2f}G ({fraction * 100:.0f}%) ✅')
72
    return b