1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549
| import os import argparse import time import tqdm import cv2 import torch import numpy as np import torch.nn as nn import torch.optim as optim import apex.optimizers as apex_optim import torch.distributed as dist from config.config import GetConfig, COCOSourceConfig, TrainingOpt from data.mydataset import MyDataset from torch.utils.data.dataloader import DataLoader from models.posenet import Network from models.loss_model import MultiTaskLoss import warnings
try: import apex.optimizers as apex_optim from apex.parallel import DistributedDataParallel as DDP from apex.fp16_utils import * from apex import amp from apex.multi_tensor_apply import multi_tensor_applier except ImportError: raise ImportError( "Please install apex from https://www.github.com/nvidia/apex to run this example.")
warnings.filterwarnings("ignore")
parser = argparse.ArgumentParser(description='PoseNet Training') parser.add_argument( '--resume', '-r', action='store_true', default=True, help='resume from checkpoint') parser.add_argument('--freeze', action='store_true', default=False, help='freeze the pre-trained layers before output layers') parser.add_argument( '--warmup', action='store_true', default=True, help='using warm-up learning rate') parser.add_argument( '--checkpoint_path', '-p', default='link2checkpoints_distributed', help='save path') parser.add_argument( '--max_grad_norm', default=10, type=float, help=( "If the norm of the gradient vector exceeds this, " "re-normalize it to have the norm equal to max_grad_norm"))
parser.add_argument("--local_rank", default=0, type=int) parser.add_argument('--opt-level', type=str, default='O1') parser.add_argument('--sync_bn', action='store_true', default=True, help='enabling apex sync BN.') parser.add_argument('--keep-batchnorm-fp32', type=str, default=None) parser.add_argument('--loss-scale', type=str, default=None) parser.add_argument( '--print-freq', '-f', default=10, type=int, metavar='N', help='print frequency (default: 10)')
torch.backends.cudnn.benchmark = True use_cuda = torch.cuda.is_available()
args = parser.parse_args()
checkpoint_path = args.checkpoint_path opt = TrainingOpt() config = GetConfig(opt.config_name)
soureconfig = COCOSourceConfig(opt.hdf5_train_data) train_data = MyDataset( config, soureconfig, shuffle=False, augment=True)
soureconfig_val = COCOSourceConfig(opt.hdf5_val_data) val_data = MyDataset( config, soureconfig_val, shuffle=False, augment=False)
best_loss = float('inf') start_epoch = 0
args.distributed = False if 'WORLD_SIZE' in os.environ: args.distributed = int(os.environ['WORLD_SIZE']) > 1
args.gpu = 0 args.world_size = 1
if args.distributed: args.gpu = args.local_rank torch.cuda.set_device(args.gpu) torch.distributed.init_process_group(backend='nccl', init_method='env://') args.world_size = torch.distributed.get_world_size() print("World Size is :", args.world_size)
assert torch.backends.cudnn.enabled, "Amp requires cudnn backend to be enabled."
model = Network(opt, config, dist=True, bn=True)
if args.sync_bn: import apex
print("Using apex synced BN.") model = apex.parallel.convert_syncbn_model(model)
model.cuda()
for param in model.parameters(): if param.requires_grad: print('Parameters of network: Autograd') break
if args.freeze: for name, param in model.named_parameters(): if 'out' or 'merge' or 'before_regress' in name: continue param.requires_grad = False
optimizer = optim.SGD( filter( lambda p: p.requires_grad, model.parameters()), lr=opt.learning_rate * args.world_size, momentum=0.9, weight_decay=5e-4)
model, optimizer = amp.initialize(model, optimizer, opt_level=args.opt_level, keep_batchnorm_fp32=args.keep_batchnorm_fp32, loss_scale=args.loss_scale)
if args.distributed: model = DDP(model, delay_allreduce=True)
if args.resume: def resume(): if os.path.isfile(opt.ckpt_path): print('Resuming from checkpoint ...... ') checkpoint = torch.load( opt.ckpt_path, map_location=torch.device('cpu'))
from collections import OrderedDict new_state_dict = OrderedDict() for k, v in checkpoint['weights'].items(): name = 'module.' + k new_state_dict[name] = v model.load_state_dict( new_state_dict, strict=False) print('Network weights have been resumed from checkpoint...')
optimizer.load_state_dict(checkpoint['optimizer_weight']) for state in optimizer.state.values(): for k, v in state.items(): if torch.is_tensor(v): state[k] = v.cuda() print('Optimizer has been resumed from checkpoint...') global best_loss, start_epoch best_loss = checkpoint['train_loss'] print('******************** Best loss resumed is :', best_loss, ' ************************') start_epoch = checkpoint['epoch'] + 1 print( "========> Resume and start training from Epoch {} ".format(start_epoch)) del checkpoint else: print("========> No checkpoint found at '{}'".format(opt.ckpt_path))
resume()
train_sampler = None val_sampler = None
if args.distributed: train_sampler = torch.utils.data.distributed.DistributedSampler(train_data) val_sampler = torch.utils.data.distributed.DistributedSampler(val_data)
train_loader = torch.utils.data.DataLoader( train_data, batch_size=opt.batch_size, shuffle=( train_sampler is None), num_workers=2, pin_memory=True, sampler=train_sampler, drop_last=True) val_loader = torch.utils.data.DataLoader( val_data, batch_size=opt.batch_size, shuffle=False, num_workers=2, pin_memory=True, sampler=val_sampler, drop_last=True)
for param in model.parameters(): if param.requires_grad: print('Parameters of network: Autograd') break
def train(epoch): print('\n ############################# Train phase, Epoch: {} #############################'.format(epoch)) torch.cuda.empty_cache() model.train() if args.distributed: train_sampler.set_epoch(epoch)
print('\nLearning rate at this epoch is: %0.9f\n' % optimizer.param_groups[0]['lr'])
batch_time = AverageMeter() losses = AverageMeter() end = time.time()
for batch_idx, target_tuple in enumerate(train_loader): adjust_learning_rate( optimizer, epoch, batch_idx, len(train_loader), use_warmup=args.warmup) if use_cuda: target_tuple = [ target_tensor.cuda( non_blocking=True) for target_tensor in target_tuple]
images, mask_misses, heatmaps = target_tuple optimizer.zero_grad() loss = model(target_tuple)
if loss.item() > 2e5: print("\nOh My God ! \nLoss is abnormal, drop this batch !") continue
with amp.scale_loss(loss, optimizer) as scaled_loss: scaled_loss.backward()
optimizer.step()
if batch_idx % args.print_freq == 0: if args.distributed: reduced_loss = reduce_tensor(loss.data) else: reduced_loss = loss.data
losses.update(to_python_float(reduced_loss), images.size(0)) torch.cuda.synchronize() batch_time.update((time.time() - end) / args.print_freq) end = time.time()
if args.local_rank == 0: print( '==================> Epoch: [{0}][{1}/{2}]\t' 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 'Speed {3:.3f} ({4:.3f})\t' 'Loss {loss.val:.10f} ({loss.avg:.4f}) <================ \t'.format( epoch, batch_idx, len(train_loader), args.world_size * opt.batch_size / batch_time.val, args.world_size * opt.batch_size / batch_time.avg, batch_time=batch_time, loss=losses))
global best_loss
if args.local_rank == 0: os.makedirs(checkpoint_path, exist_ok=True) logger = open(os.path.join('./' + checkpoint_path, 'log'), 'a+') logger.write( '\nEpoch {}\ttrain_loss: {}'.format( epoch, losses.avg)) logger.flush() logger.close()
if losses.avg < float('inf'): best_loss = losses.avg print('\nSaving model checkpoint...\n') state = { 'weights': model.module.state_dict(), 'optimizer_weight': optimizer.state_dict(), 'train_loss': losses.avg, 'epoch': epoch } torch.save( state, './' + checkpoint_path + '/PoseNet_' + str(epoch) + '_epoch.pth')
def test(epoch): print('\n ############################# Test phase, Epoch: {} #############################'.format(epoch)) model.eval() batch_time = AverageMeter() losses = AverageMeter() end = time.time()
for batch_idx, target_tuple in enumerate(val_loader): if use_cuda: target_tuple = [ target_tensor.cuda( non_blocking=True) for target_tensor in target_tuple]
images, mask_misses, heatmaps = target_tuple
with torch.no_grad(): _, loss = model(target_tuple)
if args.distributed: reduced_loss = reduce_tensor(loss.data) else: reduced_loss = loss.data
losses.update(to_python_float(reduced_loss), images.size(0)) torch.cuda.synchronize() batch_time.update((time.time() - end)) end = time.time()
if args.local_rank == 0: print('==================>Test: [{0}/{1}]\t' 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\t' 'Speed {2:.3f} ({3:.3f})\t' 'Loss {loss.val:.4f} ({loss.avg:.4f})\t'.format( batch_idx, len(val_loader), args.world_size * opt.batch_size / batch_time.val, args.world_size * opt.batch_size / batch_time.avg, batch_time=batch_time, loss=losses))
if args.local_rank == 0: os.makedirs(checkpoint_path, exist_ok=True) logger = open(os.path.join('./' + checkpoint_path, 'log'), 'a+') logger.write('\tval_loss: {}'.format(losses.avg)) logger.flush() logger.close()
def adjust_learning_rate(optimizer, epoch, step, len_epoch, use_warmup=False): factor = epoch // 15
if epoch >= 78: factor = (epoch - 78) // 5
lr = opt.learning_rate * args.world_size * (0.2 ** factor) """Warmup""" if use_warmup: if epoch < 3: lr = lr * float(1 + step + epoch * len_epoch) / \ (3. * len_epoch)
for param_group in optimizer.param_groups: param_group['lr'] = lr
def adjust_learning_rate_cyclic( optimizer, current_epoch, start_epoch, swa_freqent=5, lr_max=4e-5, lr_min=2e-5): epoch = current_epoch - start_epoch
lr = lr_max - (lr_max - lr_min) / (swa_freqent - 1) * \ (epoch - epoch // swa_freqent * swa_freqent) lr = round(lr, 8) for param_group in optimizer.param_groups: param_group['lr'] = lr
class AverageMeter(object): """Computes and stores the average and current value."""
def __init__(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0
def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count
def reduce_tensor(tensor): rt = tensor.clone() dist.all_reduce(rt, op=dist.reduce_op.SUM) rt /= args.world_size return rt
if __name__ == '__main__': for epoch in range(start_epoch, start_epoch + 100): train(epoch) test(epoch)
|