run.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import os
  15. import sys
  16. import numpy as np
  17. import argparse
  18. import paddle
  19. from ppdet.core.workspace import load_config, merge_config
  20. from ppdet.core.workspace import create
  21. from ppdet.metrics import COCOMetric, VOCMetric, KeyPointTopDownCOCOEval
  22. from paddleslim.auto_compression.config_helpers import load_config as load_slim_config
  23. from paddleslim.auto_compression import AutoCompression
  24. from post_process import PPYOLOEPostProcess
  25. from paddleslim.common.dataloader import get_feed_vars
  26. def argsparser():
  27. parser = argparse.ArgumentParser(description=__doc__)
  28. parser.add_argument(
  29. '--config_path',
  30. type=str,
  31. default=None,
  32. help="path of compression strategy config.",
  33. required=True)
  34. parser.add_argument(
  35. '--save_dir',
  36. type=str,
  37. default='output',
  38. help="directory to save compressed model.")
  39. parser.add_argument(
  40. '--devices',
  41. type=str,
  42. default='gpu',
  43. help="which device used to compress.")
  44. return parser
  45. def reader_wrapper(reader, input_list):
  46. def gen():
  47. for data in reader:
  48. in_dict = {}
  49. if isinstance(input_list, list):
  50. for input_name in input_list:
  51. in_dict[input_name] = data[input_name]
  52. elif isinstance(input_list, dict):
  53. for input_name in input_list.keys():
  54. in_dict[input_list[input_name]] = data[input_name]
  55. yield in_dict
  56. return gen
  57. def convert_numpy_data(data, metric):
  58. data_all = {}
  59. data_all = {k: np.array(v) for k, v in data.items()}
  60. if isinstance(metric, VOCMetric):
  61. for k, v in data_all.items():
  62. if not isinstance(v[0], np.ndarray):
  63. tmp_list = []
  64. for t in v:
  65. tmp_list.append(np.array(t))
  66. data_all[k] = np.array(tmp_list)
  67. else:
  68. data_all = {k: np.array(v) for k, v in data.items()}
  69. return data_all
  70. def eval_function(exe, compiled_test_program, test_feed_names, test_fetch_list):
  71. metric = global_config['metric']
  72. for batch_id, data in enumerate(val_loader):
  73. data_all = convert_numpy_data(data, metric)
  74. data_input = {}
  75. for k, v in data.items():
  76. if isinstance(global_config['input_list'], list):
  77. if k in test_feed_names:
  78. data_input[k] = np.array(v)
  79. elif isinstance(global_config['input_list'], dict):
  80. if k in global_config['input_list'].keys():
  81. data_input[global_config['input_list'][k]] = np.array(v)
  82. outs = exe.run(compiled_test_program,
  83. feed=data_input,
  84. fetch_list=test_fetch_list,
  85. return_numpy=False)
  86. res = {}
  87. if 'include_nms' in global_config and not global_config['include_nms']:
  88. if 'arch' in global_config and global_config['arch'] == 'PPYOLOE':
  89. postprocess = PPYOLOEPostProcess(
  90. score_threshold=0.01, nms_threshold=0.6)
  91. else:
  92. assert "Not support arch={} now.".format(global_config['arch'])
  93. res = postprocess(np.array(outs[0]), data_all['scale_factor'])
  94. else:
  95. for out in outs:
  96. v = np.array(out)
  97. if len(v.shape) > 1:
  98. res['bbox'] = v
  99. else:
  100. res['bbox_num'] = v
  101. metric.update(data_all, res)
  102. if batch_id % 100 == 0:
  103. print('Eval iter:', batch_id)
  104. metric.accumulate()
  105. metric.log()
  106. map_res = metric.get_results()
  107. metric.reset()
  108. map_key = 'keypoint' if 'arch' in global_config and global_config[
  109. 'arch'] == 'keypoint' else 'bbox'
  110. return map_res[map_key][0]
  111. def main():
  112. global global_config
  113. all_config = load_slim_config(FLAGS.config_path)
  114. assert "Global" in all_config, "Key 'Global' not found in config file."
  115. global_config = all_config["Global"]
  116. reader_cfg = load_config(global_config['reader_config'])
  117. train_loader = create('EvalReader')(reader_cfg['TrainDataset'],
  118. reader_cfg['worker_num'],
  119. return_list=True)
  120. if global_config.get('input_list') is None:
  121. global_config['input_list'] = get_feed_vars(
  122. global_config['model_dir'], global_config['model_filename'],
  123. global_config['params_filename'])
  124. train_loader = reader_wrapper(train_loader, global_config['input_list'])
  125. if 'Evaluation' in global_config.keys() and global_config[
  126. 'Evaluation'] and paddle.distributed.get_rank() == 0:
  127. eval_func = eval_function
  128. dataset = reader_cfg['EvalDataset']
  129. global val_loader
  130. _eval_batch_sampler = paddle.io.BatchSampler(
  131. dataset, batch_size=reader_cfg['EvalReader']['batch_size'])
  132. val_loader = create('EvalReader')(dataset,
  133. reader_cfg['worker_num'],
  134. batch_sampler=_eval_batch_sampler,
  135. return_list=True)
  136. metric = None
  137. if reader_cfg['metric'] == 'COCO':
  138. clsid2catid = {v: k for k, v in dataset.catid2clsid.items()}
  139. anno_file = dataset.get_anno()
  140. metric = COCOMetric(
  141. anno_file=anno_file, clsid2catid=clsid2catid, IouType='bbox')
  142. elif reader_cfg['metric'] == 'VOC':
  143. metric = VOCMetric(
  144. label_list=dataset.get_label_list(),
  145. class_num=reader_cfg['num_classes'],
  146. map_type=reader_cfg['map_type'])
  147. elif reader_cfg['metric'] == 'KeyPointTopDownCOCOEval':
  148. anno_file = dataset.get_anno()
  149. metric = KeyPointTopDownCOCOEval(anno_file,
  150. len(dataset), 17, 'output_eval')
  151. else:
  152. raise ValueError("metric currently only supports COCO and VOC.")
  153. global_config['metric'] = metric
  154. else:
  155. eval_func = None
  156. ac = AutoCompression(
  157. model_dir=global_config["model_dir"],
  158. model_filename=global_config["model_filename"],
  159. params_filename=global_config["params_filename"],
  160. save_dir=FLAGS.save_dir,
  161. config=all_config,
  162. train_dataloader=train_loader,
  163. eval_callback=eval_func)
  164. ac.compress()
  165. if __name__ == '__main__':
  166. paddle.enable_static()
  167. parser = argsparser()
  168. FLAGS = parser.parse_args()
  169. assert FLAGS.devices in ['cpu', 'gpu', 'xpu', 'npu']
  170. paddle.set_device(FLAGS.devices)
  171. main()