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_summarization.py 15 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2020 Huawei Technologies Co., Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. # ============================================================================
  16. """
  17. GPT-2 finetune and evaluation script for Summarization task.
  18. """
  19. import time
  20. import argparse
  21. from mindspore import context
  22. from mindspore.nn import AdamWeightDecay, Lamb, Momentum
  23. from mindspore.nn.wrap.loss_scale import DynamicLossScaleUpdateCell
  24. from mindspore.train.model import Model
  25. from mindspore.train.callback import CheckpointConfig, ModelCheckpoint, TimeMonitor, LossMonitor
  26. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  27. from src.GPT2ForSummarization import GPT2SummarizationModel
  28. from src.gpt2_for_finetune import GPT2Summarization, GPT2FinetuneCell
  29. from src.finetune_eval_config import cfg, gpt2_net_cfg
  30. from src.utils.metric_method import Rouge
  31. from src.dataset import create_language_model_dataset
  32. from src.utils.lr_schedule import GPT2LearningRate
  33. from src.utils.tokenization import Tokenizer
  34. from src.utils.task_utils import clean_hypo, modify_paramdict
  35. from src.GPT2_generation import GenerateForSummarization
  36. def do_train(dataset=None, network=None, load_checkpoint_path="", save_checkpoint_path="", epoch_num=1):
  37. """
  38. Do train
  39. Args:
  40. dataset: the train dataset.
  41. network: the network with loss
  42. load_checkpoint_path: the file path which saved pretrain model checkpoint.
  43. save_checkpoint_path: the file path which will save finetune model checkpoint.
  44. epoch_num: the number of epoch
  45. """
  46. if load_checkpoint_path == "":
  47. raise ValueError("Pretrain model missed, finetune task must load pretrain model!")
  48. steps_per_epoch = dataset.get_dataset_size()
  49. # optimizer
  50. if cfg.optimizer == 'AdamWeightDecay':
  51. lr_schedule = GPT2LearningRate(learning_rate=cfg.AdamWeightDecay.learning_rate,
  52. end_learning_rate=cfg.AdamWeightDecay.end_learning_rate,
  53. warmup_steps=int(steps_per_epoch * epoch_num * 0.1),
  54. decay_steps=steps_per_epoch * epoch_num,
  55. power=cfg.AdamWeightDecay.power)
  56. params = network.trainable_params()
  57. decay_params = list(filter(cfg.AdamWeightDecay.decay_filter, params))
  58. other_params = list(
  59. filter(lambda x: not cfg.AdamWeightDecay.decay_filter(x), params))
  60. group_params = [{'params': decay_params, 'weight_decay': cfg.AdamWeightDecay.weight_decay},
  61. {'params': other_params, 'weight_decay': 0.0}]
  62. optimizer = AdamWeightDecay(group_params, lr_schedule, eps=cfg.AdamWeightDecay.eps)
  63. elif cfg.optimizer == 'Lamb':
  64. lr_schedule = GPT2LearningRate(learning_rate=cfg.Lamb.learning_rate,
  65. end_learning_rate=cfg.Lamb.end_learning_rate,
  66. warmup_steps=int(steps_per_epoch * epoch_num * 0.1),
  67. decay_steps=steps_per_epoch * epoch_num,
  68. power=cfg.Lamb.power)
  69. optimizer = Lamb(network.trainable_params(), lr_schedule)
  70. elif cfg.optimizer == 'Momentum':
  71. optimizer = Momentum(network.trainable_params(), cfg.Momentum.learning_rate, cfg.Momentum.momentum)
  72. else:
  73. raise Exception("Optimizer not supported. support: [AdamWeightDecay, Lamb, Momentum]")
  74. # load checkpoint into network
  75. ckpt_config = CheckpointConfig(save_checkpoint_steps=steps_per_epoch, keep_checkpoint_max=1)
  76. prefix_name = "gpt2_summarization_" + str(cfg.gpt2_network) + "_" + str(cfg.optimizer) + "_" \
  77. + str(epoch_num) + "_bs" + str(gpt2_net_cfg.batch_size)
  78. ckpoint_cb = ModelCheckpoint(prefix=prefix_name,
  79. directory=None if save_checkpoint_path == "" else save_checkpoint_path,
  80. config=ckpt_config)
  81. param_dict = load_checkpoint(load_checkpoint_path)
  82. final_param_dict = {}
  83. for name, _ in param_dict.items():
  84. final_param_dict['gpt2.gpt2.' + name] = param_dict[name]
  85. final_param_dict['gpt2.lm_head.weight'] = param_dict['gpt2_embedding_lookup.embedding_table']
  86. load_param_into_net(network, final_param_dict)
  87. print("Load pretrained parameter successfully!\n")
  88. update_cell = DynamicLossScaleUpdateCell(loss_scale_value=2 ** 32, scale_factor=2, scale_window=1000)
  89. netwithgrads = GPT2FinetuneCell(network, optimizer=optimizer, scale_update_cell=update_cell)
  90. netwithgrads.set_train(True)
  91. loss_cb = LossMonitor(per_print_times=1)
  92. model = Model(netwithgrads)
  93. callbacks = [TimeMonitor(dataset.get_dataset_size()), loss_cb, ckpoint_cb]
  94. print("============== Starting Finetuning ==============")
  95. model.train(epoch_num, dataset, callbacks=callbacks, dataset_sink_mode=False)
  96. print("============== Finetuning Success ==============")
  97. def eval_result_print(metric="Rouge", callback=None):
  98. """
  99. print eval result
  100. """
  101. if metric == "Rouge":
  102. print("Rouge-1 {:.8f}, Rouge-2 {:.8f}, Rouge-L {:.8f}, Rouge-AVG{:.8f}".
  103. format(callback.Rouge1 / callback.total_num,
  104. callback.Rouge2 / callback.total_num,
  105. callback.RougeL / callback.total_num,
  106. (callback.Rouge1 + callback.Rouge2 + callback.RougeL) / (3.0 * callback.total_num)))
  107. else:
  108. raise ValueError("metric method '{}' not supported, support: [Rouge]. ".format(str(metric)))
  109. def do_eval(dataset=None, network=None, metric=None, load_checkpoint_path="", eval_type=None, tokenizer_file="",
  110. top_k=None, top_p=None, temperature=None, generate_length=None):
  111. """
  112. Do evaluation on summarization
  113. """
  114. if load_checkpoint_path == "":
  115. raise ValueError("Finetune model missed, evaluation task must load finetune model!")
  116. if metric.lower() == "rouge":
  117. print("Prepare to calculate the Rouge score ...")
  118. callback = Rouge()
  119. gpt2_loss = network(config=gpt2_net_cfg,
  120. is_training=False,
  121. use_one_hot_embeddings=False)
  122. gpt2_loss.set_train(False)
  123. param_dict = load_checkpoint(load_checkpoint_path)
  124. reorganized_param_dict = modify_paramdict(param_dict, mode=eval_type, model_prefix="gpt2.")
  125. load_param_into_net(gpt2_loss, reorganized_param_dict)
  126. # load nn.Cell into Model and initiate tokenizer and Sample
  127. model = Model(gpt2_loss)
  128. tokenizer = Tokenizer(vocab_file=tokenizer_file + 'gpt2-vocab.json',
  129. merge_file=tokenizer_file + 'gpt2-merges.txt')
  130. # load data and process text generation
  131. columns_list = ["input_ids", "input_mask", "label_ids"]
  132. summarization_generator = GenerateForSummarization(model,
  133. config=gpt2_net_cfg,
  134. tokenizer=tokenizer,
  135. select_sentence=3,
  136. eval_type=eval_type,
  137. topk=top_k,
  138. topp=float(top_p),
  139. temperature=float(temperature),
  140. generate_length=generate_length)
  141. num_data = 1
  142. print("==================== [Summrization] Testing ====================")
  143. for data in dataset.create_dict_iterator():
  144. input_data = []
  145. for value in columns_list:
  146. input_data.append(data[value])
  147. input_ids, _, label_ids = input_data
  148. print(" | [ROUGE] number : {} / {} ".format(num_data, dataset.get_dataset_size()))
  149. print("input_ids shape: {}".format(input_ids.shape))
  150. print("label_ids shape: {}".format(label_ids.shape))
  151. hypothesis, ref = summarization_generator.generate_for_summarization(input_ids)
  152. if ref[0] == '' or ref[0] is None:
  153. print("Sorry ref_list is None, skip it!")
  154. continue
  155. print("REF str:\n ", ref, "\nHYPO str:\n", hypothesis, "\n")
  156. for batch_idx in range(gpt2_net_cfg.batch_size):
  157. hypothesis[batch_idx] = clean_hypo(hypothesis[batch_idx])
  158. for batch_idx in range(gpt2_net_cfg.batch_size):
  159. hypothesis[batch_idx] = hypothesis[batch_idx].lower()
  160. ref[batch_idx] = ref[batch_idx].lower()
  161. callback.update(hypothesis, ref)
  162. num_data += 1
  163. print("\n\n")
  164. print("**********************************************************")
  165. eval_result_print(metric, callback)
  166. print("******************** Testing Finished ********************")
  167. else:
  168. raise ValueError("metric method not supported in summarization, support: [Rouge]")
  169. def run_summarization():
  170. """
  171. Run Summarization task.
  172. """
  173. # set argument parser
  174. parser = argparse.ArgumentParser(description="Finetune and Evaluate Summrization")
  175. # context and task settings
  176. parser.add_argument("--device_target", type=str, default="Ascend",
  177. help="Device type. Default: Ascend.")
  178. parser.add_argument("--device_id", type=int, default=4,
  179. help="ID of target device.")
  180. parser.add_argument("--do_train", type=str, default="false",
  181. help="Enable train. Default: false.")
  182. parser.add_argument("--do_eval", type=str, default="true",
  183. help="Enable evaluation. Default: false.")
  184. parser.add_argument("--eval_type", type=str, default="finetuned",
  185. help="The type of evaluation including [zero-shot, finetuned]. Default: zero-shot.")
  186. parser.add_argument("--metric_method", type=str, default="Rouge",
  187. help="The eval method including [Rouge(Rouge1,Rouge2,RougeL,Rouge Avg)]. Default: Rouge.")
  188. parser.add_argument("--epoch_num", type=int, default=2,
  189. help="Epoch number. Default: 2.")
  190. # dataset and params_dict file settings
  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. # sampling settings
  206. parser.add_argument("--top_k", type=int, default=2,
  207. help="top k tokens chosen for sampling")
  208. parser.add_argument("--top_p", type=str, default="1.0",
  209. help="top p accumulated probability threshold for logit to be counted")
  210. parser.add_argument("--generate_length", type=int, default=100,
  211. help="the number of generated tokens.")
  212. parser.add_argument("--temperature", type=str, default="1.0",
  213. help="temperature on logits for sampling")
  214. parser.add_argument("--tokenizer_file_path", type=str, default="",
  215. help="vocab & merge file path")
  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. eval_type = args_opt.eval_type
  223. tokenizer_file = args_opt.tokenizer_file_path
  224. if args_opt.do_train.lower() == "false" and args_opt.do_eval.lower() == "false":
  225. raise ValueError("At least one of 'do_train' or 'do_eval' must be true")
  226. if args_opt.do_train.lower() == "true" and args_opt.train_data_file_path == "":
  227. raise ValueError("'train_data_file_path' must be set when do finetune task")
  228. if args_opt.do_eval.lower() == "true" and args_opt.eval_data_file_path == "":
  229. raise ValueError("'eval_data_file_path' must be set when do evaluation task")
  230. device = args_opt.device_target
  231. if device == "Ascend":
  232. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend", device_id=args_opt.device_id)
  233. context.set_auto_parallel_context(parallel_mode="stand_alone")
  234. print(" | Device: {} | Device id: {}".format(device, args_opt.device_id))
  235. else:
  236. raise Exception("Device target error, Ascend is supported.")
  237. if args_opt.do_train.lower() == "true":
  238. train_data_file_path = args_opt.train_data_file_path
  239. gpt2_loss = GPT2Summarization(config=gpt2_net_cfg,
  240. is_training=True,
  241. use_one_hot_embeddings=False)
  242. print("============== Start Loading Train Dataset ============")
  243. train_dataset = create_language_model_dataset(do_shuffle=(args_opt.train_data_shuffle.lower() == "true"),
  244. dataset_path=train_data_file_path)
  245. do_train(train_dataset, gpt2_loss, load_pretrain_ckpt_path, save_finetune_ckpt_path, epoch_num)
  246. if args_opt.do_eval.lower() == "true":
  247. eval_dataset_file_path = args_opt.eval_data_file_path
  248. print("============== Start Loading Evaluation Dataset ============")
  249. eval_dataset = create_language_model_dataset(do_shuffle=(args_opt.train_data_shuffle.lower() == "true"),
  250. dataset_path=eval_dataset_file_path)
  251. do_eval(eval_dataset, GPT2SummarizationModel, metric, load_finetune_ckpt_path, eval_type, tokenizer_file,
  252. args_opt.top_k, args_opt.top_p, args_opt.temperature, args_opt.generate_length)
  253. if __name__ == "__main__":
  254. print("Start Time: ", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
  255. run_summarization()
  256. print("End Time: ", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))