glenn-jocher commited on
Commit
4447f4b
1 Parent(s): 5e0b90d

--resume to same runs/exp directory (#765)

Browse files

* initial commit

* add weight backup dir on resume

Files changed (1) hide show
  1. train.py +15 -11
train.py CHANGED
@@ -1,9 +1,10 @@
1
  import argparse
 
2
  import math
3
  import os
4
  import random
 
5
  import time
6
- import logging
7
  from pathlib import Path
8
 
9
  import numpy as np
@@ -34,10 +35,10 @@ logger = logging.getLogger(__name__)
34
  def train(hyp, opt, device, tb_writer=None):
35
  logger.info(f'Hyperparameters {hyp}')
36
  log_dir = Path(tb_writer.log_dir) if tb_writer else Path(opt.logdir) / 'evolve' # logging directory
37
- wdir = str(log_dir / 'weights') + os.sep # weights directory
38
  os.makedirs(wdir, exist_ok=True)
39
- last = wdir + 'last.pt'
40
- best = wdir + 'best.pt'
41
  results_file = str(log_dir / 'results.txt')
42
  epochs, batch_size, total_batch_size, weights, rank = \
43
  opt.epochs, opt.batch_size, opt.total_batch_size, opt.weights, opt.global_rank
@@ -131,6 +132,7 @@ def train(hyp, opt, device, tb_writer=None):
131
  start_epoch = ckpt['epoch'] + 1
132
  if opt.resume:
133
  assert start_epoch > 0, '%s training to %g epochs is finished, nothing to resume.' % (weights, epochs)
 
134
  if epochs < start_epoch:
135
  logger.info('%s has been trained for %g epochs. Fine-tuning for %g additional epochs.' %
136
  (weights, ckpt['epoch'], epochs))
@@ -365,13 +367,13 @@ def train(hyp, opt, device, tb_writer=None):
365
  if rank in [-1, 0]:
366
  # Strip optimizers
367
  n = ('_' if len(opt.name) and not opt.name.isnumeric() else '') + opt.name
368
- fresults, flast, fbest = 'results%s.txt' % n, wdir + 'last%s.pt' % n, wdir + 'best%s.pt' % n
369
- for f1, f2 in zip([wdir + 'last.pt', wdir + 'best.pt', 'results.txt'], [flast, fbest, fresults]):
370
  if os.path.exists(f1):
371
  os.rename(f1, f2) # rename
372
- ispt = f2.endswith('.pt') # is *.pt
373
- strip_optimizer(f2) if ispt else None # strip optimizer
374
- os.system('gsutil cp %s gs://%s/weights' % (f2, opt.bucket)) if opt.bucket and ispt else None # upload
375
  # Finish
376
  if not opt.evolve:
377
  plot_results(save_dir=log_dir) # save as results.png
@@ -421,8 +423,9 @@ if __name__ == '__main__':
421
  # Resume
422
  if opt.resume: # resume an interrupted run
423
  ckpt = opt.resume if isinstance(opt.resume, str) else get_latest_run() # specified or most recent path
 
424
  assert os.path.isfile(ckpt), 'ERROR: --resume checkpoint does not exist'
425
- with open(Path(ckpt).parent.parent / 'opt.yaml') as f:
426
  opt = argparse.Namespace(**yaml.load(f, Loader=yaml.FullLoader)) # replace
427
  opt.cfg, opt.weights, opt.resume = '', ckpt, True
428
  logger.info('Resuming training from %s' % ckpt)
@@ -432,6 +435,7 @@ if __name__ == '__main__':
432
  opt.data, opt.cfg, opt.hyp = check_file(opt.data), check_file(opt.cfg), check_file(opt.hyp) # check files
433
  assert len(opt.cfg) or len(opt.weights), 'either --cfg or --weights must be specified'
434
  opt.img_size.extend([opt.img_size[-1]] * (2 - len(opt.img_size))) # extend to 2 sizes (train, test)
 
435
 
436
  device = select_device(opt.device, batch_size=opt.batch_size)
437
 
@@ -453,7 +457,7 @@ if __name__ == '__main__':
453
  tb_writer = None
454
  if opt.global_rank in [-1, 0]:
455
  logger.info('Start Tensorboard with "tensorboard --logdir %s", view at http://localhost:6006/' % opt.logdir)
456
- tb_writer = SummaryWriter(log_dir=increment_dir(Path(opt.logdir) / 'exp', opt.name)) # runs/exp
457
 
458
  train(hyp, opt, device, tb_writer)
459
 
 
1
  import argparse
2
+ import logging
3
  import math
4
  import os
5
  import random
6
+ import shutil
7
  import time
 
8
  from pathlib import Path
9
 
10
  import numpy as np
 
35
  def train(hyp, opt, device, tb_writer=None):
36
  logger.info(f'Hyperparameters {hyp}')
37
  log_dir = Path(tb_writer.log_dir) if tb_writer else Path(opt.logdir) / 'evolve' # logging directory
38
+ wdir = log_dir / 'weights' # weights directory
39
  os.makedirs(wdir, exist_ok=True)
40
+ last = wdir / 'last.pt'
41
+ best = wdir / 'best.pt'
42
  results_file = str(log_dir / 'results.txt')
43
  epochs, batch_size, total_batch_size, weights, rank = \
44
  opt.epochs, opt.batch_size, opt.total_batch_size, opt.weights, opt.global_rank
 
132
  start_epoch = ckpt['epoch'] + 1
133
  if opt.resume:
134
  assert start_epoch > 0, '%s training to %g epochs is finished, nothing to resume.' % (weights, epochs)
135
+ shutil.copytree(wdir, wdir.parent / f'weights_backup_epoch{start_epoch - 1}') # save previous weights
136
  if epochs < start_epoch:
137
  logger.info('%s has been trained for %g epochs. Fine-tuning for %g additional epochs.' %
138
  (weights, ckpt['epoch'], epochs))
 
367
  if rank in [-1, 0]:
368
  # Strip optimizers
369
  n = ('_' if len(opt.name) and not opt.name.isnumeric() else '') + opt.name
370
+ fresults, flast, fbest = 'results%s.txt' % n, wdir / f'last{n}.pt', wdir / f'best{n}.pt'
371
+ for f1, f2 in zip([wdir / 'last.pt', wdir / 'best.pt', 'results.txt'], [flast, fbest, fresults]):
372
  if os.path.exists(f1):
373
  os.rename(f1, f2) # rename
374
+ if str(f2).endswith('.pt'): # is *.pt
375
+ strip_optimizer(f2) # strip optimizer
376
+ os.system('gsutil cp %s gs://%s/weights' % (f2, opt.bucket)) if opt.bucket else None # upload
377
  # Finish
378
  if not opt.evolve:
379
  plot_results(save_dir=log_dir) # save as results.png
 
423
  # Resume
424
  if opt.resume: # resume an interrupted run
425
  ckpt = opt.resume if isinstance(opt.resume, str) else get_latest_run() # specified or most recent path
426
+ log_dir = Path(ckpt).parent.parent # runs/exp0
427
  assert os.path.isfile(ckpt), 'ERROR: --resume checkpoint does not exist'
428
+ with open(log_dir / 'opt.yaml') as f:
429
  opt = argparse.Namespace(**yaml.load(f, Loader=yaml.FullLoader)) # replace
430
  opt.cfg, opt.weights, opt.resume = '', ckpt, True
431
  logger.info('Resuming training from %s' % ckpt)
 
435
  opt.data, opt.cfg, opt.hyp = check_file(opt.data), check_file(opt.cfg), check_file(opt.hyp) # check files
436
  assert len(opt.cfg) or len(opt.weights), 'either --cfg or --weights must be specified'
437
  opt.img_size.extend([opt.img_size[-1]] * (2 - len(opt.img_size))) # extend to 2 sizes (train, test)
438
+ log_dir = increment_dir(Path(opt.logdir) / 'exp', opt.name) # runs/exp1
439
 
440
  device = select_device(opt.device, batch_size=opt.batch_size)
441
 
 
457
  tb_writer = None
458
  if opt.global_rank in [-1, 0]:
459
  logger.info('Start Tensorboard with "tensorboard --logdir %s", view at http://localhost:6006/' % opt.logdir)
460
+ tb_writer = SummaryWriter(log_dir=log_dir) # runs/exp0
461
 
462
  train(hyp, opt, device, tb_writer)
463