trainer.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. def make_tar_file(self):
  39. """make tar file to package the training outputs"""
  40. tar_path = Path(self.global_config.output) / "best_accuracy.pdparams.tar"
  41. with tarfile.open(tar_path, "w") as tar:
  42. tar.add(self.global_config.output, arcname="best_accuracy.pdparams")
  43. def update_config(self):
  44. """update training config"""
  45. self.pdx_config.update_dataset(self.global_config.dataset_dir, "TSADDataset")
  46. if self.train_config.input_len is not None:
  47. self.pdx_config.update_input_len(self.train_config.input_len)
  48. if self.train_config.time_col is not None:
  49. self.pdx_config.update_basic_info({"time_col": self.train_config.time_col})
  50. if self.train_config.feature_cols is not None:
  51. if isinstance(self.train_config.feature_cols, tuple):
  52. feature_cols = [str(item) for item in self.train_config.feature_cols]
  53. self.pdx_config.update_basic_info({"feature_cols": feature_cols})
  54. else:
  55. self.pdx_config.update_basic_info(
  56. {"feature_cols": self.train_config.feature_cols.split(",")}
  57. )
  58. if self.train_config.label_col is not None:
  59. self.pdx_config.update_basic_info(
  60. {"label_col": self.train_config.label_col}
  61. )
  62. if self.train_config.freq is not None:
  63. try:
  64. self.train_config.freq = int(self.train_config.freq)
  65. except ValueError:
  66. pass
  67. self.pdx_config.update_basic_info({"freq": self.train_config.freq})
  68. if self.train_config.batch_size is not None:
  69. self.pdx_config.update_batch_size(self.train_config.batch_size)
  70. if self.train_config.learning_rate is not None:
  71. self.pdx_config.update_learning_rate(self.train_config.learning_rate)
  72. if self.train_config.epochs_iters is not None:
  73. self.pdx_config.update_epochs(self.train_config.epochs_iters)
  74. if self.global_config.output is not None:
  75. self.pdx_config.update_save_dir(self.global_config.output)
  76. def get_train_kwargs(self) -> dict:
  77. """get key-value arguments of model training function
  78. Returns:
  79. dict: the arguments of training function.
  80. """
  81. train_args = {"device": self.get_device()}
  82. if self.global_config.output is not None:
  83. train_args["save_dir"] = self.global_config.output
  84. return train_args