evaluator.py 5.4 KB

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