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.

512 lines
25KB

  1. import argparse
  2. import torch.distributed as dist
  3. import torch.nn.functional as F
  4. import torch.optim as optim
  5. import torch.optim.lr_scheduler as lr_scheduler
  6. import torch.utils.data
  7. from torch.cuda import amp
  8. from torch.nn.parallel import DistributedDataParallel as DDP
  9. from torch.utils.tensorboard import SummaryWriter
  10. import test # import test.py to get mAP after each epoch
  11. from models.yolo import Model
  12. from utils import google_utils
  13. from utils.datasets import *
  14. from utils.utils import *
  15. # Hyperparameters
  16. hyp = {'optimizer': 'SGD', # ['adam', 'SGD', None] if none, default is SGD
  17. 'lr0': 0.01, # initial learning rate (SGD=1E-2, Adam=1E-3)
  18. 'momentum': 0.937, # SGD momentum/Adam beta1
  19. 'weight_decay': 5e-4, # optimizer weight decay
  20. 'giou': 0.05, # giou loss gain
  21. 'cls': 0.5, # cls loss gain
  22. 'cls_pw': 1.0, # cls BCELoss positive_weight
  23. 'obj': 1.0, # obj loss gain (*=img_size/320 if img_size != 320)
  24. 'obj_pw': 1.0, # obj BCELoss positive_weight
  25. 'iou_t': 0.20, # iou training threshold
  26. 'anchor_t': 4.0, # anchor-multiple threshold
  27. 'fl_gamma': 0.0, # focal loss gamma (efficientDet default is gamma=1.5)
  28. 'hsv_h': 0.015, # image HSV-Hue augmentation (fraction)
  29. 'hsv_s': 0.7, # image HSV-Saturation augmentation (fraction)
  30. 'hsv_v': 0.4, # image HSV-Value augmentation (fraction)
  31. 'degrees': 0.0, # image rotation (+/- deg)
  32. 'translate': 0.5, # image translation (+/- fraction)
  33. 'scale': 0.5, # image scale (+/- gain)
  34. 'shear': 0.0} # image shear (+/- deg)
  35. def train(hyp, tb_writer, opt, device):
  36. print(f'Hyperparameters {hyp}')
  37. log_dir = tb_writer.log_dir if tb_writer else 'runs/evolution' # run directory
  38. wdir = str(Path(log_dir) / 'weights') + os.sep # weights directory
  39. os.makedirs(wdir, exist_ok=True)
  40. last = wdir + 'last.pt'
  41. best = wdir + 'best.pt'
  42. results_file = log_dir + os.sep + 'results.txt'
  43. epochs, batch_size, total_batch_size, weights, rank = \
  44. opt.epochs, opt.batch_size, opt.total_batch_size, opt.weights, opt.local_rank
  45. # TODO: Init DDP logging. Only the first process is allowed to log.
  46. # Since I see lots of print here, the logging configuration is skipped here. We may see repeated outputs.
  47. # Save run settings
  48. with open(Path(log_dir) / 'hyp.yaml', 'w') as f:
  49. yaml.dump(hyp, f, sort_keys=False)
  50. with open(Path(log_dir) / 'opt.yaml', 'w') as f:
  51. yaml.dump(vars(opt), f, sort_keys=False)
  52. # Configure
  53. cuda = device.type != 'cpu'
  54. init_seeds(2 + rank)
  55. with open(opt.data) as f:
  56. data_dict = yaml.load(f, Loader=yaml.FullLoader) # model dict
  57. train_path = data_dict['train']
  58. test_path = data_dict['val']
  59. nc, names = (1, ['item']) if opt.single_cls else (int(data_dict['nc']), data_dict['names']) # number classes, names
  60. assert len(names) == nc, '%g names found for nc=%g dataset in %s' % (len(names), nc, opt.data) # check
  61. # Remove previous results
  62. if rank in [-1, 0]:
  63. for f in glob.glob('*_batch*.jpg') + glob.glob(results_file):
  64. os.remove(f)
  65. # Create model
  66. model = Model(opt.cfg, nc=nc).to(device)
  67. # Image sizes
  68. gs = int(max(model.stride)) # grid size (max stride)
  69. imgsz, imgsz_test = [check_img_size(x, gs) for x in opt.img_size] # verify imgsz are gs-multiples
  70. # Optimizer
  71. nbs = 64 # nominal batch size
  72. # default DDP implementation is slow for accumulation according to: https://pytorch.org/docs/stable/notes/ddp.html
  73. # all-reduce operation is carried out during loss.backward().
  74. # Thus, there would be redundant all-reduce communications in a accumulation procedure,
  75. # which means, the result is still right but the training speed gets slower.
  76. # TODO: If acceleration is needed, there is an implementation of allreduce_post_accumulation
  77. # in https://github.com/NVIDIA/DeepLearningExamples/blob/master/PyTorch/LanguageModeling/BERT/run_pretraining.py
  78. accumulate = max(round(nbs / total_batch_size), 1) # accumulate loss before optimizing
  79. hyp['weight_decay'] *= total_batch_size * accumulate / nbs # scale weight_decay
  80. pg0, pg1, pg2 = [], [], [] # optimizer parameter groups
  81. for k, v in model.named_parameters():
  82. if v.requires_grad:
  83. if '.bias' in k:
  84. pg2.append(v) # biases
  85. elif '.weight' in k and '.bn' not in k:
  86. pg1.append(v) # apply weight decay
  87. else:
  88. pg0.append(v) # all else
  89. if hyp['optimizer'] == 'adam': # https://pytorch.org/docs/stable/_modules/torch/optim/lr_scheduler.html#OneCycleLR
  90. optimizer = optim.Adam(pg0, lr=hyp['lr0'], betas=(hyp['momentum'], 0.999)) # adjust beta1 to momentum
  91. else:
  92. optimizer = optim.SGD(pg0, lr=hyp['lr0'], momentum=hyp['momentum'], nesterov=True)
  93. optimizer.add_param_group({'params': pg1, 'weight_decay': hyp['weight_decay']}) # add pg1 with weight_decay
  94. optimizer.add_param_group({'params': pg2}) # add pg2 (biases)
  95. print('Optimizer groups: %g .bias, %g conv.weight, %g other' % (len(pg2), len(pg1), len(pg0)))
  96. del pg0, pg1, pg2
  97. # Scheduler https://arxiv.org/pdf/1812.01187.pdf
  98. lf = lambda x: (((1 + math.cos(x * math.pi / epochs)) / 2) ** 1.0) * 0.8 + 0.2 # cosine
  99. scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf)
  100. # https://discuss.pytorch.org/t/a-problem-occured-when-resuming-an-optimizer/28822
  101. # plot_lr_scheduler(optimizer, scheduler, epochs)
  102. # Load Model
  103. with torch_distributed_zero_first(rank):
  104. google_utils.attempt_download(weights)
  105. start_epoch, best_fitness = 0, 0.0
  106. if weights.endswith('.pt'): # pytorch format
  107. ckpt = torch.load(weights, map_location=device) # load checkpoint
  108. # load model
  109. try:
  110. exclude = ['anchor'] # exclude keys
  111. ckpt['model'] = {k: v for k, v in ckpt['model'].float().state_dict().items()
  112. if k in model.state_dict() and not any(x in k for x in exclude)
  113. and model.state_dict()[k].shape == v.shape}
  114. model.load_state_dict(ckpt['model'], strict=False)
  115. print('Transferred %g/%g items from %s' % (len(ckpt['model']), len(model.state_dict()), weights))
  116. except KeyError as e:
  117. s = "%s is not compatible with %s. This may be due to model differences or %s may be out of date. " \
  118. "Please delete or update %s and try again, or use --weights '' to train from scratch." \
  119. % (weights, opt.cfg, weights, weights)
  120. raise KeyError(s) from e
  121. # load optimizer
  122. if ckpt['optimizer'] is not None:
  123. optimizer.load_state_dict(ckpt['optimizer'])
  124. best_fitness = ckpt['best_fitness']
  125. # load results
  126. if ckpt.get('training_results') is not None:
  127. with open(results_file, 'w') as file:
  128. file.write(ckpt['training_results']) # write results.txt
  129. # epochs
  130. start_epoch = ckpt['epoch'] + 1
  131. if epochs < start_epoch:
  132. print('%s has been trained for %g epochs. Fine-tuning for %g additional epochs.' %
  133. (weights, ckpt['epoch'], epochs))
  134. epochs += ckpt['epoch'] # finetune additional epochs
  135. del ckpt
  136. # DP mode
  137. if cuda and rank == -1 and torch.cuda.device_count() > 1:
  138. model = torch.nn.DataParallel(model)
  139. # SyncBatchNorm
  140. if opt.sync_bn and cuda and rank != -1:
  141. model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model).to(device)
  142. print('Using SyncBatchNorm()')
  143. # Exponential moving average
  144. ema = torch_utils.ModelEMA(model) if rank in [-1, 0] else None
  145. # DDP mode
  146. if cuda and rank != -1:
  147. model = DDP(model, device_ids=[rank], output_device=rank)
  148. # Trainloader
  149. dataloader, dataset = create_dataloader(train_path, imgsz, batch_size, gs, opt, hyp=hyp, augment=True,
  150. cache=opt.cache_images, rect=opt.rect, local_rank=rank,
  151. world_size=opt.world_size)
  152. mlc = np.concatenate(dataset.labels, 0)[:, 0].max() # max label class
  153. nb = len(dataloader) # number of batches
  154. assert mlc < nc, 'Label class %g exceeds nc=%g in %s. Possible class labels are 0-%g' % (mlc, nc, opt.data, nc - 1)
  155. # Testloader
  156. if rank in [-1, 0]:
  157. # local_rank is set to -1. Because only the first process is expected to do evaluation.
  158. testloader = create_dataloader(test_path, imgsz_test, total_batch_size, gs, opt, hyp=hyp, augment=False,
  159. cache=opt.cache_images, rect=True, local_rank=-1, world_size=opt.world_size)[0]
  160. # Model parameters
  161. hyp['cls'] *= nc / 80. # scale coco-tuned hyp['cls'] to current dataset
  162. model.nc = nc # attach number of classes to model
  163. model.hyp = hyp # attach hyperparameters to model
  164. model.gr = 1.0 # giou loss ratio (obj_loss = 1.0 or giou)
  165. model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) # attach class weights
  166. model.names = names
  167. # Class frequency
  168. if rank in [-1, 0]:
  169. labels = np.concatenate(dataset.labels, 0)
  170. c = torch.tensor(labels[:, 0]) # classes
  171. # cf = torch.bincount(c.long(), minlength=nc) + 1.
  172. # model._initialize_biases(cf.to(device))
  173. plot_labels(labels, save_dir=log_dir)
  174. if tb_writer:
  175. # tb_writer.add_hparams(hyp, {}) # causes duplicate https://github.com/ultralytics/yolov5/pull/384
  176. tb_writer.add_histogram('classes', c, 0)
  177. # Check anchors
  178. if not opt.noautoanchor:
  179. check_anchors(dataset, model=model, thr=hyp['anchor_t'], imgsz=imgsz)
  180. # Start training
  181. t0 = time.time()
  182. nw = max(3 * nb, 1e3) # number of warmup iterations, max(3 epochs, 1k iterations)
  183. maps = np.zeros(nc) # mAP per class
  184. results = (0, 0, 0, 0, 0, 0, 0) # 'P', 'R', 'mAP', 'F1', 'val GIoU', 'val Objectness', 'val Classification'
  185. scheduler.last_epoch = start_epoch - 1 # do not move
  186. scaler = amp.GradScaler(enabled=cuda)
  187. if rank in [0, -1]:
  188. print('Image sizes %g train, %g test' % (imgsz, imgsz_test))
  189. print('Using %g dataloader workers' % dataloader.num_workers)
  190. print('Starting training for %g epochs...' % epochs)
  191. # torch.autograd.set_detect_anomaly(True)
  192. for epoch in range(start_epoch, epochs): # epoch ------------------------------------------------------------------
  193. model.train()
  194. # Update image weights (optional)
  195. if dataset.image_weights:
  196. # Generate indices
  197. if rank in [-1, 0]:
  198. w = model.class_weights.cpu().numpy() * (1 - maps) ** 2 # class weights
  199. image_weights = labels_to_image_weights(dataset.labels, nc=nc, class_weights=w)
  200. dataset.indices = random.choices(range(dataset.n), weights=image_weights,
  201. k=dataset.n) # rand weighted idx
  202. # Broadcast if DDP
  203. if rank != -1:
  204. indices = torch.zeros([dataset.n], dtype=torch.int)
  205. if rank == 0:
  206. indices[:] = torch.from_tensor(dataset.indices, dtype=torch.int)
  207. dist.broadcast(indices, 0)
  208. if rank != 0:
  209. dataset.indices = indices.cpu().numpy()
  210. # Update mosaic border
  211. # b = int(random.uniform(0.25 * imgsz, 0.75 * imgsz + gs) // gs * gs)
  212. # dataset.mosaic_border = [b - imgsz, -b] # height, width borders
  213. mloss = torch.zeros(4, device=device) # mean losses
  214. if rank != -1:
  215. dataloader.sampler.set_epoch(epoch)
  216. pbar = enumerate(dataloader)
  217. if rank in [-1, 0]:
  218. print(('\n' + '%10s' * 8) % ('Epoch', 'gpu_mem', 'GIoU', 'obj', 'cls', 'total', 'targets', 'img_size'))
  219. pbar = tqdm(pbar, total=nb) # progress bar
  220. optimizer.zero_grad()
  221. for i, (imgs, targets, paths, _) in pbar: # batch -------------------------------------------------------------
  222. ni = i + nb * epoch # number integrated batches (since train start)
  223. imgs = imgs.to(device, non_blocking=True).float() / 255.0 # uint8 to float32, 0-255 to 0.0-1.0
  224. # Warmup
  225. if ni <= nw:
  226. xi = [0, nw] # x interp
  227. # model.gr = np.interp(ni, xi, [0.0, 1.0]) # giou loss ratio (obj_loss = 1.0 or giou)
  228. accumulate = max(1, np.interp(ni, xi, [1, nbs / total_batch_size]).round())
  229. for j, x in enumerate(optimizer.param_groups):
  230. # bias lr falls from 0.1 to lr0, all other lrs rise from 0.0 to lr0
  231. x['lr'] = np.interp(ni, xi, [0.1 if j == 2 else 0.0, x['initial_lr'] * lf(epoch)])
  232. if 'momentum' in x:
  233. x['momentum'] = np.interp(ni, xi, [0.9, hyp['momentum']])
  234. # Multi-scale
  235. if opt.multi_scale:
  236. sz = random.randrange(imgsz * 0.5, imgsz * 1.5 + gs) // gs * gs # size
  237. sf = sz / max(imgs.shape[2:]) # scale factor
  238. if sf != 1:
  239. ns = [math.ceil(x * sf / gs) * gs for x in imgs.shape[2:]] # new shape (stretched to gs-multiple)
  240. imgs = F.interpolate(imgs, size=ns, mode='bilinear', align_corners=False)
  241. # Autocast
  242. with amp.autocast():
  243. # Forward
  244. pred = model(imgs)
  245. # Loss
  246. loss, loss_items = compute_loss(pred, targets.to(device), model) # scaled by batch_size
  247. if rank != -1:
  248. loss *= opt.world_size # gradient averaged between devices in DDP mode
  249. # if not torch.isfinite(loss):
  250. # print('WARNING: non-finite loss, ending training ', loss_items)
  251. # return results
  252. # Backward
  253. scaler.scale(loss).backward()
  254. # Optimize
  255. if ni % accumulate == 0:
  256. scaler.step(optimizer) # optimizer.step
  257. scaler.update()
  258. optimizer.zero_grad()
  259. if ema is not None:
  260. ema.update(model)
  261. # Print
  262. if rank in [-1, 0]:
  263. mloss = (mloss * i + loss_items) / (i + 1) # update mean losses
  264. mem = '%.3gG' % (torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0) # (GB)
  265. s = ('%10s' * 2 + '%10.4g' * 6) % (
  266. '%g/%g' % (epoch, epochs - 1), mem, *mloss, targets.shape[0], imgs.shape[-1])
  267. pbar.set_description(s)
  268. # Plot
  269. if ni < 3:
  270. f = str(Path(log_dir) / ('train_batch%g.jpg' % ni)) # filename
  271. result = plot_images(images=imgs, targets=targets, paths=paths, fname=f)
  272. if tb_writer and result is not None:
  273. tb_writer.add_image(f, result, dataformats='HWC', global_step=epoch)
  274. # tb_writer.add_graph(model, imgs) # add model to tensorboard
  275. # end batch ------------------------------------------------------------------------------------------------
  276. # Scheduler
  277. scheduler.step()
  278. # DDP process 0 or single-GPU
  279. if rank in [-1, 0]:
  280. # mAP
  281. if ema is not None:
  282. ema.update_attr(model, include=['yaml', 'nc', 'hyp', 'gr', 'names', 'stride'])
  283. final_epoch = epoch + 1 == epochs
  284. if not opt.notest or final_epoch: # Calculate mAP
  285. results, maps, times = test.test(opt.data,
  286. batch_size=total_batch_size,
  287. imgsz=imgsz_test,
  288. save_json=final_epoch and opt.data.endswith(os.sep + 'coco.yaml'),
  289. model=ema.ema.module if hasattr(ema.ema, 'module') else ema.ema,
  290. single_cls=opt.single_cls,
  291. dataloader=testloader,
  292. save_dir=log_dir)
  293. # Write
  294. with open(results_file, 'a') as f:
  295. f.write(s + '%10.4g' * 7 % results + '\n') # P, R, mAP, F1, test_losses=(GIoU, obj, cls)
  296. if len(opt.name) and opt.bucket:
  297. os.system('gsutil cp %s gs://%s/results/results%s.txt' % (results_file, opt.bucket, opt.name))
  298. # Tensorboard
  299. if tb_writer:
  300. tags = ['train/giou_loss', 'train/obj_loss', 'train/cls_loss',
  301. 'metrics/precision', 'metrics/recall', 'metrics/mAP_0.5', 'metrics/mAP_0.5:0.95',
  302. 'val/giou_loss', 'val/obj_loss', 'val/cls_loss']
  303. for x, tag in zip(list(mloss[:-1]) + list(results), tags):
  304. tb_writer.add_scalar(tag, x, epoch)
  305. # Update best mAP
  306. fi = fitness(np.array(results).reshape(1, -1)) # fitness_i = weighted combination of [P, R, mAP, F1]
  307. if fi > best_fitness:
  308. best_fitness = fi
  309. # Save model
  310. save = (not opt.nosave) or (final_epoch and not opt.evolve)
  311. if save:
  312. with open(results_file, 'r') as f: # create checkpoint
  313. ckpt = {'epoch': epoch,
  314. 'best_fitness': best_fitness,
  315. 'training_results': f.read(),
  316. 'model': ema.ema.module if hasattr(ema, 'module') else ema.ema,
  317. 'optimizer': None if final_epoch else optimizer.state_dict()}
  318. # Save last, best and delete
  319. torch.save(ckpt, last)
  320. if best_fitness == fi:
  321. torch.save(ckpt, best)
  322. del ckpt
  323. # end epoch ----------------------------------------------------------------------------------------------------
  324. # end training
  325. if rank in [-1, 0]:
  326. # Strip optimizers
  327. n = ('_' if len(opt.name) and not opt.name.isnumeric() else '') + opt.name
  328. fresults, flast, fbest = 'results%s.txt' % n, wdir + 'last%s.pt' % n, wdir + 'best%s.pt' % n
  329. for f1, f2 in zip([wdir + 'last.pt', wdir + 'best.pt', 'results.txt'], [flast, fbest, fresults]):
  330. if os.path.exists(f1):
  331. os.rename(f1, f2) # rename
  332. ispt = f2.endswith('.pt') # is *.pt
  333. strip_optimizer(f2) if ispt else None # strip optimizer
  334. os.system('gsutil cp %s gs://%s/weights' % (f2, opt.bucket)) if opt.bucket and ispt else None # upload
  335. # Finish
  336. if not opt.evolve:
  337. plot_results(save_dir=log_dir) # save as results.png
  338. print('%g epochs completed in %.3f hours.\n' % (epoch - start_epoch + 1, (time.time() - t0) / 3600))
  339. dist.destroy_process_group() if rank not in [-1, 0] else None
  340. torch.cuda.empty_cache()
  341. return results
  342. if __name__ == '__main__':
  343. parser = argparse.ArgumentParser()
  344. parser.add_argument('--cfg', type=str, default='models/yolov5s.yaml', help='model.yaml path')
  345. parser.add_argument('--data', type=str, default='data/coco128.yaml', help='data.yaml path')
  346. parser.add_argument('--hyp', type=str, default='', help='hyp.yaml path (optional)')
  347. parser.add_argument('--epochs', type=int, default=300)
  348. parser.add_argument('--batch-size', type=int, default=16, help="Total batch size for all gpus.")
  349. parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='train,test sizes')
  350. parser.add_argument('--rect', action='store_true', help='rectangular training')
  351. parser.add_argument('--resume', nargs='?', const='get_last', default=False,
  352. help='resume from given path/to/last.pt, or most recent run if blank.')
  353. parser.add_argument('--nosave', action='store_true', help='only save final checkpoint')
  354. parser.add_argument('--notest', action='store_true', help='only test final epoch')
  355. parser.add_argument('--noautoanchor', action='store_true', help='disable autoanchor check')
  356. parser.add_argument('--evolve', action='store_true', help='evolve hyperparameters')
  357. parser.add_argument('--bucket', type=str, default='', help='gsutil bucket')
  358. parser.add_argument('--cache-images', action='store_true', help='cache images for faster training')
  359. parser.add_argument('--weights', type=str, default='', help='initial weights path')
  360. parser.add_argument('--name', default='', help='renames results.txt to results_name.txt if supplied')
  361. parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
  362. parser.add_argument('--multi-scale', action='store_true', help='vary img-size +/- 50%%')
  363. parser.add_argument('--single-cls', action='store_true', help='train as single-class dataset')
  364. parser.add_argument('--sync-bn', action='store_true', help='use SyncBatchNorm, only available in DDP mode')
  365. parser.add_argument('--local_rank', type=int, default=-1, help='DDP parameter, do not modify')
  366. opt = parser.parse_args()
  367. # Resume
  368. last = get_latest_run() if opt.resume == 'get_last' else opt.resume # resume from most recent run
  369. if last and not opt.weights:
  370. print(f'Resuming training from {last}')
  371. opt.weights = last if opt.resume and not opt.weights else opt.weights
  372. if opt.local_rank in [-1, 0]:
  373. check_git_status()
  374. opt.cfg = check_file(opt.cfg) # check file
  375. opt.data = check_file(opt.data) # check file
  376. if opt.hyp: # update hyps
  377. opt.hyp = check_file(opt.hyp) # check file
  378. with open(opt.hyp) as f:
  379. hyp.update(yaml.load(f, Loader=yaml.FullLoader)) # update hyps
  380. opt.img_size.extend([opt.img_size[-1]] * (2 - len(opt.img_size))) # extend to 2 sizes (train, test)
  381. device = torch_utils.select_device(opt.device, batch_size=opt.batch_size)
  382. opt.total_batch_size = opt.batch_size
  383. opt.world_size = 1
  384. # DDP mode
  385. if opt.local_rank != -1:
  386. assert torch.cuda.device_count() > opt.local_rank
  387. torch.cuda.set_device(opt.local_rank)
  388. device = torch.device("cuda", opt.local_rank)
  389. dist.init_process_group(backend='nccl', init_method='env://') # distributed backend
  390. opt.world_size = dist.get_world_size()
  391. assert opt.batch_size % opt.world_size == 0, "Batch size is not a multiple of the number of devices given!"
  392. opt.batch_size = opt.total_batch_size // opt.world_size
  393. print(opt)
  394. # Train
  395. if not opt.evolve:
  396. if opt.local_rank in [-1, 0]:
  397. print('Start Tensorboard with "tensorboard --logdir=runs", view at http://localhost:6006/')
  398. tb_writer = SummaryWriter(log_dir=increment_dir('runs/exp', opt.name))
  399. else:
  400. tb_writer = None
  401. train(hyp, tb_writer, opt, device)
  402. # Evolve hyperparameters (optional)
  403. else:
  404. assert opt.local_rank == -1, 'DDP mode not implemented for --evolve'
  405. tb_writer = None
  406. opt.notest, opt.nosave = True, True # only test/save final epoch
  407. if opt.bucket:
  408. os.system('gsutil cp gs://%s/evolve.txt .' % opt.bucket) # download evolve.txt if exists
  409. for _ in range(10): # generations to evolve
  410. if os.path.exists('evolve.txt'): # if evolve.txt exists: select best hyps and mutate
  411. # Select parent(s)
  412. parent = 'single' # parent selection method: 'single' or 'weighted'
  413. x = np.loadtxt('evolve.txt', ndmin=2)
  414. n = min(5, len(x)) # number of previous results to consider
  415. x = x[np.argsort(-fitness(x))][:n] # top n mutations
  416. w = fitness(x) - fitness(x).min() # weights
  417. if parent == 'single' or len(x) == 1:
  418. # x = x[random.randint(0, n - 1)] # random selection
  419. x = x[random.choices(range(n), weights=w)[0]] # weighted selection
  420. elif parent == 'weighted':
  421. x = (x * w.reshape(n, 1)).sum(0) / w.sum() # weighted combination
  422. # Mutate
  423. mp, s = 0.9, 0.2 # mutation probability, sigma
  424. npr = np.random
  425. npr.seed(int(time.time()))
  426. g = np.array([1, 1, 1, 1, 1, 1, 1, 0, .1, 1, 0, 1, 1, 1, 1, 1, 1, 1]) # gains
  427. ng = len(g)
  428. v = np.ones(ng)
  429. while all(v == 1): # mutate until a change occurs (prevent duplicates)
  430. v = (g * (npr.random(ng) < mp) * npr.randn(ng) * npr.random() * s + 1).clip(0.3, 3.0)
  431. for i, k in enumerate(hyp.keys()): # plt.hist(v.ravel(), 300)
  432. hyp[k] = x[i + 7] * v[i] # mutate
  433. # Clip to limits
  434. keys = ['lr0', 'iou_t', 'momentum', 'weight_decay', 'hsv_s', 'hsv_v', 'translate', 'scale', 'fl_gamma']
  435. limits = [(1e-5, 1e-2), (0.00, 0.70), (0.60, 0.98), (0, 0.001), (0, .9), (0, .9), (0, .9), (0, .9), (0, 3)]
  436. for k, v in zip(keys, limits):
  437. hyp[k] = np.clip(hyp[k], v[0], v[1])
  438. # Train mutation
  439. results = train(hyp.copy(), tb_writer, opt, device)
  440. # Write mutation results
  441. print_mutation(hyp, results, opt.bucket)
  442. # Plot results
  443. # plot_evolution_results(hyp)