run_task.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  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 random
  17. import numpy as np
  18. # Import cv2 and sklearn before paddlers to solve the
  19. # "ImportError: dlopen: cannot load any more object with static TLS" issue.
  20. import cv2
  21. import sklearn
  22. import paddle
  23. import paddlers
  24. from paddlers import transforms as T
  25. import custom_model
  26. import custom_trainer
  27. from config_utils import parse_args, build_objects, CfgNode
  28. def format_cfg(cfg, indent=0):
  29. s = ''
  30. if isinstance(cfg, dict):
  31. for i, (k, v) in enumerate(sorted(cfg.items())):
  32. s += ' ' * indent + str(k) + ': '
  33. if isinstance(v, (dict, list, CfgNode)):
  34. s += '\n' + format_cfg(v, indent=indent + 1)
  35. else:
  36. s += str(v)
  37. if i != len(cfg) - 1:
  38. s += '\n'
  39. elif isinstance(cfg, list):
  40. for i, v in enumerate(cfg):
  41. s += ' ' * indent + '- '
  42. if isinstance(v, (dict, list, CfgNode)):
  43. s += '\n' + format_cfg(v, indent=indent + 1)
  44. else:
  45. s += str(v)
  46. if i != len(cfg) - 1:
  47. s += '\n'
  48. elif isinstance(cfg, CfgNode):
  49. s += ' ' * indent + f"type: {cfg.type}" + '\n'
  50. s += ' ' * indent + f"module: {cfg.module}" + '\n'
  51. s += ' ' * indent + 'args: \n' + format_cfg(cfg.args, indent + 1)
  52. return s
  53. if __name__ == '__main__':
  54. CfgNode.set_context(globals())
  55. cfg = parse_args()
  56. print(format_cfg(cfg))
  57. if cfg['seed'] is not None:
  58. random.seed(cfg['seed'])
  59. np.random.seed(cfg['seed'])
  60. paddle.seed(cfg['seed'])
  61. # Automatically download data
  62. if cfg['download_on']:
  63. paddlers.utils.download_and_decompress(
  64. cfg['download_url'], path=cfg['download_path'])
  65. if not isinstance(cfg['datasets']['eval'].args, dict):
  66. raise ValueError("args of eval dataset must be a dict!")
  67. if cfg['datasets']['eval'].args.get('transforms', None) is not None:
  68. raise ValueError(
  69. "Found key 'transforms' in args of eval dataset and the value is not None."
  70. )
  71. eval_transforms = T.Compose(build_objects(cfg['transforms']['eval'], mod=T))
  72. # Inplace modification
  73. cfg['datasets']['eval'].args['transforms'] = eval_transforms
  74. eval_dataset = build_objects(cfg['datasets']['eval'], mod=paddlers.datasets)
  75. if cfg['cmd'] == 'train':
  76. if not isinstance(cfg['datasets']['train'].args, dict):
  77. raise ValueError("args of train dataset must be a dict!")
  78. if cfg['datasets']['train'].args.get('transforms', None) is not None:
  79. raise ValueError(
  80. "Found key 'transforms' in args of train dataset and the value is not None."
  81. )
  82. train_transforms = T.Compose(
  83. build_objects(
  84. cfg['transforms']['train'], mod=T))
  85. # Inplace modification
  86. cfg['datasets']['train'].args['transforms'] = train_transforms
  87. train_dataset = build_objects(
  88. cfg['datasets']['train'], mod=paddlers.datasets)
  89. model = build_objects(
  90. cfg['model'], mod=getattr(paddlers.tasks, cfg['task']))
  91. if cfg['optimizer']:
  92. if len(cfg['optimizer'].args) == 0:
  93. cfg['optimizer'].args = {}
  94. if not isinstance(cfg['optimizer'].args, dict):
  95. raise TypeError("args of optimizer must be a dict!")
  96. if cfg['optimizer'].args.get('parameters', None) is not None:
  97. raise ValueError(
  98. "Found key 'parameters' in args of optimizer and the value is not None."
  99. )
  100. cfg['optimizer'].args['parameters'] = model.net.parameters()
  101. optimizer = build_objects(cfg['optimizer'], mod=paddle.optimizer)
  102. else:
  103. optimizer = None
  104. model.train(
  105. num_epochs=cfg['num_epochs'],
  106. train_dataset=train_dataset,
  107. train_batch_size=cfg['train_batch_size'],
  108. eval_dataset=eval_dataset,
  109. optimizer=optimizer,
  110. save_interval_epochs=cfg['save_interval_epochs'],
  111. log_interval_steps=cfg['log_interval_steps'],
  112. save_dir=cfg['save_dir'],
  113. learning_rate=cfg['learning_rate'],
  114. early_stop=cfg['early_stop'],
  115. early_stop_patience=cfg['early_stop_patience'],
  116. use_vdl=cfg['use_vdl'],
  117. resume_checkpoint=cfg['resume_checkpoint'] or None,
  118. **cfg['train'])
  119. elif cfg['cmd'] == 'eval':
  120. model = paddlers.tasks.load_model(cfg['resume_checkpoint'])
  121. res = model.evaluate(eval_dataset)
  122. print(res)