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.0 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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. """Training entry file"""
  16. import os
  17. import argparse
  18. from absl import logging
  19. from mindspore.train.callback import ModelCheckpoint, CheckpointConfig, LossMonitor, TimeMonitor
  20. from mindspore import context, Model
  21. from mindspore.context import ParallelMode
  22. from mindspore.communication.management import get_rank, get_group_size, init
  23. from src.dataset import create_dataset
  24. from src.ncf import NCFModel, NetWithLossClass, TrainStepWrap
  25. from config import cfg
  26. logging.set_verbosity(logging.INFO)
  27. parser = argparse.ArgumentParser(description='NCF')
  28. parser.add_argument("--data_path", type=str, default="./dataset/") # The location of the input data.
  29. parser.add_argument("--dataset", type=str, default="ml-1m", choices=["ml-1m", "ml-20m"]) # Dataset to be trained and evaluated. ["ml-1m", "ml-20m"]
  30. parser.add_argument("--train_epochs", type=int, default=14) # The number of epochs used to train.
  31. parser.add_argument("--batch_size", type=int, default=256) # Batch size for training and evaluation
  32. parser.add_argument("--num_neg", type=int, default=4) # The Number of negative instances to pair with a positive instance.
  33. parser.add_argument("--output_path", type=str, default="./output/") # The location of the output file.
  34. parser.add_argument("--loss_file_name", type=str, default="loss.log") # Loss output file.
  35. parser.add_argument("--checkpoint_path", type=str, default="./checkpoint/") # The location of the checkpoint file.
  36. parser.add_argument('--device_target', type=str, default='Ascend', choices=['Ascend', 'GPU'],
  37. help='device where the code will be implemented. (Default: Ascend)')
  38. parser.add_argument('--device_id', type=int, default=1, help='device id of GPU or Ascend. (Default: None)')
  39. parser.add_argument('--is_distributed', type=int, default=0, help='if multi device')
  40. parser.add_argument('--rank', type=int, default=0, help='local rank of distributed')
  41. parser.add_argument('--group_size', type=int, default=1, help='world size of distributed')
  42. args = parser.parse_args()
  43. def test_train():
  44. """train entry method"""
  45. if args.is_distributed:
  46. if args.device_target == "Ascend":
  47. init()
  48. context.set_context(device_id=args.device_id)
  49. elif args.device_target == "GPU":
  50. init()
  51. args.rank = get_rank()
  52. args.group_size = get_group_size()
  53. device_num = args.group_size
  54. context.reset_auto_parallel_context()
  55. context.set_auto_parallel_context(device_num=device_num, parallel_mode=ParallelMode.DATA_PARALLEL,
  56. parameter_broadcast=True, gradients_mean=True)
  57. else:
  58. context.set_context(device_id=args.device_id)
  59. context.set_context(mode=context.GRAPH_MODE, device_target=args.device_target)
  60. if not os.path.exists(args.output_path):
  61. os.makedirs(args.output_path)
  62. layers = cfg.layers
  63. num_factors = cfg.num_factors
  64. epochs = args.train_epochs
  65. ds_train, num_train_users, num_train_items = create_dataset(test_train=True, data_dir=args.data_path,
  66. dataset=args.dataset, train_epochs=1,
  67. batch_size=args.batch_size, num_neg=args.num_neg)
  68. print("ds_train.size: {}".format(ds_train.get_dataset_size()))
  69. ncf_net = NCFModel(num_users=num_train_users,
  70. num_items=num_train_items,
  71. num_factors=num_factors,
  72. model_layers=layers,
  73. mf_regularization=0,
  74. mlp_reg_layers=[0.0, 0.0, 0.0, 0.0],
  75. mf_dim=16)
  76. loss_net = NetWithLossClass(ncf_net)
  77. train_net = TrainStepWrap(loss_net)
  78. train_net.set_train()
  79. model = Model(train_net)
  80. callback = LossMonitor(per_print_times=ds_train.get_dataset_size())
  81. ckpt_config = CheckpointConfig(save_checkpoint_steps=(4970845+args.batch_size-1)//(args.batch_size),
  82. keep_checkpoint_max=100)
  83. ckpoint_cb = ModelCheckpoint(prefix='NCF', directory=args.checkpoint_path, config=ckpt_config)
  84. model.train(epochs,
  85. ds_train,
  86. callbacks=[TimeMonitor(ds_train.get_dataset_size()), callback, ckpoint_cb],
  87. dataset_sink_mode=True)
  88. if __name__ == '__main__':
  89. test_train()