You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
665 lines
30 KiB
665 lines
30 KiB
2 years ago
|
# Ultralytics YOLO 🚀, AGPL-3.0 license
|
||
2 years ago
|
"""
|
||
2 years ago
|
Train a model on a dataset
|
||
2 years ago
|
|
||
2 years ago
|
Usage:
|
||
|
$ yolo mode=train model=yolov8n.pt data=coco128.yaml imgsz=640 epochs=100 batch=16
|
||
|
"""
|
||
2 years ago
|
import math
|
||
2 years ago
|
import os
|
||
2 years ago
|
import subprocess
|
||
2 years ago
|
import time
|
||
2 years ago
|
from copy import deepcopy
|
||
2 years ago
|
from datetime import datetime, timedelta
|
||
2 years ago
|
from pathlib import Path
|
||
|
|
||
2 years ago
|
import numpy as np
|
||
2 years ago
|
import torch
|
||
2 years ago
|
from torch import distributed as dist
|
||
|
from torch import nn, optim
|
||
2 years ago
|
from torch.cuda import amp
|
||
|
from torch.nn.parallel import DistributedDataParallel as DDP
|
||
|
from tqdm import tqdm
|
||
|
|
||
1 year ago
|
from ultralytics.cfg import get_cfg
|
||
|
from ultralytics.data.utils import check_cls_dataset, check_det_dataset
|
||
2 years ago
|
from ultralytics.nn.tasks import attempt_load_one_weight, attempt_load_weights
|
||
1 year ago
|
from ultralytics.utils import (DEFAULT_CFG, LOGGER, RANK, SETTINGS, TQDM_BAR_FORMAT, __version__, callbacks, clean_url,
|
||
|
colorstr, emojis, yaml_save)
|
||
|
from ultralytics.utils.autobatch import check_train_batch_size
|
||
|
from ultralytics.utils.checks import check_amp, check_file, check_imgsz, print_args
|
||
|
from ultralytics.utils.dist import ddp_cleanup, generate_ddp_command
|
||
|
from ultralytics.utils.files import get_latest_run, increment_path
|
||
|
from ultralytics.utils.torch_utils import (EarlyStopping, ModelEMA, de_parallel, init_seeds, one_cycle, select_device,
|
||
|
strip_optimizer)
|
||
2 years ago
|
|
||
|
|
||
|
class BaseTrainer:
|
||
2 years ago
|
"""
|
||
|
BaseTrainer
|
||
|
|
||
2 years ago
|
A base class for creating trainers.
|
||
2 years ago
|
|
||
|
Attributes:
|
||
2 years ago
|
args (SimpleNamespace): Configuration for the trainer.
|
||
2 years ago
|
check_resume (method): Method to check if training should be resumed from a saved checkpoint.
|
||
|
validator (BaseValidator): Validator instance.
|
||
|
model (nn.Module): Model instance.
|
||
|
callbacks (defaultdict): Dictionary of callbacks.
|
||
|
save_dir (Path): Directory to save results.
|
||
|
wdir (Path): Directory to save weights.
|
||
|
last (Path): Path to last checkpoint.
|
||
|
best (Path): Path to best checkpoint.
|
||
2 years ago
|
save_period (int): Save checkpoint every x epochs (disabled if < 1).
|
||
2 years ago
|
batch_size (int): Batch size for training.
|
||
|
epochs (int): Number of epochs to train for.
|
||
|
start_epoch (int): Starting epoch for training.
|
||
|
device (torch.device): Device to use for training.
|
||
|
amp (bool): Flag to enable AMP (Automatic Mixed Precision).
|
||
|
scaler (amp.GradScaler): Gradient scaler for AMP.
|
||
|
data (str): Path to data.
|
||
|
trainset (torch.utils.data.Dataset): Training dataset.
|
||
|
testset (torch.utils.data.Dataset): Testing dataset.
|
||
|
ema (nn.Module): EMA (Exponential Moving Average) of the model.
|
||
|
lf (nn.Module): Loss function.
|
||
|
scheduler (torch.optim.lr_scheduler._LRScheduler): Learning rate scheduler.
|
||
|
best_fitness (float): The best fitness value achieved.
|
||
|
fitness (float): Current fitness value.
|
||
|
loss (float): Current loss value.
|
||
|
tloss (float): Total loss value.
|
||
|
loss_names (list): List of loss names.
|
||
|
csv (Path): Path to results CSV file.
|
||
|
"""
|
||
|
|
||
2 years ago
|
def __init__(self, cfg=DEFAULT_CFG, overrides=None, _callbacks=None):
|
||
2 years ago
|
"""
|
||
2 years ago
|
Initializes the BaseTrainer class.
|
||
2 years ago
|
|
||
2 years ago
|
Args:
|
||
2 years ago
|
cfg (str, optional): Path to a configuration file. Defaults to DEFAULT_CFG.
|
||
2 years ago
|
overrides (dict, optional): Configuration overrides. Defaults to None.
|
||
|
"""
|
||
2 years ago
|
self.args = get_cfg(cfg, overrides)
|
||
2 years ago
|
self.device = select_device(self.args.device, self.args.batch)
|
||
2 years ago
|
self.check_resume()
|
||
2 years ago
|
self.validator = None
|
||
2 years ago
|
self.model = None
|
||
2 years ago
|
self.metrics = None
|
||
2 years ago
|
self.plots = {}
|
||
2 years ago
|
init_seeds(self.args.seed + 1 + RANK, deterministic=self.args.deterministic)
|
||
2 years ago
|
|
||
2 years ago
|
# Dirs
|
||
2 years ago
|
project = self.args.project or Path(SETTINGS['runs_dir']) / self.args.task
|
||
2 years ago
|
name = self.args.name or f'{self.args.mode}'
|
||
2 years ago
|
if hasattr(self.args, 'save_dir'):
|
||
|
self.save_dir = Path(self.args.save_dir)
|
||
|
else:
|
||
|
self.save_dir = Path(
|
||
2 years ago
|
increment_path(Path(project) / name, exist_ok=self.args.exist_ok if RANK in (-1, 0) else True))
|
||
2 years ago
|
self.wdir = self.save_dir / 'weights' # weights dir
|
||
2 years ago
|
if RANK in (-1, 0):
|
||
2 years ago
|
self.wdir.mkdir(parents=True, exist_ok=True) # make dir
|
||
2 years ago
|
self.args.save_dir = str(self.save_dir)
|
||
|
yaml_save(self.save_dir / 'args.yaml', vars(self.args)) # save run args
|
||
2 years ago
|
self.last, self.best = self.wdir / 'last.pt', self.wdir / 'best.pt' # checkpoint paths
|
||
2 years ago
|
self.save_period = self.args.save_period
|
||
2 years ago
|
|
||
2 years ago
|
self.batch_size = self.args.batch
|
||
2 years ago
|
self.epochs = self.args.epochs
|
||
2 years ago
|
self.start_epoch = 0
|
||
2 years ago
|
if RANK == -1:
|
||
2 years ago
|
print_args(vars(self.args))
|
||
2 years ago
|
|
||
2 years ago
|
# Device
|
||
2 years ago
|
if self.device.type == 'cpu':
|
||
|
self.args.workers = 0 # faster CPU training as time dominated by inference, not dataloading
|
||
2 years ago
|
|
||
2 years ago
|
# Model and Dataset
|
||
2 years ago
|
self.model = self.args.model
|
||
2 years ago
|
try:
|
||
|
if self.args.task == 'classify':
|
||
|
self.data = check_cls_dataset(self.args.data)
|
||
2 years ago
|
elif self.args.data.endswith('.yaml') or self.args.task in ('detect', 'segment'):
|
||
2 years ago
|
self.data = check_det_dataset(self.args.data)
|
||
|
if 'yaml_file' in self.data:
|
||
|
self.args.data = self.data['yaml_file'] # for validating 'yolo train data=url.zip' usage
|
||
|
except Exception as e:
|
||
2 years ago
|
raise RuntimeError(emojis(f"Dataset '{clean_url(self.args.data)}' error ❌ {e}")) from e
|
||
2 years ago
|
|
||
2 years ago
|
self.trainset, self.testset = self.get_dataset(self.data)
|
||
2 years ago
|
self.ema = None
|
||
2 years ago
|
|
||
2 years ago
|
# Optimization utils init
|
||
|
self.lf = None
|
||
|
self.scheduler = None
|
||
|
|
||
2 years ago
|
# Epoch level metrics
|
||
2 years ago
|
self.best_fitness = None
|
||
|
self.fitness = None
|
||
|
self.loss = None
|
||
2 years ago
|
self.tloss = None
|
||
2 years ago
|
self.loss_names = ['Loss']
|
||
2 years ago
|
self.csv = self.save_dir / 'results.csv'
|
||
2 years ago
|
self.plot_idx = [0, 1, 2]
|
||
2 years ago
|
|
||
2 years ago
|
# Callbacks
|
||
2 years ago
|
self.callbacks = _callbacks or callbacks.get_default_callbacks()
|
||
2 years ago
|
if RANK in (-1, 0):
|
||
2 years ago
|
callbacks.add_integration_callbacks(self)
|
||
2 years ago
|
|
||
2 years ago
|
def add_callback(self, event: str, callback):
|
||
2 years ago
|
"""
|
||
2 years ago
|
Appends the given callback.
|
||
2 years ago
|
"""
|
||
2 years ago
|
self.callbacks[event].append(callback)
|
||
2 years ago
|
|
||
2 years ago
|
def set_callback(self, event: str, callback):
|
||
2 years ago
|
"""
|
||
2 years ago
|
Overrides the existing callbacks with the given callback.
|
||
2 years ago
|
"""
|
||
2 years ago
|
self.callbacks[event] = [callback]
|
||
2 years ago
|
|
||
2 years ago
|
def run_callbacks(self, event: str):
|
||
2 years ago
|
"""Run all existing callbacks associated with a particular event."""
|
||
2 years ago
|
for callback in self.callbacks.get(event, []):
|
||
2 years ago
|
callback(self)
|
||
|
|
||
2 years ago
|
def train(self):
|
||
2 years ago
|
"""Allow device='', device=None on Multi-GPU systems to default to device=0."""
|
||
2 years ago
|
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=''
|
||
|
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
|
||
2 years ago
|
if world_size > 1 and 'LOCAL_RANK' not in os.environ:
|
||
2 years ago
|
# 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)
|
||
2 years ago
|
try:
|
||
2 years ago
|
LOGGER.info(f'DDP command: {cmd}')
|
||
2 years ago
|
subprocess.run(cmd, check=True)
|
||
2 years ago
|
except Exception as e:
|
||
2 years ago
|
raise e
|
||
2 years ago
|
finally:
|
||
2 years ago
|
ddp_cleanup(self, str(file))
|
||
2 years ago
|
else:
|
||
2 years ago
|
self._do_train(world_size)
|
||
2 years ago
|
|
||
2 years ago
|
def _setup_ddp(self, world_size):
|
||
2 years ago
|
"""Initializes and sets the DistributedDataParallel parameters for training."""
|
||
2 years ago
|
torch.cuda.set_device(RANK)
|
||
|
self.device = torch.device('cuda', RANK)
|
||
2 years ago
|
LOGGER.info(f'DDP info: RANK {RANK}, WORLD_SIZE {world_size}, DEVICE {self.device}')
|
||
2 years ago
|
os.environ['NCCL_BLOCKING_WAIT'] = '1' # set to enforce timeout
|
||
2 years ago
|
dist.init_process_group(
|
||
|
'nccl' if dist.is_nccl_available() else 'gloo',
|
||
|
timeout=timedelta(seconds=10800), # 3 hours
|
||
|
rank=RANK,
|
||
|
world_size=world_size)
|
||
2 years ago
|
|
||
2 years ago
|
def _setup_train(self, world_size):
|
||
2 years ago
|
"""
|
||
2 years ago
|
Builds dataloaders and optimizer on correct rank process.
|
||
2 years ago
|
"""
|
||
2 years ago
|
# Model
|
||
2 years ago
|
self.run_callbacks('on_pretrain_routine_start')
|
||
2 years ago
|
ckpt = self.setup_model()
|
||
2 years ago
|
self.model = self.model.to(self.device)
|
||
2 years ago
|
self.set_model_attributes()
|
||
2 years ago
|
# Check AMP
|
||
2 years ago
|
self.amp = torch.tensor(self.args.amp).to(self.device) # True or False
|
||
|
if self.amp and RANK in (-1, 0): # Single-GPU and DDP
|
||
2 years ago
|
callbacks_backup = callbacks.default_callbacks.copy() # backup callbacks as check_amp() resets them
|
||
|
self.amp = torch.tensor(check_amp(self.model), device=self.device)
|
||
|
callbacks.default_callbacks = callbacks_backup # restore callbacks
|
||
2 years ago
|
if RANK > -1 and world_size > 1: # DDP
|
||
2 years ago
|
dist.broadcast(self.amp, src=0) # broadcast the tensor from rank 0 to all other ranks (returns None)
|
||
|
self.amp = bool(self.amp) # as boolean
|
||
2 years ago
|
self.scaler = amp.GradScaler(enabled=self.amp)
|
||
2 years ago
|
if world_size > 1:
|
||
2 years ago
|
self.model = DDP(self.model, device_ids=[RANK])
|
||
2 years ago
|
# Check imgsz
|
||
|
gs = max(int(self.model.stride.max() if hasattr(self.model, 'stride') else 32), 32) # grid size (max stride)
|
||
2 years ago
|
self.args.imgsz = check_imgsz(self.args.imgsz, stride=gs, floor=gs, max_dim=1)
|
||
2 years ago
|
# Batch size
|
||
|
if self.batch_size == -1:
|
||
|
if RANK == -1: # single-GPU only, estimate best batch size
|
||
2 years ago
|
self.args.batch = self.batch_size = check_train_batch_size(self.model, self.args.imgsz, self.amp)
|
||
2 years ago
|
else:
|
||
|
SyntaxError('batch=-1 to use AutoBatch is only available in Single-GPU training. '
|
||
|
'Please pass a valid batch size value for Multi-GPU DDP training, i.e. batch=16')
|
||
|
|
||
2 years ago
|
# Dataloaders
|
||
|
batch_size = self.batch_size // max(world_size, 1)
|
||
|
self.train_loader = self.get_dataloader(self.trainset, batch_size=batch_size, rank=RANK, mode='train')
|
||
|
if RANK in (-1, 0):
|
||
|
self.test_loader = self.get_dataloader(self.testset, batch_size=batch_size * 2, rank=-1, mode='val')
|
||
|
self.validator = self.get_validator()
|
||
|
metric_keys = self.validator.metrics.keys + self.label_loss_items(prefix='val')
|
||
|
self.metrics = dict(zip(metric_keys, [0] * len(metric_keys))) # TODO: init metrics for plot_results()?
|
||
|
self.ema = ModelEMA(self.model)
|
||
1 year ago
|
if self.args.plots:
|
||
2 years ago
|
self.plot_training_labels()
|
||
|
|
||
2 years ago
|
# Optimizer
|
||
2 years ago
|
self.accumulate = max(round(self.args.nbs / self.batch_size), 1) # accumulate loss before optimizing
|
||
2 years ago
|
weight_decay = self.args.weight_decay * self.batch_size * self.accumulate / self.args.nbs # scale weight_decay
|
||
2 years ago
|
iterations = math.ceil(len(self.train_loader.dataset) / max(self.batch_size, self.args.nbs)) * self.epochs
|
||
2 years ago
|
self.optimizer = self.build_optimizer(model=self.model,
|
||
|
name=self.args.optimizer,
|
||
|
lr=self.args.lr0,
|
||
|
momentum=self.args.momentum,
|
||
2 years ago
|
decay=weight_decay,
|
||
|
iterations=iterations)
|
||
2 years ago
|
# Scheduler
|
||
|
if self.args.cos_lr:
|
||
2 years ago
|
self.lf = one_cycle(1, self.args.lrf, self.epochs) # cosine 1->hyp['lrf']
|
||
2 years ago
|
else:
|
||
2 years ago
|
self.lf = lambda x: (1 - x / self.epochs) * (1.0 - self.args.lrf) + self.args.lrf # linear
|
||
2 years ago
|
self.scheduler = optim.lr_scheduler.LambdaLR(self.optimizer, lr_lambda=self.lf)
|
||
2 years ago
|
self.stopper, self.stop = EarlyStopping(patience=self.args.patience), False
|
||
2 years ago
|
self.resume_training(ckpt)
|
||
2 years ago
|
self.scheduler.last_epoch = self.start_epoch - 1 # do not move
|
||
2 years ago
|
self.run_callbacks('on_pretrain_routine_end')
|
||
2 years ago
|
|
||
2 years ago
|
def _do_train(self, world_size=1):
|
||
2 years ago
|
"""Train completed, evaluate and plot if specified by arguments."""
|
||
2 years ago
|
if world_size > 1:
|
||
2 years ago
|
self._setup_ddp(world_size)
|
||
2 years ago
|
|
||
2 years ago
|
self._setup_train(world_size)
|
||
2 years ago
|
|
||
|
self.epoch_time = None
|
||
|
self.epoch_time_start = time.time()
|
||
|
self.train_time_start = time.time()
|
||
2 years ago
|
nb = len(self.train_loader) # number of batches
|
||
2 years ago
|
nw = max(round(self.args.warmup_epochs *
|
||
|
nb), 100) if self.args.warmup_epochs > 0 else -1 # number of warmup iterations
|
||
2 years ago
|
last_opt_step = -1
|
||
2 years ago
|
self.run_callbacks('on_train_start')
|
||
2 years ago
|
LOGGER.info(f'Image sizes {self.args.imgsz} train, {self.args.imgsz} val\n'
|
||
|
f'Using {self.train_loader.num_workers * (world_size or 1)} dataloader workers\n'
|
||
|
f"Logging results to {colorstr('bold', self.save_dir)}\n"
|
||
|
f'Starting training for {self.epochs} epochs...')
|
||
2 years ago
|
if self.args.close_mosaic:
|
||
|
base_idx = (self.epochs - self.args.close_mosaic) * nb
|
||
|
self.plot_idx.extend([base_idx, base_idx + 1, base_idx + 2])
|
||
2 years ago
|
epoch = self.epochs # predefine for resume fully trained model edge cases
|
||
2 years ago
|
for epoch in range(self.start_epoch, self.epochs):
|
||
|
self.epoch = epoch
|
||
2 years ago
|
self.run_callbacks('on_train_epoch_start')
|
||
2 years ago
|
self.model.train()
|
||
2 years ago
|
if RANK != -1:
|
||
2 years ago
|
self.train_loader.sampler.set_epoch(epoch)
|
||
2 years ago
|
pbar = enumerate(self.train_loader)
|
||
2 years ago
|
# Update dataloader attributes (optional)
|
||
|
if epoch == (self.epochs - self.args.close_mosaic):
|
||
2 years ago
|
LOGGER.info('Closing dataloader mosaic')
|
||
2 years ago
|
if hasattr(self.train_loader.dataset, 'mosaic'):
|
||
|
self.train_loader.dataset.mosaic = False
|
||
|
if hasattr(self.train_loader.dataset, 'close_mosaic'):
|
||
|
self.train_loader.dataset.close_mosaic(hyp=self.args)
|
||
2 years ago
|
self.train_loader.reset()
|
||
2 years ago
|
|
||
2 years ago
|
if RANK in (-1, 0):
|
||
2 years ago
|
LOGGER.info(self.progress_string())
|
||
2 years ago
|
pbar = tqdm(enumerate(self.train_loader), total=nb, bar_format=TQDM_BAR_FORMAT)
|
||
2 years ago
|
self.tloss = None
|
||
2 years ago
|
self.optimizer.zero_grad()
|
||
2 years ago
|
for i, batch in pbar:
|
||
2 years ago
|
self.run_callbacks('on_train_batch_start')
|
||
2 years ago
|
# Warmup
|
||
2 years ago
|
ni = i + nb * epoch
|
||
|
if ni <= nw:
|
||
|
xi = [0, nw] # x interp
|
||
2 years ago
|
self.accumulate = max(1, np.interp(ni, xi, [1, self.args.nbs / self.batch_size]).round())
|
||
2 years ago
|
for j, x in enumerate(self.optimizer.param_groups):
|
||
2 years ago
|
# Bias lr falls from 0.1 to lr0, all other lrs rise from 0.0 to lr0
|
||
2 years ago
|
x['lr'] = np.interp(
|
||
|
ni, xi, [self.args.warmup_bias_lr if j == 0 else 0.0, x['initial_lr'] * self.lf(epoch)])
|
||
|
if 'momentum' in x:
|
||
|
x['momentum'] = np.interp(ni, xi, [self.args.warmup_momentum, self.args.momentum])
|
||
|
|
||
2 years ago
|
# Forward
|
||
2 years ago
|
with torch.cuda.amp.autocast(self.amp):
|
||
|
batch = self.preprocess_batch(batch)
|
||
2 years ago
|
self.loss, self.loss_items = self.model(batch)
|
||
2 years ago
|
if RANK != -1:
|
||
2 years ago
|
self.loss *= world_size
|
||
|
self.tloss = (self.tloss * i + self.loss_items) / (i + 1) if self.tloss is not None \
|
||
|
else self.loss_items
|
||
|
|
||
2 years ago
|
# Backward
|
||
2 years ago
|
self.scaler.scale(self.loss).backward()
|
||
|
|
||
2 years ago
|
# Optimize - https://pytorch.org/docs/master/notes/amp_examples.html
|
||
2 years ago
|
if ni - last_opt_step >= self.accumulate:
|
||
2 years ago
|
self.optimizer_step()
|
||
|
last_opt_step = ni
|
||
2 years ago
|
|
||
2 years ago
|
# Log
|
||
2 years ago
|
mem = f'{torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0:.3g}G' # (GB)
|
||
2 years ago
|
loss_len = self.tloss.shape[0] if len(self.tloss.size()) else 1
|
||
|
losses = self.tloss if loss_len > 1 else torch.unsqueeze(self.tloss, 0)
|
||
2 years ago
|
if RANK in (-1, 0):
|
||
2 years ago
|
pbar.set_description(
|
||
2 years ago
|
('%11s' * 2 + '%11.4g' * (2 + loss_len)) %
|
||
2 years ago
|
(f'{epoch + 1}/{self.epochs}', mem, *losses, batch['cls'].shape[0], batch['img'].shape[-1]))
|
||
2 years ago
|
self.run_callbacks('on_batch_end')
|
||
2 years ago
|
if self.args.plots and ni in self.plot_idx:
|
||
2 years ago
|
self.plot_training_samples(batch, ni)
|
||
|
|
||
2 years ago
|
self.run_callbacks('on_train_batch_end')
|
||
2 years ago
|
|
||
2 years ago
|
self.lr = {f'lr/pg{ir}': x['lr'] for ir, x in enumerate(self.optimizer.param_groups)} # for loggers
|
||
2 years ago
|
|
||
2 years ago
|
self.scheduler.step()
|
||
2 years ago
|
self.run_callbacks('on_train_epoch_end')
|
||
2 years ago
|
|
||
2 years ago
|
if RANK in (-1, 0):
|
||
2 years ago
|
|
||
2 years ago
|
# Validation
|
||
2 years ago
|
self.ema.update_attr(self.model, include=['yaml', 'nc', 'args', 'names', 'stride', 'class_weights'])
|
||
2 years ago
|
final_epoch = (epoch + 1 == self.epochs) or self.stopper.possible_stop
|
||
|
|
||
2 years ago
|
if self.args.val or final_epoch:
|
||
2 years ago
|
self.metrics, self.fitness = self.validate()
|
||
2 years ago
|
self.save_metrics(metrics={**self.label_loss_items(self.tloss), **self.metrics, **self.lr})
|
||
2 years ago
|
self.stop = self.stopper(epoch + 1, self.fitness)
|
||
2 years ago
|
|
||
2 years ago
|
# Save model
|
||
|
if self.args.save or (epoch + 1 == self.epochs):
|
||
2 years ago
|
self.save_model()
|
||
2 years ago
|
self.run_callbacks('on_model_save')
|
||
2 years ago
|
|
||
|
tnow = time.time()
|
||
|
self.epoch_time = tnow - self.epoch_time_start
|
||
|
self.epoch_time_start = tnow
|
||
2 years ago
|
self.run_callbacks('on_fit_epoch_end')
|
||
2 years ago
|
torch.cuda.empty_cache() # clears GPU vRAM at end of epoch, can help with out of memory errors
|
||
2 years ago
|
|
||
|
# Early Stopping
|
||
|
if RANK != -1: # if DDP training
|
||
|
broadcast_list = [self.stop if RANK == 0 else None]
|
||
|
dist.broadcast_object_list(broadcast_list, 0) # broadcast 'stop' to all ranks
|
||
|
if RANK != 0:
|
||
|
self.stop = broadcast_list[0]
|
||
|
if self.stop:
|
||
|
break # must break all DDP ranks
|
||
2 years ago
|
|
||
2 years ago
|
if RANK in (-1, 0):
|
||
2 years ago
|
# Do final val with best.pt
|
||
2 years ago
|
LOGGER.info(f'\n{epoch - self.start_epoch + 1} epochs completed in '
|
||
|
f'{(time.time() - self.train_time_start) / 3600:.3f} hours.')
|
||
2 years ago
|
self.final_eval()
|
||
|
if self.args.plots:
|
||
|
self.plot_metrics()
|
||
2 years ago
|
self.run_callbacks('on_train_end')
|
||
2 years ago
|
torch.cuda.empty_cache()
|
||
2 years ago
|
self.run_callbacks('teardown')
|
||
2 years ago
|
|
||
|
def save_model(self):
|
||
2 years ago
|
"""Save model checkpoints based on various conditions."""
|
||
2 years ago
|
ckpt = {
|
||
|
'epoch': self.epoch,
|
||
|
'best_fitness': self.best_fitness,
|
||
2 years ago
|
'model': deepcopy(de_parallel(self.model)).half(),
|
||
|
'ema': deepcopy(self.ema.ema).half(),
|
||
|
'updates': self.ema.updates,
|
||
|
'optimizer': self.optimizer.state_dict(),
|
||
2 years ago
|
'train_args': vars(self.args), # save as dict
|
||
2 years ago
|
'date': datetime.now().isoformat(),
|
||
|
'version': __version__}
|
||
2 years ago
|
|
||
2 years ago
|
# Use dill (if exists) to serialize the lambda functions where pickle does not do this
|
||
|
try:
|
||
|
import dill as pickle
|
||
|
except ImportError:
|
||
|
import pickle
|
||
|
|
||
2 years ago
|
# Save last, best and delete
|
||
2 years ago
|
torch.save(ckpt, self.last, pickle_module=pickle)
|
||
2 years ago
|
if self.best_fitness == self.fitness:
|
||
2 years ago
|
torch.save(ckpt, self.best, pickle_module=pickle)
|
||
2 years ago
|
if (self.epoch > 0) and (self.save_period > 0) and (self.epoch % self.save_period == 0):
|
||
2 years ago
|
torch.save(ckpt, self.wdir / f'epoch{self.epoch}.pt', pickle_module=pickle)
|
||
2 years ago
|
del ckpt
|
||
|
|
||
2 years ago
|
@staticmethod
|
||
|
def get_dataset(data):
|
||
2 years ago
|
"""
|
||
2 years ago
|
Get train, val path from data dict if it exists. Returns None if data format is not recognized.
|
||
2 years ago
|
"""
|
||
2 years ago
|
return data['train'], data.get('val') or data.get('test')
|
||
2 years ago
|
|
||
2 years ago
|
def setup_model(self):
|
||
2 years ago
|
"""
|
||
2 years ago
|
load/create/download model for any task.
|
||
2 years ago
|
"""
|
||
2 years ago
|
if isinstance(self.model, torch.nn.Module): # if model is loaded beforehand. No setup needed
|
||
2 years ago
|
return
|
||
2 years ago
|
|
||
2 years ago
|
model, weights = self.model, None
|
||
|
ckpt = None
|
||
2 years ago
|
if str(model).endswith('.pt'):
|
||
2 years ago
|
weights, ckpt = attempt_load_one_weight(model)
|
||
2 years ago
|
cfg = ckpt['model'].yaml
|
||
2 years ago
|
else:
|
||
|
cfg = model
|
||
2 years ago
|
self.model = self.get_model(cfg=cfg, weights=weights, verbose=RANK == -1) # calls Model(cfg, weights)
|
||
2 years ago
|
return ckpt
|
||
2 years ago
|
|
||
|
def optimizer_step(self):
|
||
2 years ago
|
"""Perform a single step of the training optimizer with gradient clipping and EMA update."""
|
||
2 years ago
|
self.scaler.unscale_(self.optimizer) # unscale gradients
|
||
|
torch.nn.utils.clip_grad_norm_(self.model.parameters(), max_norm=10.0) # clip gradients
|
||
|
self.scaler.step(self.optimizer)
|
||
|
self.scaler.update()
|
||
|
self.optimizer.zero_grad()
|
||
2 years ago
|
if self.ema:
|
||
|
self.ema.update(self.model)
|
||
2 years ago
|
|
||
2 years ago
|
def preprocess_batch(self, batch):
|
||
2 years ago
|
"""
|
||
2 years ago
|
Allows custom preprocessing model inputs and ground truths depending on task type.
|
||
2 years ago
|
"""
|
||
2 years ago
|
return batch
|
||
2 years ago
|
|
||
|
def validate(self):
|
||
|
"""
|
||
2 years ago
|
Runs validation on test set using self.validator. The returned dict is expected to contain "fitness" key.
|
||
2 years ago
|
"""
|
||
2 years ago
|
metrics = self.validator(self)
|
||
2 years ago
|
fitness = metrics.pop('fitness', -self.loss.detach().cpu().numpy()) # use loss as fitness measure if not found
|
||
2 years ago
|
if not self.best_fitness or self.best_fitness < fitness:
|
||
2 years ago
|
self.best_fitness = fitness
|
||
2 years ago
|
return metrics, fitness
|
||
2 years ago
|
|
||
2 years ago
|
def get_model(self, cfg=None, weights=None, verbose=True):
|
||
2 years ago
|
"""Get model and raise NotImplementedError for loading cfg files."""
|
||
2 years ago
|
raise NotImplementedError("This task trainer doesn't support loading cfg files")
|
||
|
|
||
|
def get_validator(self):
|
||
2 years ago
|
"""Returns a NotImplementedError when the get_validator function is called."""
|
||
2 years ago
|
raise NotImplementedError('get_validator function not implemented in trainer')
|
||
2 years ago
|
|
||
2 years ago
|
def get_dataloader(self, dataset_path, batch_size=16, rank=0, mode='train'):
|
||
2 years ago
|
"""
|
||
2 years ago
|
Returns dataloader derived from torch.data.Dataloader.
|
||
2 years ago
|
"""
|
||
2 years ago
|
raise NotImplementedError('get_dataloader function not implemented in trainer')
|
||
2 years ago
|
|
||
2 years ago
|
def build_dataset(self, img_path, mode='train', batch=None):
|
||
|
"""Build dataset"""
|
||
|
raise NotImplementedError('build_dataset function not implemented in trainer')
|
||
|
|
||
2 years ago
|
def label_loss_items(self, loss_items=None, prefix='train'):
|
||
2 years ago
|
"""
|
||
2 years ago
|
Returns a loss dict with labelled training loss items tensor
|
||
2 years ago
|
"""
|
||
2 years ago
|
# Not needed for classification but necessary for segmentation & detection
|
||
2 years ago
|
return {'loss': loss_items} if loss_items is not None else ['loss']
|
||
2 years ago
|
|
||
2 years ago
|
def set_model_attributes(self):
|
||
2 years ago
|
"""
|
||
2 years ago
|
To set or update model parameters before training.
|
||
2 years ago
|
"""
|
||
2 years ago
|
self.model.names = self.data['names']
|
||
2 years ago
|
|
||
2 years ago
|
def build_targets(self, preds, targets):
|
||
2 years ago
|
"""Builds target tensors for training YOLO model."""
|
||
2 years ago
|
pass
|
||
2 years ago
|
|
||
2 years ago
|
def progress_string(self):
|
||
2 years ago
|
"""Returns a string describing training progress."""
|
||
2 years ago
|
return ''
|
||
2 years ago
|
|
||
|
# TODO: may need to put these following functions into callback
|
||
|
def plot_training_samples(self, batch, ni):
|
||
2 years ago
|
"""Plots training samples during YOLOv5 training."""
|
||
2 years ago
|
pass
|
||
|
|
||
2 years ago
|
def plot_training_labels(self):
|
||
2 years ago
|
"""Plots training labels for YOLO model."""
|
||
2 years ago
|
pass
|
||
|
|
||
2 years ago
|
def save_metrics(self, metrics):
|
||
2 years ago
|
"""Saves training metrics to a CSV file."""
|
||
2 years ago
|
keys, vals = list(metrics.keys()), list(metrics.values())
|
||
|
n = len(metrics) + 1 # number of cols
|
||
|
s = '' if self.csv.exists() else (('%23s,' * n % tuple(['epoch'] + keys)).rstrip(',') + '\n') # header
|
||
|
with open(self.csv, 'a') as f:
|
||
|
f.write(s + ('%23.5g,' * n % tuple([self.epoch] + vals)).rstrip(',') + '\n')
|
||
|
|
||
|
def plot_metrics(self):
|
||
2 years ago
|
"""Plot and display metrics visually."""
|
||
2 years ago
|
pass
|
||
|
|
||
2 years ago
|
def on_plot(self, name, data=None):
|
||
|
"""Registers plots (e.g. to be consumed in callbacks)"""
|
||
|
self.plots[name] = {'data': data, 'timestamp': time.time()}
|
||
|
|
||
2 years ago
|
def final_eval(self):
|
||
2 years ago
|
"""Performs final evaluation and validation for object detection YOLO model."""
|
||
2 years ago
|
for f in self.last, self.best:
|
||
|
if f.exists():
|
||
|
strip_optimizer(f) # strip optimizers
|
||
|
if f is self.best:
|
||
2 years ago
|
LOGGER.info(f'\nValidating {f}...')
|
||
2 years ago
|
self.metrics = self.validator(model=f)
|
||
|
self.metrics.pop('fitness', None)
|
||
2 years ago
|
self.run_callbacks('on_fit_epoch_end')
|
||
2 years ago
|
|
||
2 years ago
|
def check_resume(self):
|
||
2 years ago
|
"""Check if resume checkpoint exists and update arguments accordingly."""
|
||
2 years ago
|
resume = self.args.resume
|
||
|
if resume:
|
||
2 years ago
|
try:
|
||
2 years ago
|
exists = isinstance(resume, (str, Path)) and Path(resume).exists()
|
||
|
last = Path(check_file(resume) if exists else get_latest_run())
|
||
|
|
||
|
# Check that resume data YAML exists, otherwise strip to force re-download of dataset
|
||
|
ckpt_args = attempt_load_weights(last).args
|
||
|
if not Path(ckpt_args['data']).exists():
|
||
|
ckpt_args['data'] = self.args.data
|
||
|
|
||
|
self.args = get_cfg(ckpt_args)
|
||
2 years ago
|
self.args.model, resume = str(last), True # reinstate
|
||
|
except Exception as e:
|
||
2 years ago
|
raise FileNotFoundError('Resume checkpoint not found. Please pass a valid checkpoint to resume from, '
|
||
2 years ago
|
"i.e. 'yolo train resume model=path/to/last.pt'") from e
|
||
2 years ago
|
self.resume = resume
|
||
2 years ago
|
|
||
|
def resume_training(self, ckpt):
|
||
2 years ago
|
"""Resume YOLO training from given epoch and best fitness."""
|
||
2 years ago
|
if ckpt is None:
|
||
|
return
|
||
|
best_fitness = 0.0
|
||
|
start_epoch = ckpt['epoch'] + 1
|
||
|
if ckpt['optimizer'] is not None:
|
||
|
self.optimizer.load_state_dict(ckpt['optimizer']) # optimizer
|
||
|
best_fitness = ckpt['best_fitness']
|
||
|
if self.ema and ckpt.get('ema'):
|
||
|
self.ema.ema.load_state_dict(ckpt['ema'].float().state_dict()) # EMA
|
||
|
self.ema.updates = ckpt['updates']
|
||
2 years ago
|
if self.resume:
|
||
2 years ago
|
assert start_epoch > 0, \
|
||
|
f'{self.args.model} training to {self.epochs} epochs is finished, nothing to resume.\n' \
|
||
2 years ago
|
f"Start a new training without resuming, i.e. 'yolo train model={self.args.model}'"
|
||
2 years ago
|
LOGGER.info(
|
||
2 years ago
|
f'Resuming training from {self.args.model} from epoch {start_epoch + 1} to {self.epochs} total epochs')
|
||
2 years ago
|
if self.epochs < start_epoch:
|
||
|
LOGGER.info(
|
||
2 years ago
|
f"{self.model} has been trained for {ckpt['epoch']} epochs. Fine-tuning for {self.epochs} more epochs.")
|
||
2 years ago
|
self.epochs += ckpt['epoch'] # finetune additional epochs
|
||
|
self.best_fitness = best_fitness
|
||
|
self.start_epoch = start_epoch
|
||
2 years ago
|
if start_epoch > (self.epochs - self.args.close_mosaic):
|
||
2 years ago
|
LOGGER.info('Closing dataloader mosaic')
|
||
2 years ago
|
if hasattr(self.train_loader.dataset, 'mosaic'):
|
||
|
self.train_loader.dataset.mosaic = False
|
||
|
if hasattr(self.train_loader.dataset, 'close_mosaic'):
|
||
|
self.train_loader.dataset.close_mosaic(hyp=self.args)
|
||
2 years ago
|
|
||
2 years ago
|
def build_optimizer(self, model, name='auto', lr=0.001, momentum=0.9, decay=1e-5, iterations=1e5):
|
||
2 years ago
|
"""
|
||
2 years ago
|
Constructs an optimizer for the given model, based on the specified optimizer name, learning rate,
|
||
|
momentum, weight decay, and number of iterations.
|
||
2 years ago
|
|
||
|
Args:
|
||
2 years ago
|
model (torch.nn.Module): The model for which to build an optimizer.
|
||
|
name (str, optional): The name of the optimizer to use. If 'auto', the optimizer is selected
|
||
|
based on the number of iterations. Default: 'auto'.
|
||
|
lr (float, optional): The learning rate for the optimizer. Default: 0.001.
|
||
|
momentum (float, optional): The momentum factor for the optimizer. Default: 0.9.
|
||
|
decay (float, optional): The weight decay for the optimizer. Default: 1e-5.
|
||
|
iterations (float, optional): The number of iterations, which determines the optimizer if
|
||
|
name is 'auto'. Default: 1e5.
|
||
2 years ago
|
|
||
|
Returns:
|
||
2 years ago
|
(torch.optim.Optimizer): The constructed optimizer.
|
||
2 years ago
|
"""
|
||
2 years ago
|
|
||
2 years ago
|
g = [], [], [] # optimizer parameter groups
|
||
|
bn = tuple(v for k, v in nn.__dict__.items() if 'Norm' in k) # normalization layers, i.e. BatchNorm2d()
|
||
2 years ago
|
if name == 'auto':
|
||
2 years ago
|
nc = getattr(model, 'nc', 10) # number of classes
|
||
|
lr_fit = round(0.002 * 5 / (4 + nc), 6) # lr0 fit equation to 6 decimal places
|
||
|
name, lr, momentum = ('SGD', 0.01, 0.9) if iterations > 10000 else ('AdamW', lr_fit, 0.9)
|
||
|
self.args.warmup_bias_lr = 0.0 # no higher than 0.01 for Adam
|
||
2 years ago
|
|
||
|
for module_name, module in model.named_modules():
|
||
|
for param_name, param in module.named_parameters(recurse=False):
|
||
|
fullname = f'{module_name}.{param_name}' if module_name else param_name
|
||
|
if 'bias' in fullname: # bias (no decay)
|
||
|
g[2].append(param)
|
||
|
elif isinstance(module, bn): # weight (no decay)
|
||
|
g[1].append(param)
|
||
|
else: # weight (with decay)
|
||
|
g[0].append(param)
|
||
2 years ago
|
|
||
2 years ago
|
if name in ('Adam', 'Adamax', 'AdamW', 'NAdam', 'RAdam'):
|
||
|
optimizer = getattr(optim, name, optim.Adam)(g[2], lr=lr, betas=(momentum, 0.999), weight_decay=0.0)
|
||
2 years ago
|
elif name == 'RMSProp':
|
||
2 years ago
|
optimizer = optim.RMSprop(g[2], lr=lr, momentum=momentum)
|
||
2 years ago
|
elif name == 'SGD':
|
||
2 years ago
|
optimizer = optim.SGD(g[2], lr=lr, momentum=momentum, nesterov=True)
|
||
2 years ago
|
else:
|
||
2 years ago
|
raise NotImplementedError(
|
||
|
f"Optimizer '{name}' not found in list of available optimizers "
|
||
|
f'[Adam, AdamW, NAdam, RAdam, RMSProp, SGD, auto].'
|
||
|
'To request support for addition optimizers please visit https://github.com/ultralytics/ultralytics.')
|
||
2 years ago
|
|
||
2 years ago
|
optimizer.add_param_group({'params': g[0], 'weight_decay': decay}) # add g0 with weight_decay
|
||
|
optimizer.add_param_group({'params': g[1], 'weight_decay': 0.0}) # add g1 (BatchNorm2d weights)
|
||
2 years ago
|
LOGGER.info(
|
||
|
f"{colorstr('optimizer:')} {type(optimizer).__name__}(lr={lr}, momentum={momentum}) with parameter groups "
|
||
|
f'{len(g[1])} weight(decay=0.0), {len(g[0])} weight(decay={decay}), {len(g[2])} bias(decay=0.0)')
|
||
2 years ago
|
return optimizer
|