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.

454 satır
22KB

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