run_task.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  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 bootstrap
  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. if cfg['seed'] is not None:
  52. random.seed(cfg['seed'])
  53. np.random.seed(cfg['seed'])
  54. paddle.seed(cfg['seed'])
  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)