runner.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. # Copyright (c) 2024 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. from ...base import BaseRunner
  16. from ...base.utils.arg import CLIArgument, gather_opts_args
  17. from ...base.utils.subprocess import CompletedProcess
  18. class InstanceSegRunner(BaseRunner):
  19. """InstanceSegRunner"""
  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. cli_args = self._gather_opts_args(cli_args)
  42. cmd = [*args, "tools/train.py"]
  43. if do_eval:
  44. cmd.append("--eval")
  45. cmd.extend(["--config", config_path, *cli_args])
  46. return self.run_cmd(
  47. cmd,
  48. env=env,
  49. switch_wdir=True,
  50. echo=True,
  51. silent=False,
  52. capture_output=True,
  53. log_path=self._get_train_log_path(save_dir),
  54. )
  55. def evaluate(
  56. self, config_path: str, cli_args: list, device: str, ips: str
  57. ) -> CompletedProcess:
  58. """run model evaluating
  59. Args:
  60. config_path (str): the config file path used to evaluate.
  61. cli_args (list): the additional parameters.
  62. device (str): the evaluating device.
  63. ips (str): the ip addresses of nodes when using distribution.
  64. Returns:
  65. CompletedProcess: the result of evaluating subprocess execution.
  66. """
  67. args, env = self.distributed(device, ips)
  68. cli_args = self._gather_opts_args(cli_args)
  69. cmd = [*args, "tools/eval.py", "--config", config_path, *cli_args]
  70. cp = self.run_cmd(
  71. cmd, env=env, switch_wdir=True, echo=True, silent=False, capture_output=True
  72. )
  73. if cp.returncode == 0:
  74. metric_dict = _extract_eval_metrics(cp.stdout)
  75. cp.metrics = metric_dict
  76. return cp
  77. def predict(
  78. self, config_path: str, cli_args: list, device: str
  79. ) -> CompletedProcess:
  80. """run predicting using dynamic mode
  81. Args:
  82. config_path (str): the config file path used to predict.
  83. cli_args (list): the additional parameters.
  84. device (str): unused.
  85. Returns:
  86. CompletedProcess: the result of predicting subprocess execution.
  87. """
  88. # `device` unused
  89. cli_args = self._gather_opts_args(cli_args)
  90. cmd = [self.python, "tools/infer.py", "-c", config_path, *cli_args]
  91. return self.run_cmd(cmd, switch_wdir=True, echo=True, silent=False)
  92. def export(self, config_path: str, cli_args: list, device: str) -> CompletedProcess:
  93. """run exporting
  94. Args:
  95. config_path (str): the path of config file used to export.
  96. cli_args (list): the additional parameters.
  97. device (str): unused.
  98. save_dir (str, optional): the directory path to save exporting output. Defaults to None.
  99. Returns:
  100. CompletedProcess: the result of exporting subprocess execution.
  101. """
  102. # `device` unused
  103. cli_args = self._gather_opts_args(cli_args)
  104. cmd = [
  105. self.python,
  106. "tools/export_model.py",
  107. "--for_fd",
  108. "-c",
  109. config_path,
  110. *cli_args,
  111. ]
  112. cp = self.run_cmd(cmd, switch_wdir=True, echo=True, silent=False)
  113. return cp
  114. def infer(self, cli_args: list, device: str) -> CompletedProcess:
  115. """run predicting using inference model
  116. Args:
  117. cli_args (list): the additional parameters.
  118. device (str): unused.
  119. Returns:
  120. CompletedProcess: the result of inferring subprocess execution.
  121. """
  122. # `device` unused
  123. cmd = [self.python, "deploy/python/infer.py", "--use_fd_format", *cli_args]
  124. return self.run_cmd(cmd, switch_wdir=True, echo=True, silent=False)
  125. def compression(
  126. self,
  127. config_path: str,
  128. train_cli_args: list,
  129. export_cli_args: list,
  130. device: str,
  131. train_save_dir: str,
  132. ) -> CompletedProcess:
  133. """run compression model
  134. Args:
  135. config_path (str): the path of config file used to predict.
  136. train_cli_args (list): the additional training parameters.
  137. export_cli_args (list): the additional exporting parameters.
  138. device (str): the running device.
  139. train_save_dir (str): the directory path to save output.
  140. Returns:
  141. CompletedProcess: the result of compression subprocess execution.
  142. """
  143. args, env = self.distributed(device, log_dir=train_save_dir)
  144. train_cli_args = self._gather_opts_args(train_cli_args)
  145. cmd = [*args, "tools/train.py", "-c", config_path, *train_cli_args]
  146. cp_train = self.run_cmd(
  147. cmd,
  148. env=env,
  149. switch_wdir=True,
  150. echo=True,
  151. silent=False,
  152. capture_output=True,
  153. log_path=self._get_train_log_path(train_save_dir),
  154. )
  155. cps_weight_path = os.path.join(train_save_dir, "model_final")
  156. export_cli_args.append(CLIArgument("-o", f"weights={cps_weight_path}"))
  157. export_cli_args = self._gather_opts_args(export_cli_args)
  158. cmd = [
  159. self.python,
  160. "tools/export_model.py",
  161. "--for_fd",
  162. "-c",
  163. config_path,
  164. *export_cli_args,
  165. ]
  166. cp_export = self.run_cmd(cmd, switch_wdir=True, echo=True, silent=False)
  167. return cp_train, cp_export
  168. def _gather_opts_args(self, args):
  169. """_gather_opts_args"""
  170. return gather_opts_args(args, "-o")
  171. def _extract_eval_metrics(stdout):
  172. """extract evaluation metrics from training log
  173. Args:
  174. stdout (str): the training log
  175. Returns:
  176. dict: the training metric
  177. """
  178. import re
  179. pattern = r".*\(AP\)\s*@\[\s*IoU=0\.50:0\.95\s*\|\s*area=\s*all\s\|\smaxDets=\s*\d+\s\]\s*=\s*[0-1]?\.[0-9]{3}$"
  180. key = "AP"
  181. metric_dict = dict()
  182. pattern = re.compile(pattern)
  183. # TODO: Use lazy version to make it more efficient
  184. lines = stdout.splitlines()
  185. metric_dict[key] = 0
  186. for line in lines:
  187. match = pattern.search(line)
  188. if match:
  189. metric_dict[key] = float(match.group(0)[-5:])
  190. return metric_dict