run_task.py 4.8 KB

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