trainer.py 3.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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 json
  16. import time
  17. from pathlib import Path
  18. import tarfile
  19. import lazy_paddle as paddle
  20. from ..base import BaseTrainer
  21. from ...utils.config import AttrDict
  22. from .model_list import MODELS
  23. class TSADTrainer(BaseTrainer):
  24. """TS Anomaly Detection Model Trainer"""
  25. entities = MODELS
  26. def train(self):
  27. """firstly, update and dump train config, then train model"""
  28. # XXX: using super().train() instead when the train_hook() is supported.
  29. os.makedirs(self.global_config.output, exist_ok=True)
  30. self.update_config()
  31. self.dump_config()
  32. train_result = self.pdx_model.train(**self.get_train_kwargs())
  33. assert (
  34. train_result.returncode == 0
  35. ), f"Encountered an unexpected error({train_result.returncode}) in \
  36. training!"
  37. self.make_tar_file()
  38. self.deamon.stop()
  39. def make_tar_file(self):
  40. """make tar file to package the training outputs"""
  41. tar_path = Path(self.global_config.output) / "best_accuracy.pdparams.tar"
  42. with tarfile.open(tar_path, "w") as tar:
  43. tar.add(self.global_config.output, arcname="best_accuracy.pdparams")
  44. def update_config(self):
  45. """update training config"""
  46. self.pdx_config.update_dataset(self.global_config.dataset_dir, "TSADDataset")
  47. if self.train_config.input_len is not None:
  48. self.pdx_config.update_input_len(self.train_config.input_len)
  49. if self.train_config.time_col is not None:
  50. self.pdx_config.update_basic_info({"time_col": self.train_config.time_col})
  51. if self.train_config.feature_cols is not None:
  52. if isinstance(self.train_config.feature_cols, tuple):
  53. feature_cols = [str(item) for item in self.train_config.feature_cols]
  54. self.pdx_config.update_basic_info({"feature_cols": feature_cols})
  55. else:
  56. self.pdx_config.update_basic_info(
  57. {"feature_cols": self.train_config.feature_cols.split(",")}
  58. )
  59. if self.train_config.label_col is not None:
  60. self.pdx_config.update_basic_info(
  61. {"label_col": self.train_config.label_col}
  62. )
  63. if self.train_config.freq is not None:
  64. try:
  65. self.train_config.freq = int(self.train_config.freq)
  66. except ValueError:
  67. pass
  68. self.pdx_config.update_basic_info({"freq": self.train_config.freq})
  69. if self.train_config.batch_size is not None:
  70. self.pdx_config.update_batch_size(self.train_config.batch_size)
  71. if self.train_config.learning_rate is not None:
  72. self.pdx_config.update_learning_rate(self.train_config.learning_rate)
  73. if self.train_config.epochs_iters is not None:
  74. self.pdx_config.update_epochs(self.train_config.epochs_iters)
  75. if self.global_config.output is not None:
  76. self.pdx_config.update_save_dir(self.global_config.output)
  77. def get_train_kwargs(self) -> dict:
  78. """get key-value arguments of model training function
  79. Returns:
  80. dict: the arguments of training function.
  81. """
  82. train_args = {"device": self.get_device()}
  83. if self.global_config.output is not None:
  84. train_args["save_dir"] = self.global_config.output
  85. return train_args