model.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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.device import parse_device
  19. from ....utils.misc import abspath
  20. from ....utils.download import download
  21. from ....utils.cache import DEFAULT_CACHE_DIR
  22. class SegModel(BaseModel):
  23. """Semantic Segmentation Model"""
  24. def train(
  25. self,
  26. batch_size: int = None,
  27. learning_rate: float = None,
  28. epochs_iters: int = None,
  29. ips: str = None,
  30. device: str = "gpu",
  31. resume_path: str = None,
  32. dy2st: bool = False,
  33. amp: str = "OFF",
  34. num_workers: int = None,
  35. use_vdl: bool = True,
  36. save_dir: str = None,
  37. **kwargs,
  38. ) -> CompletedProcess:
  39. """train self
  40. Args:
  41. batch_size (int, optional): the train batch size value. Defaults to None.
  42. learning_rate (float, optional): the train learning rate value. Defaults to None.
  43. epochs_iters (int, optional): the train epochs value. Defaults to None.
  44. ips (str, optional): the ip addresses of nodes when using distribution. Defaults to None.
  45. device (str, optional): the running device. Defaults to 'gpu'.
  46. resume_path (str, optional): the checkpoint file path to resume training. Train from scratch if it is set
  47. to None. Defaults to None.
  48. dy2st (bool, optional): Enable dynamic to static. Defaults to False.
  49. amp (str, optional): the amp settings. Defaults to 'OFF'.
  50. num_workers (int, optional): the workers number. Defaults to None.
  51. use_vdl (bool, optional): enable VisualDL. Defaults to True.
  52. save_dir (str, optional): the directory path to save train output. Defaults to None.
  53. Returns:
  54. CompletedProcess: the result of training subprocess execution.
  55. """
  56. config = self.config.copy()
  57. cli_args = []
  58. if batch_size is not None:
  59. cli_args.append(CLIArgument("--batch_size", batch_size))
  60. if learning_rate is not None:
  61. cli_args.append(CLIArgument("--learning_rate", learning_rate))
  62. if epochs_iters is not None:
  63. cli_args.append(CLIArgument("--iters", epochs_iters))
  64. # No need to handle `ips`
  65. if device is not None:
  66. device_type, _ = parse_device(device)
  67. cli_args.append(CLIArgument("--device", device_type))
  68. # For compatibility
  69. resume_dir = kwargs.pop("resume_dir", None)
  70. if resume_path is None and resume_dir is not None:
  71. resume_path = os.path.join(resume_dir, "model.pdparams")
  72. if resume_path is not None:
  73. # NOTE: We must use an absolute path here,
  74. # so we can run the scripts either inside or outside the repo dir.
  75. resume_path = abspath(resume_path)
  76. if os.path.basename(resume_path) != "model.pdparams":
  77. raise ValueError(f"{resume_path} has an incorrect file name.")
  78. if not os.path.exists(resume_path):
  79. raise FileNotFoundError(f"{resume_path} does not exist.")
  80. resume_dir = os.path.dirname(resume_path)
  81. opts_path = os.path.join(resume_dir, "model.pdopt")
  82. if not os.path.exists(opts_path):
  83. raise FileNotFoundError(f"{opts_path} must exist.")
  84. cli_args.append(CLIArgument("--resume_model", resume_dir))
  85. if dy2st:
  86. config.update_dy2st(dy2st)
  87. if use_vdl:
  88. cli_args.append(CLIArgument("--use_vdl"))
  89. if save_dir is not None:
  90. save_dir = abspath(save_dir)
  91. else:
  92. # `save_dir` is None
  93. save_dir = abspath(os.path.join("output", "train"))
  94. cli_args.append(CLIArgument("--save_dir", save_dir))
  95. save_interval = kwargs.pop("save_interval", None)
  96. if save_interval is not None:
  97. cli_args.append(CLIArgument("--save_interval", save_interval))
  98. do_eval = kwargs.pop("do_eval", True)
  99. repeats = kwargs.pop("repeats", None)
  100. seed = kwargs.pop("seed", None)
  101. profile = kwargs.pop("profile", None)
  102. if profile is not None:
  103. cli_args.append(CLIArgument("--profiler_options", profile))
  104. log_iters = kwargs.pop("log_iters", None)
  105. if log_iters is not None:
  106. cli_args.append(CLIArgument("--log_iters", log_iters))
  107. # Benchmarking mode settings
  108. benchmark = kwargs.pop("benchmark", None)
  109. if benchmark is not None:
  110. envs = benchmark.get("env", None)
  111. seed = benchmark.get("seed", None)
  112. repeats = benchmark.get("repeats", None)
  113. do_eval = benchmark.get("do_eval", False)
  114. num_workers = benchmark.get("num_workers", None)
  115. config.update_log_ranks(device)
  116. amp = benchmark.get("amp", None)
  117. config.update_print_mem_info(benchmark.get("print_mem_info", True))
  118. config.update_shuffle(benchmark.get("shuffle", False))
  119. if repeats is not None:
  120. assert isinstance(repeats, int), "repeats must be an integer."
  121. cli_args.append(CLIArgument("--repeats", repeats))
  122. if num_workers is not None:
  123. assert isinstance(num_workers, int), "num_workers must be an integer."
  124. cli_args.append(CLIArgument("--num_workers", num_workers))
  125. if seed is not None:
  126. assert isinstance(seed, int), "seed must be an integer."
  127. cli_args.append(CLIArgument("--seed", seed))
  128. if amp in ["O1", "O2"]:
  129. cli_args.append(CLIArgument("--precision", "fp16"))
  130. cli_args.append(CLIArgument("--amp_level", amp))
  131. if envs is not None:
  132. for env_name, env_value in envs.items():
  133. os.environ[env_name] = str(env_value)
  134. else:
  135. if amp is not None:
  136. if amp != "OFF":
  137. cli_args.append(CLIArgument("--precision", "fp16"))
  138. cli_args.append(CLIArgument("--amp_level", amp))
  139. if num_workers is not None:
  140. cli_args.append(CLIArgument("--num_workers", num_workers))
  141. if repeats is not None:
  142. cli_args.append(CLIArgument("--repeats", repeats))
  143. if seed is not None:
  144. cli_args.append(CLIArgument("--seed", seed))
  145. # PDX related settings
  146. config.set_val("uniform_output_enabled", True)
  147. config.set_val("pdx_model_name", self.name)
  148. hpi_config_path = self.model_info.get("hpi_config_path", None)
  149. if hpi_config_path:
  150. hpi_config_path = hpi_config_path.as_posix()
  151. config.set_val("hpi_config_path", hpi_config_path)
  152. self._assert_empty_kwargs(kwargs)
  153. with self._create_new_config_file() as config_path:
  154. config.dump(config_path)
  155. return self.runner.train(
  156. config_path, cli_args, device, ips, save_dir, do_eval=do_eval
  157. )
  158. def evaluate(
  159. self,
  160. weight_path: str,
  161. batch_size: int = None,
  162. ips: str = None,
  163. device: str = "gpu",
  164. amp: str = "OFF",
  165. num_workers: int = None,
  166. **kwargs,
  167. ) -> CompletedProcess:
  168. """evaluate self using specified weight
  169. Args:
  170. weight_path (str): the path of model weight file to be evaluated.
  171. batch_size (int, optional): the batch size value in evaluating. Defaults to None.
  172. ips (str, optional): the ip addresses of nodes when using distribution. Defaults to None.
  173. device (str, optional): the running device. Defaults to 'gpu'.
  174. amp (str, optional): the AMP setting. Defaults to 'OFF'.
  175. num_workers (int, optional): the workers number in evaluating. Defaults to None.
  176. Returns:
  177. CompletedProcess: the result of evaluating subprocess execution.
  178. """
  179. config = self.config.copy()
  180. cli_args = []
  181. weight_path = abspath(weight_path)
  182. cli_args.append(CLIArgument("--model_path", weight_path))
  183. if batch_size is not None:
  184. if batch_size != 1:
  185. raise ValueError("Batch size other than 1 is not supported.")
  186. # No need to handle `ips`
  187. if device is not None:
  188. device_type, _ = parse_device(device)
  189. cli_args.append(CLIArgument("--device", device_type))
  190. if amp is not None:
  191. if amp != "OFF":
  192. cli_args.append(CLIArgument("--precision", "fp16"))
  193. cli_args.append(CLIArgument("--amp_level", amp))
  194. if num_workers is not None:
  195. cli_args.append(CLIArgument("--num_workers", num_workers))
  196. self._assert_empty_kwargs(kwargs)
  197. with self._create_new_config_file() as config_path:
  198. config.dump(config_path)
  199. cp = self.runner.evaluate(config_path, cli_args, device, ips)
  200. return cp
  201. def predict(
  202. self,
  203. weight_path: str,
  204. input_path: str,
  205. device: str = "gpu",
  206. save_dir: str = None,
  207. **kwargs,
  208. ) -> CompletedProcess:
  209. """predict using specified weight
  210. Args:
  211. weight_path (str): the path of model weight file used to predict.
  212. input_path (str): the path of image file to be predicted.
  213. device (str, optional): the running device. Defaults to 'gpu'.
  214. save_dir (str, optional): the directory path to save predict output. Defaults to None.
  215. Returns:
  216. CompletedProcess: the result of predicting subprocess execution.
  217. """
  218. config = self.config.copy()
  219. cli_args = []
  220. weight_path = abspath(weight_path)
  221. cli_args.append(CLIArgument("--model_path", weight_path))
  222. input_path = abspath(input_path)
  223. cli_args.append(CLIArgument("--image_path", input_path))
  224. if device is not None:
  225. device_type, _ = parse_device(device)
  226. cli_args.append(CLIArgument("--device", device_type))
  227. if save_dir is not None:
  228. save_dir = abspath(save_dir)
  229. else:
  230. # `save_dir` is None
  231. save_dir = abspath(os.path.join("output", "predict"))
  232. cli_args.append(CLIArgument("--save_dir", save_dir))
  233. self._assert_empty_kwargs(kwargs)
  234. with self._create_new_config_file() as config_path:
  235. config.dump(config_path)
  236. return self.runner.predict(config_path, cli_args, device)
  237. def analyse(self, weight_path, ips=None, device="gpu", save_dir=None, **kwargs):
  238. """analyse"""
  239. config = self.config.copy()
  240. cli_args = []
  241. weight_path = abspath(weight_path)
  242. cli_args.append(CLIArgument("--model_path", weight_path))
  243. if device is not None:
  244. device_type, _ = parse_device(device)
  245. cli_args.append(CLIArgument("--device", device_type))
  246. if save_dir is not None:
  247. save_dir = abspath(save_dir)
  248. else:
  249. # `save_dir` is None
  250. save_dir = abspath(os.path.join("output", "analysis"))
  251. cli_args.append(CLIArgument("--save_dir", save_dir))
  252. self._assert_empty_kwargs(kwargs)
  253. with self._create_new_config_file() as config_path:
  254. config.dump(config_path)
  255. cp = self.runner.analyse(config_path, cli_args, device, ips)
  256. return cp
  257. def export(self, weight_path: str, save_dir: str, **kwargs) -> CompletedProcess:
  258. """export the dynamic model to static model
  259. Args:
  260. weight_path (str): the model weight file path that used to export.
  261. save_dir (str): the directory path to save export output.
  262. Returns:
  263. CompletedProcess: the result of exporting subprocess execution.
  264. """
  265. config = self.config.copy()
  266. cli_args = []
  267. if not weight_path.startswith("http"):
  268. weight_path = abspath(weight_path)
  269. else:
  270. filename = os.path.basename(weight_path)
  271. save_path = os.path.join(DEFAULT_CACHE_DIR, filename)
  272. download(weight_path, save_path, print_progress=True, overwrite=True)
  273. weight_path = save_path
  274. cli_args.append(CLIArgument("--model_path", weight_path))
  275. if save_dir is not None:
  276. save_dir = abspath(save_dir)
  277. else:
  278. # `save_dir` is None
  279. save_dir = abspath(os.path.join("output", "export"))
  280. cli_args.append(CLIArgument("--save_dir", save_dir))
  281. input_shape = kwargs.pop("input_shape", None)
  282. if input_shape is not None:
  283. cli_args.append(CLIArgument("--input_shape", *input_shape))
  284. try:
  285. output_op = config["output_op"]
  286. except:
  287. output_op = kwargs.pop("output_op", None)
  288. if output_op is not None:
  289. assert output_op in [
  290. "softmax",
  291. "argmax",
  292. "none",
  293. ], "`output_op` must be 'none', 'softmax' or 'argmax'."
  294. cli_args.append(CLIArgument("--output_op", output_op))
  295. # PDX related settings
  296. config.set_val("pdx_model_name", self.name)
  297. hpi_config_path = self.model_info.get("hpi_config_path", None)
  298. if hpi_config_path:
  299. hpi_config_path = hpi_config_path.as_posix()
  300. config.set_val("hpi_config_path", hpi_config_path)
  301. self._assert_empty_kwargs(kwargs)
  302. with self._create_new_config_file() as config_path:
  303. config.dump(config_path)
  304. return self.runner.export(config_path, cli_args, None)
  305. def infer(
  306. self,
  307. model_dir: str,
  308. input_path: str,
  309. device: str = "gpu",
  310. save_dir: str = None,
  311. **kwargs,
  312. ) -> CompletedProcess:
  313. """predict image using infernece model
  314. Args:
  315. model_dir (str): the directory path of inference model files that would use to predict.
  316. input_path (str): the path of image that would be predict.
  317. device (str, optional): the running device. Defaults to 'gpu'.
  318. save_dir (str, optional): the directory path to save output. Defaults to None.
  319. Returns:
  320. CompletedProcess: the result of infering subprocess execution.
  321. """
  322. config = self.config.copy()
  323. cli_args = []
  324. model_dir = abspath(model_dir)
  325. input_path = abspath(input_path)
  326. cli_args.append(CLIArgument("--image_path", input_path))
  327. if device is not None:
  328. device_type, _ = parse_device(device)
  329. cli_args.append(CLIArgument("--device", device_type))
  330. if save_dir is not None:
  331. save_dir = abspath(save_dir)
  332. else:
  333. # `save_dir` is None
  334. save_dir = abspath(os.path.join("output", "infer"))
  335. cli_args.append(CLIArgument("--save_dir", save_dir))
  336. self._assert_empty_kwargs(kwargs)
  337. with self._create_new_config_file() as config_path:
  338. config.dump(config_path)
  339. deploy_config_path = os.path.join(model_dir, "inference.yml")
  340. return self.runner.infer(deploy_config_path, cli_args, device)
  341. def compression(
  342. self,
  343. weight_path: str,
  344. batch_size: int = None,
  345. learning_rate: float = None,
  346. epochs_iters: int = None,
  347. device: str = "gpu",
  348. use_vdl: bool = True,
  349. save_dir: str = None,
  350. **kwargs,
  351. ) -> CompletedProcess:
  352. """compression model
  353. Args:
  354. weight_path (str): the path to weight file of model.
  355. batch_size (int, optional): the batch size value of compression training. Defaults to None.
  356. learning_rate (float, optional): the learning rate value of compression training. Defaults to None.
  357. epochs_iters (int, optional): the epochs or iters of compression training. Defaults to None.
  358. device (str, optional): the device to run compression training. Defaults to 'gpu'.
  359. use_vdl (bool, optional): whether or not to use VisualDL. Defaults to True.
  360. save_dir (str, optional): the directory to save output. Defaults to None.
  361. Returns:
  362. CompletedProcess: the result of compression subprocess execution.
  363. """
  364. # Update YAML config file
  365. # NOTE: In PaddleSeg, QAT does not use a different config file than regular training
  366. # Reusing `self.config` preserves the config items modified by the user when
  367. # `SegModel` is initialized with a `SegConfig` object.
  368. config = self.config.copy()
  369. train_cli_args = []
  370. export_cli_args = []
  371. weight_path = abspath(weight_path)
  372. train_cli_args.append(CLIArgument("--model_path", weight_path))
  373. if batch_size is not None:
  374. train_cli_args.append(CLIArgument("--batch_size", batch_size))
  375. if learning_rate is not None:
  376. train_cli_args.append(CLIArgument("--learning_rate", learning_rate))
  377. if epochs_iters is not None:
  378. train_cli_args.append(CLIArgument("--iters", epochs_iters))
  379. if device is not None:
  380. device_type, _ = parse_device(device)
  381. train_cli_args.append(CLIArgument("--device", device_type))
  382. if use_vdl:
  383. train_cli_args.append(CLIArgument("--use_vdl"))
  384. if save_dir is not None:
  385. save_dir = abspath(save_dir)
  386. else:
  387. # `save_dir` is None
  388. save_dir = abspath(os.path.join("output", "compress"))
  389. train_cli_args.append(CLIArgument("--save_dir", save_dir))
  390. # The exported model saved in a subdirectory named `export`
  391. export_cli_args.append(
  392. CLIArgument("--save_dir", os.path.join(save_dir, "export"))
  393. )
  394. input_shape = kwargs.pop("input_shape", None)
  395. if input_shape is not None:
  396. export_cli_args.append(CLIArgument("--input_shape", *input_shape))
  397. self._assert_empty_kwargs(kwargs)
  398. with self._create_new_config_file() as config_path:
  399. config.dump(config_path)
  400. return self.runner.compression(
  401. config_path, train_cli_args, export_cli_args, device, save_dir
  402. )