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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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. """FastText for train"""
  16. import os
  17. import time
  18. import argparse
  19. from mindspore import context
  20. from mindspore.nn.optim import Adam
  21. from mindspore.common import set_seed
  22. from mindspore.train.model import Model
  23. import mindspore.common.dtype as mstype
  24. from mindspore.common.tensor import Tensor
  25. from mindspore.context import ParallelMode
  26. from mindspore.train.callback import Callback, TimeMonitor
  27. from mindspore.communication import management as MultiAscend
  28. from mindspore.train.callback import CheckpointConfig, ModelCheckpoint
  29. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  30. from src.load_dataset import load_dataset
  31. from src.lr_schedule import polynomial_decay_scheduler
  32. from src.fasttext_train import FastTextTrainOneStepCell, FastTextNetWithLoss
  33. parser = argparse.ArgumentParser()
  34. parser.add_argument('--data_path', type=str, required=True, help='FastText input data file path.')
  35. parser.add_argument('--data_name', type=str, required=True, default='ag', help='dataset name. eg. ag, dbpedia')
  36. args = parser.parse_args()
  37. if args.data_name == "ag":
  38. from src.config import config_ag as config
  39. elif args.data_name == 'dbpedia':
  40. from src.config import config_db as config
  41. elif args.data_name == 'yelp_p':
  42. from src.config import config_yelpp as config
  43. def get_ms_timestamp():
  44. t = time.time()
  45. return int(round(t * 1000))
  46. set_seed(5)
  47. time_stamp_init = False
  48. time_stamp_first = 0
  49. rank_id = os.getenv('DEVICE_ID')
  50. context.set_context(
  51. mode=context.GRAPH_MODE,
  52. save_graphs=False,
  53. device_target="Ascend")
  54. class LossCallBack(Callback):
  55. """
  56. Monitor the loss in training.
  57. If the loss is NAN or INF terminating training.
  58. Note:
  59. If per_print_times is 0 do not print loss.
  60. Args:
  61. per_print_times (int): Print loss every times. Default: 1.
  62. """
  63. def __init__(self, per_print_times=1, rank_ids=0):
  64. super(LossCallBack, self).__init__()
  65. if not isinstance(per_print_times, int) or per_print_times < 0:
  66. raise ValueError("print_step must be int and >= 0.")
  67. self._per_print_times = per_print_times
  68. self.rank_id = rank_ids
  69. global time_stamp_init, time_stamp_first
  70. if not time_stamp_init:
  71. time_stamp_first = get_ms_timestamp()
  72. time_stamp_init = True
  73. def step_end(self, run_context):
  74. """Monitor the loss in training."""
  75. global time_stamp_first
  76. time_stamp_current = get_ms_timestamp()
  77. cb_params = run_context.original_args()
  78. print("time: {}, epoch: {}, step: {}, outputs are {}".format(time_stamp_current - time_stamp_first,
  79. cb_params.cur_epoch_num,
  80. cb_params.cur_step_num,
  81. str(cb_params.net_outputs)))
  82. with open("./loss_{}.log".format(self.rank_id), "a+") as f:
  83. f.write("time: {}, epoch: {}, step: {}, loss: {}".format(
  84. time_stamp_current - time_stamp_first,
  85. cb_params.cur_epoch_num,
  86. cb_params.cur_step_num,
  87. str(cb_params.net_outputs.asnumpy())))
  88. f.write('\n')
  89. def _build_training_pipeline(pre_dataset):
  90. """
  91. Build training pipeline
  92. Args:
  93. pre_dataset: preprocessed dataset
  94. """
  95. net_with_loss = FastTextNetWithLoss(config.vocab_size, config.embedding_dims, config.num_class)
  96. net_with_loss.init_parameters_data()
  97. if config.pretrain_ckpt_dir:
  98. parameter_dict = load_checkpoint(config.pretrain_ckpt_dir)
  99. load_param_into_net(net_with_loss, parameter_dict)
  100. if pre_dataset is None:
  101. raise ValueError("pre-process dataset must be provided")
  102. #get learning rate
  103. update_steps = config.epoch * pre_dataset.get_dataset_size()
  104. decay_steps = pre_dataset.get_dataset_size()
  105. rank_size = os.getenv("RANK_SIZE")
  106. if isinstance(rank_size, int):
  107. raise ValueError("RANK_SIZE must be integer")
  108. if rank_size is not None and int(rank_size) > 1:
  109. base_lr = config.lr
  110. else:
  111. base_lr = config.lr / 10
  112. print("+++++++++++Total update steps ", update_steps)
  113. lr = Tensor(polynomial_decay_scheduler(lr=base_lr,
  114. min_lr=config.min_lr,
  115. decay_steps=decay_steps,
  116. total_update_num=update_steps,
  117. warmup_steps=config.warmup_steps,
  118. power=config.poly_lr_scheduler_power), dtype=mstype.float32)
  119. optimizer = Adam(net_with_loss.trainable_params(), lr, beta1=0.9, beta2=0.999)
  120. net_with_grads = FastTextTrainOneStepCell(net_with_loss, optimizer=optimizer)
  121. net_with_grads.set_train(True)
  122. model = Model(net_with_grads)
  123. loss_monitor = LossCallBack(rank_ids=rank_id)
  124. dataset_size = pre_dataset.get_dataset_size()
  125. time_monitor = TimeMonitor(data_size=dataset_size)
  126. ckpt_config = CheckpointConfig(save_checkpoint_steps=decay_steps * config.epoch,
  127. keep_checkpoint_max=config.keep_ckpt_max)
  128. callbacks = [time_monitor, loss_monitor]
  129. if rank_size is None or int(rank_size) == 1:
  130. ckpt_callback = ModelCheckpoint(prefix='fasttext',
  131. directory=os.path.join('./', 'ckpt_{}'.format(os.getenv("DEVICE_ID"))),
  132. config=ckpt_config)
  133. callbacks.append(ckpt_callback)
  134. if rank_size is not None and int(rank_size) > 1 and MultiAscend.get_rank() % 8 == 0:
  135. ckpt_callback = ModelCheckpoint(prefix='fasttext',
  136. directory=os.path.join('./', 'ckpt_{}'.format(os.getenv("DEVICE_ID"))),
  137. config=ckpt_config)
  138. callbacks.append(ckpt_callback)
  139. print("Prepare to Training....")
  140. epoch_size = pre_dataset.get_repeat_count()
  141. print("Epoch size ", epoch_size)
  142. if os.getenv("RANK_SIZE") is not None and int(os.getenv("RANK_SIZE")) > 1:
  143. print(f" | Rank {MultiAscend.get_rank()} Call model train.")
  144. model.train(epoch=config.epoch, train_dataset=pre_dataset, callbacks=callbacks, dataset_sink_mode=False)
  145. def train_single(input_file_path):
  146. """
  147. Train model on single device
  148. Args:
  149. input_file_path: preprocessed dataset path
  150. """
  151. print("Staring training on single device.")
  152. preprocessed_data = load_dataset(dataset_path=input_file_path,
  153. batch_size=config.batch_size,
  154. epoch_count=config.epoch_count,
  155. bucket=config.buckets)
  156. _build_training_pipeline(preprocessed_data)
  157. def set_parallel_env():
  158. context.reset_auto_parallel_context()
  159. MultiAscend.init()
  160. context.set_auto_parallel_context(parallel_mode=ParallelMode.DATA_PARALLEL,
  161. device_num=MultiAscend.get_group_size(),
  162. gradients_mean=True)
  163. def train_paralle(input_file_path):
  164. """
  165. Train model on multi device
  166. Args:
  167. input_file_path: preprocessed dataset path
  168. """
  169. set_parallel_env()
  170. print("Starting traning on multiple devices. |~ _ ~| |~ _ ~| |~ _ ~| |~ _ ~|")
  171. preprocessed_data = load_dataset(dataset_path=input_file_path,
  172. batch_size=config.batch_size,
  173. epoch_count=config.epoch_count,
  174. rank_size=MultiAscend.get_group_size(),
  175. rank_id=MultiAscend.get_rank(),
  176. bucket=config.buckets,
  177. shuffle=False)
  178. _build_training_pipeline(preprocessed_data)
  179. if __name__ == "__main__":
  180. _rank_size = os.getenv("RANK_SIZE")
  181. if _rank_size is not None and int(_rank_size) > 1:
  182. train_paralle(args.data_path)
  183. else:
  184. train_single(args.data_path)