train.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. # Copyright (c) OpenMMLab. All rights reserved.
  2. import argparse
  3. import os
  4. import os.path as osp
  5. from mmengine.config import Config, DictAction
  6. from mmengine.runner import Runner
  7. def parse_args():
  8. parser = argparse.ArgumentParser(description='Train a pose model')
  9. parser.add_argument('config', help='train config file path')
  10. parser.add_argument('--work-dir', help='the dir to save logs and models')
  11. parser.add_argument(
  12. '--resume',
  13. nargs='?',
  14. type=str,
  15. const='auto',
  16. help='If specify checkpint path, resume from it, while if not '
  17. 'specify, try to auto resume from the latest checkpoint '
  18. 'in the work directory.')
  19. parser.add_argument(
  20. '--amp',
  21. action='store_true',
  22. default=False,
  23. help='enable automatic-mixed-precision training')
  24. parser.add_argument(
  25. '--no-validate',
  26. action='store_true',
  27. help='whether not to evaluate the checkpoint during training')
  28. parser.add_argument(
  29. '--auto-scale-lr',
  30. action='store_true',
  31. help='whether to auto scale the learning rate according to the '
  32. 'actual batch size and the original batch size.')
  33. parser.add_argument(
  34. '--show-dir',
  35. help='directory where the visualization images will be saved.')
  36. parser.add_argument(
  37. '--show',
  38. action='store_true',
  39. help='whether to display the prediction results in a window.')
  40. parser.add_argument(
  41. '--interval',
  42. type=int,
  43. default=1,
  44. help='visualize per interval samples.')
  45. parser.add_argument(
  46. '--wait-time',
  47. type=float,
  48. default=1,
  49. help='display time of every window. (second)')
  50. parser.add_argument(
  51. '--cfg-options',
  52. nargs='+',
  53. action=DictAction,
  54. help='override some settings in the used config, the key-value pair '
  55. 'in xxx=yyy format will be merged into config file. If the value to '
  56. 'be overwritten is a list, it should be like key="[a,b]" or key=a,b '
  57. 'It also allows nested list/tuple values, e.g. key="[(a,b),(c,d)]" '
  58. 'Note that the quotation marks are necessary and that no white space '
  59. 'is allowed.')
  60. parser.add_argument(
  61. '--launcher',
  62. choices=['none', 'pytorch', 'slurm', 'mpi'],
  63. default='none',
  64. help='job launcher')
  65. # When using PyTorch version >= 2.0.0, the `torch.distributed.launch`
  66. # will pass the `--local-rank` parameter to `tools/train.py` instead
  67. # of `--local_rank`.
  68. parser.add_argument('--local_rank', '--local-rank', type=int, default=0)
  69. args = parser.parse_args()
  70. if 'LOCAL_RANK' not in os.environ:
  71. os.environ['LOCAL_RANK'] = str(args.local_rank)
  72. return args
  73. def merge_args(cfg, args):
  74. """Merge CLI arguments to config."""
  75. if args.no_validate:
  76. cfg.val_cfg = None
  77. cfg.val_dataloader = None
  78. cfg.val_evaluator = None
  79. cfg.launcher = args.launcher
  80. # work_dir is determined in this priority: CLI > segment in file > filename
  81. if args.work_dir is not None:
  82. # update configs according to CLI args if args.work_dir is not None
  83. cfg.work_dir = args.work_dir
  84. elif cfg.get('work_dir', None) is None:
  85. # use config filename as default work_dir if cfg.work_dir is None
  86. cfg.work_dir = osp.join('./work_dirs',
  87. osp.splitext(osp.basename(args.config))[0])
  88. # enable automatic-mixed-precision training
  89. if args.amp is True:
  90. optim_wrapper = cfg.optim_wrapper.get('type', 'OptimWrapper')
  91. assert optim_wrapper in ['OptimWrapper', 'AmpOptimWrapper'], \
  92. '`--amp` is not supported custom optimizer wrapper type ' \
  93. f'`{optim_wrapper}.'
  94. cfg.optim_wrapper.type = 'AmpOptimWrapper'
  95. cfg.optim_wrapper.setdefault('loss_scale', 'dynamic')
  96. # resume training
  97. if args.resume == 'auto':
  98. cfg.resume = True
  99. cfg.load_from = None
  100. elif args.resume is not None:
  101. cfg.resume = True
  102. cfg.load_from = args.resume
  103. # enable auto scale learning rate
  104. if args.auto_scale_lr:
  105. cfg.auto_scale_lr.enable = True
  106. # visualization-
  107. if args.show or (args.show_dir is not None):
  108. assert 'visualization' in cfg.default_hooks, \
  109. 'PoseVisualizationHook is not set in the ' \
  110. '`default_hooks` field of config. Please set ' \
  111. '`visualization=dict(type="PoseVisualizationHook")`'
  112. cfg.default_hooks.visualization.enable = True
  113. cfg.default_hooks.visualization.show = args.show
  114. if args.show:
  115. cfg.default_hooks.visualization.wait_time = args.wait_time
  116. cfg.default_hooks.visualization.out_dir = args.show_dir
  117. cfg.default_hooks.visualization.interval = args.interval
  118. if args.cfg_options is not None:
  119. cfg.merge_from_dict(args.cfg_options)
  120. return cfg
  121. def main():
  122. args = parse_args()
  123. # load config
  124. cfg = Config.fromfile(args.config)
  125. # merge CLI arguments to config
  126. cfg = merge_args(cfg, args)
  127. # set preprocess configs to model
  128. if 'preprocess_cfg' in cfg:
  129. cfg.model.setdefault('data_preprocessor',
  130. cfg.get('preprocess_cfg', {}))
  131. # build the runner from config
  132. runner = Runner.from_cfg(cfg)
  133. # start training
  134. runner.train()
  135. if __name__ == '__main__':
  136. main()