run_task.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. #!/usr/bin/env python
  2. # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import os
  16. # Import cv2 and sklearn before paddlers to solve the
  17. # "ImportError: dlopen: cannot load any more object with static TLS" issue.
  18. import cv2
  19. import sklearn
  20. import paddle
  21. import paddlers
  22. from paddlers import transforms as T
  23. import custom_model
  24. import custom_trainer
  25. from config_utils import parse_args, build_objects, CfgNode
  26. def format_cfg(cfg, indent=0):
  27. s = ''
  28. if isinstance(cfg, dict):
  29. for i, (k, v) in enumerate(sorted(cfg.items())):
  30. s += ' ' * indent + str(k) + ': '
  31. if isinstance(v, (dict, list, CfgNode)):
  32. s += '\n' + format_cfg(v, indent=indent + 1)
  33. else:
  34. s += str(v)
  35. if i != len(cfg) - 1:
  36. s += '\n'
  37. elif isinstance(cfg, list):
  38. for i, v in enumerate(cfg):
  39. s += ' ' * indent + '- '
  40. if isinstance(v, (dict, list, CfgNode)):
  41. s += '\n' + format_cfg(v, indent=indent + 1)
  42. else:
  43. s += str(v)
  44. if i != len(cfg) - 1:
  45. s += '\n'
  46. elif isinstance(cfg, CfgNode):
  47. s += ' ' * indent + f"type: {cfg.type}" + '\n'
  48. s += ' ' * indent + f"module: {cfg.module}" + '\n'
  49. s += ' ' * indent + 'args: \n' + format_cfg(cfg.args, indent + 1)
  50. return s
  51. if __name__ == '__main__':
  52. CfgNode.set_context(globals())
  53. cfg = parse_args()
  54. print(format_cfg(cfg))
  55. # Automatically download data
  56. if cfg['download_on']:
  57. paddlers.utils.download_and_decompress(
  58. cfg['download_url'], path=cfg['download_path'])
  59. if not isinstance(cfg['datasets']['eval'].args, dict):
  60. raise ValueError("args of eval dataset must be a dict!")
  61. if cfg['datasets']['eval'].args.get('transforms', None) is not None:
  62. raise ValueError(
  63. "Found key 'transforms' in args of eval dataset and the value is not None."
  64. )
  65. eval_transforms = T.Compose(build_objects(cfg['transforms']['eval'], mod=T))
  66. # Inplace modification
  67. cfg['datasets']['eval'].args['transforms'] = eval_transforms
  68. eval_dataset = build_objects(cfg['datasets']['eval'], mod=paddlers.datasets)
  69. if cfg['cmd'] == 'train':
  70. if not isinstance(cfg['datasets']['train'].args, dict):
  71. raise ValueError("args of train dataset must be a dict!")
  72. if cfg['datasets']['train'].args.get('transforms', None) is not None:
  73. raise ValueError(
  74. "Found key 'transforms' in args of train dataset and the value is not None."
  75. )
  76. train_transforms = T.Compose(
  77. build_objects(
  78. cfg['transforms']['train'], mod=T))
  79. # Inplace modification
  80. cfg['datasets']['train'].args['transforms'] = train_transforms
  81. train_dataset = build_objects(
  82. cfg['datasets']['train'], mod=paddlers.datasets)
  83. model = build_objects(
  84. cfg['model'], mod=getattr(paddlers.tasks, cfg['task']))
  85. if cfg['optimizer']:
  86. if len(cfg['optimizer'].args) == 0:
  87. cfg['optimizer'].args = {}
  88. if not isinstance(cfg['optimizer'].args, dict):
  89. raise TypeError("args of optimizer must be a dict!")
  90. if cfg['optimizer'].args.get('parameters', None) is not None:
  91. raise ValueError(
  92. "Found key 'parameters' in args of optimizer and the value is not None."
  93. )
  94. cfg['optimizer'].args['parameters'] = model.net.parameters()
  95. optimizer = build_objects(cfg['optimizer'], mod=paddle.optimizer)
  96. else:
  97. optimizer = None
  98. model.train(
  99. num_epochs=cfg['num_epochs'],
  100. train_dataset=train_dataset,
  101. train_batch_size=cfg['train_batch_size'],
  102. eval_dataset=eval_dataset,
  103. optimizer=optimizer,
  104. save_interval_epochs=cfg['save_interval_epochs'],
  105. log_interval_steps=cfg['log_interval_steps'],
  106. save_dir=cfg['save_dir'],
  107. learning_rate=cfg['learning_rate'],
  108. early_stop=cfg['early_stop'],
  109. early_stop_patience=cfg['early_stop_patience'],
  110. use_vdl=cfg['use_vdl'],
  111. resume_checkpoint=cfg['resume_checkpoint'] or None,
  112. **cfg['train'])
  113. elif cfg['cmd'] == 'eval':
  114. model = paddlers.tasks.load_model(cfg['resume_checkpoint'])
  115. res = model.evaluate(eval_dataset)
  116. print(res)