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.

eval.py 5.2 kB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  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 evaluation script.
  17. """
  18. import math
  19. import argparse
  20. import numpy as np
  21. from mindspore import context
  22. import mindspore.common.dtype as mstype
  23. from mindspore.common.tensor import Tensor
  24. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  25. from src.inference import generate
  26. from src.dataset import create_dataset
  27. from src.gpt import GPT, EvalNet, GPTWithLoss, CrossEntropyLoss
  28. from src.utils import GPTConfig
  29. context.set_context(mode=context.GRAPH_MODE)
  30. def ppl_score(probs, length, is_logsoftmax=True):
  31. """ calculate perplexity with prob or log_prob inputs """
  32. probs = probs[:length]
  33. if is_logsoftmax:
  34. prob = np.sum(probs) / length
  35. ppl = 1.0 / np.power(np.e, prob)
  36. else:
  37. prob = 1.0
  38. for p in probs:
  39. prob *= (1.0 / p)
  40. ppl = np.power(prob, 1.0/length)
  41. return ppl
  42. def get_ppl(model, dataset):
  43. """ calculate perplexity for input dataset """
  44. PPL = []
  45. tokens = 0
  46. for data in dataset:
  47. data = data[0].asnumpy()
  48. input_ids = data
  49. logits = model(Tensor(input_ids, mstype.int32)).asnumpy()
  50. PPL.append(logits * len(data))
  51. tokens += len(data)
  52. val_loss = sum(PPL) / tokens
  53. ppl = math.exp(min(20, val_loss))
  54. return ppl
  55. def get_acc(model, dataset):
  56. """ calculate accuracy for input dataset """
  57. total_num = 0
  58. acc_num = 0
  59. for data in dataset:
  60. data = data[0].asnumpy()
  61. input_mask = (data != 0).astype(np.int32)
  62. length = np.sum(input_mask, 1)
  63. label = np.zeros(length.shape)
  64. for i, idx in enumerate(length):
  65. label[i] = data[i][idx-1]
  66. input_mask[i][idx-1] = 0
  67. data[i][idx-1] = 0
  68. length = np.sum(data != 50256, 1)
  69. input_ids = data
  70. logits = model(Tensor(input_ids, mstype.int32)).asnumpy()
  71. logits = logits.reshape(len(length), -1)
  72. predicted_label = np.zeros(length.shape)
  73. for i, idx in enumerate(length):
  74. predicted_label[i] = logits[i][idx-2]
  75. total_num += len(label)
  76. acc_num += sum(label == predicted_label)
  77. acc = acc_num / total_num
  78. return acc
  79. def run_eval():
  80. """ evaluate scripts """
  81. parser = argparse.ArgumentParser(description="GPT inferencing")
  82. parser.add_argument('--task_type', type=str, default="", help="Evaluation task.")
  83. parser.add_argument('--metrics', type=str, default="acc", choices=["ppl", "acc"], help="Evaluation metrics.")
  84. parser.add_argument('--ckpt_path', type=str, default="", help="path of checkpoint file.")
  85. parser.add_argument('--data_path', type=str, default="", help="path of MindRecord file.")
  86. args = parser.parse_args()
  87. task = args.task_type
  88. metrics = args.metrics
  89. ckpt_path = args.ckpt_path
  90. if task not in ["generate", "lambada", "wikitext"]:
  91. raise ValueError("{} is not supported now".format(task))
  92. if metrics not in ["acc", "ppl"]:
  93. raise ValueError("{} is not supported now".format(metrics))
  94. config = GPTConfig(batch_size=16,
  95. seq_length=1024,
  96. vocab_size=50257,
  97. embedding_size=1024,
  98. num_layers=24,
  99. num_heads=16,
  100. expand_ratio=4,
  101. post_layernorm_residual=False,
  102. dropout_rate=0.0,
  103. compute_dtype=mstype.float16,
  104. use_past=False)
  105. ckpt_dict = load_checkpoint(ckpt_path)
  106. gpt = GPT(config)
  107. if task == "generate":
  108. gpt_eval = EvalNet(gpt, generate=True)
  109. elif metrics == "acc":
  110. gpt_eval = EvalNet(gpt, generate=False)
  111. else:
  112. loss = CrossEntropyLoss(config)
  113. gpt_eval = GPTWithLoss(gpt, loss)
  114. gpt_eval.set_train(False)
  115. load_param_into_net(gpt_eval, ckpt_dict)
  116. if task == "generate":
  117. start_sentence = [6170, 318, 257]
  118. input_ids = np.array(start_sentence).reshape(1, -1)
  119. outputs = generate(gpt_eval, input_ids, config.seq_length)
  120. output_list = outputs.tolist()
  121. print("output id is ", output_list)
  122. else:
  123. data_path = args.data_path
  124. eval_dataset = create_dataset(config.batch_size, data_path=data_path, drop=False)
  125. if metrics == "acc":
  126. acc = get_acc(gpt_eval, eval_dataset)
  127. print("Accuracy is ", acc)
  128. elif metrics == "ppl":
  129. ppl = get_ppl(gpt_eval, eval_dataset)
  130. print("Perplexity is ", ppl)
  131. if __name__ == "__main__":
  132. run_eval()