2018-08-26 08:51:39 +00:00
|
|
|
|
import argparse
|
|
|
|
|
import time
|
|
|
|
|
|
2019-07-25 11:19:26 +00:00
|
|
|
|
import torch.distributed as dist
|
2019-04-17 13:52:51 +00:00
|
|
|
|
import torch.optim as optim
|
2019-05-30 17:02:55 +00:00
|
|
|
|
import torch.optim.lr_scheduler as lr_scheduler
|
2019-03-21 12:48:40 +00:00
|
|
|
|
|
2019-06-24 11:43:17 +00:00
|
|
|
|
import test # import test.py to get mAP after each epoch
|
2018-08-26 08:51:39 +00:00
|
|
|
|
from models import *
|
|
|
|
|
from utils.datasets import *
|
|
|
|
|
from utils.utils import *
|
|
|
|
|
|
2019-07-24 16:02:26 +00:00
|
|
|
|
mixed_precision = True
|
|
|
|
|
try: # Mixed precision training https://github.com/NVIDIA/apex
|
|
|
|
|
from apex import amp
|
2019-08-01 16:29:57 +00:00
|
|
|
|
except:
|
|
|
|
|
mixed_precision = False # not installed
|
2019-07-24 16:02:26 +00:00
|
|
|
|
|
2019-08-18 00:08:47 +00:00
|
|
|
|
# Hyperparameters (j-series, 50.5 mAP yolov3-320) evolved by @ktian08 https://github.com/ultralytics/yolov3/issues/310
|
|
|
|
|
hyp = {'giou': 1.582, # giou loss gain
|
2019-08-20 22:13:30 +00:00
|
|
|
|
'cls': 27.76, # cls loss gain (CE=~1.0, uCE=~20)
|
2019-08-18 00:08:47 +00:00
|
|
|
|
'cls_pw': 1.446, # cls BCELoss positive_weight
|
2019-08-20 22:21:36 +00:00
|
|
|
|
'obj': 21.35, # obj loss gain (*=80 for uBCE with 80 classes)
|
|
|
|
|
'obj_pw': 3.941, # obj BCELoss positive_weight
|
2019-08-18 00:08:47 +00:00
|
|
|
|
'iou_t': 0.2635, # iou training threshold
|
2019-08-18 00:15:16 +00:00
|
|
|
|
'lr0': 0.002324, # initial learning rate
|
2019-07-20 12:54:37 +00:00
|
|
|
|
'lrf': -4., # final LambdaLR learning rate = lr0 * (10 ** lrf)
|
2019-08-08 17:41:26 +00:00
|
|
|
|
'momentum': 0.97, # SGD momentum
|
2019-08-18 00:08:47 +00:00
|
|
|
|
'weight_decay': 0.0004569, # optimizer weight decay
|
|
|
|
|
'hsv_s': 0.5703, # image HSV-Saturation augmentation (fraction)
|
|
|
|
|
'hsv_v': 0.3174, # image HSV-Value augmentation (fraction)
|
|
|
|
|
'degrees': 1.113, # image rotation (+/- deg)
|
|
|
|
|
'translate': 0.06797, # image translation (+/- fraction)
|
|
|
|
|
'scale': 0.1059, # image scale (+/- gain)
|
|
|
|
|
'shear': 0.5768} # image shear (+/- deg)
|
|
|
|
|
|
2019-08-18 11:05:32 +00:00
|
|
|
|
|
2019-08-23 11:25:27 +00:00
|
|
|
|
def train():
|
|
|
|
|
cfg = opt.cfg
|
|
|
|
|
data = opt.data
|
|
|
|
|
img_size = opt.img_size
|
2019-08-25 18:20:15 +00:00
|
|
|
|
epochs = 1 if opt.prebias else opt.epochs # 500200 batches at bs 16, 117263 images = 273 epochs
|
2019-08-23 11:25:27 +00:00
|
|
|
|
batch_size = opt.batch_size
|
|
|
|
|
accumulate = opt.accumulate # effective bs = batch_size * accumulate = 16 * 4 = 64
|
2019-08-23 13:17:17 +00:00
|
|
|
|
weights = opt.weights # initial training weights
|
2019-08-23 11:25:27 +00:00
|
|
|
|
|
2019-08-25 18:19:53 +00:00
|
|
|
|
if 'pw' not in opt.arc: # remove BCELoss positive weights
|
2019-08-27 10:57:19 +00:00
|
|
|
|
hyp['cls_pw'] = 1.
|
|
|
|
|
hyp['obj_pw'] = 1.
|
2019-08-25 18:19:53 +00:00
|
|
|
|
|
2019-07-15 15:00:04 +00:00
|
|
|
|
# Initialize
|
2019-04-17 15:27:51 +00:00
|
|
|
|
init_seeds()
|
2019-08-23 13:17:17 +00:00
|
|
|
|
wdir = 'weights' + os.sep # weights dir
|
|
|
|
|
last = wdir + 'last.pt'
|
|
|
|
|
best = wdir + 'best.pt'
|
2019-07-24 16:28:11 +00:00
|
|
|
|
device = torch_utils.select_device(apex=mixed_precision)
|
2019-07-10 18:47:05 +00:00
|
|
|
|
multi_scale = opt.multi_scale
|
2018-12-05 10:55:27 +00:00
|
|
|
|
|
2019-06-13 16:13:30 +00:00
|
|
|
|
if multi_scale:
|
2019-08-04 00:50:35 +00:00
|
|
|
|
img_sz_min = round(img_size / 32 / 1.5) + 1
|
|
|
|
|
img_sz_max = round(img_size / 32 * 1.5) - 1
|
2019-07-20 11:20:01 +00:00
|
|
|
|
img_size = img_sz_max * 32 # initiate with maximum multi_scale size
|
2019-08-04 00:50:35 +00:00
|
|
|
|
print('Using multi-scale %g - %g' % (img_sz_min * 32, img_size))
|
2018-08-26 08:51:39 +00:00
|
|
|
|
|
|
|
|
|
# Configure run
|
2019-07-20 13:10:31 +00:00
|
|
|
|
data_dict = parse_data_cfg(data)
|
2019-04-27 15:57:07 +00:00
|
|
|
|
train_path = data_dict['train']
|
|
|
|
|
nc = int(data_dict['classes']) # number of classes
|
2018-08-26 08:51:39 +00:00
|
|
|
|
|
|
|
|
|
# Initialize model
|
2019-08-23 15:18:59 +00:00
|
|
|
|
model = Darknet(cfg, arc=opt.arc).to(device)
|
2018-08-26 08:51:39 +00:00
|
|
|
|
|
2019-03-21 10:08:55 +00:00
|
|
|
|
# Optimizer
|
2019-08-26 12:47:36 +00:00
|
|
|
|
pg0, pg1 = [], [] # optimizer parameter groups
|
|
|
|
|
for k, v in dict(model.named_parameters()).items():
|
|
|
|
|
if 'Conv2d.weight' in k:
|
|
|
|
|
pg1 += [v] # parameter group 1 (apply weight_decay)
|
|
|
|
|
else:
|
|
|
|
|
pg0 += [v] # parameter group 0
|
|
|
|
|
|
|
|
|
|
# optimizer = optim.Adam(pg0, lr=hyp['lr0'])
|
|
|
|
|
# optimizer = AdaBound(pg0, lr=hyp['lr0'], final_lr=0.1)
|
|
|
|
|
optimizer = optim.SGD(pg0, lr=hyp['lr0'], momentum=hyp['momentum'], nesterov=True)
|
|
|
|
|
optimizer.add_param_group({'params': pg1, 'weight_decay': hyp['weight_decay']}) # add pg1 with weight_decay
|
|
|
|
|
del pg0, pg1
|
2018-08-26 08:51:39 +00:00
|
|
|
|
|
2019-02-21 14:57:18 +00:00
|
|
|
|
cutoff = -1 # backbone reaches to cutoff layer
|
2019-02-22 15:15:20 +00:00
|
|
|
|
start_epoch = 0
|
2019-07-24 13:56:10 +00:00
|
|
|
|
best_fitness = 0.
|
2019-08-23 13:17:17 +00:00
|
|
|
|
if weights.endswith('.pt'): # pytorch format
|
|
|
|
|
# possible weights are 'last.pt', 'yolov3-spp.pt', 'yolov3-tiny.pt' etc.
|
|
|
|
|
if opt.bucket:
|
|
|
|
|
os.system('gsutil cp gs://%s/last.pt %s' % (opt.bucket, last)) # download from bucket
|
|
|
|
|
chkpt = torch.load(weights, map_location=device)
|
2019-04-02 16:04:04 +00:00
|
|
|
|
|
2019-08-23 13:17:17 +00:00
|
|
|
|
# load model
|
|
|
|
|
if opt.transfer:
|
|
|
|
|
chkpt['model'] = {k: v for k, v in chkpt['model'].items() if model.state_dict()[k].numel() == v.numel()}
|
2019-08-23 13:27:29 +00:00
|
|
|
|
model.load_state_dict(chkpt['model'], strict=False)
|
|
|
|
|
else:
|
|
|
|
|
model.load_state_dict(chkpt['model'])
|
2019-04-02 16:04:04 +00:00
|
|
|
|
|
2019-08-23 13:17:17 +00:00
|
|
|
|
# load optimizer
|
2019-04-02 16:04:04 +00:00
|
|
|
|
if chkpt['optimizer'] is not None:
|
|
|
|
|
optimizer.load_state_dict(chkpt['optimizer'])
|
2019-07-02 16:21:28 +00:00
|
|
|
|
best_fitness = chkpt['best_fitness']
|
2019-07-08 16:00:19 +00:00
|
|
|
|
|
2019-08-23 13:17:17 +00:00
|
|
|
|
# load results
|
2019-07-31 12:12:27 +00:00
|
|
|
|
if chkpt.get('training_results') is not None:
|
2019-07-08 17:26:46 +00:00
|
|
|
|
with open('results.txt', 'w') as file:
|
|
|
|
|
file.write(chkpt['training_results']) # write results.txt
|
2019-07-08 16:00:19 +00:00
|
|
|
|
|
|
|
|
|
start_epoch = chkpt['epoch'] + 1
|
2019-04-02 16:04:04 +00:00
|
|
|
|
del chkpt
|
2018-10-30 14:18:52 +00:00
|
|
|
|
|
2019-08-23 13:37:25 +00:00
|
|
|
|
elif len(weights) > 0: # darknet format
|
2019-08-23 13:17:17 +00:00
|
|
|
|
# possible weights are 'yolov3.weights', 'yolov3-tiny.conv.15', 'darknet53.conv.74' etc.
|
|
|
|
|
cutoff = load_darknet_weights(model, weights)
|
2018-10-30 14:18:52 +00:00
|
|
|
|
|
2019-08-24 18:55:01 +00:00
|
|
|
|
if opt.transfer or opt.prebias: # transfer learning edge (yolo) layers
|
2019-08-23 13:17:17 +00:00
|
|
|
|
nf = int(model.module_defs[model.yolo_layers[0] - 1]['filters']) # yolo layer size (i.e. 255)
|
2019-08-23 13:43:16 +00:00
|
|
|
|
|
2019-08-26 12:47:36 +00:00
|
|
|
|
for p in optimizer.param_groups:
|
|
|
|
|
# lower param count allows more aggressive training settings: i.e. SGD ~0.1 lr0, ~0.9 momentum
|
|
|
|
|
p['lr'] *= 100
|
|
|
|
|
p['momentum'] *= 0.9
|
2019-08-23 13:43:16 +00:00
|
|
|
|
|
2019-08-23 13:17:17 +00:00
|
|
|
|
for p in model.parameters():
|
2019-08-26 12:47:36 +00:00
|
|
|
|
if opt.prebias and p.numel() == nf: # train (yolo biases)
|
2019-08-24 18:55:01 +00:00
|
|
|
|
p.requires_grad = True
|
2019-08-26 12:47:36 +00:00
|
|
|
|
elif opt.transfer and p.shape[0] == nf: # train (yolo biases+weights)
|
2019-08-24 18:55:01 +00:00
|
|
|
|
p.requires_grad = True
|
2019-08-26 12:47:36 +00:00
|
|
|
|
else: # freeze layer
|
2019-08-24 18:55:01 +00:00
|
|
|
|
p.requires_grad = False
|
2019-06-16 21:17:40 +00:00
|
|
|
|
|
2019-04-24 10:58:14 +00:00
|
|
|
|
# Scheduler https://github.com/ultralytics/yolov3/issues/238
|
2019-04-17 13:52:51 +00:00
|
|
|
|
# lf = lambda x: 1 - x / epochs # linear ramp to zero
|
2019-04-24 11:30:24 +00:00
|
|
|
|
# lf = lambda x: 10 ** (hyp['lrf'] * x / epochs) # exp ramp
|
2019-05-30 17:02:55 +00:00
|
|
|
|
# lf = lambda x: 1 - 10 ** (hyp['lrf'] * (1 - x / epochs)) # inverse exp ramp
|
|
|
|
|
# scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf)
|
2019-07-30 16:25:53 +00:00
|
|
|
|
scheduler = lr_scheduler.MultiStepLR(optimizer, milestones=[round(opt.epochs * x) for x in [0.8, 0.9]], gamma=0.1)
|
2019-05-30 17:02:55 +00:00
|
|
|
|
scheduler.last_epoch = start_epoch - 1
|
2019-04-18 19:56:50 +00:00
|
|
|
|
|
2019-04-24 10:58:14 +00:00
|
|
|
|
# # Plot lr schedule
|
2019-04-18 19:44:57 +00:00
|
|
|
|
# y = []
|
|
|
|
|
# for _ in range(epochs):
|
|
|
|
|
# scheduler.step()
|
|
|
|
|
# y.append(optimizer.param_groups[0]['lr'])
|
2019-04-24 10:58:14 +00:00
|
|
|
|
# plt.plot(y, label='LambdaLR')
|
|
|
|
|
# plt.xlabel('epoch')
|
2019-06-21 11:19:23 +00:00
|
|
|
|
# plt.ylabel('LR')
|
2019-04-24 10:58:14 +00:00
|
|
|
|
# plt.tight_layout()
|
|
|
|
|
# plt.savefig('LR.png', dpi=300)
|
2019-04-17 14:15:08 +00:00
|
|
|
|
|
2019-07-24 16:02:26 +00:00
|
|
|
|
# Mixed precision training https://github.com/NVIDIA/apex
|
|
|
|
|
if mixed_precision:
|
|
|
|
|
model, optimizer = amp.initialize(model, optimizer, opt_level='O1', verbosity=0)
|
|
|
|
|
|
|
|
|
|
# Initialize distributed training
|
|
|
|
|
if torch.cuda.device_count() > 1:
|
|
|
|
|
dist.init_process_group(backend='nccl', # 'distributed backend'
|
|
|
|
|
init_method='tcp://127.0.0.1:9999', # distributed training init method
|
|
|
|
|
world_size=1, # number of nodes for distributed training
|
|
|
|
|
rank=0) # distributed training node rank
|
|
|
|
|
model = torch.nn.parallel.DistributedDataParallel(model)
|
2019-08-05 15:25:50 +00:00
|
|
|
|
model.yolo_layers = model.module.yolo_layers # move yolo layer indices to top level
|
2019-07-24 16:02:26 +00:00
|
|
|
|
|
2019-03-25 13:59:38 +00:00
|
|
|
|
# Dataset
|
2019-05-21 15:37:34 +00:00
|
|
|
|
dataset = LoadImagesAndLabels(train_path,
|
|
|
|
|
img_size,
|
|
|
|
|
batch_size,
|
|
|
|
|
augment=True,
|
2019-07-20 12:54:37 +00:00
|
|
|
|
hyp=hyp, # augmentation hyperparameters
|
2019-07-30 15:51:19 +00:00
|
|
|
|
rect=opt.rect, # rectangular training
|
2019-08-07 14:45:13 +00:00
|
|
|
|
image_weights=opt.img_weights,
|
2019-08-28 14:50:34 +00:00
|
|
|
|
cache_images=False if opt.prebias else opt.cache_images)
|
2019-03-25 13:59:38 +00:00
|
|
|
|
|
|
|
|
|
# Dataloader
|
2019-07-24 13:56:10 +00:00
|
|
|
|
dataloader = torch.utils.data.DataLoader(dataset,
|
|
|
|
|
batch_size=batch_size,
|
2019-08-15 11:44:42 +00:00
|
|
|
|
num_workers=min(os.cpu_count(), batch_size),
|
2019-07-24 13:56:10 +00:00
|
|
|
|
shuffle=not opt.rect, # Shuffle=True unless rectangular training is used
|
|
|
|
|
pin_memory=True,
|
|
|
|
|
collate_fn=dataset.collate_fn)
|
2018-08-26 08:51:39 +00:00
|
|
|
|
|
2019-08-23 13:17:17 +00:00
|
|
|
|
# Remove previous results
|
|
|
|
|
for f in glob.glob('*_batch*.jpg') + glob.glob('results.txt'):
|
|
|
|
|
os.remove(f)
|
|
|
|
|
|
2019-03-07 16:16:38 +00:00
|
|
|
|
# Start training
|
2019-08-05 14:59:32 +00:00
|
|
|
|
model.nc = nc # attach number of classes to model
|
2019-08-23 15:37:29 +00:00
|
|
|
|
model.arc = opt.arc # attach yolo architecture
|
2019-04-17 13:52:51 +00:00
|
|
|
|
model.hyp = hyp # attach hyperparameters to model
|
2019-08-17 12:08:10 +00:00
|
|
|
|
model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) # attach class weights
|
2019-06-24 11:43:17 +00:00
|
|
|
|
model_info(model, report='summary') # 'full' or 'summary'
|
2019-04-17 13:52:51 +00:00
|
|
|
|
nb = len(dataloader)
|
2019-05-10 12:15:09 +00:00
|
|
|
|
maps = np.zeros(nc) # mAP per class
|
2019-08-24 15:16:20 +00:00
|
|
|
|
results = (0, 0, 0, 0, 0, 0, 0) # 'P', 'R', 'mAP', 'F1', 'val GIoU', 'val Objectness', 'val Classification'
|
2019-07-16 15:56:39 +00:00
|
|
|
|
t0 = time.time()
|
2019-08-28 14:50:34 +00:00
|
|
|
|
print('Starting %s for %g epochs...' % ('prebias' if opt.prebias else 'training', epochs))
|
2019-08-22 22:36:48 +00:00
|
|
|
|
for epoch in range(start_epoch, epochs): # epoch ------------------------------------------------------------------
|
2019-03-17 21:45:39 +00:00
|
|
|
|
model.train()
|
2019-08-24 14:43:43 +00:00
|
|
|
|
print(('\n' + '%10s' * 8) % ('Epoch', 'gpu_mem', 'GIoU', 'obj', 'cls', 'total', 'targets', 'img_size'))
|
2018-09-20 16:03:19 +00:00
|
|
|
|
|
2019-03-25 13:59:38 +00:00
|
|
|
|
# Update scheduler
|
2019-08-09 16:22:27 +00:00
|
|
|
|
if epoch > 0:
|
|
|
|
|
scheduler.step()
|
2018-08-26 08:51:39 +00:00
|
|
|
|
|
2019-05-23 10:32:11 +00:00
|
|
|
|
# Freeze backbone at epoch 0, unfreeze at epoch 1 (optional)
|
2019-07-15 15:00:04 +00:00
|
|
|
|
freeze_backbone = False
|
2019-03-19 08:38:32 +00:00
|
|
|
|
if freeze_backbone and epoch < 2:
|
2019-03-25 13:59:38 +00:00
|
|
|
|
for name, p in model.named_parameters():
|
2019-02-21 14:57:18 +00:00
|
|
|
|
if int(name.split('.')[1]) < cutoff: # if layer < 75
|
2019-03-25 13:59:38 +00:00
|
|
|
|
p.requires_grad = False if epoch == 0 else True
|
2018-11-27 17:14:48 +00:00
|
|
|
|
|
2019-07-30 15:51:19 +00:00
|
|
|
|
# Update image weights (optional)
|
|
|
|
|
if dataset.image_weights:
|
2019-08-01 23:33:24 +00:00
|
|
|
|
w = model.class_weights.cpu().numpy() * (1 - maps) ** 2 # class weights
|
2019-07-30 15:51:19 +00:00
|
|
|
|
image_weights = labels_to_image_weights(dataset.labels, nc=nc, class_weights=w)
|
|
|
|
|
dataset.indices = random.choices(range(dataset.n), weights=image_weights, k=dataset.n) # rand weighted idx
|
2019-05-10 12:15:09 +00:00
|
|
|
|
|
2019-08-24 14:43:43 +00:00
|
|
|
|
mloss = torch.zeros(4).to(device) # mean losses
|
2019-06-30 15:34:29 +00:00
|
|
|
|
pbar = tqdm(enumerate(dataloader), total=nb) # progress bar
|
2019-08-22 22:36:48 +00:00
|
|
|
|
for i, (imgs, targets, paths, _) in pbar: # batch -------------------------------------------------------------
|
2019-08-23 11:39:43 +00:00
|
|
|
|
ni = i + nb * epoch # number integrated batches (since train start)
|
2019-03-25 13:59:38 +00:00
|
|
|
|
imgs = imgs.to(device)
|
|
|
|
|
targets = targets.to(device)
|
2018-09-19 02:21:46 +00:00
|
|
|
|
|
2019-08-08 17:49:15 +00:00
|
|
|
|
# Multi-Scale training
|
2019-06-13 16:13:30 +00:00
|
|
|
|
if multi_scale:
|
2019-08-08 18:16:32 +00:00
|
|
|
|
if ni / accumulate % 10 == 0: # adjust (67% - 150%) every 10 batches
|
2019-07-20 11:20:01 +00:00
|
|
|
|
img_size = random.randrange(img_sz_min, img_sz_max + 1) * 32
|
|
|
|
|
sf = img_size / max(imgs.shape[2:]) # scale factor
|
|
|
|
|
if sf != 1:
|
2019-08-08 17:49:15 +00:00
|
|
|
|
ns = [math.ceil(x * sf / 32.) * 32 for x in imgs.shape[2:]] # new shape (stretched to 32-multiple)
|
2019-07-20 11:20:01 +00:00
|
|
|
|
imgs = F.interpolate(imgs, size=ns, mode='bilinear', align_corners=False)
|
2019-06-12 11:04:58 +00:00
|
|
|
|
|
2019-03-21 20:41:12 +00:00
|
|
|
|
# Plot images with bounding boxes
|
2019-08-23 11:31:32 +00:00
|
|
|
|
if ni == 0:
|
2019-08-09 14:37:19 +00:00
|
|
|
|
fname = 'train_batch%g.jpg' % i
|
2019-08-09 17:29:36 +00:00
|
|
|
|
plot_images(imgs=imgs, targets=targets, paths=paths, fname=fname)
|
2019-08-09 14:37:19 +00:00
|
|
|
|
if tb_writer:
|
2019-08-09 17:29:36 +00:00
|
|
|
|
tb_writer.add_image(fname, cv2.imread(fname)[:, :, ::-1], dataformats='HWC')
|
2019-03-21 20:41:12 +00:00
|
|
|
|
|
2019-08-08 17:49:15 +00:00
|
|
|
|
# Hyperparameter burn-in
|
2019-08-08 19:16:09 +00:00
|
|
|
|
# n_burn = nb - 1 # min(nb // 5 + 1, 1000) # number of burn-in batches
|
2019-08-08 18:16:32 +00:00
|
|
|
|
# if ni <= n_burn:
|
2019-08-08 17:49:15 +00:00
|
|
|
|
# for m in model.named_modules():
|
|
|
|
|
# if m[0].endswith('BatchNorm2d'):
|
2019-08-08 18:16:32 +00:00
|
|
|
|
# m[1].momentum = 1 - i / n_burn * 0.99 # BatchNorm2d momentum falls from 1 - 0.01
|
|
|
|
|
# g = (i / n_burn) ** 4 # gain rises from 0 - 1
|
2019-07-22 23:35:03 +00:00
|
|
|
|
# for x in optimizer.param_groups:
|
|
|
|
|
# x['lr'] = hyp['lr0'] * g
|
|
|
|
|
# x['weight_decay'] = hyp['weight_decay'] * g
|
2018-09-20 16:03:19 +00:00
|
|
|
|
|
2019-03-17 21:45:39 +00:00
|
|
|
|
# Run model
|
2019-03-25 13:59:38 +00:00
|
|
|
|
pred = model(imgs)
|
2019-03-17 21:45:39 +00:00
|
|
|
|
|
2019-03-07 16:16:38 +00:00
|
|
|
|
# Compute loss
|
2019-08-23 15:37:29 +00:00
|
|
|
|
loss, loss_items = compute_loss(pred, targets, model)
|
2019-08-31 15:55:19 +00:00
|
|
|
|
if not torch.isfinite(loss):
|
|
|
|
|
print('WARNING: non-finite loss, skipping batch ', loss_items)
|
2019-08-29 13:44:15 +00:00
|
|
|
|
continue
|
2019-03-07 16:16:38 +00:00
|
|
|
|
|
2019-08-26 14:24:19 +00:00
|
|
|
|
# Scale loss by nominal batch_size of 64
|
|
|
|
|
loss *= batch_size / 64
|
2019-08-24 21:58:08 +00:00
|
|
|
|
|
2019-03-07 16:16:38 +00:00
|
|
|
|
# Compute gradient
|
2019-04-13 14:02:45 +00:00
|
|
|
|
if mixed_precision:
|
|
|
|
|
with amp.scale_loss(loss, optimizer) as scaled_loss:
|
|
|
|
|
scaled_loss.backward()
|
|
|
|
|
else:
|
|
|
|
|
loss.backward()
|
2018-10-09 17:22:33 +00:00
|
|
|
|
|
2019-03-07 16:16:38 +00:00
|
|
|
|
# Accumulate gradient for x batches before optimizing
|
2019-08-23 11:31:32 +00:00
|
|
|
|
if ni % accumulate == 0:
|
2018-12-16 14:16:19 +00:00
|
|
|
|
optimizer.step()
|
|
|
|
|
optimizer.zero_grad()
|
2018-09-19 02:21:46 +00:00
|
|
|
|
|
2019-04-15 11:55:52 +00:00
|
|
|
|
# Print batch results
|
2019-05-23 10:32:11 +00:00
|
|
|
|
mloss = (mloss * i + loss_items) / (i + 1) # update mean losses
|
2019-07-16 15:56:39 +00:00
|
|
|
|
mem = torch.cuda.memory_cached() / 1E9 if torch.cuda.is_available() else 0 # (GB)
|
2019-08-24 14:43:43 +00:00
|
|
|
|
s = ('%10s' * 2 + '%10.3g' * 6) % (
|
2019-07-16 16:18:08 +00:00
|
|
|
|
'%g/%g' % (epoch, epochs - 1), '%.3gG' % mem, *mloss, len(targets), img_size)
|
2019-08-29 12:29:07 +00:00
|
|
|
|
pbar.set_description(s)
|
2019-08-24 19:20:25 +00:00
|
|
|
|
|
2019-08-29 12:29:07 +00:00
|
|
|
|
# end batch ------------------------------------------------------------------------------------------------
|
|
|
|
|
|
|
|
|
|
# Process epoch results
|
2019-08-24 19:35:56 +00:00
|
|
|
|
final_epoch = epoch + 1 == epochs
|
2019-08-24 19:20:25 +00:00
|
|
|
|
if opt.prebias:
|
|
|
|
|
print_model_biases(model)
|
|
|
|
|
else:
|
|
|
|
|
# Calculate mAP (always test final epoch, skip first 10 if opt.nosave)
|
|
|
|
|
if not (opt.notest or (opt.nosave and epoch < 10)) or final_epoch:
|
|
|
|
|
with torch.no_grad():
|
|
|
|
|
results, maps = test.test(cfg,
|
|
|
|
|
data,
|
|
|
|
|
batch_size=batch_size,
|
|
|
|
|
img_size=opt.img_size,
|
|
|
|
|
model=model,
|
|
|
|
|
conf_thres=0.001 if final_epoch and epoch > 0 else 0.1, # 0.1 for speed
|
|
|
|
|
save_json=final_epoch and epoch > 0 and 'coco.data' in data)
|
2019-04-05 13:34:42 +00:00
|
|
|
|
|
|
|
|
|
# Write epoch results
|
|
|
|
|
with open('results.txt', 'a') as file:
|
2019-08-24 14:43:43 +00:00
|
|
|
|
file.write(s + '%10.3g' * 7 % results + '\n') # P, R, mAP, F1, test_losses=(GIoU, obj, cls)
|
2019-04-05 13:34:42 +00:00
|
|
|
|
|
2019-08-08 20:30:34 +00:00
|
|
|
|
# Write Tensorboard results
|
2019-08-09 14:37:19 +00:00
|
|
|
|
if tb_writer:
|
2019-08-24 14:43:43 +00:00
|
|
|
|
x = list(mloss) + list(results)
|
|
|
|
|
titles = ['GIoU', 'Objectness', 'Classification', 'Train loss',
|
|
|
|
|
'Precision', 'Recall', 'mAP', 'F1', 'val GIoU', 'val Objectness', 'val Classification']
|
2019-08-09 14:37:19 +00:00
|
|
|
|
for xi, title in zip(x, titles):
|
|
|
|
|
tb_writer.add_scalar(title, xi, epoch)
|
2019-08-08 20:30:34 +00:00
|
|
|
|
|
2019-08-24 19:20:25 +00:00
|
|
|
|
# Update best mAP
|
2019-08-03 22:12:46 +00:00
|
|
|
|
fitness = results[2] # mAP
|
2019-07-02 16:21:28 +00:00
|
|
|
|
if fitness > best_fitness:
|
|
|
|
|
best_fitness = fitness
|
2019-03-17 21:45:39 +00:00
|
|
|
|
|
2019-03-19 08:38:32 +00:00
|
|
|
|
# Save training results
|
2019-08-15 12:10:08 +00:00
|
|
|
|
save = (not opt.nosave) or ((not opt.evolve) and final_epoch)
|
2019-03-17 21:45:39 +00:00
|
|
|
|
if save:
|
2019-07-08 16:00:19 +00:00
|
|
|
|
with open('results.txt', 'r') as file:
|
|
|
|
|
# Create checkpoint
|
|
|
|
|
chkpt = {'epoch': epoch,
|
|
|
|
|
'best_fitness': best_fitness,
|
|
|
|
|
'training_results': file.read(),
|
|
|
|
|
'model': model.module.state_dict() if type(
|
|
|
|
|
model) is nn.parallel.DistributedDataParallel else model.state_dict(),
|
2019-08-23 10:57:26 +00:00
|
|
|
|
'optimizer': None if final_epoch else optimizer.state_dict()}
|
2019-04-05 13:34:42 +00:00
|
|
|
|
|
2019-07-15 15:54:31 +00:00
|
|
|
|
# Save last checkpoint
|
|
|
|
|
torch.save(chkpt, last)
|
2019-07-08 16:32:31 +00:00
|
|
|
|
if opt.bucket:
|
2019-07-15 15:54:31 +00:00
|
|
|
|
os.system('gsutil cp %s gs://%s' % (last, opt.bucket)) # upload to bucket
|
2019-03-17 21:45:39 +00:00
|
|
|
|
|
|
|
|
|
# Save best checkpoint
|
2019-07-02 16:21:28 +00:00
|
|
|
|
if best_fitness == fitness:
|
2019-04-02 16:04:04 +00:00
|
|
|
|
torch.save(chkpt, best)
|
2019-03-17 21:45:39 +00:00
|
|
|
|
|
2019-04-02 16:04:04 +00:00
|
|
|
|
# Save backup every 10 epochs (optional)
|
2019-04-02 12:07:14 +00:00
|
|
|
|
if epoch > 0 and epoch % 10 == 0:
|
2019-08-23 13:17:17 +00:00
|
|
|
|
torch.save(chkpt, wdir + 'backup%g.pt' % epoch)
|
2019-04-02 14:33:52 +00:00
|
|
|
|
|
2019-04-05 13:34:42 +00:00
|
|
|
|
# Delete checkpoint
|
2019-08-29 12:29:07 +00:00
|
|
|
|
del chkpt
|
|
|
|
|
|
|
|
|
|
# end epoch ----------------------------------------------------------------------------------------------------
|
2018-08-26 08:51:39 +00:00
|
|
|
|
|
2019-07-16 15:56:39 +00:00
|
|
|
|
# Report time
|
2019-08-23 11:45:49 +00:00
|
|
|
|
plot_results() # save as results.png
|
2019-08-24 19:39:25 +00:00
|
|
|
|
print('%g epochs completed in %.3f hours.\n' % (epoch - start_epoch + 1, (time.time() - t0) / 3600))
|
2019-07-24 17:31:38 +00:00
|
|
|
|
dist.destroy_process_group() if torch.cuda.device_count() > 1 else None
|
2019-07-23 22:22:07 +00:00
|
|
|
|
torch.cuda.empty_cache()
|
2019-04-17 14:15:08 +00:00
|
|
|
|
return results
|
|
|
|
|
|
2018-08-26 08:51:39 +00:00
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2018-12-05 13:31:08 +00:00
|
|
|
|
parser = argparse.ArgumentParser()
|
2019-08-23 11:25:27 +00:00
|
|
|
|
parser.add_argument('--epochs', type=int, default=273) # 500200 batches at bs 16, 117263 images = 273 epochs
|
|
|
|
|
parser.add_argument('--batch-size', type=int, default=32) # effective bs = batch_size * accumulate = 16 * 4 = 64
|
|
|
|
|
parser.add_argument('--accumulate', type=int, default=2, help='batches to accumulate before optimizing')
|
2019-08-23 13:24:26 +00:00
|
|
|
|
parser.add_argument('--cfg', type=str, default='cfg/yolov3-spp.cfg', help='cfg file path')
|
2019-08-23 11:25:27 +00:00
|
|
|
|
parser.add_argument('--data', type=str, default='data/coco.data', help='*.data file path')
|
2019-08-23 11:31:32 +00:00
|
|
|
|
parser.add_argument('--multi-scale', action='store_true', help='adjust (67% - 150%) img_size every 10 batches')
|
2019-08-06 12:57:12 +00:00
|
|
|
|
parser.add_argument('--img-size', type=int, default=416, help='inference size (pixels)')
|
2019-07-08 13:02:20 +00:00
|
|
|
|
parser.add_argument('--rect', action='store_true', help='rectangular training')
|
2019-08-23 11:25:27 +00:00
|
|
|
|
parser.add_argument('--resume', action='store_true', help='resume training from last.pt')
|
|
|
|
|
parser.add_argument('--transfer', action='store_true', help='transfer learning')
|
2019-06-24 12:46:00 +00:00
|
|
|
|
parser.add_argument('--nosave', action='store_true', help='only save final checkpoint')
|
2019-04-17 15:27:51 +00:00
|
|
|
|
parser.add_argument('--notest', action='store_true', help='only test final epoch')
|
2019-07-01 15:17:29 +00:00
|
|
|
|
parser.add_argument('--evolve', action='store_true', help='evolve hyperparameters')
|
2019-07-08 16:32:31 +00:00
|
|
|
|
parser.add_argument('--bucket', type=str, default='', help='gsutil bucket')
|
2019-07-30 16:27:37 +00:00
|
|
|
|
parser.add_argument('--img-weights', action='store_true', help='select training images by weight')
|
2019-08-07 14:45:13 +00:00
|
|
|
|
parser.add_argument('--cache-images', action='store_true', help='cache images for faster training')
|
2019-08-23 13:17:17 +00:00
|
|
|
|
parser.add_argument('--weights', type=str, default='', help='initial weights') # i.e. weights/darknet.53.conv.74
|
2019-08-25 18:19:53 +00:00
|
|
|
|
parser.add_argument('--arc', type=str, default='defaultpw', help='yolo architecture') # defaultpw, uCE, uBCE
|
2019-08-24 18:55:01 +00:00
|
|
|
|
parser.add_argument('--prebias', action='store_true', help='transfer-learn yolo biases prior to training')
|
2018-12-05 13:31:08 +00:00
|
|
|
|
opt = parser.parse_args()
|
2019-08-23 13:17:17 +00:00
|
|
|
|
opt.weights = 'weights/last.pt' if opt.resume else opt.weights
|
2019-05-03 16:14:16 +00:00
|
|
|
|
print(opt)
|
2018-12-05 13:31:08 +00:00
|
|
|
|
|
2019-08-09 17:35:02 +00:00
|
|
|
|
tb_writer = None
|
2019-07-24 17:02:24 +00:00
|
|
|
|
if not opt.evolve: # Train normally
|
2019-08-09 14:37:19 +00:00
|
|
|
|
try:
|
|
|
|
|
# Start Tensorboard with "tensorboard --logdir=runs", view at http://localhost:6006/
|
|
|
|
|
from torch.utils.tensorboard import SummaryWriter
|
|
|
|
|
|
|
|
|
|
tb_writer = SummaryWriter()
|
|
|
|
|
except:
|
2019-08-09 17:35:02 +00:00
|
|
|
|
pass
|
2019-08-08 20:30:34 +00:00
|
|
|
|
|
2019-08-24 18:55:01 +00:00
|
|
|
|
if opt.prebias:
|
|
|
|
|
train() # transfer-learn yolo biases for 1 epoch
|
|
|
|
|
create_backbone('weights/last.pt') # saved results as backbone.pt
|
|
|
|
|
opt.weights = 'weights/backbone.pt' # assign backbone
|
2019-08-24 19:20:25 +00:00
|
|
|
|
opt.prebias = False # disable prebias
|
|
|
|
|
print(opt) # display options
|
2019-08-24 18:55:01 +00:00
|
|
|
|
|
2019-08-24 19:20:25 +00:00
|
|
|
|
train() # train normally
|
2019-07-24 17:02:24 +00:00
|
|
|
|
|
|
|
|
|
else: # Evolve hyperparameters (optional)
|
2019-06-24 12:46:00 +00:00
|
|
|
|
opt.notest = True # only test final epoch
|
|
|
|
|
opt.nosave = True # only save final checkpoint
|
2019-07-24 17:02:24 +00:00
|
|
|
|
if opt.bucket:
|
|
|
|
|
os.system('gsutil cp gs://%s/evolve.txt .' % opt.bucket) # download evolve.txt if exists
|
2019-04-17 15:51:39 +00:00
|
|
|
|
|
2019-08-05 01:02:48 +00:00
|
|
|
|
for _ in range(100): # generations to evolve
|
2019-07-24 18:16:35 +00:00
|
|
|
|
if os.path.exists('evolve.txt'): # if evolve.txt exists: select best hyps and mutate
|
2019-07-24 17:02:24 +00:00
|
|
|
|
# Get best hyperparameters
|
|
|
|
|
x = np.loadtxt('evolve.txt', ndmin=2)
|
|
|
|
|
x = x[fitness(x).argmax()] # select best fitness hyps
|
|
|
|
|
for i, k in enumerate(hyp.keys()):
|
2019-08-06 12:36:12 +00:00
|
|
|
|
hyp[k] = x[i + 7]
|
2019-07-24 17:02:24 +00:00
|
|
|
|
|
|
|
|
|
# Mutate
|
|
|
|
|
init_seeds(seed=int(time.time()))
|
2019-08-24 14:45:49 +00:00
|
|
|
|
s = [.15, .15, .15, .15, .15, .15, .15, .00, .02, .20, .20, .20, .20, .20, .20, .20] # sigmas
|
2019-07-24 17:02:24 +00:00
|
|
|
|
for i, k in enumerate(hyp.keys()):
|
|
|
|
|
x = (np.random.randn(1) * s[i] + 1) ** 2.0 # plt.hist(x.ravel(), 300)
|
|
|
|
|
hyp[k] *= float(x) # vary by sigmas
|
2019-04-17 15:27:51 +00:00
|
|
|
|
|
2019-04-24 12:09:15 +00:00
|
|
|
|
# Clip to limits
|
2019-07-20 12:54:37 +00:00
|
|
|
|
keys = ['lr0', 'iou_t', 'momentum', 'weight_decay', 'hsv_s', 'hsv_v', 'translate', 'scale']
|
2019-08-06 12:38:03 +00:00
|
|
|
|
limits = [(1e-4, 1e-2), (0.00, 0.70), (0.60, 0.98), (0, 0.001), (0, .9), (0, .9), (0, .9), (0, .9)]
|
2019-04-24 12:09:15 +00:00
|
|
|
|
for k, v in zip(keys, limits):
|
|
|
|
|
hyp[k] = np.clip(hyp[k], v[0], v[1])
|
2019-04-17 17:04:01 +00:00
|
|
|
|
|
2019-07-01 15:14:42 +00:00
|
|
|
|
# Train mutation
|
2019-08-23 11:25:27 +00:00
|
|
|
|
results = train()
|
2019-04-17 15:27:51 +00:00
|
|
|
|
|
|
|
|
|
# Write mutation results
|
2019-07-25 15:49:54 +00:00
|
|
|
|
print_mutation(hyp, results, opt.bucket)
|
|
|
|
|
|
|
|
|
|
# Plot results
|
2019-07-26 10:00:43 +00:00
|
|
|
|
# plot_evolution_results(hyp)
|