finetune_pruned.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
  2. """
  3. Train a YOLOv5 model on a custom dataset.
  4. Models and datasets download automatically from the latest YOLOv5 release.
  5. Models: https://github.com/ultralytics/yolov5/tree/master/models
  6. Datasets: https://github.com/ultralytics/yolov5/tree/master/data
  7. Tutorial: https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data
  8. Usage:
  9. $ python path/to/train.py --data coco128.yaml --weights yolov5s.pt --img 640 # from pretrained (RECOMMENDED)
  10. $ python path/to/train.py --data coco128.yaml --weights '' --cfg yolov5s.yaml --img 640 # from scratch
  11. """
  12. import argparse
  13. import math
  14. import os
  15. import random
  16. import sys
  17. import time
  18. from copy import deepcopy
  19. from datetime import datetime
  20. from pathlib import Path
  21. from models.yolo import ModelPruned
  22. import numpy as np
  23. import torch
  24. import torch.distributed as dist
  25. import torch.nn as nn
  26. import yaml
  27. from torch.cuda import amp
  28. from torch.nn.parallel import DistributedDataParallel as DDP
  29. from torch.optim import SGD, Adam, AdamW, lr_scheduler
  30. from tqdm import tqdm
  31. from models.common import Bottleneck
  32. FILE = Path(__file__).resolve()
  33. ROOT = FILE.parents[0] # YOLOv5 root directory
  34. if str(ROOT) not in sys.path:
  35. sys.path.append(str(ROOT)) # add ROOT to PATH
  36. ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
  37. import val # for end-of-epoch mAP
  38. from models.experimental import attempt_load
  39. from models.yolo import Model
  40. from utils.autoanchor import check_anchors
  41. from utils.autobatch import check_train_batch_size
  42. from utils.callbacks import Callbacks
  43. from utils.datasets import create_dataloader
  44. from utils.downloads import attempt_download
  45. from utils.general import (LOGGER, check_dataset, check_file, check_git_status, check_img_size, check_requirements,
  46. check_suffix, check_yaml, colorstr, get_latest_run, increment_path, init_seeds,
  47. intersect_dicts, labels_to_class_weights, labels_to_image_weights, methods, one_cycle,
  48. print_args, print_mutation, strip_optimizer)
  49. from utils.loggers import Loggers
  50. from utils.loggers.wandb.wandb_utils import check_wandb_resume
  51. from utils.loss import ComputeLoss
  52. from utils.metrics import fitness
  53. from utils.plots import plot_evolve, plot_labels
  54. from utils.torch_utils import EarlyStopping, ModelEMA, de_parallel, select_device, torch_distributed_zero_first
  55. LOCAL_RANK = int(os.getenv('LOCAL_RANK', -1)) # https://pytorch.org/docs/stable/elastic/run.html
  56. RANK = int(os.getenv('RANK', -1))
  57. WORLD_SIZE = int(os.getenv('WORLD_SIZE', 1))
  58. def train(hyp, # path/to/hyp.yaml or hyp dictionary
  59. opt,
  60. device,
  61. callbacks
  62. ):
  63. save_dir, epochs, batch_size, weights, single_cls, evolve, data, cfg, resume, noval, nosave, workers, freeze = \
  64. Path(opt.save_dir), opt.epochs, opt.batch_size, opt.weights, opt.single_cls, opt.evolve, opt.data, opt.cfg, \
  65. opt.resume, opt.noval, opt.nosave, opt.workers, opt.freeze
  66. # Directories
  67. w = save_dir / 'weights' # weights dir
  68. (w.parent if evolve else w).mkdir(parents=True, exist_ok=True) # make dir
  69. last, best = w / 'last.pt', w / 'best.pt'
  70. # Hyperparameters
  71. if isinstance(hyp, str):
  72. with open(hyp, errors='ignore') as f:
  73. hyp = yaml.safe_load(f) # load hyps dict
  74. LOGGER.info(colorstr('hyperparameters: ') + ', '.join(f'{k}={v}' for k, v in hyp.items()))
  75. # Save run settings
  76. if not evolve:
  77. with open(save_dir / 'hyp.yaml', 'w') as f:
  78. yaml.safe_dump(hyp, f, sort_keys=False)
  79. with open(save_dir / 'opt.yaml', 'w') as f:
  80. yaml.safe_dump(vars(opt), f, sort_keys=False)
  81. # Loggers
  82. data_dict = None
  83. if RANK in [-1, 0]:
  84. loggers = Loggers(save_dir, weights, opt, hyp, LOGGER) # loggers instance
  85. if loggers.wandb:
  86. data_dict = loggers.wandb.data_dict
  87. if resume:
  88. weights, epochs, hyp, batch_size = opt.weights, opt.epochs, opt.hyp, opt.batch_size
  89. # Register actions
  90. for k in methods(loggers):
  91. callbacks.register_action(k, callback=getattr(loggers, k))
  92. # Config
  93. plots = not evolve # create plots
  94. cuda = device.type != 'cpu'
  95. init_seeds(1 + RANK)
  96. with torch_distributed_zero_first(LOCAL_RANK):
  97. data_dict = data_dict or check_dataset(data) # check if None
  98. train_path, val_path = data_dict['train'], data_dict['val']
  99. nc = 1 if single_cls else int(data_dict['nc']) # number of classes
  100. names = ['item'] if single_cls and len(data_dict['names']) != 1 else data_dict['names'] # class names
  101. assert len(names) == nc, f'{len(names)} names found for nc={nc} dataset in {data}' # check
  102. is_coco = isinstance(val_path, str) and val_path.endswith('coco/val2017.txt') # COCO dataset
  103. # Model
  104. check_suffix(weights, '.pt') # check weights
  105. pretrained = weights.endswith('.pt')
  106. if pretrained:
  107. with torch_distributed_zero_first(LOCAL_RANK):
  108. weights = attempt_download(weights) # download if not found locally
  109. ckpt = torch.load(weights, map_location=device) # load checkpoint
  110. model = ckpt["model"]
  111. maskbndict = ckpt['model'].maskbndict
  112. model = ModelPruned(maskbndict, ckpt['model'].yaml, ch=3, nc=nc, anchors=hyp.get('anchors')).to(device) # create
  113. exclude = ['anchor'] if (cfg or hyp.get('anchors')) and not resume else [] # exclude keys
  114. csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32
  115. csd = intersect_dicts(csd, model.state_dict(), exclude=exclude) # intersect
  116. model.load_state_dict(csd, strict=False) # load
  117. LOGGER.info(f'Transferred {len(csd)}/{len(model.state_dict())} items from {weights}') # report
  118. else:
  119. LOGGER.info('No pruned weights loaded, please set the right pruned weight path ...') # report
  120. return
  121. # Freeze
  122. freeze = [f'model.{x}.' for x in (freeze if len(freeze) > 1 else range(freeze[0]))] # layers to freeze
  123. for k, v in model.named_parameters():
  124. v.requires_grad = True # train all layers
  125. if any(x in k for x in freeze):
  126. LOGGER.info(f'freezing {k}')
  127. v.requires_grad = False
  128. # Image size
  129. gs = max(int(model.stride.max()), 32) # grid size (max stride)
  130. imgsz = check_img_size(opt.imgsz, gs, floor=gs * 2) # verify imgsz is gs-multiple
  131. # Batch size
  132. if RANK == -1 and batch_size == -1: # single-GPU only, estimate best batch size
  133. batch_size = check_train_batch_size(model, imgsz)
  134. loggers.on_params_update({"batch_size": batch_size})
  135. # Optimizer
  136. nbs = 64 # nominal batch size
  137. accumulate = max(round(nbs / batch_size), 1) # accumulate loss before optimizing
  138. hyp['weight_decay'] *= batch_size * accumulate / nbs # scale weight_decay
  139. LOGGER.info(f"Scaled weight_decay = {hyp['weight_decay']}")
  140. g0, g1, g2 = [], [], [] # optimizer parameter groups
  141. for v in model.modules():
  142. if hasattr(v, 'bias') and isinstance(v.bias, nn.Parameter): # bias
  143. g2.append(v.bias)
  144. if isinstance(v, nn.BatchNorm2d): # weight (no decay)
  145. g0.append(v.weight)
  146. elif hasattr(v, 'weight') and isinstance(v.weight, nn.Parameter): # weight (with decay)
  147. g1.append(v.weight)
  148. if opt.optimizer == 'Adam':
  149. optimizer = Adam(g0, lr=hyp['lr0'], betas=(hyp['momentum'], 0.999)) # adjust beta1 to momentum
  150. elif opt.optimizer == 'AdamW':
  151. optimizer = AdamW(g0, lr=hyp['lr0'], betas=(hyp['momentum'], 0.999)) # adjust beta1 to momentum
  152. else:
  153. optimizer = SGD(g0, lr=hyp['lr0'], momentum=hyp['momentum'], nesterov=True)
  154. optimizer.add_param_group({'params': g1, 'weight_decay': hyp['weight_decay']}) # add g1 with weight_decay
  155. optimizer.add_param_group({'params': g2}) # add g2 (biases)
  156. LOGGER.info(f"{colorstr('optimizer:')} {type(optimizer).__name__} with parameter groups "
  157. f"{len(g0)} weight (no decay), {len(g1)} weight, {len(g2)} bias")
  158. del g0, g1, g2
  159. # Scheduler
  160. if opt.cos_lr:
  161. lf = one_cycle(1, hyp['lrf'], epochs) # cosine 1->hyp['lrf']
  162. else:
  163. lf = lambda x: (1 - x / epochs) * (1.0 - hyp['lrf']) + hyp['lrf'] # linear
  164. scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf) # plot_lr_scheduler(optimizer, scheduler, epochs)
  165. # EMA
  166. ema = ModelEMA(model) if RANK in [-1, 0] else None
  167. # Resume
  168. start_epoch, best_fitness = 0, 0.0
  169. # DP mode
  170. if cuda and RANK == -1 and torch.cuda.device_count() > 1:
  171. LOGGER.warning('WARNING: DP not recommended, use torch.distributed.run for best DDP Multi-GPU results.\n'
  172. 'See Multi-GPU Tutorial at https://github.com/ultralytics/yolov5/issues/475 to get started.')
  173. model = torch.nn.DataParallel(model)
  174. # SyncBatchNorm
  175. if opt.sync_bn and cuda and RANK != -1:
  176. model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model).to(device)
  177. LOGGER.info('Using SyncBatchNorm()')
  178. # Trainloader
  179. train_loader, dataset = create_dataloader(train_path, imgsz, batch_size // WORLD_SIZE, gs, single_cls,
  180. hyp=hyp, augment=True, cache=None if opt.cache == 'val' else opt.cache,
  181. rect=opt.rect, rank=LOCAL_RANK, workers=workers,
  182. image_weights=opt.image_weights, quad=opt.quad,
  183. prefix=colorstr('train: '), shuffle=True)
  184. mlc = int(np.concatenate(dataset.labels, 0)[:, 0].max()) # max label class
  185. nb = len(train_loader) # number of batches
  186. assert mlc < nc, f'Label class {mlc} exceeds nc={nc} in {data}. Possible class labels are 0-{nc - 1}'
  187. # Process 0
  188. if RANK in [-1, 0]:
  189. val_loader = create_dataloader(val_path, imgsz, batch_size // WORLD_SIZE * 2, gs, single_cls,
  190. hyp=hyp, cache=None if noval else opt.cache,
  191. rect=True, rank=-1, workers=workers * 2, pad=0.5,
  192. prefix=colorstr('val: '))[0]
  193. if not resume:
  194. labels = np.concatenate(dataset.labels, 0)
  195. # c = torch.tensor(labels[:, 0]) # classes
  196. # cf = torch.bincount(c.long(), minlength=nc) + 1. # frequency
  197. # model._initialize_biases(cf.to(device))
  198. if plots:
  199. plot_labels(labels, names, save_dir)
  200. # Anchors
  201. if not opt.noautoanchor:
  202. check_anchors(dataset, model=model, thr=hyp['anchor_t'], imgsz=imgsz)
  203. model.half().float() # pre-reduce anchor precision
  204. callbacks.run('on_pretrain_routine_end')
  205. # DDP mode
  206. if cuda and RANK != -1:
  207. model = DDP(model, device_ids=[LOCAL_RANK], output_device=LOCAL_RANK)
  208. # Model attributes
  209. nl = de_parallel(model).model[-1].nl # number of detection layers (to scale hyps)
  210. hyp['box'] *= 3 / nl # scale to layers
  211. hyp['cls'] *= nc / 80 * 3 / nl # scale to classes and layers
  212. hyp['obj'] *= (imgsz / 640) ** 2 * 3 / nl # scale to image size and layers
  213. hyp['label_smoothing'] = opt.label_smoothing
  214. model.nc = nc # attach number of classes to model
  215. model.hyp = hyp # attach hyperparameters to model
  216. model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) * nc # attach class weights
  217. model.names = names
  218. # Start training
  219. t0 = time.time()
  220. nw = max(round(hyp['warmup_epochs'] * nb), 1000) # number of warmup iterations, max(3 epochs, 1k iterations)
  221. # nw = min(nw, (epochs - start_epoch) / 2 * nb) # limit warmup to < 1/2 of training
  222. last_opt_step = -1
  223. maps = np.zeros(nc) # mAP per class
  224. results = (0, 0, 0, 0, 0, 0, 0) # P, R, mAP@.5, mAP@.5-.95, val_loss(box, obj, cls)
  225. scheduler.last_epoch = start_epoch - 1 # do not move
  226. scaler = amp.GradScaler(enabled=cuda)
  227. stopper = EarlyStopping(patience=opt.patience)
  228. compute_loss = ComputeLoss(model) # init loss class
  229. LOGGER.info(f'Image sizes {imgsz} train, {imgsz} val\n'
  230. f'Using {train_loader.num_workers * WORLD_SIZE} dataloader workers\n'
  231. f"Logging results to {colorstr('bold', save_dir)}\n"
  232. f'Starting training for {epochs} epochs...')
  233. for epoch in range(start_epoch, epochs): # epoch ------------------------------------------------------------------
  234. model.train()
  235. ignore_bn_list = []
  236. for k, m in model.named_modules():
  237. if isinstance(m, Bottleneck):
  238. if m.add:
  239. ignore_bn_list.append(k.rsplit(".", 2)[0] + ".cv1.bn")
  240. ignore_bn_list.append(k + '.cv1.bn')
  241. ignore_bn_list.append(k + '.cv2.bn')
  242. # Update image weights (optional, single-GPU only)
  243. if opt.image_weights:
  244. cw = model.class_weights.cpu().numpy() * (1 - maps) ** 2 / nc # class weights
  245. iw = labels_to_image_weights(dataset.labels, nc=nc, class_weights=cw) # image weights
  246. dataset.indices = random.choices(range(dataset.n), weights=iw, k=dataset.n) # rand weighted idx
  247. # Update mosaic border (optional)
  248. # b = int(random.uniform(0.25 * imgsz, 0.75 * imgsz + gs) // gs * gs)
  249. # dataset.mosaic_border = [b - imgsz, -b] # height, width borders
  250. mloss = torch.zeros(3, device=device) # mean losses
  251. if RANK != -1:
  252. train_loader.sampler.set_epoch(epoch)
  253. pbar = enumerate(train_loader)
  254. LOGGER.info(('\n' + '%10s' * 7) % ('Epoch', 'gpu_mem', 'box', 'obj', 'cls', 'labels', 'img_size'))
  255. if RANK in [-1, 0]:
  256. pbar = tqdm(pbar, total=nb, bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}') # progress bar
  257. optimizer.zero_grad()
  258. for i, (imgs, targets, paths, _) in pbar: # batch -------------------------------------------------------------
  259. ni = i + nb * epoch # number integrated batches (since train start)
  260. imgs = imgs.to(device, non_blocking=True).float() / 255 # uint8 to float32, 0-255 to 0.0-1.0
  261. # Warmup
  262. if ni <= nw:
  263. xi = [0, nw] # x interp
  264. # compute_loss.gr = np.interp(ni, xi, [0.0, 1.0]) # iou loss ratio (obj_loss = 1.0 or iou)
  265. accumulate = max(1, np.interp(ni, xi, [1, nbs / batch_size]).round())
  266. for j, x in enumerate(optimizer.param_groups):
  267. # bias lr falls from 0.1 to lr0, all other lrs rise from 0.0 to lr0
  268. x['lr'] = np.interp(ni, xi, [hyp['warmup_bias_lr'] if j == 2 else 0.0, x['initial_lr'] * lf(epoch)])
  269. if 'momentum' in x:
  270. x['momentum'] = np.interp(ni, xi, [hyp['warmup_momentum'], hyp['momentum']])
  271. # Multi-scale
  272. if opt.multi_scale:
  273. sz = random.randrange(imgsz * 0.5, imgsz * 1.5 + gs) // gs * gs # size
  274. sf = sz / max(imgs.shape[2:]) # scale factor
  275. if sf != 1:
  276. ns = [math.ceil(x * sf / gs) * gs for x in imgs.shape[2:]] # new shape (stretched to gs-multiple)
  277. imgs = nn.functional.interpolate(imgs, size=ns, mode='bilinear', align_corners=False)
  278. # Forward
  279. with amp.autocast(enabled=cuda):
  280. pred = model(imgs) # forward
  281. loss, loss_items = compute_loss(pred, targets.to(device)) # loss scaled by batch_size
  282. if RANK != -1:
  283. loss *= WORLD_SIZE # gradient averaged between devices in DDP mode
  284. if opt.quad:
  285. loss *= 4.
  286. # Backward
  287. scaler.scale(loss).backward()
  288. # Optimize
  289. if ni - last_opt_step >= accumulate:
  290. scaler.step(optimizer) # optimizer.step
  291. scaler.update()
  292. optimizer.zero_grad()
  293. if ema:
  294. ema.update(model)
  295. last_opt_step = ni
  296. # Log
  297. if RANK in [-1, 0]:
  298. mloss = (mloss * i + loss_items) / (i + 1) # update mean losses
  299. mem = f'{torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0:.3g}G' # (GB)
  300. pbar.set_description(('%10s' * 2 + '%10.4g' * 5) % (
  301. f'{epoch}/{epochs - 1}', mem, *mloss, targets.shape[0], imgs.shape[-1]))
  302. callbacks.run('on_train_batch_end', ni, model, imgs, targets, paths, plots, opt.sync_bn)
  303. if callbacks.stop_training:
  304. return
  305. # end batch ------------------------------------------------------------------------------------------------
  306. # Scheduler
  307. lr = [x['lr'] for x in optimizer.param_groups] # for loggers
  308. scheduler.step()
  309. # =============== show bn weights ===================== #
  310. module_list = []
  311. # module_bias_list = []
  312. for i, layer in model.named_modules():
  313. if isinstance(layer, nn.BatchNorm2d) and i not in ignore_bn_list:
  314. bnw = layer.state_dict()['weight']
  315. bnb = layer.state_dict()['bias']
  316. module_list.append(bnw)
  317. # module_bias_list.append(bnb)
  318. # bnw = bnw.sort()
  319. # print(f"{i} : {bnw} : ")
  320. size_list = [idx.data.shape[0] for idx in module_list]
  321. bn_weights = torch.zeros(sum(size_list))
  322. bnb_weights = torch.zeros(sum(size_list))
  323. index = 0
  324. for idx, size in enumerate(size_list):
  325. bn_weights[index:(index + size)] = module_list[idx].data.abs().clone()
  326. # bnb_weights[index:(index + size)] = module_bias_list[idx].data.abs().clone()
  327. index += size
  328. if RANK in [-1, 0]:
  329. # mAP
  330. callbacks.run('on_train_epoch_end', epoch=epoch)
  331. ema.update_attr(model, include=['yaml', 'nc', 'hyp', 'names', 'stride', 'class_weights'])
  332. final_epoch = (epoch + 1 == epochs) or stopper.possible_stop
  333. if not noval or final_epoch: # Calculate mAP
  334. results, maps, _ = val.run(data_dict,
  335. batch_size=batch_size // WORLD_SIZE * 2,
  336. imgsz=imgsz,
  337. model=ema.ema,
  338. single_cls=single_cls,
  339. dataloader=val_loader,
  340. save_dir=save_dir,
  341. plots=False,
  342. callbacks=callbacks,
  343. compute_loss=compute_loss)
  344. # Update best mAP
  345. fi = fitness(np.array(results).reshape(1, -1)) # weighted combination of [P, R, mAP@.5, mAP@.5-.95]
  346. if fi > best_fitness:
  347. best_fitness = fi
  348. log_vals = list(mloss) + list(results) + lr #+ [0]
  349. callbacks.run('on_fit_epoch_end', log_vals, epoch, best_fitness, fi)
  350. callbacks.run('on_fit_epoch_end_prune', bn_weights.numpy(), epoch)
  351. # Save model
  352. if (not nosave) or (final_epoch and not evolve): # if save
  353. ckpt = {'epoch': epoch,
  354. 'best_fitness': best_fitness,
  355. 'model': deepcopy(de_parallel(model)).half(),
  356. 'ema': deepcopy(ema.ema).half(),
  357. 'updates': ema.updates,
  358. 'optimizer': optimizer.state_dict(),
  359. 'wandb_id': loggers.wandb.wandb_run.id if loggers.wandb else None,
  360. 'date': datetime.now().isoformat()}
  361. # Save last, best and delete
  362. torch.save(ckpt, last)
  363. if best_fitness == fi:
  364. torch.save(ckpt, best)
  365. if (epoch > 0) and (opt.save_period > 0) and (epoch % opt.save_period == 0):
  366. torch.save(ckpt, w / f'epoch{epoch}.pt')
  367. del ckpt
  368. callbacks.run('on_model_save', last, epoch, final_epoch, best_fitness, fi)
  369. # Stop Single-GPU
  370. if RANK == -1 and stopper(epoch=epoch, fitness=fi):
  371. break
  372. # Stop DDP TODO: known issues shttps://github.com/ultralytics/yolov5/pull/4576
  373. # stop = stopper(epoch=epoch, fitness=fi)
  374. # if RANK == 0:
  375. # dist.broadcast_object_list([stop], 0) # broadcast 'stop' to all ranks
  376. # Stop DPP
  377. # with torch_distributed_zero_first(RANK):
  378. # if stop:
  379. # break # must break all DDP ranks
  380. # end epoch ----------------------------------------------------------------------------------------------------
  381. # end training -----------------------------------------------------------------------------------------------------
  382. if RANK in [-1, 0]:
  383. LOGGER.info(f'\n{epoch - start_epoch + 1} epochs completed in {(time.time() - t0) / 3600:.3f} hours.')
  384. for f in last, best:
  385. if f.exists():
  386. strip_optimizer(f) # strip optimizers
  387. if f is best:
  388. LOGGER.info(f'\nValidating {f}...')
  389. results, _, _ = val.run(data_dict,
  390. batch_size=batch_size // WORLD_SIZE * 2,
  391. imgsz=imgsz,
  392. model=attempt_load(f, device).half(),
  393. iou_thres=0.65 if is_coco else 0.60, # best pycocotools results at 0.65
  394. single_cls=single_cls,
  395. dataloader=val_loader,
  396. save_dir=save_dir,
  397. save_json=is_coco,
  398. verbose=True,
  399. plots=True,
  400. callbacks=callbacks,
  401. compute_loss=compute_loss) # val best model with plots
  402. if is_coco:
  403. callbacks.run('on_fit_epoch_end', list(mloss) + list(results) + lr, epoch, best_fitness, fi)
  404. callbacks.run('on_train_end', last, best, plots, epoch, results)
  405. LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}")
  406. torch.cuda.empty_cache()
  407. return results
  408. def parse_opt(known=False):
  409. parser = argparse.ArgumentParser()
  410. parser.add_argument('--weights', type=str, default=ROOT / 'VOC2007_wm/prune/exp4/weights/pruned_model.pt', help='initial weights path')
  411. parser.add_argument('--cfg', type=str, default='', help='model.yaml path')
  412. parser.add_argument('--data', type=str, default=ROOT / 'data/VOC.yaml', help='dataset.yaml path')
  413. parser.add_argument('--hyp', type=str, default=ROOT / 'data/hyps/hyp.scratch-low.yaml', help='hyperparameters path')
  414. parser.add_argument('--epochs', type=int, default=100)
  415. parser.add_argument('--batch-size', type=int, default=16, help='total batch size for all GPUs, -1 for autobatch')
  416. parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=640, help='train, val image size (pixels)')
  417. parser.add_argument('--rect', action='store_true', help='rectangular training')
  418. parser.add_argument('--resume', nargs='?', const=True, default=False, help='resume most recent training')
  419. parser.add_argument('--nosave', action='store_true', help='only save final checkpoint')
  420. parser.add_argument('--noval', action='store_true', help='only validate final epoch')
  421. parser.add_argument('--noautoanchor', action='store_true', help='disable AutoAnchor')
  422. parser.add_argument('--evolve', type=int, nargs='?', const=300, help='evolve hyperparameters for x generations')
  423. parser.add_argument('--bucket', type=str, default='', help='gsutil bucket')
  424. parser.add_argument('--cache', type=str, nargs='?', const='ram', help='--cache images in "ram" (default) or "disk"')
  425. parser.add_argument('--image-weights', action='store_true', help='use weighted image selection for training')
  426. parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
  427. parser.add_argument('--multi-scale', action='store_true', help='vary img-size +/- 50%%')
  428. parser.add_argument('--single-cls', action='store_true', help='train multi-class data as single-class')
  429. parser.add_argument('--optimizer', type=str, choices=['SGD', 'Adam', 'AdamW'], default='SGD', help='optimizer')
  430. parser.add_argument('--sync-bn', action='store_true', help='use SyncBatchNorm, only available in DDP mode')
  431. parser.add_argument('--workers', type=int, default=8, help='max dataloader workers (per RANK in DDP mode)')
  432. parser.add_argument('--project', default=ROOT / 'VOC2007_wm/finetune_pruned', help='save to project/name')
  433. parser.add_argument('--name', default='exp', help='save to project/name')
  434. parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
  435. parser.add_argument('--quad', action='store_true', help='quad dataloader')
  436. parser.add_argument('--cos-lr', action='store_true', help='cosine LR scheduler')
  437. parser.add_argument('--label-smoothing', type=float, default=0.0, help='Label smoothing epsilon')
  438. parser.add_argument('--patience', type=int, default=100, help='EarlyStopping patience (epochs without improvement)')
  439. parser.add_argument('--freeze', nargs='+', type=int, default=[0], help='Freeze layers: backbone=10, first3=0 1 2')
  440. parser.add_argument('--save-period', type=int, default=-1, help='Save checkpoint every x epochs (disabled if < 1)')
  441. parser.add_argument('--local_rank', type=int, default=-1, help='DDP parameter, do not modify')
  442. # Weights & Biases arguments
  443. parser.add_argument('--entity', default=None, help='W&B: Entity')
  444. parser.add_argument('--upload_dataset', nargs='?', const=True, default=False, help='W&B: Upload data, "val" option')
  445. parser.add_argument('--bbox_interval', type=int, default=-1, help='W&B: Set bounding-box image logging interval')
  446. parser.add_argument('--artifact_alias', type=str, default='latest', help='W&B: Version of dataset artifact to use')
  447. opt = parser.parse_known_args()[0] if known else parser.parse_args()
  448. return opt
  449. def main(opt, callbacks=Callbacks()):
  450. # Checks
  451. if RANK in [-1, 0]:
  452. print_args(FILE.stem, opt)
  453. check_git_status()
  454. check_requirements(exclude=['thop'])
  455. # Resume
  456. if opt.resume and not check_wandb_resume(opt) and not opt.evolve: # resume an interrupted run
  457. ckpt = opt.resume if isinstance(opt.resume, str) else get_latest_run() # specified or most recent path
  458. assert os.path.isfile(ckpt), 'ERROR: --resume checkpoint does not exist'
  459. with open(Path(ckpt).parent.parent / 'opt.yaml', errors='ignore') as f:
  460. opt = argparse.Namespace(**yaml.safe_load(f)) # replace
  461. opt.cfg, opt.weights, opt.resume = '', ckpt, True # reinstate
  462. LOGGER.info(f'Resuming training from {ckpt}')
  463. else:
  464. opt.data, opt.cfg, opt.hyp, opt.weights, opt.project = \
  465. check_file(opt.data), check_yaml(opt.cfg), check_yaml(opt.hyp), str(opt.weights), str(opt.project) # checks
  466. assert len(opt.cfg) or len(opt.weights), 'either --cfg or --weights must be specified'
  467. if opt.evolve:
  468. if opt.project == str(ROOT / 'runs/train'): # if default project name, rename to runs/evolve
  469. opt.project = str(ROOT / 'runs/evolve')
  470. opt.exist_ok, opt.resume = opt.resume, False # pass resume to exist_ok and disable resume
  471. opt.save_dir = str(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok))
  472. # DDP mode
  473. device = select_device(opt.device, batch_size=opt.batch_size)
  474. if LOCAL_RANK != -1:
  475. msg = 'is not compatible with YOLOv5 Multi-GPU DDP training'
  476. assert not opt.image_weights, f'--image-weights {msg}'
  477. assert not opt.evolve, f'--evolve {msg}'
  478. assert opt.batch_size != -1, f'AutoBatch with --batch-size -1 {msg}, please pass a valid --batch-size'
  479. assert opt.batch_size % WORLD_SIZE == 0, f'--batch-size {opt.batch_size} must be multiple of WORLD_SIZE'
  480. assert torch.cuda.device_count() > LOCAL_RANK, 'insufficient CUDA devices for DDP command'
  481. torch.cuda.set_device(LOCAL_RANK)
  482. device = torch.device('cuda', LOCAL_RANK)
  483. dist.init_process_group(backend="nccl" if dist.is_nccl_available() else "gloo")
  484. # Train
  485. if not opt.evolve:
  486. train(opt.hyp, opt, device, callbacks)
  487. if WORLD_SIZE > 1 and RANK == 0:
  488. LOGGER.info('Destroying process group... ')
  489. dist.destroy_process_group()
  490. # Evolve hyperparameters (optional)
  491. else:
  492. # Hyperparameter evolution metadata (mutation scale 0-1, lower_limit, upper_limit)
  493. meta = {'lr0': (1, 1e-5, 1e-1), # initial learning rate (SGD=1E-2, Adam=1E-3)
  494. 'lrf': (1, 0.01, 1.0), # final OneCycleLR learning rate (lr0 * lrf)
  495. 'momentum': (0.3, 0.6, 0.98), # SGD momentum/Adam beta1
  496. 'weight_decay': (1, 0.0, 0.001), # optimizer weight decay
  497. 'warmup_epochs': (1, 0.0, 5.0), # warmup epochs (fractions ok)
  498. 'warmup_momentum': (1, 0.0, 0.95), # warmup initial momentum
  499. 'warmup_bias_lr': (1, 0.0, 0.2), # warmup initial bias lr
  500. 'box': (1, 0.02, 0.2), # box loss gain
  501. 'cls': (1, 0.2, 4.0), # cls loss gain
  502. 'cls_pw': (1, 0.5, 2.0), # cls BCELoss positive_weight
  503. 'obj': (1, 0.2, 4.0), # obj loss gain (scale with pixels)
  504. 'obj_pw': (1, 0.5, 2.0), # obj BCELoss positive_weight
  505. 'iou_t': (0, 0.1, 0.7), # IoU training threshold
  506. 'anchor_t': (1, 2.0, 8.0), # anchor-multiple threshold
  507. 'anchors': (2, 2.0, 10.0), # anchors per output grid (0 to ignore)
  508. 'fl_gamma': (0, 0.0, 2.0), # focal loss gamma (efficientDet default gamma=1.5)
  509. 'hsv_h': (1, 0.0, 0.1), # image HSV-Hue augmentation (fraction)
  510. 'hsv_s': (1, 0.0, 0.9), # image HSV-Saturation augmentation (fraction)
  511. 'hsv_v': (1, 0.0, 0.9), # image HSV-Value augmentation (fraction)
  512. 'degrees': (1, 0.0, 45.0), # image rotation (+/- deg)
  513. 'translate': (1, 0.0, 0.9), # image translation (+/- fraction)
  514. 'scale': (1, 0.0, 0.9), # image scale (+/- gain)
  515. 'shear': (1, 0.0, 10.0), # image shear (+/- deg)
  516. 'perspective': (0, 0.0, 0.001), # image perspective (+/- fraction), range 0-0.001
  517. 'flipud': (1, 0.0, 1.0), # image flip up-down (probability)
  518. 'fliplr': (0, 0.0, 1.0), # image flip left-right (probability)
  519. 'mosaic': (1, 0.0, 1.0), # image mixup (probability)
  520. 'mixup': (1, 0.0, 1.0), # image mixup (probability)
  521. 'copy_paste': (1, 0.0, 1.0)} # segment copy-paste (probability)
  522. with open(opt.hyp, errors='ignore') as f:
  523. hyp = yaml.safe_load(f) # load hyps dict
  524. if 'anchors' not in hyp: # anchors commented in hyp.yaml
  525. hyp['anchors'] = 3
  526. opt.noval, opt.nosave, save_dir = True, True, Path(opt.save_dir) # only val/save final epoch
  527. # ei = [isinstance(x, (int, float)) for x in hyp.values()] # evolvable indices
  528. evolve_yaml, evolve_csv = save_dir / 'hyp_evolve.yaml', save_dir / 'evolve.csv'
  529. if opt.bucket:
  530. os.system(f'gsutil cp gs://{opt.bucket}/evolve.csv {evolve_csv}') # download evolve.csv if exists
  531. for _ in range(opt.evolve): # generations to evolve
  532. if evolve_csv.exists(): # if evolve.csv exists: select best hyps and mutate
  533. # Select parent(s)
  534. parent = 'single' # parent selection method: 'single' or 'weighted'
  535. x = np.loadtxt(evolve_csv, ndmin=2, delimiter=',', skiprows=1)
  536. n = min(5, len(x)) # number of previous results to consider
  537. x = x[np.argsort(-fitness(x))][:n] # top n mutations
  538. w = fitness(x) - fitness(x).min() + 1E-6 # weights (sum > 0)
  539. if parent == 'single' or len(x) == 1:
  540. # x = x[random.randint(0, n - 1)] # random selection
  541. x = x[random.choices(range(n), weights=w)[0]] # weighted selection
  542. elif parent == 'weighted':
  543. x = (x * w.reshape(n, 1)).sum(0) / w.sum() # weighted combination
  544. # Mutate
  545. mp, s = 0.8, 0.2 # mutation probability, sigma
  546. npr = np.random
  547. npr.seed(int(time.time()))
  548. g = np.array([meta[k][0] for k in hyp.keys()]) # gains 0-1
  549. ng = len(meta)
  550. v = np.ones(ng)
  551. while all(v == 1): # mutate until a change occurs (prevent duplicates)
  552. v = (g * (npr.random(ng) < mp) * npr.randn(ng) * npr.random() * s + 1).clip(0.3, 3.0)
  553. for i, k in enumerate(hyp.keys()): # plt.hist(v.ravel(), 300)
  554. hyp[k] = float(x[i + 7] * v[i]) # mutate
  555. # Constrain to limits
  556. for k, v in meta.items():
  557. hyp[k] = max(hyp[k], v[1]) # lower limit
  558. hyp[k] = min(hyp[k], v[2]) # upper limit
  559. hyp[k] = round(hyp[k], 5) # significant digits
  560. # Train mutation
  561. results = train(hyp.copy(), opt, device, callbacks)
  562. callbacks = Callbacks()
  563. # Write mutation results
  564. print_mutation(results, hyp.copy(), save_dir, opt.bucket)
  565. # Plot results
  566. plot_evolve(evolve_csv)
  567. LOGGER.info(f'Hyperparameter evolution finished {opt.evolve} generations\n'
  568. f"Results saved to {colorstr('bold', save_dir)}\n"
  569. f'Usage example: $ python train.py --hyp {evolve_yaml}')
  570. def run(**kwargs):
  571. # Usage: import train; train.run(data='coco128.yaml', imgsz=320, weights='yolov5m.pt')
  572. opt = parse_opt(True)
  573. for k, v in kwargs.items():
  574. setattr(opt, k, v)
  575. main(opt)
  576. return opt
  577. if __name__ == "__main__":
  578. opt = parse_opt()
  579. main(opt)