train.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import argparse
  15. import os
  16. import sys
  17. from collections import defaultdict
  18. import random
  19. import numpy as np
  20. import paddle
  21. import paddle.nn as nn
  22. import paddleseg
  23. from paddleseg.cvlibs import manager
  24. from paddleseg.utils import get_sys_env, logger
  25. LOCAL_PATH = os.path.dirname(os.path.abspath(__file__))
  26. sys.path.append(os.path.join(LOCAL_PATH, '..'))
  27. manager.BACKBONES._components_dict.clear()
  28. manager.TRANSFORMS._components_dict.clear()
  29. import ppmatting
  30. from ppmatting.core import train
  31. from ppmatting.utils import Config, MatBuilder
  32. def parse_args():
  33. parser = argparse.ArgumentParser(description='Model training')
  34. parser.add_argument(
  35. "--config", dest="cfg", help="The config file.", default=None, type=str)
  36. parser.add_argument(
  37. '--iters',
  38. dest='iters',
  39. help='iters for training',
  40. type=int,
  41. default=None)
  42. parser.add_argument(
  43. '--batch_size',
  44. dest='batch_size',
  45. help='Mini batch size of one gpu or cpu',
  46. type=int,
  47. default=None)
  48. parser.add_argument(
  49. '--learning_rate',
  50. dest='learning_rate',
  51. help='Learning rate',
  52. type=float,
  53. default=None)
  54. parser.add_argument(
  55. '--opts',
  56. help='Update the key-value pairs of all options.',
  57. default=None,
  58. nargs='+')
  59. parser.add_argument(
  60. '--save_interval',
  61. dest='save_interval',
  62. help='How many iters to save a model snapshot once during training.',
  63. type=int,
  64. default=1000)
  65. parser.add_argument(
  66. '--resume_model',
  67. dest='resume_model',
  68. help='The path of resume model',
  69. type=str,
  70. default=None)
  71. parser.add_argument(
  72. '--save_dir',
  73. dest='save_dir',
  74. help='The directory for saving the model snapshot',
  75. type=str,
  76. default='./output')
  77. parser.add_argument(
  78. '--keep_checkpoint_max',
  79. dest='keep_checkpoint_max',
  80. help='Maximum number of checkpoints to save',
  81. type=int,
  82. default=5)
  83. parser.add_argument(
  84. '--num_workers',
  85. dest='num_workers',
  86. help='Num workers for data loader',
  87. type=int,
  88. default=0)
  89. parser.add_argument(
  90. '--do_eval',
  91. dest='do_eval',
  92. help='Eval while training',
  93. action='store_true')
  94. parser.add_argument(
  95. '--metrics',
  96. dest='metrics',
  97. nargs='+',
  98. help='The metrics to evaluate, it may be the combination of ("sad", "mse", "grad", "conn")',
  99. type=str,
  100. default='sad')
  101. parser.add_argument(
  102. '--log_iters',
  103. dest='log_iters',
  104. help='Display logging information at every log_iters',
  105. default=10,
  106. type=int)
  107. parser.add_argument(
  108. '--use_vdl',
  109. dest='use_vdl',
  110. help='Whether to record the data to VisualDL during training',
  111. action='store_true')
  112. parser.add_argument(
  113. '--eval_begin_iters',
  114. dest='eval_begin_iters',
  115. help='The iters begin evaluation.',
  116. default=0,
  117. type=int)
  118. parser.add_argument(
  119. '--seed',
  120. dest='seed',
  121. help='Set the random seed during training.',
  122. default=None,
  123. type=int)
  124. parser.add_argument(
  125. "--precision",
  126. default="fp32",
  127. type=str,
  128. choices=["fp32", "fp16"],
  129. help="Use AMP (Auto mixed precision) if precision='fp16'. If precision='fp32', the training is normal."
  130. )
  131. parser.add_argument(
  132. "--amp_level",
  133. default="O1",
  134. type=str,
  135. choices=["O1", "O2"],
  136. help="Auto mixed precision level. Accepted values are “O1” and “O2”: O1 represent mixed precision, the input \
  137. data type of each operator will be casted by white_list and black_list; O2 represent Pure fp16, all operators \
  138. parameters and input data will be casted to fp16, except operators in black_list, don’t support fp16 kernel \
  139. and batchnorm. Default is O1(amp)")
  140. parser.add_argument(
  141. '--profiler_options',
  142. type=str,
  143. default=None,
  144. help='The option of train profiler. If profiler_options is not None, the train ' \
  145. 'profiler is enabled. Refer to the paddleseg/utils/train_profiler.py for details.'
  146. )
  147. parser.add_argument(
  148. '--repeats',
  149. type=int,
  150. default=1,
  151. help="Repeat the samples in the dataset for `repeats` times in each epoch."
  152. )
  153. parser.add_argument(
  154. '--device',
  155. dest='device',
  156. help='Set the device type, which may be GPU, CPU or XPU.',
  157. default='gpu',
  158. type=str)
  159. return parser.parse_args()
  160. def main(args):
  161. assert args.cfg is not None, \
  162. 'No configuration file specified, please set --config'
  163. cfg = Config(
  164. args.cfg,
  165. learning_rate=args.learning_rate,
  166. iters=args.iters,
  167. batch_size=args.batch_size,
  168. opts=args.opts)
  169. builder = MatBuilder(cfg)
  170. paddleseg.utils.show_env_info()
  171. paddleseg.utils.show_cfg_info(cfg)
  172. paddleseg.utils.set_seed(args.seed)
  173. paddleseg.utils.set_device(args.device)
  174. paddleseg.utils.set_cv2_num_threads(args.num_workers)
  175. model = paddleseg.utils.convert_sync_batchnorm(builder.model, args.device)
  176. train_dataset = builder.train_dataset
  177. if args.repeats > 1:
  178. train_dataset.fg_bg_list *= args.repeats
  179. val_dataset = builder.val_dataset if args.do_eval else None
  180. optimizer = builder.optimizer
  181. if args.seed is not None:
  182. paddle.seed(args.seed)
  183. np.random.seed(args.seed)
  184. random.seed(args.seed)
  185. train(
  186. model,
  187. train_dataset=train_dataset,
  188. val_dataset=val_dataset,
  189. optimizer=optimizer,
  190. iters=cfg.iters,
  191. batch_size=cfg.batch_size,
  192. num_workers=args.num_workers,
  193. use_vdl=args.use_vdl,
  194. save_interval=args.save_interval,
  195. log_iters=args.log_iters,
  196. resume_model=args.resume_model,
  197. save_dir=args.save_dir,
  198. eval_begin_iters=args.eval_begin_iters,
  199. metrics=args.metrics,
  200. precision=args.precision,
  201. amp_level=args.amp_level,
  202. profiler_options=args.profiler_options)
  203. if __name__ == '__main__':
  204. args = parse_args()
  205. main(args)