evaluator.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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. from pathlib import Path
  16. from abc import ABC, abstractmethod
  17. from .build_model import build_model
  18. from ...utils.device import update_device_num, set_env_for_device
  19. from ...utils.misc import AutoRegisterABCMetaClass
  20. from ...utils.config import AttrDict
  21. from ...utils.logging import *
  22. def build_evaluater(config: AttrDict) -> "BaseEvaluator":
  23. """build model evaluater
  24. Args:
  25. config (AttrDict): PaddleX pipeline config, which is loaded from pipeline yaml file.
  26. Returns:
  27. BaseEvaluator: the evaluater, which is subclass of BaseEvaluator.
  28. """
  29. model_name = config.Global.model
  30. try:
  31. import feature_line_modules
  32. except ModuleNotFoundError:
  33. pass
  34. return BaseEvaluator.get(model_name)(config)
  35. class BaseEvaluator(ABC, metaclass=AutoRegisterABCMetaClass):
  36. """Base Model Evaluator"""
  37. __is_base = True
  38. def __init__(self, config):
  39. """Initialize the instance.
  40. Args:
  41. config (AttrDict): PaddleX pipeline config, which is loaded from pipeline yaml file.
  42. """
  43. super().__init__()
  44. self.global_config = config.Global
  45. self.eval_config = config.Evaluate
  46. config_path = self.get_config_path(self.eval_config.weight_path)
  47. if self.eval_config.get("basic_config_path", None):
  48. config_path = self.eval_config.get("basic_config_path", None)
  49. self.pdx_config, self.pdx_model = build_model(
  50. self.global_config.model, config_path=config_path
  51. )
  52. def get_config_path(self, weight_path):
  53. """
  54. get config path
  55. Args:
  56. weight_path (str): The path to the weight
  57. Returns:
  58. config_path (str): The path to the config
  59. """
  60. config_path = Path(weight_path).parent / "config.yaml"
  61. if not config_path.exists():
  62. config_path = config_path.parent.parent / "config.yaml"
  63. if not config_path.exists():
  64. warning(
  65. f"The config file (`{config_path}`) related to weight file (`{weight_path}`) does not exist. Using default instead."
  66. )
  67. config_path = None
  68. return config_path
  69. def check_return(self, metrics: dict) -> bool:
  70. """check evaluation metrics
  71. Args:
  72. metrics (dict): evaluation output metrics
  73. Returns:
  74. bool: whether the format of evaluation metrics is legal
  75. """
  76. if not isinstance(metrics, dict):
  77. return False
  78. for metric in metrics:
  79. val = metrics[metric]
  80. if not isinstance(val, (float, int)):
  81. return False
  82. return True
  83. def evaluate(self) -> dict:
  84. """execute model evaluating
  85. Returns:
  86. dict: the evaluation metrics
  87. """
  88. self.update_config()
  89. # self.dump_config()
  90. evaluate_result = self.pdx_model.evaluate(**self.get_eval_kwargs())
  91. assert (
  92. evaluate_result.returncode == 0
  93. ), f"Encountered an unexpected error({evaluate_result.returncode}) in \
  94. evaling!"
  95. metrics = evaluate_result.metrics
  96. assert self.check_return(
  97. metrics
  98. ), f"The return value({metrics}) of Evaluator.eval() is illegal!"
  99. return {"metrics": metrics}
  100. def dump_config(self, config_file_path=None):
  101. """dump the config
  102. Args:
  103. config_file_path (str, optional): the path to save dumped config.
  104. Defaults to None, means that save in `Global.output` as `config.yaml`.
  105. """
  106. if config_file_path is None:
  107. config_file_path = os.path.join(self.global_config.output, "config.yaml")
  108. self.pdx_config.dump(config_file_path)
  109. def get_device(self, using_device_number: int = None) -> str:
  110. """get device setting from config
  111. Args:
  112. using_device_number (int, optional): specify device number to use.
  113. Defaults to None, means that base on config setting.
  114. Returns:
  115. str: device setting, such as: `gpu:0,1`, `npu:0,1`, `cpu`.
  116. """
  117. set_env_for_device(self.global_config.device)
  118. if using_device_number:
  119. return update_device_num(self.global_config.device, using_device_number)
  120. return self.global_config.device
  121. @abstractmethod
  122. def update_config(self):
  123. """update evalution config"""
  124. raise NotImplementedError
  125. @abstractmethod
  126. def get_eval_kwargs(self):
  127. """get key-value arguments of model evalution function"""
  128. raise NotImplementedError