run_task.py 5.0 KB

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