train_deamon.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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. import sys
  16. import time
  17. import json
  18. import traceback
  19. import threading
  20. from abc import ABC, abstractmethod
  21. from pathlib import Path
  22. from ..build_model import build_model
  23. from ....utils.file_interface import write_json_file
  24. from ....utils import logging
  25. def try_except_decorator(func):
  26. """ try-except """
  27. def wrap(self, *args, **kwargs):
  28. try:
  29. func(self, *args, **kwargs)
  30. except Exception as e:
  31. exc_type, exc_value, exc_tb = sys.exc_info()
  32. self.save_json()
  33. traceback.print_exception(exc_type, exc_value, exc_tb)
  34. finally:
  35. self.processing = False
  36. return wrap
  37. class BaseTrainDeamon(ABC):
  38. """ BaseTrainResultDemon """
  39. update_interval = 600
  40. last_k = 5
  41. def __init__(self, global_config):
  42. """ init """
  43. self.global_config = global_config
  44. self.init_pre_hook()
  45. self.output = global_config.output
  46. self.train_outputs = self.get_train_outputs()
  47. self.save_paths = self.get_save_paths()
  48. self.results = self.init_train_result()
  49. self.save_json()
  50. self.models = {}
  51. self.init_post_hook()
  52. self.config_recorder = {}
  53. self.model_recorder = {}
  54. self.processing = False
  55. self.start()
  56. def init_train_result(self):
  57. """ init train result structure """
  58. model_names = self.init_model_names()
  59. configs = self.init_configs()
  60. train_log = self.init_train_log()
  61. vdl = self.init_vdl_log()
  62. results = []
  63. for i, model_name in enumerate(model_names):
  64. results.append({
  65. "model_name": model_name,
  66. "done_flag": False,
  67. "config": configs[i],
  68. "label_dict": "",
  69. "train_log": train_log,
  70. "visualdl_log": vdl,
  71. "models": self.init_model_pkg()
  72. })
  73. return results
  74. def get_save_names(self):
  75. """ get names to save """
  76. return ["train_result.json"]
  77. def get_train_outputs(self):
  78. """ get training outputs dir """
  79. return [Path(self.output)]
  80. def init_model_names(self):
  81. """ get models name """
  82. return [self.global_config.model]
  83. def get_save_paths(self):
  84. """ get the path to save train_result.json """
  85. return [
  86. Path(self.output, save_name) for save_name in self.get_save_names()
  87. ]
  88. def init_configs(self):
  89. """ get the init value of config field in result """
  90. return [""] * len(self.init_model_names())
  91. def init_train_log(self):
  92. """ get train log """
  93. return ""
  94. def init_vdl_log(self):
  95. """ get visualdl log """
  96. return ""
  97. def init_model_pkg(self):
  98. """ get model package """
  99. init_content = self.init_model_content()
  100. model_pkg = {}
  101. for pkg in self.get_watched_model():
  102. model_pkg[pkg] = init_content
  103. return model_pkg
  104. def normlize_path(self, dict_obj, relative_to):
  105. """ normlize path to string type path relative to the output """
  106. for key in dict_obj:
  107. if isinstance(dict_obj[key], dict):
  108. self.normlize_path(dict_obj[key], relative_to)
  109. if isinstance(dict_obj[key], Path):
  110. dict_obj[key] = dict_obj[key].resolve().relative_to(
  111. relative_to.resolve()).as_posix()
  112. def save_json(self):
  113. """ save result to json """
  114. for i, result in enumerate(self.results):
  115. self.save_paths[i].parent.mkdir(parents=True, exist_ok=True)
  116. self.normlize_path(result, relative_to=self.save_paths[i].parent)
  117. write_json_file(result, self.save_paths[i], indent=2)
  118. def start(self):
  119. """ start deamon thread """
  120. self.exit = False
  121. self.thread = threading.Thread(target=self.run)
  122. self.thread.daemon = True
  123. self.thread.start()
  124. def stop_hook(self):
  125. """ hook befor stop """
  126. for result in self.results:
  127. result["done_flag"] = True
  128. self.update()
  129. def stop(self):
  130. """ stop self """
  131. self.exit = True
  132. while True:
  133. if not self.processing:
  134. self.stop_hook()
  135. break
  136. time.sleep(60)
  137. def run(self):
  138. """ main function """
  139. while not self.exit:
  140. self.update()
  141. if self.exit:
  142. break
  143. time.sleep(self.update_interval)
  144. def update_train_log(self, train_output):
  145. """ update train log """
  146. train_log_path = train_output / "train.log"
  147. if train_log_path.exists():
  148. return train_log_path
  149. def update_vdl_log(self, train_output):
  150. """ update visualdl log """
  151. vdl_path = list(train_output.glob("vdlrecords*log"))
  152. if len(vdl_path) >= 1:
  153. return vdl_path[0]
  154. def update_label_dict(self, train_output):
  155. """ update label dict """
  156. dict_path = train_output.joinpath("label_dict.txt")
  157. if not dict_path.exists():
  158. return ""
  159. return dict_path
  160. @try_except_decorator
  161. def update(self):
  162. """ update train result json """
  163. self.processing = True
  164. for i in range(len(self.results)):
  165. self.results[i] = self.update_result(self.results[i],
  166. self.train_outputs[i])
  167. self.save_json()
  168. self.processing = False
  169. def get_model(self, model_name, config_path):
  170. """ initialize the model """
  171. if model_name not in self.models:
  172. config, model = build_model(
  173. model_name,
  174. device=self.global_config.device,
  175. config_path=config_path)
  176. self.models[model_name] = model
  177. return self.models[model_name]
  178. def get_watched_model(self):
  179. """ get the models needed to be watched """
  180. watched_models = [f"last_{i}" for i in range(1, self.last_k + 1)]
  181. watched_models.append("best")
  182. return watched_models
  183. def init_model_content(self):
  184. """ get model content structure """
  185. return {
  186. "score": "",
  187. "pdparams": "",
  188. "pdema": "",
  189. "pdopt": "",
  190. "pdstates": "",
  191. "inference_config": "",
  192. "pdmodel": "",
  193. "pdiparams": "",
  194. "pdiparams.info": ""
  195. }
  196. def update_result(self, result, train_output):
  197. """ update every result """
  198. train_output = Path(train_output).resolve()
  199. config_path = train_output.joinpath("config.yaml").resolve()
  200. if not config_path.exists():
  201. return result
  202. model_name = result["model_name"]
  203. if model_name in self.config_recorder and self.config_recorder[
  204. model_name] != config_path:
  205. result["models"] = self.init_model_pkg()
  206. result["config"] = config_path
  207. self.config_recorder[model_name] = config_path
  208. result["train_log"] = self.update_train_log(train_output)
  209. result["visualdl_log"] = self.update_vdl_log(train_output)
  210. result["label_dict"] = self.update_label_dict(train_output)
  211. model = self.get_model(result["model_name"], config_path)
  212. params_path_list = list(
  213. train_output.glob(".".join([
  214. self.get_ith_ckp_prefix("[0-9]*"), self.get_the_pdparams_suffix(
  215. )
  216. ])))
  217. epoch_ids = []
  218. for params_path in params_path_list:
  219. epoch_id = self.get_epoch_id_by_pdparams_prefix(params_path.stem)
  220. epoch_ids.append(epoch_id)
  221. epoch_ids.sort()
  222. # TODO(gaotingquan): how to avoid that the latest ckp files is being saved
  223. # epoch_ids = epoch_ids[:-1]
  224. for i in range(1, self.last_k + 1):
  225. if len(epoch_ids) < i:
  226. break
  227. self.update_models(result, model, train_output, f"last_{i}",
  228. self.get_ith_ckp_prefix(epoch_ids[-i]))
  229. self.update_models(result, model, train_output, "best",
  230. self.get_best_ckp_prefix())
  231. return result
  232. def update_models(self, result, model, train_output, model_key, ckp_prefix):
  233. """ update info of the models to be saved """
  234. pdparams = train_output.joinpath(".".join(
  235. [ckp_prefix, self.get_the_pdparams_suffix()]))
  236. if pdparams.exists():
  237. recorder_key = f"{train_output.name}_{model_key}"
  238. if model_key != "best" and recorder_key in self.model_recorder and self.model_recorder[
  239. recorder_key] == pdparams:
  240. return
  241. self.model_recorder[recorder_key] = pdparams
  242. pdema = ""
  243. pdema_suffix = self.get_the_pdema_suffix()
  244. if pdema_suffix:
  245. pdema = pdparams.parent.joinpath(".".join(
  246. [ckp_prefix, pdema_suffix]))
  247. if not pdema.exists():
  248. pdema = ""
  249. pdopt = ""
  250. pdopt_suffix = self.get_the_pdopt_suffix()
  251. if pdopt_suffix:
  252. pdopt = pdparams.parent.joinpath(".".join(
  253. [ckp_prefix, pdopt_suffix]))
  254. if not pdopt.exists():
  255. pdopt = ""
  256. pdstates = ""
  257. pdstates_suffix = self.get_the_pdstates_suffix()
  258. if pdstates_suffix:
  259. pdstates = pdparams.parent.joinpath(".".join(
  260. [ckp_prefix, pdstates_suffix]))
  261. if not pdstates.exists():
  262. pdstates = ""
  263. score = self.get_score(Path(pdstates).resolve().as_posix())
  264. result["models"][model_key] = {
  265. "score": score,
  266. "pdparams": pdparams,
  267. "pdema": pdema,
  268. "pdopt": pdopt,
  269. "pdstates": pdstates
  270. }
  271. self.update_inference_model(model, pdparams,
  272. train_output.joinpath(f"{ckp_prefix}"),
  273. result["models"][model_key])
  274. def update_inference_model(self, model, weight_path, export_save_dir,
  275. result_the_model):
  276. """ update inference model """
  277. export_save_dir.mkdir(parents=True, exist_ok=True)
  278. export_result = model.export(
  279. weight_path=weight_path, save_dir=export_save_dir)
  280. if export_result.returncode == 0:
  281. inference_config = export_save_dir.joinpath("inference.yml")
  282. if not inference_config.exists():
  283. inference_config = ""
  284. pdmodel = export_save_dir.joinpath("inference.pdmodel")
  285. pdiparams = export_save_dir.joinpath("inference.pdiparams")
  286. pdiparams_info = export_save_dir.joinpath(
  287. "inference.pdiparams.info")
  288. else:
  289. inference_config = ""
  290. pdmodel = ""
  291. pdiparams = ""
  292. pdiparams_info = ""
  293. result_the_model["inference_config"] = inference_config
  294. result_the_model["pdmodel"] = pdmodel
  295. result_the_model["pdiparams"] = pdiparams
  296. result_the_model["pdiparams.info"] = pdiparams_info
  297. def init_pre_hook(self):
  298. """ hook func that would be called befor init """
  299. pass
  300. def init_post_hook(self):
  301. """ hook func that would be called after init """
  302. pass
  303. @abstractmethod
  304. def get_the_pdparams_suffix(self):
  305. """ get the suffix of pdparams file """
  306. raise NotImplementedError
  307. @abstractmethod
  308. def get_the_pdema_suffix(self):
  309. """ get the suffix of pdema file """
  310. raise NotImplementedError
  311. @abstractmethod
  312. def get_the_pdopt_suffix(self):
  313. """ get the suffix of pdopt file """
  314. raise NotImplementedError
  315. @abstractmethod
  316. def get_the_pdstates_suffix(self):
  317. """ get the suffix of pdstates file """
  318. raise NotImplementedError
  319. @abstractmethod
  320. def get_ith_ckp_prefix(self, epoch_id):
  321. """ get the prefix of the epoch_id checkpoint file """
  322. raise NotImplementedError
  323. @abstractmethod
  324. def get_best_ckp_prefix(self):
  325. """ get the prefix of the best checkpoint file """
  326. raise NotImplementedError
  327. @abstractmethod
  328. def get_score(self, pdstates_path):
  329. """ get the score by pdstates file """
  330. raise NotImplementedError
  331. @abstractmethod
  332. def get_epoch_id_by_pdparams_prefix(self, pdparams_prefix):
  333. """ get the epoch_id by pdparams file """
  334. raise NotImplementedError