model.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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. uniform_output_enabled = kwargs.pop("uniform_output_enabled", True)
  147. config.set_val("uniform_output_enabled", uniform_output_enabled)
  148. config.set_val("pdx_model_name", self.name)
  149. self._assert_empty_kwargs(kwargs)
  150. with self._create_new_config_file() as config_path:
  151. config.dump(config_path)
  152. return self.runner.train(
  153. config_path, cli_args, device, ips, save_dir, do_eval=do_eval
  154. )
  155. def evaluate(
  156. self,
  157. weight_path: str,
  158. batch_size: int = None,
  159. ips: str = None,
  160. device: str = "gpu",
  161. amp: str = "OFF",
  162. num_workers: int = None,
  163. **kwargs,
  164. ) -> CompletedProcess:
  165. """evaluate self using specified weight
  166. Args:
  167. weight_path (str): the path of model weight file to be evaluated.
  168. batch_size (int, optional): the batch size value in evaluating. Defaults to None.
  169. ips (str, optional): the ip addresses of nodes when using distribution. Defaults to None.
  170. device (str, optional): the running device. Defaults to 'gpu'.
  171. amp (str, optional): the AMP setting. Defaults to 'OFF'.
  172. num_workers (int, optional): the workers number in evaluating. Defaults to None.
  173. Returns:
  174. CompletedProcess: the result of evaluating subprocess execution.
  175. """
  176. config = self.config.copy()
  177. cli_args = []
  178. weight_path = abspath(weight_path)
  179. cli_args.append(CLIArgument("--model_path", weight_path))
  180. if batch_size is not None:
  181. if batch_size != 1:
  182. raise ValueError("Batch size other than 1 is not supported.")
  183. # No need to handle `ips`
  184. if device is not None:
  185. device_type, _ = parse_device(device)
  186. cli_args.append(CLIArgument("--device", device_type))
  187. if amp is not None:
  188. if amp != "OFF":
  189. cli_args.append(CLIArgument("--precision", "fp16"))
  190. cli_args.append(CLIArgument("--amp_level", amp))
  191. if num_workers is not None:
  192. cli_args.append(CLIArgument("--num_workers", num_workers))
  193. self._assert_empty_kwargs(kwargs)
  194. with self._create_new_config_file() as config_path:
  195. config.dump(config_path)
  196. cp = self.runner.evaluate(config_path, cli_args, device, ips)
  197. return cp
  198. def predict(
  199. self,
  200. weight_path: str,
  201. input_path: str,
  202. device: str = "gpu",
  203. save_dir: str = None,
  204. **kwargs,
  205. ) -> CompletedProcess:
  206. """predict using specified weight
  207. Args:
  208. weight_path (str): the path of model weight file used to predict.
  209. input_path (str): the path of image file to be predicted.
  210. device (str, optional): the running device. Defaults to 'gpu'.
  211. save_dir (str, optional): the directory path to save predict output. Defaults to None.
  212. Returns:
  213. CompletedProcess: the result of predicting subprocess execution.
  214. """
  215. config = self.config.copy()
  216. cli_args = []
  217. weight_path = abspath(weight_path)
  218. cli_args.append(CLIArgument("--model_path", weight_path))
  219. input_path = abspath(input_path)
  220. cli_args.append(CLIArgument("--image_path", input_path))
  221. if device is not None:
  222. device_type, _ = parse_device(device)
  223. cli_args.append(CLIArgument("--device", device_type))
  224. if save_dir is not None:
  225. save_dir = abspath(save_dir)
  226. else:
  227. # `save_dir` is None
  228. save_dir = abspath(os.path.join("output", "predict"))
  229. cli_args.append(CLIArgument("--save_dir", save_dir))
  230. self._assert_empty_kwargs(kwargs)
  231. with self._create_new_config_file() as config_path:
  232. config.dump(config_path)
  233. return self.runner.predict(config_path, cli_args, device)
  234. def analyse(self, weight_path, ips=None, device="gpu", save_dir=None, **kwargs):
  235. """analyse"""
  236. config = self.config.copy()
  237. cli_args = []
  238. weight_path = abspath(weight_path)
  239. cli_args.append(CLIArgument("--model_path", weight_path))
  240. if device is not None:
  241. device_type, _ = parse_device(device)
  242. cli_args.append(CLIArgument("--device", device_type))
  243. if save_dir is not None:
  244. save_dir = abspath(save_dir)
  245. else:
  246. # `save_dir` is None
  247. save_dir = abspath(os.path.join("output", "analysis"))
  248. cli_args.append(CLIArgument("--save_dir", save_dir))
  249. self._assert_empty_kwargs(kwargs)
  250. with self._create_new_config_file() as config_path:
  251. config.dump(config_path)
  252. cp = self.runner.analyse(config_path, cli_args, device, ips)
  253. return cp
  254. def export(self, weight_path: str, save_dir: str, **kwargs) -> CompletedProcess:
  255. """export the dynamic model to static model
  256. Args:
  257. weight_path (str): the model weight file path that used to export.
  258. save_dir (str): the directory path to save export output.
  259. Returns:
  260. CompletedProcess: the result of exporting subprocess execution.
  261. """
  262. config = self.config.copy()
  263. cli_args = []
  264. if not weight_path.startswith("http"):
  265. weight_path = abspath(weight_path)
  266. else:
  267. filename = os.path.basename(weight_path)
  268. save_path = os.path.join(DEFAULT_CACHE_DIR, filename)
  269. download(weight_path, save_path, print_progress=True, overwrite=True)
  270. weight_path = save_path
  271. cli_args.append(CLIArgument("--model_path", weight_path))
  272. if save_dir is not None:
  273. save_dir = abspath(save_dir)
  274. else:
  275. # `save_dir` is None
  276. save_dir = abspath(os.path.join("output", "export"))
  277. cli_args.append(CLIArgument("--save_dir", save_dir))
  278. input_shape = kwargs.pop("input_shape", None)
  279. if input_shape is not None:
  280. cli_args.append(CLIArgument("--input_shape", *input_shape))
  281. try:
  282. output_op = config["output_op"]
  283. except:
  284. output_op = kwargs.pop("output_op", None)
  285. if output_op is not None:
  286. assert output_op in [
  287. "softmax",
  288. "argmax",
  289. "none",
  290. ], "`output_op` must be 'none', 'softmax' or 'argmax'."
  291. cli_args.append(CLIArgument("--output_op", output_op))
  292. # PDX related settings
  293. uniform_output_enabled = kwargs.pop("uniform_output_enabled", True)
  294. config.set_val("uniform_output_enabled", uniform_output_enabled)
  295. config.set_val("pdx_model_name", self.name)
  296. self._assert_empty_kwargs(kwargs)
  297. with self._create_new_config_file() as config_path:
  298. config.dump(config_path)
  299. return self.runner.export(config_path, cli_args, None)
  300. def infer(
  301. self,
  302. model_dir: str,
  303. input_path: str,
  304. device: str = "gpu",
  305. save_dir: str = None,
  306. **kwargs,
  307. ) -> CompletedProcess:
  308. """predict image using infernece model
  309. Args:
  310. model_dir (str): the directory path of inference model files that would use to predict.
  311. input_path (str): the path of image that would be predict.
  312. device (str, optional): the running device. Defaults to 'gpu'.
  313. save_dir (str, optional): the directory path to save output. Defaults to None.
  314. Returns:
  315. CompletedProcess: the result of infering subprocess execution.
  316. """
  317. config = self.config.copy()
  318. cli_args = []
  319. model_dir = abspath(model_dir)
  320. input_path = abspath(input_path)
  321. cli_args.append(CLIArgument("--image_path", input_path))
  322. if device is not None:
  323. device_type, _ = parse_device(device)
  324. cli_args.append(CLIArgument("--device", device_type))
  325. if save_dir is not None:
  326. save_dir = abspath(save_dir)
  327. else:
  328. # `save_dir` is None
  329. save_dir = abspath(os.path.join("output", "infer"))
  330. cli_args.append(CLIArgument("--save_dir", save_dir))
  331. self._assert_empty_kwargs(kwargs)
  332. with self._create_new_config_file() as config_path:
  333. config.dump(config_path)
  334. deploy_config_path = os.path.join(model_dir, "inference.yml")
  335. return self.runner.infer(deploy_config_path, cli_args, device)
  336. def compression(
  337. self,
  338. weight_path: str,
  339. batch_size: int = None,
  340. learning_rate: float = None,
  341. epochs_iters: int = None,
  342. device: str = "gpu",
  343. use_vdl: bool = True,
  344. save_dir: str = None,
  345. **kwargs,
  346. ) -> CompletedProcess:
  347. """compression model
  348. Args:
  349. weight_path (str): the path to weight file of model.
  350. batch_size (int, optional): the batch size value of compression training. Defaults to None.
  351. learning_rate (float, optional): the learning rate value of compression training. Defaults to None.
  352. epochs_iters (int, optional): the epochs or iters of compression training. Defaults to None.
  353. device (str, optional): the device to run compression training. Defaults to 'gpu'.
  354. use_vdl (bool, optional): whether or not to use VisualDL. Defaults to True.
  355. save_dir (str, optional): the directory to save output. Defaults to None.
  356. Returns:
  357. CompletedProcess: the result of compression subprocess execution.
  358. """
  359. # Update YAML config file
  360. # NOTE: In PaddleSeg, QAT does not use a different config file than regular training
  361. # Reusing `self.config` preserves the config items modified by the user when
  362. # `SegModel` is initialized with a `SegConfig` object.
  363. config = self.config.copy()
  364. train_cli_args = []
  365. export_cli_args = []
  366. weight_path = abspath(weight_path)
  367. train_cli_args.append(CLIArgument("--model_path", weight_path))
  368. if batch_size is not None:
  369. train_cli_args.append(CLIArgument("--batch_size", batch_size))
  370. if learning_rate is not None:
  371. train_cli_args.append(CLIArgument("--learning_rate", learning_rate))
  372. if epochs_iters is not None:
  373. train_cli_args.append(CLIArgument("--iters", epochs_iters))
  374. if device is not None:
  375. device_type, _ = parse_device(device)
  376. train_cli_args.append(CLIArgument("--device", device_type))
  377. if use_vdl:
  378. train_cli_args.append(CLIArgument("--use_vdl"))
  379. if save_dir is not None:
  380. save_dir = abspath(save_dir)
  381. else:
  382. # `save_dir` is None
  383. save_dir = abspath(os.path.join("output", "compress"))
  384. train_cli_args.append(CLIArgument("--save_dir", save_dir))
  385. # The exported model saved in a subdirectory named `export`
  386. export_cli_args.append(
  387. CLIArgument("--save_dir", os.path.join(save_dir, "export"))
  388. )
  389. input_shape = kwargs.pop("input_shape", None)
  390. if input_shape is not None:
  391. export_cli_args.append(CLIArgument("--input_shape", *input_shape))
  392. self._assert_empty_kwargs(kwargs)
  393. with self._create_new_config_file() as config_path:
  394. config.dump(config_path)
  395. return self.runner.compression(
  396. config_path, train_cli_args, export_cli_args, device, save_dir
  397. )