model.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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 .config import DetConfig
  20. class DetModel(BaseModel):
  21. """Object Detection Model"""
  22. def train(
  23. self,
  24. batch_size: int = None,
  25. learning_rate: float = None,
  26. epochs_iters: int = None,
  27. ips: str = None,
  28. device: str = "gpu",
  29. resume_path: str = None,
  30. dy2st: bool = False,
  31. amp: str = "OFF",
  32. num_workers: int = None,
  33. use_vdl: bool = True,
  34. save_dir: str = None,
  35. **kwargs,
  36. ) -> CompletedProcess:
  37. """train self
  38. Args:
  39. batch_size (int, optional): the train batch size value. Defaults to None.
  40. learning_rate (float, optional): the train learning rate value. Defaults to None.
  41. epochs_iters (int, optional): the train epochs value. Defaults to None.
  42. ips (str, optional): the ip addresses of nodes when using distribution. Defaults to None.
  43. device (str, optional): the running device. Defaults to 'gpu'.
  44. resume_path (str, optional): the checkpoint file path to resume training. Train from scratch if it is set
  45. to None. Defaults to None.
  46. dy2st (bool, optional): Enable dynamic to static. Defaults to False.
  47. amp (str, optional): the amp settings. Defaults to 'OFF'.
  48. num_workers (int, optional): the workers number. Defaults to None.
  49. use_vdl (bool, optional): enable VisualDL. Defaults to True.
  50. save_dir (str, optional): the directory path to save train output. Defaults to None.
  51. Returns:
  52. CompletedProcess: the result of training subprocess execution.
  53. """
  54. config = self.config.copy()
  55. cli_args = []
  56. if batch_size is not None:
  57. config.update_batch_size(batch_size, "train")
  58. if learning_rate is not None:
  59. config.update_learning_rate(learning_rate)
  60. if epochs_iters is not None:
  61. config.update_epochs(epochs_iters)
  62. config.update_cossch_epoch(epochs_iters)
  63. device_type, _ = self.runner.parse_device(device)
  64. config.update_device(device_type)
  65. if resume_path is not None:
  66. assert resume_path.endswith(
  67. ".pdparams"
  68. ), "resume_path should be endswith .pdparam"
  69. resume_dir = resume_path[0:-9]
  70. cli_args.append(CLIArgument("--resume", resume_dir))
  71. if dy2st:
  72. cli_args.append(CLIArgument("--to_static"))
  73. if num_workers is not None:
  74. config.update_num_workers(num_workers)
  75. if save_dir is None:
  76. save_dir = abspath(config.get_train_save_dir())
  77. else:
  78. save_dir = abspath(save_dir)
  79. config.update_save_dir(save_dir)
  80. if use_vdl:
  81. cli_args.append(CLIArgument("--use_vdl", use_vdl))
  82. cli_args.append(CLIArgument("--vdl_log_dir", save_dir))
  83. do_eval = kwargs.pop("do_eval", True)
  84. enable_ce = kwargs.pop("enable_ce", None)
  85. profile = kwargs.pop("profile", None)
  86. if profile is not None:
  87. cli_args.append(CLIArgument("--profiler_options", profile))
  88. # Benchmarking mode settings
  89. benchmark = kwargs.pop("benchmark", None)
  90. if benchmark is not None:
  91. envs = benchmark.get("env", None)
  92. amp = benchmark.get("amp", None)
  93. do_eval = benchmark.get("do_eval", False)
  94. num_workers = benchmark.get("num_workers", None)
  95. config.update_log_ranks(device)
  96. config.update_shuffle(benchmark.get("shuffle", False))
  97. config.update_shared_memory(benchmark.get("shared_memory", True))
  98. config.update_print_mem_info(benchmark.get("print_mem_info", True))
  99. if num_workers is not None:
  100. config.update_num_workers(num_workers)
  101. if amp == "O1":
  102. # TODO: ppdet only support ampO1
  103. cli_args.append(CLIArgument("--amp"))
  104. if envs is not None:
  105. for env_name, env_value in envs.items():
  106. os.environ[env_name] = str(env_value)
  107. # set seed to 0 for benchmark mode by enable_ce
  108. cli_args.append(CLIArgument("--enable_ce", True))
  109. else:
  110. if amp != "OFF" and amp is not None:
  111. # TODO: consider amp is O1 or O2 in ppdet
  112. cli_args.append(CLIArgument("--amp"))
  113. if enable_ce is not None:
  114. cli_args.append(CLIArgument("--enable_ce", enable_ce))
  115. # PDX related settings
  116. config.update({"pdx_model_name": self.name})
  117. hpi_config_path = self.model_info.get("hpi_config_path", None)
  118. if hpi_config_path:
  119. hpi_config_path = hpi_config_path.as_posix()
  120. config.update({"hpi_config_path": hpi_config_path})
  121. self._assert_empty_kwargs(kwargs)
  122. with self._create_new_config_file() as config_path:
  123. config.dump(config_path)
  124. return self.runner.train(
  125. config_path, cli_args, device, ips, save_dir, do_eval=do_eval
  126. )
  127. def evaluate(
  128. self,
  129. weight_path: str,
  130. batch_size: int = None,
  131. ips: bool = None,
  132. device: bool = "gpu",
  133. amp: bool = "OFF",
  134. num_workers: int = None,
  135. **kwargs,
  136. ) -> CompletedProcess:
  137. """evaluate self using specified weight
  138. Args:
  139. weight_path (str): the path of model weight file to be evaluated.
  140. batch_size (int, optional): the batch size value in evaluating. Defaults to None.
  141. ips (str, optional): the ip addresses of nodes when using distribution. Defaults to None.
  142. device (str, optional): the running device. Defaults to 'gpu'.
  143. amp (str, optional): the AMP setting. Defaults to 'OFF'.
  144. num_workers (int, optional): the workers number in evaluating. Defaults to None.
  145. Returns:
  146. CompletedProcess: the result of evaluating subprocess execution.
  147. """
  148. config = self.config.copy()
  149. cli_args = []
  150. weight_path = abspath(weight_path)
  151. config.update_weights(weight_path)
  152. if batch_size is not None:
  153. config.update_batch_size(batch_size, "eval")
  154. device_type, device_ids = self.runner.parse_device(device)
  155. if len(device_ids) > 1:
  156. raise ValueError(
  157. f"multi-{device_type} evaluation is not supported. Please use a single {device_type}."
  158. )
  159. config.update_device(device_type)
  160. if amp != "OFF":
  161. # TODO: consider amp is O1 or O2 in ppdet
  162. cli_args.append(CLIArgument("--amp"))
  163. if num_workers is not None:
  164. config.update_num_workers(num_workers)
  165. self._assert_empty_kwargs(kwargs)
  166. with self._create_new_config_file() as config_path:
  167. config.dump(config_path)
  168. cp = self.runner.evaluate(config_path, cli_args, device, ips)
  169. return cp
  170. def predict(
  171. self,
  172. input_path: str,
  173. weight_path: str,
  174. device: str = "gpu",
  175. save_dir: str = None,
  176. **kwargs,
  177. ) -> CompletedProcess:
  178. """predict using specified weight
  179. Args:
  180. weight_path (str): the path of model weight file used to predict.
  181. input_path (str): the path of image file to be predicted.
  182. device (str, optional): the running device. Defaults to 'gpu'.
  183. save_dir (str, optional): the directory path to save predict output. Defaults to None.
  184. Returns:
  185. CompletedProcess: the result of predicting subprocess execution.
  186. """
  187. config = self.config.copy()
  188. cli_args = []
  189. input_path = abspath(input_path)
  190. if os.path.isfile(input_path):
  191. cli_args.append(CLIArgument("--infer_img", input_path))
  192. else:
  193. cli_args.append(CLIArgument("--infer_dir", input_path))
  194. if "infer_list" in kwargs:
  195. infer_list = abspath(kwargs.get("infer_list"))
  196. cli_args.append(CLIArgument("--infer_list", infer_list))
  197. if "visualize" in kwargs:
  198. cli_args.append(CLIArgument("--visualize", kwargs["visualize"]))
  199. if "save_results" in kwargs:
  200. cli_args.append(CLIArgument("--save_results", kwargs["save_results"]))
  201. if "save_threshold" in kwargs:
  202. cli_args.append(CLIArgument("--save_threshold", kwargs["save_threshold"]))
  203. if "rtn_im_file" in kwargs:
  204. cli_args.append(CLIArgument("--rtn_im_file", kwargs["rtn_im_file"]))
  205. weight_path = abspath(weight_path)
  206. config.update_weights(weight_path)
  207. device_type, _ = self.runner.parse_device(device)
  208. config.update_device(device_type)
  209. if save_dir is not None:
  210. save_dir = abspath(save_dir)
  211. cli_args.append(CLIArgument("--output_dir", save_dir))
  212. self._assert_empty_kwargs(kwargs)
  213. with self._create_new_config_file() as config_path:
  214. config.dump(config_path)
  215. return self.runner.predict(config_path, cli_args, device)
  216. def export(self, weight_path: str, save_dir: str, **kwargs) -> CompletedProcess:
  217. """export the dynamic model to static model
  218. Args:
  219. weight_path (str): the model weight file path that used to export.
  220. save_dir (str): the directory path to save export output.
  221. Returns:
  222. CompletedProcess: the result of exporting subprocess execution.
  223. """
  224. config = self.config.copy()
  225. cli_args = []
  226. if not weight_path.startswith("http"):
  227. weight_path = abspath(weight_path)
  228. config.update_weights(weight_path)
  229. save_dir = abspath(save_dir)
  230. cli_args.append(CLIArgument("--output_dir", save_dir))
  231. input_shape = kwargs.pop("input_shape", None)
  232. if input_shape is not None:
  233. cli_args.append(
  234. CLIArgument("-o", f"TestReader.inputs_def.image_shape={input_shape}")
  235. )
  236. use_trt = kwargs.pop("use_trt", None)
  237. if use_trt is not None:
  238. cli_args.append(CLIArgument("-o", f"trt={bool(use_trt)}"))
  239. exclude_nms = kwargs.pop("exclude_nms", None)
  240. if exclude_nms is not None:
  241. cli_args.append(CLIArgument("-o", f"exclude_nms={bool(exclude_nms)}"))
  242. # PDX related settings
  243. config.update({"pdx_model_name": self.name})
  244. hpi_config_path = self.model_info.get("hpi_config_path", None)
  245. if hpi_config_path:
  246. hpi_config_path = hpi_config_path.as_posix()
  247. config.update({"hpi_config_path": hpi_config_path})
  248. self._assert_empty_kwargs(kwargs)
  249. with self._create_new_config_file() as config_path:
  250. config.dump(config_path)
  251. return self.runner.export(config_path, cli_args, None)
  252. def infer(
  253. self,
  254. model_dir: str,
  255. input_path: str,
  256. device: str = "gpu",
  257. save_dir: str = None,
  258. **kwargs,
  259. ):
  260. """predict image using infernece model
  261. Args:
  262. model_dir (str): the directory path of inference model files that would use to predict.
  263. input_path (str): the path of image that would be predict.
  264. device (str, optional): the running device. Defaults to 'gpu'.
  265. save_dir (str, optional): the directory path to save output. Defaults to None.
  266. Returns:
  267. CompletedProcess: the result of infering subprocess execution.
  268. """
  269. model_dir = abspath(model_dir)
  270. input_path = abspath(input_path)
  271. if save_dir is not None:
  272. save_dir = abspath(save_dir)
  273. cli_args = []
  274. cli_args.append(CLIArgument("--model_dir", model_dir))
  275. cli_args.append(CLIArgument("--image_file", input_path))
  276. if save_dir is not None:
  277. cli_args.append(CLIArgument("--output_dir", save_dir))
  278. device_type, _ = self.runner.parse_device(device)
  279. cli_args.append(CLIArgument("--device", device_type))
  280. self._assert_empty_kwargs(kwargs)
  281. return self.runner.infer(cli_args, device)
  282. def compression(
  283. self,
  284. weight_path: str,
  285. batch_size: int = None,
  286. learning_rate: float = None,
  287. epochs_iters: int = None,
  288. device: str = None,
  289. use_vdl: bool = True,
  290. save_dir: str = None,
  291. **kwargs,
  292. ) -> CompletedProcess:
  293. """compression model
  294. Args:
  295. weight_path (str): the path to weight file of model.
  296. batch_size (int, optional): the batch size value of compression training. Defaults to None.
  297. learning_rate (float, optional): the learning rate value of compression training. Defaults to None.
  298. epochs_iters (int, optional): the epochs or iters of compression training. Defaults to None.
  299. device (str, optional): the device to run compression training. Defaults to 'gpu'.
  300. use_vdl (bool, optional): whether or not to use VisualDL. Defaults to True.
  301. save_dir (str, optional): the directory to save output. Defaults to None.
  302. Returns:
  303. CompletedProcess: the result of compression subprocess execution.
  304. """
  305. weight_path = abspath(weight_path)
  306. if save_dir is None:
  307. save_dir = self.config["save_dir"]
  308. save_dir = abspath(save_dir)
  309. config = self.config.copy()
  310. cps_config = DetConfig(
  311. self.name, config_path=self.model_info["auto_compression_config_path"]
  312. )
  313. train_cli_args = []
  314. export_cli_args = []
  315. cps_config.update_pretrained_weights(weight_path)
  316. if batch_size is not None:
  317. cps_config.update_batch_size(batch_size, "train")
  318. if learning_rate is not None:
  319. cps_config.update_learning_rate(learning_rate)
  320. if epochs_iters is not None:
  321. cps_config.update_epochs(epochs_iters)
  322. if device is not None:
  323. device_type, _ = self.runner.parse_device(device)
  324. config.update_device(device_type)
  325. if save_dir is not None:
  326. save_dir = abspath(config.get_train_save_dir())
  327. else:
  328. save_dir = abspath(save_dir)
  329. cps_config.update_save_dir(save_dir)
  330. if use_vdl:
  331. train_cli_args.append(CLIArgument("--use_vdl", use_vdl))
  332. train_cli_args.append(CLIArgument("--vdl_log_dir", save_dir))
  333. export_cli_args.append(
  334. CLIArgument("--output_dir", os.path.join(save_dir, "export"))
  335. )
  336. with self._create_new_config_file() as config_path:
  337. config.dump(config_path)
  338. # TODO: refactor me
  339. cps_config_path = config_path[0:-4] + "_compression" + config_path[-4:]
  340. cps_config.dump(cps_config_path)
  341. train_cli_args.append(CLIArgument("--slim_config", cps_config_path))
  342. export_cli_args.append(CLIArgument("--slim_config", cps_config_path))
  343. self._assert_empty_kwargs(kwargs)
  344. self.runner.compression(
  345. config_path, train_cli_args, export_cli_args, device, save_dir
  346. )