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

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