yolov8逐步分解(2)_DetectionTrainer类初始化过程
接上2篇文章,继续讲解yolov8训练过程中的模型加载过程。
使用默认参数完成训练器trainer的初始化后,执行训练函数train()开始YOLOV8的训练。
1. train()方法实现代码如下所示:
def train(self):
"""Allow device='', device=None on Multi-GPU systems to default to device=0."""
#判断设置使用设备总数
if isinstance(self.args.device, int) or self.args.device: # i.e.device=0 or device=[0,1,2,3]
world_size = torch.cuda.device_count() #计算当前可用设备数
elif torch.cuda.is_available(): # i.e. device=None or device=''#判断cuda是否可用
world_size = 1 # default to device 0
else: # i.e. device='cpu' or 'mps'
world_size = 0
# Run subprocess if DDP training, else train normally 分布式训练
#分布式训练
if world_size > 1 and 'LOCAL_RANK' not in os.environ:
# Argument checks
if self.args.rect:
LOGGER.warning("WARNING ⚠️ 'rect=True' is incompatible with Multi-GPU training, setting rect=False")
self.args.rect = False
# Command
cmd, file = generate_ddp_command(world_size, self)
try:
LOGGER.info(f'DDP command: {cmd}')
subprocess.run(cmd, check=True)
except Exception as e:
raise e
finally:
ddp_cleanup(self, str(file))
else:
self._do_train(world_size)
上述代码中,主要实现一个功能:判断本次训练使用的机器的个数即world_size的值。world_size 可用于配置分布式训练系统,确保所有设备都能够正确地参与到训练过程中。详细解释请参考博客yolo中RANK、LOACL_RANK以及WORLD_SIZE的介绍-CSDN博客。
若world_size > 1,则进行分布式训练,本次训练使用的机器为单机单卡,所以world_size = 1,不支持分布式训练。直接进入单机训练函数self._do_train(world_size)。
2. _do_train()函数实现代码(部分)截图如下:
下面将逐步讲解_setup_train()函数的功能.
3. _setup_train()代码实现如下
def _setup_train(self, world_size):
"""
Builds dataloaders and optimizer on correct rank process. #构建数据加载器和优化器
"""
# Model
self.run_callbacks('on_pretrain_routine_start')
c