glenn-jocher commited on
Commit
3c6e2f7
1 Parent(s): d7cfbc4

Single-source training (#680)

Browse files

* Single-source training

* Extract hyperparameters into seperate files

* weight decay scientific notation yaml reader bug fix

* remove import glob

* intersect_dicts() implementation

* 'or' bug fix

* .to(device) bug fix

data/hyp.finetune.yaml ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Hyperparameters for VOC fine-tuning
2
+ # python train.py --batch 64 --cfg '' --weights yolov5m.pt --data voc.yaml --img 512 --epochs 50
3
+ # See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
4
+
5
+
6
+ lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
7
+ momentum: 0.937 # SGD momentum/Adam beta1
8
+ weight_decay: 0.0005 # optimizer weight decay 5e-4
9
+ giou: 0.05 # GIoU loss gain
10
+ cls: 0.5 # cls loss gain
11
+ cls_pw: 1.0 # cls BCELoss positive_weight
12
+ obj: 1.0 # obj loss gain (scale with pixels)
13
+ obj_pw: 1.0 # obj BCELoss positive_weight
14
+ iou_t: 0.20 # IoU training threshold
15
+ anchor_t: 4.0 # anchor-multiple threshold
16
+ fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
17
+ hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
18
+ hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
19
+ hsv_v: 0.4 # image HSV-Value augmentation (fraction)
20
+ degrees: 0.0 # image rotation (+/- deg)
21
+ translate: 0.5 # image translation (+/- fraction)
22
+ scale: 0.5 # image scale (+/- gain)
23
+ shear: 0.0 # image shear (+/- deg)
24
+ perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
25
+ flipud: 0.0 # image flip up-down (probability)
26
+ fliplr: 0.5 # image flip left-right (probability)
27
+ mixup: 0.0 # image mixup (probability)
data/hyp.scratch.yaml ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Hyperparameters for COCO training from scratch
2
+ # python train.py --batch 40 --cfg yolov5m.yaml --weights '' --data coco.yaml --img 640 --epochs 300
3
+ # See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
4
+
5
+
6
+ lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
7
+ momentum: 0.937 # SGD momentum/Adam beta1
8
+ weight_decay: 0.0005 # optimizer weight decay 5e-4
9
+ giou: 0.05 # GIoU loss gain
10
+ cls: 0.5 # cls loss gain
11
+ cls_pw: 1.0 # cls BCELoss positive_weight
12
+ obj: 1.0 # obj loss gain (scale with pixels)
13
+ obj_pw: 1.0 # obj BCELoss positive_weight
14
+ iou_t: 0.20 # IoU training threshold
15
+ anchor_t: 4.0 # anchor-multiple threshold
16
+ fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
17
+ hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
18
+ hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
19
+ hsv_v: 0.4 # image HSV-Value augmentation (fraction)
20
+ degrees: 0.0 # image rotation (+/- deg)
21
+ translate: 0.5 # image translation (+/- fraction)
22
+ scale: 0.5 # image scale (+/- gain)
23
+ shear: 0.0 # image shear (+/- deg)
24
+ perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
25
+ flipud: 0.0 # image flip up-down (probability)
26
+ fliplr: 0.5 # image flip left-right (probability)
27
+ mixup: 0.0 # image mixup (probability)
train.py CHANGED
@@ -1,5 +1,4 @@
1
  import argparse
2
- import glob
3
  import math
4
  import os
5
  import random
@@ -26,31 +25,7 @@ from utils.general import (
26
  labels_to_image_weights, compute_loss, plot_images, fitness, strip_optimizer, plot_results,
27
  get_latest_run, check_git_status, check_file, increment_dir, print_mutation, plot_evolution)
28
  from utils.google_utils import attempt_download
29
- from utils.torch_utils import init_seeds, ModelEMA, select_device
30
-
31
- # Hyperparameters
32
- hyp = {'lr0': 0.01, # initial learning rate (SGD=1E-2, Adam=1E-3)
33
- 'momentum': 0.937, # SGD momentum/Adam beta1
34
- 'weight_decay': 5e-4, # optimizer weight decay
35
- 'giou': 0.05, # GIoU loss gain
36
- 'cls': 0.5, # cls loss gain
37
- 'cls_pw': 1.0, # cls BCELoss positive_weight
38
- 'obj': 1.0, # obj loss gain (scale with pixels)
39
- 'obj_pw': 1.0, # obj BCELoss positive_weight
40
- 'iou_t': 0.20, # IoU training threshold
41
- 'anchor_t': 4.0, # anchor-multiple threshold
42
- 'fl_gamma': 0.0, # focal loss gamma (efficientDet default gamma=1.5)
43
- 'hsv_h': 0.015, # image HSV-Hue augmentation (fraction)
44
- 'hsv_s': 0.7, # image HSV-Saturation augmentation (fraction)
45
- 'hsv_v': 0.4, # image HSV-Value augmentation (fraction)
46
- 'degrees': 0.0, # image rotation (+/- deg)
47
- 'translate': 0.5, # image translation (+/- fraction)
48
- 'scale': 0.5, # image scale (+/- gain)
49
- 'shear': 0.0, # image shear (+/- deg)
50
- 'perspective': 0.0, # image perspective (+/- fraction), range 0-0.001
51
- 'flipud': 0.0, # image flip up-down (probability)
52
- 'fliplr': 0.5, # image flip left-right (probability)
53
- 'mixup': 0.0} # image mixup (probability)
54
 
55
 
56
  def train(hyp, opt, device, tb_writer=None):
@@ -63,7 +38,7 @@ def train(hyp, opt, device, tb_writer=None):
63
  results_file = str(log_dir / 'results.txt')
64
  epochs, batch_size, total_batch_size, weights, rank = \
65
  opt.epochs, opt.batch_size, opt.total_batch_size, opt.weights, opt.global_rank
66
-
67
  # TODO: Use DDP logging. Only the first process is allowed to log.
68
  # Save run settings
69
  with open(log_dir / 'hyp.yaml', 'w') as f:
@@ -81,38 +56,35 @@ def train(hyp, opt, device, tb_writer=None):
81
  nc, names = (1, ['item']) if opt.single_cls else (int(data_dict['nc']), data_dict['names']) # number classes, names
82
  assert len(names) == nc, '%g names found for nc=%g dataset in %s' % (len(names), nc, opt.data) # check
83
 
84
- # Remove previous results
85
- if rank in [-1, 0]:
86
- for f in glob.glob('*_batch*.jpg') + glob.glob(results_file):
87
- os.remove(f)
88
-
89
- # Create model
90
- model = Model(opt.cfg, nc=nc).to(device)
91
-
92
- # Image sizes
93
- gs = int(max(model.stride)) # grid size (max stride)
94
- imgsz, imgsz_test = [check_img_size(x, gs) for x in opt.img_size] # verify imgsz are gs-multiples
 
 
 
95
 
96
  # Optimizer
97
  nbs = 64 # nominal batch size
98
- # default DDP implementation is slow for accumulation according to: https://pytorch.org/docs/stable/notes/ddp.html
99
- # all-reduce operation is carried out during loss.backward().
100
- # Thus, there would be redundant all-reduce communications in a accumulation procedure,
101
- # which means, the result is still right but the training speed gets slower.
102
- # TODO: If acceleration is needed, there is an implementation of allreduce_post_accumulation
103
- # in https://github.com/NVIDIA/DeepLearningExamples/blob/master/PyTorch/LanguageModeling/BERT/run_pretraining.py
104
  accumulate = max(round(nbs / total_batch_size), 1) # accumulate loss before optimizing
105
  hyp['weight_decay'] *= total_batch_size * accumulate / nbs # scale weight_decay
106
 
107
  pg0, pg1, pg2 = [], [], [] # optimizer parameter groups
108
  for k, v in model.named_parameters():
109
- if v.requires_grad:
110
- if '.bias' in k:
111
- pg2.append(v) # biases
112
- elif '.weight' in k and '.bn' not in k:
113
- pg1.append(v) # apply weight decay
114
- else:
115
- pg0.append(v) # all else
116
 
117
  if opt.adam:
118
  optimizer = optim.Adam(pg0, lr=hyp['lr0'], betas=(hyp['momentum'], 0.999)) # adjust beta1 to momentum
@@ -130,45 +102,27 @@ def train(hyp, opt, device, tb_writer=None):
130
  scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf)
131
  # plot_lr_scheduler(optimizer, scheduler, epochs)
132
 
133
- # Load Model
134
- with torch_distributed_zero_first(rank):
135
- attempt_download(weights)
136
  start_epoch, best_fitness = 0, 0.0
137
- if weights.endswith('.pt'): # pytorch format
138
- ckpt = torch.load(weights, map_location=device) # load checkpoint
139
-
140
- # load model
141
- try:
142
- exclude = ['anchor'] # exclude keys
143
- ckpt['model'] = {k: v for k, v in ckpt['model'].float().state_dict().items()
144
- if k in model.state_dict() and not any(x in k for x in exclude)
145
- and model.state_dict()[k].shape == v.shape}
146
- model.load_state_dict(ckpt['model'], strict=False)
147
- print('Transferred %g/%g items from %s' % (len(ckpt['model']), len(model.state_dict()), weights))
148
- except KeyError as e:
149
- s = "%s is not compatible with %s. This may be due to model differences or %s may be out of date. " \
150
- "Please delete or update %s and try again, or use --weights '' to train from scratch." \
151
- % (weights, opt.cfg, weights, weights)
152
- raise KeyError(s) from e
153
-
154
- # load optimizer
155
  if ckpt['optimizer'] is not None:
156
  optimizer.load_state_dict(ckpt['optimizer'])
157
  best_fitness = ckpt['best_fitness']
158
 
159
- # load results
160
  if ckpt.get('training_results') is not None:
161
  with open(results_file, 'w') as file:
162
  file.write(ckpt['training_results']) # write results.txt
163
 
164
- # epochs
165
  start_epoch = ckpt['epoch'] + 1
166
  if epochs < start_epoch:
167
  print('%s has been trained for %g epochs. Fine-tuning for %g additional epochs.' %
168
  (weights, ckpt['epoch'], epochs))
169
  epochs += ckpt['epoch'] # finetune additional epochs
170
 
171
- del ckpt
172
 
173
  # DP mode
174
  if cuda and rank == -1 and torch.cuda.device_count() > 1:
@@ -186,6 +140,10 @@ def train(hyp, opt, device, tb_writer=None):
186
  if cuda and rank != -1:
187
  model = DDP(model, device_ids=[opt.local_rank], output_device=(opt.local_rank))
188
 
 
 
 
 
189
  # Trainloader
190
  dataloader, dataset = create_dataloader(train_path, imgsz, batch_size, gs, opt, hyp=hyp, augment=True,
191
  cache=opt.cache_images, rect=opt.rect, local_rank=rank,
@@ -411,9 +369,10 @@ def train(hyp, opt, device, tb_writer=None):
411
 
412
  if __name__ == '__main__':
413
  parser = argparse.ArgumentParser()
414
- parser.add_argument('--cfg', type=str, default='models/yolov5s.yaml', help='model.yaml path')
 
415
  parser.add_argument('--data', type=str, default='data/coco128.yaml', help='data.yaml path')
416
- parser.add_argument('--hyp', type=str, default='', help='hyp.yaml path (optional)')
417
  parser.add_argument('--epochs', type=int, default=300)
418
  parser.add_argument('--batch-size', type=int, default=16, help='total batch size for all GPUs')
419
  parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='train,test sizes')
@@ -426,7 +385,6 @@ if __name__ == '__main__':
426
  parser.add_argument('--evolve', action='store_true', help='evolve hyperparameters')
427
  parser.add_argument('--bucket', type=str, default='', help='gsutil bucket')
428
  parser.add_argument('--cache-images', action='store_true', help='cache images for faster training')
429
- parser.add_argument('--weights', type=str, default='', help='initial weights path')
430
  parser.add_argument('--name', default='', help='renames results.txt to results_name.txt if supplied')
431
  parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
432
  parser.add_argument('--multi-scale', action='store_true', help='vary img-size +/- 50%%')
@@ -444,18 +402,17 @@ if __name__ == '__main__':
444
  opt.weights = last if opt.resume and not opt.weights else opt.weights
445
  if opt.local_rank == -1 or ("RANK" in os.environ and os.environ["RANK"] == "0"):
446
  check_git_status()
447
- opt.cfg = check_file(opt.cfg) # check file
448
- opt.data = check_file(opt.data) # check file
449
- if opt.hyp: # update hyps
450
- opt.hyp = check_file(opt.hyp) # check file
451
- with open(opt.hyp) as f:
452
- hyp.update(yaml.load(f, Loader=yaml.FullLoader)) # update hyps
453
  opt.img_size.extend([opt.img_size[-1]] * (2 - len(opt.img_size))) # extend to 2 sizes (train, test)
454
  device = select_device(opt.device, batch_size=opt.batch_size)
455
  opt.total_batch_size = opt.batch_size
456
  opt.world_size = 1
457
  opt.global_rank = -1
458
-
459
  # DDP mode
460
  if opt.local_rank != -1:
461
  assert torch.cuda.device_count() > opt.local_rank
@@ -468,6 +425,8 @@ if __name__ == '__main__':
468
  opt.batch_size = opt.total_batch_size // opt.world_size
469
 
470
  print(opt)
 
 
471
 
472
  # Train
473
  if not opt.evolve:
 
1
  import argparse
 
2
  import math
3
  import os
4
  import random
 
25
  labels_to_image_weights, compute_loss, plot_images, fitness, strip_optimizer, plot_results,
26
  get_latest_run, check_git_status, check_file, increment_dir, print_mutation, plot_evolution)
27
  from utils.google_utils import attempt_download
28
+ from utils.torch_utils import init_seeds, ModelEMA, select_device, intersect_dicts
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
 
31
  def train(hyp, opt, device, tb_writer=None):
 
38
  results_file = str(log_dir / 'results.txt')
39
  epochs, batch_size, total_batch_size, weights, rank = \
40
  opt.epochs, opt.batch_size, opt.total_batch_size, opt.weights, opt.global_rank
41
+
42
  # TODO: Use DDP logging. Only the first process is allowed to log.
43
  # Save run settings
44
  with open(log_dir / 'hyp.yaml', 'w') as f:
 
56
  nc, names = (1, ['item']) if opt.single_cls else (int(data_dict['nc']), data_dict['names']) # number classes, names
57
  assert len(names) == nc, '%g names found for nc=%g dataset in %s' % (len(names), nc, opt.data) # check
58
 
59
+ # Model
60
+ pretrained = weights.endswith('.pt')
61
+ if pretrained:
62
+ with torch_distributed_zero_first(rank):
63
+ attempt_download(weights) # download if not found locally
64
+ ckpt = torch.load(weights, map_location=device) # load checkpoint
65
+ model = Model(opt.cfg or ckpt['model'].yaml, ch=3, nc=nc).to(device) # create
66
+ exclude = ['anchor'] if opt.cfg else [] # exclude keys
67
+ state_dict = ckpt['model'].float().state_dict() # to FP32
68
+ state_dict = intersect_dicts(state_dict, model.state_dict(), exclude=exclude) # intersect
69
+ model.load_state_dict(state_dict, strict=False) # load
70
+ print('Transferred %g/%g items from %s' % (len(state_dict), len(model.state_dict()), weights)) # report
71
+ else:
72
+ model = Model(opt.cfg, ch=3, nc=nc).to(device) # create
73
 
74
  # Optimizer
75
  nbs = 64 # nominal batch size
 
 
 
 
 
 
76
  accumulate = max(round(nbs / total_batch_size), 1) # accumulate loss before optimizing
77
  hyp['weight_decay'] *= total_batch_size * accumulate / nbs # scale weight_decay
78
 
79
  pg0, pg1, pg2 = [], [], [] # optimizer parameter groups
80
  for k, v in model.named_parameters():
81
+ v.requires_grad = True
82
+ if '.bias' in k:
83
+ pg2.append(v) # biases
84
+ elif '.weight' in k and '.bn' not in k:
85
+ pg1.append(v) # apply weight decay
86
+ else:
87
+ pg0.append(v) # all else
88
 
89
  if opt.adam:
90
  optimizer = optim.Adam(pg0, lr=hyp['lr0'], betas=(hyp['momentum'], 0.999)) # adjust beta1 to momentum
 
102
  scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf)
103
  # plot_lr_scheduler(optimizer, scheduler, epochs)
104
 
105
+ # Resume
 
 
106
  start_epoch, best_fitness = 0, 0.0
107
+ if pretrained:
108
+ # Optimizer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  if ckpt['optimizer'] is not None:
110
  optimizer.load_state_dict(ckpt['optimizer'])
111
  best_fitness = ckpt['best_fitness']
112
 
113
+ # Results
114
  if ckpt.get('training_results') is not None:
115
  with open(results_file, 'w') as file:
116
  file.write(ckpt['training_results']) # write results.txt
117
 
118
+ # Epochs
119
  start_epoch = ckpt['epoch'] + 1
120
  if epochs < start_epoch:
121
  print('%s has been trained for %g epochs. Fine-tuning for %g additional epochs.' %
122
  (weights, ckpt['epoch'], epochs))
123
  epochs += ckpt['epoch'] # finetune additional epochs
124
 
125
+ del ckpt, state_dict
126
 
127
  # DP mode
128
  if cuda and rank == -1 and torch.cuda.device_count() > 1:
 
140
  if cuda and rank != -1:
141
  model = DDP(model, device_ids=[opt.local_rank], output_device=(opt.local_rank))
142
 
143
+ # Image sizes
144
+ gs = int(max(model.stride)) # grid size (max stride)
145
+ imgsz, imgsz_test = [check_img_size(x, gs) for x in opt.img_size] # verify imgsz are gs-multiples
146
+
147
  # Trainloader
148
  dataloader, dataset = create_dataloader(train_path, imgsz, batch_size, gs, opt, hyp=hyp, augment=True,
149
  cache=opt.cache_images, rect=opt.rect, local_rank=rank,
 
369
 
370
  if __name__ == '__main__':
371
  parser = argparse.ArgumentParser()
372
+ parser.add_argument('--weights', type=str, default='yolov5s.pt', help='initial weights path')
373
+ parser.add_argument('--cfg', type=str, default='', help='model.yaml path')
374
  parser.add_argument('--data', type=str, default='data/coco128.yaml', help='data.yaml path')
375
+ parser.add_argument('--hyp', type=str, default='data/hyp.finetune.yaml', help='hyperparameters path')
376
  parser.add_argument('--epochs', type=int, default=300)
377
  parser.add_argument('--batch-size', type=int, default=16, help='total batch size for all GPUs')
378
  parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='train,test sizes')
 
385
  parser.add_argument('--evolve', action='store_true', help='evolve hyperparameters')
386
  parser.add_argument('--bucket', type=str, default='', help='gsutil bucket')
387
  parser.add_argument('--cache-images', action='store_true', help='cache images for faster training')
 
388
  parser.add_argument('--name', default='', help='renames results.txt to results_name.txt if supplied')
389
  parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
390
  parser.add_argument('--multi-scale', action='store_true', help='vary img-size +/- 50%%')
 
402
  opt.weights = last if opt.resume and not opt.weights else opt.weights
403
  if opt.local_rank == -1 or ("RANK" in os.environ and os.environ["RANK"] == "0"):
404
  check_git_status()
405
+
406
+ opt.data, opt.cfg, opt.hyp = check_file(opt.data), check_file(opt.cfg), check_file(opt.hyp) # check files
407
+ assert len(opt.cfg) or len(opt.weights), 'either --cfg or --weights must be specified'
408
+ assert len(opt.hyp), '--hyp must be specified'
409
+
 
410
  opt.img_size.extend([opt.img_size[-1]] * (2 - len(opt.img_size))) # extend to 2 sizes (train, test)
411
  device = select_device(opt.device, batch_size=opt.batch_size)
412
  opt.total_batch_size = opt.batch_size
413
  opt.world_size = 1
414
  opt.global_rank = -1
415
+
416
  # DDP mode
417
  if opt.local_rank != -1:
418
  assert torch.cuda.device_count() > opt.local_rank
 
425
  opt.batch_size = opt.total_batch_size // opt.world_size
426
 
427
  print(opt)
428
+ with open(opt.hyp) as f:
429
+ hyp = yaml.load(f, Loader=yaml.FullLoader) # load hyps
430
 
431
  # Train
432
  if not opt.evolve:
utils/general.py CHANGED
@@ -120,7 +120,7 @@ def check_anchor_order(m):
120
 
121
  def check_file(file):
122
  # Searches for file if not found locally
123
- if os.path.isfile(file):
124
  return file
125
  else:
126
  files = glob.glob('./**/' + file, recursive=True) # find file
 
120
 
121
  def check_file(file):
122
  # Searches for file if not found locally
123
+ if os.path.isfile(file) or file == '':
124
  return file
125
  else:
126
  files = glob.glob('./**/' + file, recursive=True) # find file
utils/torch_utils.py CHANGED
@@ -55,10 +55,14 @@ def time_synchronized():
55
 
56
 
57
  def is_parallel(model):
58
- # is model is parallel with DP or DDP
59
  return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel)
60
 
61
 
 
 
 
 
 
62
  def initialize_weights(model):
63
  for m in model.modules():
64
  t = type(m)
@@ -72,7 +76,7 @@ def initialize_weights(model):
72
 
73
 
74
  def find_modules(model, mclass=nn.Conv2d):
75
- # finds layer indices matching module class 'mclass'
76
  return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)]
77
 
78
 
 
55
 
56
 
57
  def is_parallel(model):
 
58
  return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel)
59
 
60
 
61
+ def intersect_dicts(da, db, exclude=()):
62
+ # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values
63
+ return {k: v for k, v in da.items() if k in db and not any(x in k for x in exclude) and v.shape == db[k].shape}
64
+
65
+
66
  def initialize_weights(model):
67
  for m in model.modules():
68
  t = type(m)
 
76
 
77
 
78
  def find_modules(model, mclass=nn.Conv2d):
79
+ # Finds layer indices matching module class 'mclass'
80
  return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)]
81
 
82