model.py 16 KB

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