runner.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  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. from ....utils.errors import raise_unsupported_api_error
  15. from ...base import BaseRunner
  16. from ...base.utils.arg import gather_opts_args
  17. from ...base.utils.subprocess import CompletedProcess
  18. class TSCLSRunner(BaseRunner):
  19. """TS Classify 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. cli_args = self._gather_opts_args(cli_args)
  42. cmd = [*args, "tools/train.py", "--config", config_path, *cli_args]
  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. cli_args = self._gather_opts_args(cli_args)
  66. cmd = [*args, "tools/val.py", "--config", config_path, *cli_args]
  67. cp = self.run_cmd(
  68. cmd, env=env, switch_wdir=True, echo=True, silent=False, capture_output=True
  69. )
  70. if cp.returncode == 0:
  71. metric_dict = _extract_eval_metrics(cp.stderr)
  72. cp.metrics = metric_dict
  73. return cp
  74. def predict(
  75. self, config_path: str, cli_args: list, device: str
  76. ) -> CompletedProcess:
  77. """run predicting using dynamic mode
  78. Args:
  79. config_path (str): the config file path used to predict.
  80. cli_args (list): the additional parameters.
  81. device (str): unused.
  82. Returns:
  83. CompletedProcess: the result of predicting subprocess execution.
  84. """
  85. # `device` unused
  86. cli_args = self._gather_opts_args(cli_args)
  87. cmd = [self.python, "tools/predict.py", "--config", config_path, *cli_args]
  88. return self.run_cmd(cmd, switch_wdir=True, echo=True, silent=False)
  89. def export(self, config_path, cli_args, device):
  90. """export"""
  91. cmd = [
  92. self.python,
  93. "tools/export.py",
  94. "--config",
  95. config_path,
  96. *cli_args,
  97. ]
  98. cp = self.run_cmd(cmd, switch_wdir=True, echo=True, silent=False)
  99. return cp
  100. def infer(self, config_path, cli_args, device):
  101. """infer"""
  102. raise_unsupported_api_error("infer", self.__class__)
  103. def compression(
  104. self, config_path, train_cli_args, export_cli_args, device, train_save_dir
  105. ):
  106. """compression"""
  107. raise_unsupported_api_error("compression", self.__class__)
  108. def _gather_opts_args(self, args):
  109. # Since `--opts` in PaddleSeg does not use `action='append'`
  110. # We collect and arrange all opts args here
  111. # e.g.: python tools/train.py --config xxx --opts a=1 c=3 --opts b=2
  112. # => python tools/train.py --config xxx c=3 --opts a=1 b=2
  113. return gather_opts_args(args, "--opts")
  114. def _extract_eval_metrics(stdout):
  115. """extract evaluation metrics from training log
  116. Args:
  117. stdout (str): the training log
  118. Returns:
  119. dict: the training metric
  120. """
  121. import re
  122. pattern = r"\'acc\':\s+(\d+\.\d+),+[\s|\n]+\'f1\':\s+(\d+\.\d+)"
  123. keys = ["acc", "f1"]
  124. metric_dict = dict()
  125. pattern = re.compile(pattern)
  126. lines = stdout.splitlines()
  127. for line in lines:
  128. match = pattern.search(line)
  129. if match:
  130. for k, v in zip(keys, map(float, match.groups())):
  131. metric_dict[k] = v
  132. return metric_dict