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.

run_translation.py 16 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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. GPT-2 finetune and evaluation script for Translation task.
  17. """
  18. import argparse
  19. import time
  20. from mindspore import context
  21. from mindspore.nn.wrap.loss_scale import DynamicLossScaleUpdateCell
  22. from mindspore.nn import AdamWeightDecay, Lamb, Momentum
  23. from mindspore.train.model import Model
  24. from mindspore.train.callback import CheckpointConfig, ModelCheckpoint, TimeMonitor, LossMonitor
  25. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  26. from src.GPT2ForTranslation import GPT2TranslationModel
  27. from src.gpt2_for_finetune import GPT2FinetuneCell, GPT2Translation
  28. from src.finetune_eval_config import cfg, gpt2_net_cfg
  29. from src.dataset import create_language_model_dataset
  30. from src.utils.lr_schedule import GPT2LearningRate
  31. from src.utils.tokenization import Tokenizer
  32. from src.utils.metric_method import BLEU
  33. from src.GPT2_generation import GenerateForTranslation
  34. def do_train(dataset=None, network=None, load_checkpoint_path="", save_checkpoint_path="", epoch_num=1):
  35. """
  36. Do train
  37. Args:
  38. dataset: the train dataset.
  39. network: the network with loss
  40. load_checkpoint_path: the file path which saved pretrained model checkpoint.
  41. save_checkpoint_path: the file path which will save finetuned model checkpoint.
  42. epoch_num: the number of epoch.
  43. """
  44. if load_checkpoint_path == "":
  45. raise ValueError("Pretrain model missed, finetune task must load pretrain model!")
  46. steps_per_epoch = dataset.get_dataset_size()
  47. # optimizer
  48. if cfg.optimizer == 'AdamWeightDecay':
  49. lr_schedule = GPT2LearningRate(learning_rate=cfg.AdamWeightDecay.learning_rate,
  50. end_learning_rate=cfg.AdamWeightDecay.end_learning_rate,
  51. warmup_steps=int(steps_per_epoch * epoch_num * 0.1),
  52. decay_steps=steps_per_epoch * epoch_num,
  53. power=cfg.AdamWeightDecay.power)
  54. params = network.trainable_params()
  55. decay_params = list(filter(cfg.AdamWeightDecay.decay_filter, params))
  56. other_params = list(filter(lambda x: not cfg.AdamWeightDecay.decay_filter(x), params))
  57. group_params = [{'params': decay_params, 'weight_decay': cfg.AdamWeightDecay.weight_decay},
  58. {'params': other_params, 'weight_decay': 0.0}]
  59. optimizer = AdamWeightDecay(group_params, lr_schedule, eps=cfg.AdamWeightDecay.eps)
  60. elif cfg.optimizer == 'Lamb':
  61. lr_schedule = GPT2LearningRate(learning_rate=cfg.Lamb.learning_rate,
  62. end_learning_rate=cfg.Lamb.end_learning_rate,
  63. warmup_steps=int(steps_per_epoch * epoch_num * 0.1),
  64. decay_steps=steps_per_epoch * epoch_num,
  65. power=cfg.Lamb.power)
  66. optimizer = Lamb(network.trainable_params(), lr_schedule)
  67. elif cfg.optimizer == 'Momentum':
  68. optimizer = Momentum(network.trainable_params(), cfg.Momentum.learning_rate, cfg.Momentum.momentum)
  69. else:
  70. raise Exception("Optimizer not supported. support: [AdamWeightDecay, Lamb, Momentum]")
  71. # load checkpoint into network
  72. ckpt_config = CheckpointConfig(save_checkpoint_steps=steps_per_epoch, keep_checkpoint_max=1)
  73. prefix_name = "gpt2_translation_" + str(cfg.gpt2_network) + "_" + str(cfg.optimizer) + "_" \
  74. + str(epoch_num) + "_bs" + str(gpt2_net_cfg.batch_size)
  75. ckpoint_cb = ModelCheckpoint(prefix=prefix_name,
  76. directory=None if save_checkpoint_path == "" else save_checkpoint_path,
  77. config=ckpt_config)
  78. param_dict = load_checkpoint(load_checkpoint_path)
  79. final_param_dict = {}
  80. for name, _ in param_dict.items():
  81. final_param_dict['gpt2.gpt2.' + name] = param_dict[name]
  82. final_param_dict['gpt2.dense1.weight'] = param_dict['gpt2_embedding_lookup.embedding_table']
  83. load_param_into_net(network, final_param_dict)
  84. print("Load the pretrained parameter successfully! \n")
  85. update_cell = DynamicLossScaleUpdateCell(loss_scale_value=2 ** 32, scale_factor=2, scale_window=1000)
  86. netwithgrads = GPT2FinetuneCell(network, optimizer=optimizer, scale_update_cell=update_cell)
  87. netwithgrads.set_train(True)
  88. loss_cb = LossMonitor(per_print_times=1)
  89. model = Model(netwithgrads)
  90. callbacks = [TimeMonitor(dataset.get_dataset_size()), loss_cb, ckpoint_cb]
  91. print("=================== Starting Training For Translation Task ====================")
  92. model.train(epoch_num, dataset, callbacks=callbacks, dataset_sink_mode=False)
  93. print("=================== Translation Training Success ====================")
  94. def eval_result_print(metric="BLEU", callback=None):
  95. """ print eval result"""
  96. if metric == "BLEU":
  97. print(" | BLEU: {:.6f}".format(callback.bleu / float(callback.total_num)))
  98. else:
  99. raise ValueError("metric method '{}' not supported, support: [BLEU]. ".format(str(metric)))
  100. def do_eval(dataset=None, network=None, metric=None, load_checkpoint_path="", eval_type=None, tokenizer_file_path="",
  101. generate_length=1, top_k=1, top_p=1.0, temperature=1.0):
  102. """
  103. Do evaluation on Translation
  104. Args:
  105. dataset: the eval dataset.
  106. network: the network with loss.
  107. metric: the evaluation method.
  108. load_checkpoint_path: the file path which saved finetune model checkpoint.
  109. """
  110. if load_checkpoint_path == "":
  111. raise ValueError("Finetune model missed, evaluation task must load finetune model!")
  112. if metric.lower() == "bleu":
  113. print("Prepare to calculate the BLEU score ...")
  114. gpt2_translation = network(config=gpt2_net_cfg,
  115. is_training=False,
  116. use_one_hot_embeddings=False)
  117. gpt2_translation.set_train(False)
  118. param_dict = load_checkpoint(load_checkpoint_path)
  119. if eval_type == "zero-shot":
  120. final_param_dict = {}
  121. for name, _ in param_dict.items():
  122. final_param_dict['gpt2.' + name] = param_dict[name]
  123. final_param_dict['dense1.weight'] = param_dict['gpt2_embedding_lookup.embedding_table']
  124. load_param_into_net(gpt2_translation, final_param_dict)
  125. print("load pretrained parameter successfully!\n")
  126. elif eval_type == "finetuned":
  127. load_param_into_net(gpt2_translation, param_dict)
  128. print("load finetuned parameter successfully!\n")
  129. else:
  130. raise ValueError("Evaluation type missed, eval_type should be [zero-shot, finetuned]")
  131. model = Model(gpt2_translation)
  132. tokenizer = Tokenizer(vocab_file=tokenizer_file_path + 'gpt2-vocab.json',
  133. merge_file=tokenizer_file_path + 'gpt2-merges.txt')
  134. callback = BLEU(tokenizer)
  135. translation_generator = GenerateForTranslation(decoder=model,
  136. config=gpt2_net_cfg,
  137. tokenizer=tokenizer,
  138. generate_length=1,
  139. use_hint=True,
  140. select_first_sentence=True,
  141. topk_num=top_k,
  142. topp_prob=float(top_p),
  143. temperature=float(temperature)
  144. )
  145. columns_list = ["input_ids", "input_mask", "label_ids"]
  146. print("==================== [BLEU] Testing ====================")
  147. num_data = 1
  148. for data in dataset.create_dict_iterator():
  149. input_data = []
  150. for i in columns_list:
  151. input_data.append(data[i])
  152. input_ids, input_mask, label_ids = input_data
  153. print("| Data count: {}".format(num_data * gpt2_net_cfg.batch_size))
  154. print("input_ids shape: {}".format(input_ids.shape))
  155. print("input_mask shape: {}".format(input_mask.shape))
  156. print("label_ids shape: {}".format(label_ids.shape))
  157. ts_predict_list, ref_list = translation_generator.generate_for_translation(input_ids)
  158. print("| Batch Reference translation:\n{}\n".format(ref_list))
  159. if ref_list == '' or ref_list is None:
  160. print("Sorry ref_list is None, skip it!")
  161. continue
  162. else:
  163. print(" | Batch Predict translation:\n{}\n".format(ts_predict_list))
  164. callback.update(ref_list, ts_predict_list)
  165. num_data += 1
  166. print("\n\n")
  167. print("**************************************************************")
  168. eval_result_print(metric, callback)
  169. print("********************** Testing Finished **********************")
  170. else:
  171. raise ValueError("metric method not supported in translation, support: [BLEU]")
  172. def run_translation():
  173. """
  174. run translation task
  175. """
  176. parser = argparse.ArgumentParser(description="Finetune and Evaluate translation")
  177. parser.add_argument("--device_target", type=str, default="Ascend",
  178. help="Device type. Default: Ascend.")
  179. parser.add_argument("--device_id", type=int, default=0,
  180. help="ID of target device. ")
  181. parser.add_argument("--metric_method", type=str, default="BLEU",
  182. help="The eval method including [BLEU]. Default: BLEU.")
  183. parser.add_argument("--do_train", type=str, default="false",
  184. help="Enable train. Default: false.")
  185. parser.add_argument("--do_eval", type=str, default="true",
  186. help="Enable evaluation. Default: false.")
  187. parser.add_argument("--eval_type", type=str, default="zero-shot",
  188. help="The type of evaluation including [zero-shot, finetuned]. Default: zero-shot.")
  189. parser.add_argument("--epoch_num", type=int, default=1,
  190. help="Epoch number. Default: 1.")
  191. parser.add_argument("--train_data_shuffle", type=str, default="true",
  192. help="Enable train data shuffle. Default: true.")
  193. parser.add_argument("--eval_data_shuffle", type=str, default="false",
  194. help="Enable eval data shuffle. Default: false.")
  195. parser.add_argument("--save_finetune_ckpt_path", type=str, default="",
  196. help="Save the checkpoint path.")
  197. parser.add_argument("--load_pretrain_ckpt_path", type=str, default="",
  198. help="Load the checkpoint file path.")
  199. parser.add_argument("--load_finetune_ckpt_path", type=str, default="",
  200. help="Load the checkpoint file path.")
  201. parser.add_argument("--train_data_file_path", type=str, default="",
  202. help="Data path, it is better to use absolute path")
  203. parser.add_argument("--eval_data_file_path", type=str, default="",
  204. help="Data path, it is better to use absolute path")
  205. parser.add_argument("--tokenizer_file_path", type=str, default="",
  206. help="pretrained vocab and merge file path.")
  207. parser.add_argument("--generate_length", type=int, default=150,
  208. help="The generation length of translation sentence.")
  209. parser.add_argument("--top_k", type=int, default=1,
  210. help="Parameter for Top-K sampling.")
  211. parser.add_argument("--top_p", type=str, default="1.0",
  212. help="parameter for Top-P sampling.")
  213. parser.add_argument("--temperature", type=str, default="1.0",
  214. help="Parameter for generation, greater if generation more diverse. ")
  215. args_opt = parser.parse_args()
  216. epoch_num = args_opt.epoch_num
  217. metric = args_opt.metric_method
  218. save_finetune_ckpt_path = args_opt.save_finetune_ckpt_path
  219. load_finetune_ckpt_path = args_opt.load_finetune_ckpt_path
  220. load_pretrain_ckpt_path = args_opt.load_pretrain_ckpt_path
  221. if args_opt.do_train.lower() == "false" and args_opt.do_eval.lower() == "false":
  222. raise ValueError("At least one of 'do_train' or 'do_eval' must be true")
  223. if args_opt.do_train.lower() == "true" and args_opt.train_data_file_path == "":
  224. raise ValueError("'train_data_file_path' must be set when do finetune task")
  225. if args_opt.do_eval.lower() == "true" and args_opt.eval_data_file_path == "":
  226. raise ValueError("'eval_data_file_path' must be set when do evaluation task")
  227. device_target = args_opt.device_target
  228. if device_target == "Ascend":
  229. context.set_context(mode=context.GRAPH_MODE,
  230. device_target=device_target,
  231. device_id=args_opt.device_id,
  232. max_call_depth=3000)
  233. context.set_auto_parallel_context(parallel_mode="stand_alone")
  234. print(" | Device: {} | Device id: {}".format(device_target, args_opt.device_id))
  235. else:
  236. raise Exception("Device target error, Ascend is supported.")
  237. gpt2_loss = GPT2Translation(config=gpt2_net_cfg,
  238. is_training=True,
  239. use_one_hot_embeddings=False)
  240. if args_opt.do_train.lower() == "true":
  241. print("============== Start Loading Translation Train Dataset ==============")
  242. print(" | Train Dataset: {}".format(args_opt.train_data_file_path))
  243. print(" | Checkpoint: {}".format(args_opt.load_pretrain_ckpt_path))
  244. train_dataset = create_language_model_dataset(do_shuffle=(args_opt.train_data_shuffle.lower() == "true"),
  245. dataset_path=args_opt.train_data_file_path)
  246. do_train(train_dataset, gpt2_loss, load_pretrain_ckpt_path, save_finetune_ckpt_path, epoch_num)
  247. if args_opt.do_eval.lower() == "true":
  248. print("============ Start Loading Translation Evaluation Dataset ============")
  249. print(" | Eval Dataset: {}".format(args_opt.eval_data_file_path))
  250. print(" | Checkpoint: {}".format(args_opt.load_finetune_ckpt_path))
  251. eval_dataset = create_language_model_dataset(do_shuffle=(args_opt.eval_data_shuffle.lower() == "true"),
  252. dataset_path=args_opt.eval_data_file_path)
  253. do_eval(eval_dataset, GPT2TranslationModel, metric, load_finetune_ckpt_path, args_opt.eval_type,
  254. args_opt.tokenizer_file_path, args_opt.generate_length, args_opt.top_k, args_opt.top_p,
  255. args_opt.temperature)
  256. if __name__ == "__main__":
  257. print("Start Time: \n", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
  258. run_translation()
  259. print("End Time: \n", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))