You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

train.py 5.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  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. # ============================================================================
  15. """train_criteo."""
  16. import os
  17. import sys
  18. import argparse
  19. from mindspore import context
  20. from mindspore.context import ParallelMode
  21. from mindspore.communication.management import init, get_rank
  22. from mindspore.train.model import Model
  23. from mindspore.train.callback import ModelCheckpoint, CheckpointConfig, TimeMonitor
  24. from mindspore.common import set_seed
  25. from src.autodis import ModelBuilder, AUCMetric
  26. from src.config import DataConfig, ModelConfig, TrainConfig
  27. from src.dataset import create_dataset, DataType
  28. from src.callback import EvalCallBack, LossCallBack
  29. sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  30. parser = argparse.ArgumentParser(description='CTR Prediction')
  31. parser.add_argument('--dataset_path', type=str, default=None, help='Dataset path')
  32. parser.add_argument('--ckpt_path', type=str, default=None, help='Checkpoint path')
  33. parser.add_argument('--eval_file_name', type=str, default="./auc.log",
  34. help='Auc log file path. Default: "./auc.log"')
  35. parser.add_argument('--loss_file_name', type=str, default="./loss.log",
  36. help='Loss log file path. Default: "./loss.log"')
  37. parser.add_argument('--do_eval', type=str, default='True', choices=["True", "False"],
  38. help='Do evaluation or not, only support "True" or "False". Default: "True"')
  39. parser.add_argument('--device_target', type=str, default="Ascend", choices=["Ascend"],
  40. help='Default: Ascend')
  41. args_opt, _ = parser.parse_known_args()
  42. args_opt.do_eval = args_opt.do_eval == 'True'
  43. rank_size = int(os.environ.get("RANK_SIZE", 1))
  44. set_seed(1)
  45. if __name__ == '__main__':
  46. data_config = DataConfig()
  47. model_config = ModelConfig()
  48. train_config = TrainConfig()
  49. if rank_size > 1:
  50. if args_opt.device_target == "Ascend":
  51. device_id = int(os.getenv('DEVICE_ID'))
  52. context.set_context(mode=context.GRAPH_MODE, device_target=args_opt.device_target, device_id=device_id)
  53. context.reset_auto_parallel_context()
  54. context.set_auto_parallel_context(parallel_mode=ParallelMode.DATA_PARALLEL, gradients_mean=True)
  55. init()
  56. rank_id = int(os.environ.get('RANK_ID'))
  57. else:
  58. print("Unsupported device_target ", args_opt.device_target)
  59. exit()
  60. else:
  61. if args_opt.device_target == "Ascend":
  62. device_id = int(os.getenv('DEVICE_ID'))
  63. context.set_context(mode=context.GRAPH_MODE, device_target=args_opt.device_target, device_id=device_id)
  64. else:
  65. print("Unsupported device_target ", args_opt.device_target)
  66. exit()
  67. rank_size = None
  68. rank_id = None
  69. # Init Profiler
  70. ds_train = create_dataset(args_opt.dataset_path,
  71. train_mode=True,
  72. epochs=1,
  73. batch_size=train_config.batch_size,
  74. data_type=DataType(data_config.data_format),
  75. rank_size=rank_size,
  76. rank_id=rank_id)
  77. print("ds_train.size: {}".format(ds_train.get_dataset_size()))
  78. steps_size = ds_train.get_dataset_size()
  79. model_builder = ModelBuilder(ModelConfig, TrainConfig)
  80. train_net, eval_net = model_builder.get_train_eval_net()
  81. auc_metric = AUCMetric()
  82. model = Model(train_net, eval_network=eval_net, metrics={"auc": auc_metric})
  83. time_callback = TimeMonitor(data_size=ds_train.get_dataset_size())
  84. loss_callback = LossCallBack(loss_file_path=args_opt.loss_file_name)
  85. callback_list = [time_callback, loss_callback]
  86. if train_config.save_checkpoint:
  87. if rank_size:
  88. train_config.ckpt_file_name_prefix = train_config.ckpt_file_name_prefix + str(get_rank())
  89. args_opt.ckpt_path = os.path.join(args_opt.ckpt_path, 'ckpt_' + str(get_rank()) + '/')
  90. config_ck = CheckpointConfig(save_checkpoint_steps=train_config.save_checkpoint_steps,
  91. keep_checkpoint_max=train_config.keep_checkpoint_max)
  92. ckpt_cb = ModelCheckpoint(prefix=train_config.ckpt_file_name_prefix,
  93. directory=args_opt.ckpt_path,
  94. config=config_ck)
  95. callback_list.append(ckpt_cb)
  96. if args_opt.do_eval:
  97. ds_eval = create_dataset(args_opt.dataset_path, train_mode=False,
  98. epochs=1,
  99. batch_size=train_config.batch_size,
  100. data_type=DataType(data_config.data_format))
  101. eval_callback = EvalCallBack(model, ds_eval, auc_metric,
  102. eval_file_path=args_opt.eval_file_name)
  103. callback_list.append(eval_callback)
  104. model.train(train_config.train_epochs, ds_train, callbacks=callback_list)