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.

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