model.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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 ...base import BaseModel
  16. from ...base.utils.arg import CLIArgument
  17. from ...base.utils.subprocess import CompletedProcess
  18. from ....utils.misc import abspath
  19. from ....utils import logging
  20. class ClsModel(BaseModel):
  21. """ Image Classification Model """
  22. def train(self,
  23. batch_size: int=None,
  24. learning_rate: float=None,
  25. epochs_iters: int=None,
  26. ips: str=None,
  27. device: str='gpu',
  28. resume_path: str=None,
  29. dy2st: bool=False,
  30. amp: str='OFF',
  31. num_workers: int=None,
  32. use_vdl: bool=True,
  33. save_dir: str=None,
  34. **kwargs) -> CompletedProcess:
  35. """train self
  36. Args:
  37. batch_size (int, optional): the train batch size value. Defaults to None.
  38. learning_rate (float, optional): the train learning rate value. Defaults to None.
  39. epochs_iters (int, optional): the train epochs value. Defaults to None.
  40. ips (str, optional): the ip addresses of nodes when using distribution. Defaults to None.
  41. device (str, optional): the running device. Defaults to 'gpu'.
  42. resume_path (str, optional): the checkpoint file path to resume training. Train from scratch if it is set
  43. to None. Defaults to None.
  44. dy2st (bool, optional): Enable dynamic to static. Defaults to False.
  45. amp (str, optional): the amp settings. Defaults to 'OFF'.
  46. num_workers (int, optional): the workers number. Defaults to None.
  47. use_vdl (bool, optional): enable VisualDL. Defaults to True.
  48. save_dir (str, optional): the directory path to save train output. Defaults to None.
  49. Returns:
  50. CompletedProcess: the result of training subprocess execution.
  51. """
  52. if resume_path is not None:
  53. resume_path = abspath(resume_path)
  54. with self._create_new_config_file() as config_path:
  55. # Update YAML config file
  56. config = self.config.copy()
  57. config._update_amp(amp)
  58. config.update_device(device)
  59. config._update_to_static(dy2st)
  60. config._update_use_vdl(use_vdl)
  61. config.update_log_ranks(device)
  62. config.enable_print_mem_info()
  63. if batch_size is not None:
  64. config.update_batch_size(batch_size)
  65. if learning_rate is not None:
  66. config.update_learning_rate(learning_rate)
  67. if epochs_iters is not None:
  68. config._update_epochs(epochs_iters)
  69. config._update_checkpoints(resume_path)
  70. if save_dir is not None:
  71. save_dir = abspath(save_dir)
  72. else:
  73. # `save_dir` is None
  74. save_dir = abspath(config.get_train_save_dir())
  75. config._update_output_dir(save_dir)
  76. if num_workers is not None:
  77. config.update_num_workers(num_workers)
  78. config.dump(config_path)
  79. cli_args = []
  80. do_eval = kwargs.pop('do_eval', True)
  81. profile = kwargs.pop('profile', None)
  82. if profile is not None:
  83. cli_args.append(CLIArgument('--profiler_options', profile))
  84. self._assert_empty_kwargs(kwargs)
  85. return self.runner.train(
  86. config_path, cli_args, device, ips, save_dir, do_eval=do_eval)
  87. def evaluate(self,
  88. weight_path: str,
  89. batch_size: int=None,
  90. ips: str=None,
  91. device: str='gpu',
  92. amp: str='OFF',
  93. num_workers: int=None,
  94. **kwargs) -> CompletedProcess:
  95. """evaluate self using specified weight
  96. Args:
  97. weight_path (str): the path of model weight file to be evaluated.
  98. batch_size (int, optional): the batch size value in evaluating. Defaults to None.
  99. ips (str, optional): the ip addresses of nodes when using distribution. Defaults to None.
  100. device (str, optional): the running device. Defaults to 'gpu'.
  101. amp (str, optional): the AMP setting. Defaults to 'OFF'.
  102. num_workers (int, optional): the workers number in evaluating. Defaults to None.
  103. Returns:
  104. CompletedProcess: the result of evaluating subprocess execution.
  105. """
  106. weight_path = abspath(weight_path)
  107. with self._create_new_config_file() as config_path:
  108. # Update YAML config file
  109. config = self.config.copy()
  110. config._update_amp(amp)
  111. config.update_device(device)
  112. config.update_pretrained_weights(weight_path)
  113. if batch_size is not None:
  114. config.update_batch_size(batch_size)
  115. if num_workers is not None:
  116. config.update_num_workers(num_workers)
  117. config.dump(config_path)
  118. self._assert_empty_kwargs(kwargs)
  119. cp = self.runner.evaluate(config_path, [], device, ips)
  120. return cp
  121. def predict(self,
  122. weight_path: str,
  123. input_path: str,
  124. input_list_path: str=None,
  125. device: str='gpu',
  126. save_dir: str=None,
  127. **kwargs) -> CompletedProcess:
  128. """predict using specified weight
  129. Args:
  130. weight_path (str): the path of model weight file used to predict.
  131. input_path (str): the path of image file to be predicted.
  132. input_list_path (str, optional): the paths of images to be predicted if is not None. Defaults to None.
  133. device (str, optional): the running device. Defaults to 'gpu'.
  134. save_dir (str, optional): the directory path to save predict output. Defaults to None.
  135. Returns:
  136. CompletedProcess: the result of predicting subprocess execution.
  137. """
  138. weight_path = abspath(weight_path)
  139. input_path = abspath(input_path)
  140. if input_list_path:
  141. input_list_path = abspath(input_list_path)
  142. with self._create_new_config_file() as config_path:
  143. # Update YAML config file
  144. config = self.config.copy()
  145. config.update_pretrained_weights(weight_path)
  146. config._update_predict_img(input_path, input_list_path)
  147. config.update_device(device)
  148. config._update_save_predict_result(save_dir)
  149. config.dump(config_path)
  150. self._assert_empty_kwargs(kwargs)
  151. return self.runner.predict(config_path, [], device)
  152. def export(self, weight_path: str, save_dir: str,
  153. **kwargs) -> CompletedProcess:
  154. """export the dynamic model to static model
  155. Args:
  156. weight_path (str): the model weight file path that used to export.
  157. save_dir (str): the directory path to save export output.
  158. Returns:
  159. CompletedProcess: the result of exporting subprocess execution.
  160. """
  161. weight_path = abspath(weight_path)
  162. save_dir = abspath(save_dir)
  163. with self._create_new_config_file() as config_path:
  164. # Update YAML config file
  165. config = self.config.copy()
  166. config.update_pretrained_weights(weight_path)
  167. config._update_save_inference_dir(save_dir)
  168. config.dump(config_path)
  169. self._assert_empty_kwargs(kwargs)
  170. return self.runner.export(config_path, [], None, save_dir)
  171. def infer(self,
  172. model_dir: str,
  173. input_path: str,
  174. device: str='gpu',
  175. save_dir: str=None,
  176. dict_path: str=None,
  177. **kwargs) -> CompletedProcess:
  178. """predict image using infernece model
  179. Args:
  180. model_dir (str): the directory path of inference model files that would use to predict.
  181. input_path (str): the path of image that would be predict.
  182. device (str, optional): the running device. Defaults to 'gpu'.
  183. save_dir (str, optional): the directory path to save output. Defaults to None.
  184. dict_path (str, optional): the label dict file path. Defaults to None.
  185. Returns:
  186. CompletedProcess: the result of infering subprocess execution.
  187. """
  188. model_dir = abspath(model_dir)
  189. input_path = abspath(input_path)
  190. if save_dir is not None:
  191. logging.warning("`save_dir` will not be used.")
  192. config_path = os.path.join(model_dir, 'inference.yml')
  193. config = self.config.copy()
  194. config.load(config_path)
  195. config._update_inference_model_dir(model_dir)
  196. config._update_infer_img(input_path)
  197. config._update_infer_device(device)
  198. if dict_path is not None:
  199. dict_path = abspath(dict_path)
  200. config.update_label_dict_path(dict_path)
  201. if 'enable_mkldnn' in kwargs:
  202. config._update_enable_mkldnn(kwargs.pop('enable_mkldnn'))
  203. with self._create_new_config_file() as config_path:
  204. config.dump(config_path)
  205. self._assert_empty_kwargs(kwargs)
  206. return self.runner.infer(config_path, [], device)
  207. def compression(self,
  208. weight_path: str,
  209. batch_size: int=None,
  210. learning_rate: float=None,
  211. epochs_iters: int=None,
  212. device: str='gpu',
  213. use_vdl: bool=True,
  214. save_dir: str=None,
  215. **kwargs) -> CompletedProcess:
  216. """compression model
  217. Args:
  218. weight_path (str): the path to weight file of model.
  219. batch_size (int, optional): the batch size value of compression training. Defaults to None.
  220. learning_rate (float, optional): the learning rate value of compression training. Defaults to None.
  221. epochs_iters (int, optional): the epochs or iters of compression training. Defaults to None.
  222. device (str, optional): the device to run compression training. Defaults to 'gpu'.
  223. use_vdl (bool, optional): whether or not to use VisualDL. Defaults to True.
  224. save_dir (str, optional): the directory to save output. Defaults to None.
  225. Returns:
  226. CompletedProcess: the result of compression subprocess execution.
  227. """
  228. weight_path = abspath(weight_path)
  229. with self._create_new_config_file() as config_path:
  230. # Update YAML config file
  231. config = self.config.copy()
  232. config._update_amp(None)
  233. config.update_device(device)
  234. config._update_use_vdl(use_vdl)
  235. config._update_slim_config(self.model_info[
  236. 'auto_compression_config_path'])
  237. config.update_pretrained_weights(weight_path)
  238. if batch_size is not None:
  239. config.update_batch_size(batch_size)
  240. if learning_rate is not None:
  241. config.update_learning_rate(learning_rate)
  242. if epochs_iters is not None:
  243. config._update_epochs(epochs_iters)
  244. if save_dir is not None:
  245. save_dir = abspath(save_dir)
  246. else:
  247. # `save_dir` is None
  248. save_dir = abspath(config.get_train_save_dir())
  249. config._update_output_dir(save_dir)
  250. config.dump(config_path)
  251. export_cli_args = []
  252. export_cli_args.append(
  253. CLIArgument(
  254. '-o',
  255. f"Global.save_inference_dir={os.path.join(save_dir, 'export')}"
  256. ))
  257. self._assert_empty_kwargs(kwargs)
  258. return self.runner.compression(config_path, [], export_cli_args,
  259. device, save_dir)