trainer.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  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 tarfile
  16. from pathlib import Path
  17. from ..base import BaseTrainer
  18. from .model_list import MODELS
  19. class TSCLSTrainer(BaseTrainer):
  20. """TS Classification Model Trainer"""
  21. entities = MODELS
  22. def train(self):
  23. """firstly, update and dump train config, then train model"""
  24. # XXX: using super().train() instead when the train_hook() is supported.
  25. os.makedirs(self.global_config.output, exist_ok=True)
  26. self.update_config()
  27. self.dump_config()
  28. train_args = self.get_train_kwargs()
  29. export_with_pir = self.global_config.get("export_with_pir", False) or os.getenv(
  30. "FLAGS_json_format_model"
  31. ) in ["1", "True"]
  32. train_args.update(
  33. {
  34. "uniform_output_enabled": self.train_config.get(
  35. "uniform_output_enabled", True
  36. ),
  37. "export_with_pir": export_with_pir,
  38. }
  39. )
  40. if self.benchmark_config is not None:
  41. train_args.update({"benchmark": self.benchmark_config})
  42. train_result = self.pdx_model.train(**train_args)
  43. assert (
  44. train_result.returncode == 0
  45. ), f"Encountered an unexpected error({train_result.returncode}) in \
  46. training!"
  47. self.make_tar_file()
  48. def make_tar_file(self):
  49. """make tar file to package the training outputs"""
  50. tar_path = Path(self.global_config.output) / "best_accuracy.pdparams.tar"
  51. with tarfile.open(tar_path, "w") as tar:
  52. tar.add(self.global_config.output, arcname="best_accuracy.pdparams")
  53. def update_config(self):
  54. """update training config"""
  55. self.pdx_config.update_dataset(self.global_config.dataset_dir, "TSCLSDataset")
  56. if self.train_config.time_col is not None:
  57. self.pdx_config.update_basic_info({"time_col": self.train_config.time_col})
  58. if self.train_config.target_cols is not None:
  59. self.pdx_config.update_basic_info(
  60. {"target_cols": self.train_config.target_cols.split(",")}
  61. )
  62. if self.train_config.group_id is not None:
  63. self.pdx_config.update_basic_info({"group_id": self.train_config.group_id})
  64. if self.train_config.static_cov_cols is not None:
  65. self.pdx_config.update_basic_info(
  66. {"static_cov_cols": self.train_config.static_cov_cols}
  67. )
  68. if self.train_config.freq is not None:
  69. try:
  70. self.train_config.freq = int(self.train_config.freq)
  71. except ValueError:
  72. pass
  73. self.pdx_config.update_basic_info({"freq": self.train_config.freq})
  74. if self.train_config.batch_size is not None:
  75. self.pdx_config.update_batch_size(self.train_config.batch_size)
  76. if self.train_config.learning_rate is not None:
  77. self.pdx_config.update_learning_rate(self.train_config.learning_rate)
  78. if self.train_config.epochs_iters is not None:
  79. self.pdx_config.update_epochs(self.train_config.epochs_iters)
  80. if self.train_config.log_interval is not None:
  81. self.pdx_config.update_log_interval(self.train_config.log_interval)
  82. if self.train_config.get("dy2st", False):
  83. self.pdx_config.update_to_static(self.train_config.dy2st)
  84. if self.global_config.output is not None:
  85. self.pdx_config.update_save_dir(self.global_config.output)
  86. def get_train_kwargs(self) -> dict:
  87. """get key-value arguments of model training function
  88. Returns:
  89. dict: the arguments of training function.
  90. """
  91. train_args = {"device": self.get_device(using_device_number=1)}
  92. if self.global_config.output is not None:
  93. train_args["save_dir"] = self.global_config.output
  94. return train_args