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 6.3 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  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. """
  16. #################train lstm example on aclImdb########################
  17. """
  18. import argparse
  19. import os
  20. import numpy as np
  21. from src.config import lstm_cfg, lstm_cfg_ascend, lstm_cfg_ascend_8p
  22. from src.dataset import convert_to_mindrecord
  23. from src.dataset import lstm_create_dataset
  24. from src.lr_schedule import get_lr
  25. from src.lstm import SentimentNet
  26. from mindspore import Tensor, nn, Model, context
  27. from mindspore.nn import Accuracy
  28. from mindspore.train.callback import LossMonitor, CheckpointConfig, ModelCheckpoint, TimeMonitor
  29. from mindspore.train.serialization import load_param_into_net, load_checkpoint
  30. from mindspore.communication.management import init, get_rank
  31. from mindspore.context import ParallelMode
  32. if __name__ == '__main__':
  33. parser = argparse.ArgumentParser(description='MindSpore LSTM Example')
  34. parser.add_argument('--preprocess', type=str, default='false', choices=['true', 'false'],
  35. help='whether to preprocess data.')
  36. parser.add_argument('--aclimdb_path', type=str, default="./aclImdb",
  37. help='path where the dataset is stored.')
  38. parser.add_argument('--glove_path', type=str, default="./glove",
  39. help='path where the GloVe is stored.')
  40. parser.add_argument('--preprocess_path', type=str, default="./preprocess",
  41. help='path where the pre-process data is stored.')
  42. parser.add_argument('--ckpt_path', type=str, default="./",
  43. help='the path to save the checkpoint file.')
  44. parser.add_argument('--pre_trained', type=str, default=None,
  45. help='the pretrained checkpoint file path.')
  46. parser.add_argument('--device_target', type=str, default="Ascend", choices=['GPU', 'CPU', 'Ascend'],
  47. help='the target device to run, support "GPU", "CPU". Default: "Ascend".')
  48. parser.add_argument("--device_num", type=int, default=1, help="Use device nums, default is 1.")
  49. parser.add_argument("--distribute", type=str, default="false", choices=["true", "false"],
  50. help="Run distribute, default is false.")
  51. args = parser.parse_args()
  52. context.set_context(
  53. mode=context.GRAPH_MODE,
  54. save_graphs=False,
  55. device_target=args.device_target)
  56. rank = 0
  57. device_num = 1
  58. if args.device_target == 'Ascend':
  59. cfg = lstm_cfg_ascend
  60. if args.distribute == "true":
  61. cfg = lstm_cfg_ascend_8p
  62. init()
  63. device_num = args.device_num
  64. rank = get_rank()
  65. context.reset_auto_parallel_context()
  66. context.set_auto_parallel_context(parallel_mode=ParallelMode.DATA_PARALLEL, gradients_mean=True,
  67. device_num=device_num)
  68. else:
  69. cfg = lstm_cfg
  70. if args.preprocess == "true":
  71. print("============== Starting Data Pre-processing ==============")
  72. convert_to_mindrecord(cfg.embed_size, args.aclimdb_path, args.preprocess_path, args.glove_path)
  73. embedding_table = np.loadtxt(os.path.join(args.preprocess_path, "weight.txt")).astype(np.float32)
  74. # DynamicRNN in this network on Ascend platform only support the condition that the shape of input_size
  75. # and hiddle_size is multiples of 16, this problem will be solved later.
  76. if args.device_target == 'Ascend':
  77. pad_num = int(np.ceil(cfg.embed_size / 16) * 16 - cfg.embed_size)
  78. if pad_num > 0:
  79. embedding_table = np.pad(embedding_table, [(0, 0), (0, pad_num)], 'constant')
  80. cfg.embed_size = int(np.ceil(cfg.embed_size / 16) * 16)
  81. network = SentimentNet(vocab_size=embedding_table.shape[0],
  82. embed_size=cfg.embed_size,
  83. num_hiddens=cfg.num_hiddens,
  84. num_layers=cfg.num_layers,
  85. bidirectional=cfg.bidirectional,
  86. num_classes=cfg.num_classes,
  87. weight=Tensor(embedding_table),
  88. batch_size=cfg.batch_size)
  89. # pre_trained
  90. if args.pre_trained:
  91. load_param_into_net(network, load_checkpoint(args.pre_trained))
  92. ds_train = lstm_create_dataset(args.preprocess_path, cfg.batch_size, 1, device_num=device_num, rank=rank)
  93. loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True, reduction='mean')
  94. if cfg.dynamic_lr:
  95. lr = Tensor(get_lr(global_step=cfg.global_step,
  96. lr_init=cfg.lr_init, lr_end=cfg.lr_end, lr_max=cfg.lr_max,
  97. warmup_epochs=cfg.warmup_epochs,
  98. total_epochs=cfg.num_epochs,
  99. steps_per_epoch=ds_train.get_dataset_size(),
  100. lr_adjust_epoch=cfg.lr_adjust_epoch))
  101. else:
  102. lr = cfg.learning_rate
  103. opt = nn.Momentum(network.trainable_params(), lr, cfg.momentum)
  104. loss_cb = LossMonitor()
  105. model = Model(network, loss, opt, {'acc': Accuracy()})
  106. print("============== Starting Training ==============")
  107. config_ck = CheckpointConfig(save_checkpoint_steps=cfg.save_checkpoint_steps,
  108. keep_checkpoint_max=cfg.keep_checkpoint_max)
  109. ckpoint_cb = ModelCheckpoint(prefix="lstm", directory=args.ckpt_path, config=config_ck)
  110. time_cb = TimeMonitor(data_size=ds_train.get_dataset_size())
  111. if args.device_target == "CPU":
  112. model.train(cfg.num_epochs, ds_train, callbacks=[time_cb, ckpoint_cb, loss_cb], dataset_sink_mode=False)
  113. else:
  114. model.train(cfg.num_epochs, ds_train, callbacks=[time_cb, ckpoint_cb, loss_cb])
  115. print("============== Training Success ==============")