在使用 Pytorch 进行训练模型的时候,常常需要配置 CPU、GPU训练,甚至多卡用户还需要管理GPU。除此之外,用户虽然配置好了显卡配置,但是还需要检测下配置,以防报错,因此需要还是需要检测下
在此,通过 select_device 函数进行判断,首先获取 时间信息 和 torch的版本信息,然后首先判断是否是 cpu设备,然后再判断 GPU设备
如果是多卡用户,记得 batch_size 与 cuda数量匹配
assert batch_size % n == 0, f’batch-size {batch_size} not multiple of GPU count {n}’
import os
import torch
import datetime
def date_modified(path=__file__):
# return human-readable file modification date, i.e. '2021-3-26'
t = datetime.datetime.fromtimestamp(Path(path).stat().st_mtime)
return f'{
t.year}-{
t.month}-{
t.day}'
def select_device(device='', batch_size=None):
# device = 'cpu' or '0' or '0,1,2,3'
s = f'YOLOv5 {
date_modified()} torch {
torch.__version__} ' # string
cpu = device.lower() == 'cpu'
if cpu:
os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # force torch.cuda.is_available() = False
elif device: # non-cpu device requested
os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable
assert torch.cuda.is_available(), f'CUDA unavailable, invalid device {
device} requested' # check availability
cuda = not cpu and torch.cuda.is_available()
if cuda:
n = torch.cuda.device_count()
if n > 1 and batch_size: # check that batch_size is compatible with device_count
assert batch_size % n == 0, f'batch-size {
batch_size} not multiple of GPU count {
n}'
space = ' ' * len(s)
for i, d in enumerate(device.split(',') if device else range(n)):
p = torch.cuda.get_device_properties(i)
s += f"{
'' if i == 0 else space}CUDA:{
d} ({
p.name}, {
p.total_memory / 1024 ** 2}MB)\n" # bytes to MB
else:
s += 'CPU\n'
# logger.info(s.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else s) # emoji-safe
print(s)
return torch.device('cuda:0' if cuda else 'cpu')
# Print 结果
# Out[1]: 'YOLOv5 2021-7-2 torch 1.13+cu116 CUDA:0 (NVIDIA GeForce RTX 4090, 24563.5MB)\n'
文章评论