runner.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  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 tempfile
  16. from ...base import BaseRunner
  17. from ...base.utils.subprocess import CompletedProcess
  18. class ClsRunner(BaseRunner):
  19. """Cls Runner"""
  20. def train(
  21. self,
  22. config_path: str,
  23. cli_args: list,
  24. device: str,
  25. ips: str,
  26. save_dir: str,
  27. do_eval=True,
  28. ) -> CompletedProcess:
  29. """train model
  30. Args:
  31. config_path (str): the config file path used to train.
  32. cli_args (list): the additional parameters.
  33. device (str): the training device.
  34. ips (str): the ip addresses of nodes when using distribution.
  35. save_dir (str): the directory path to save training output.
  36. do_eval (bool, optional): whether or not to evaluate model during training. Defaults to True.
  37. Returns:
  38. CompletedProcess: the result of training subprocess execution.
  39. """
  40. args, env = self.distributed(device, ips, log_dir=save_dir)
  41. cmd = [*args, "tools/train.py", "-c", config_path, *cli_args]
  42. cmd.extend(["-o", f"Global.eval_during_train={do_eval}"])
  43. return self.run_cmd(
  44. cmd,
  45. env=env,
  46. switch_wdir=True,
  47. echo=True,
  48. silent=False,
  49. capture_output=True,
  50. log_path=self._get_train_log_path(save_dir),
  51. )
  52. def evaluate(
  53. self, config_path: str, cli_args: list, device: str, ips: str
  54. ) -> CompletedProcess:
  55. """run model evaluating
  56. Args:
  57. config_path (str): the config file path used to evaluate.
  58. cli_args (list): the additional parameters.
  59. device (str): the evaluating device.
  60. ips (str): the ip addresses of nodes when using distribution.
  61. Returns:
  62. CompletedProcess: the result of evaluating subprocess execution.
  63. """
  64. args, env = self.distributed(device, ips)
  65. cmd = [*args, "tools/eval.py", "-c", config_path, *cli_args]
  66. cp = self.run_cmd(
  67. cmd, env=env, switch_wdir=True, echo=True, silent=False, capture_output=True
  68. )
  69. if cp.returncode == 0:
  70. metric_dict = _extract_eval_metrics(cp.stdout)
  71. cp.metrics = metric_dict
  72. return cp
  73. def predict(
  74. self, config_path: str, cli_args: list, device: str
  75. ) -> CompletedProcess:
  76. """run predicting using dynamic mode
  77. Args:
  78. config_path (str): the config file path used to predict.
  79. cli_args (list): the additional parameters.
  80. device (str): unused.
  81. Returns:
  82. CompletedProcess: the result of predicting subprocess execution.
  83. """
  84. # `device` unused
  85. cmd = [self.python, "tools/infer.py", "-c", config_path, *cli_args]
  86. return self.run_cmd(cmd, switch_wdir=True, echo=True, silent=False)
  87. def export(
  88. self, config_path: str, cli_args: list, device: str, save_dir: str = None
  89. ) -> CompletedProcess:
  90. """run exporting
  91. Args:
  92. config_path (str): the path of config file used to export.
  93. cli_args (list): the additional parameters.
  94. device (str): unused.
  95. save_dir (str, optional): the directory path to save exporting output. Defaults to None.
  96. Returns:
  97. CompletedProcess: the result of exporting subprocess execution.
  98. """
  99. # `device` unused
  100. cmd = [
  101. self.python,
  102. "tools/export_model.py",
  103. "-c",
  104. config_path,
  105. *cli_args,
  106. "-o",
  107. "Global.export_for_fd=True",
  108. ]
  109. cp = self.run_cmd(cmd, switch_wdir=True, echo=True, silent=False)
  110. return cp
  111. def infer(self, config_path: str, cli_args: list, device: str) -> CompletedProcess:
  112. """run predicting using inference model
  113. Args:
  114. config_path (str): the path of config file used to predict.
  115. cli_args (list): the additional parameters.
  116. device (str): unused.
  117. Returns:
  118. CompletedProcess: the result of infering subprocess execution.
  119. """
  120. # `device` unused
  121. cmd = [self.python, "python/predict_cls.py", "-c", config_path, *cli_args]
  122. return self.run_cmd(cmd, switch_wdir="deploy", echo=True, silent=False)
  123. def compression(
  124. self,
  125. config_path: str,
  126. train_cli_args: list,
  127. export_cli_args: list,
  128. device: str,
  129. train_save_dir: str,
  130. ) -> CompletedProcess:
  131. """run compression model
  132. Args:
  133. config_path (str): the path of config file used to predict.
  134. train_cli_args (list): the additional training parameters.
  135. export_cli_args (list): the additional exporting parameters.
  136. device (str): the running device.
  137. train_save_dir (str): the directory path to save output.
  138. Returns:
  139. CompletedProcess: the result of compression subprocess execution.
  140. """
  141. # Step 1: Train model
  142. cp_train = self.train(config_path, train_cli_args, device, None, train_save_dir)
  143. # Step 2: Export model
  144. weight_path = os.path.join(train_save_dir, "best_model", "model")
  145. export_cli_args = [
  146. *export_cli_args,
  147. "-o",
  148. f"Global.pretrained_model={weight_path}",
  149. ]
  150. cp_export = self.export(config_path, export_cli_args, device)
  151. return cp_train, cp_export
  152. def _extract_eval_metrics(stdout: str) -> dict:
  153. """extract evaluation metrics from training log
  154. Args:
  155. stdout (str): the training log
  156. Returns:
  157. dict: the training metric
  158. """
  159. import re
  160. _DP = r"[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?"
  161. patterns = [
  162. r"\[Eval\]\[Epoch 0\]\[Avg\].*top1: (_dp)".replace("_dp", _DP),
  163. r"\[Eval\]\[Epoch 0\]\[Avg\].*top1: (_dp), top5: (_dp)".replace("_dp", _DP),
  164. r"\[Eval\]\[Epoch 0\]\[Avg\].*recall1: (_dp), recall5: (_dp), mAP: (_dp)".replace(
  165. "_dp", _DP
  166. ),
  167. r"\[Eval\]\[Epoch 0\]\[Avg\].*MultiLabelMAP\(integral\): (_dp)".replace(
  168. "_dp", _DP
  169. ),
  170. r"\[Eval\]\[Epoch 0\]\[Avg\].*evalres:\ ma: (_dp)".replace("_dp", _DP),
  171. ]
  172. keys = [
  173. ["val.top1"],
  174. ["val.top1", "val.top5"],
  175. ["recall1", "recall5", "mAP"],
  176. ["MultiLabelMAP"],
  177. ["evalres: ma"],
  178. ]
  179. metric_dict = dict()
  180. for pattern, key in zip(patterns, keys):
  181. pattern = re.compile(pattern)
  182. for line in stdout.splitlines():
  183. match = pattern.search(line)
  184. if match:
  185. for k, v in zip(key, map(float, match.groups())):
  186. metric_dict[k] = v
  187. return metric_dict