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.

pretrain_eval.py 5.9 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  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. Bert evaluation script.
  17. """
  18. import os
  19. from src import BertModel, GetMaskedLMOutput
  20. from src.evaluation_config import cfg, bert_net_cfg
  21. import mindspore.common.dtype as mstype
  22. from mindspore import context
  23. from mindspore.common.tensor import Tensor
  24. import mindspore.dataset as de
  25. import mindspore.dataset.transforms.c_transforms as C
  26. from mindspore.train.model import Model
  27. from mindspore.train.serialization import load_checkpoint, load_param_into_net
  28. import mindspore.nn as nn
  29. from mindspore.nn.metrics import Metric
  30. from mindspore.ops import operations as P
  31. from mindspore.common.parameter import Parameter
  32. class myMetric(Metric):
  33. '''
  34. Self-defined Metric as a callback.
  35. '''
  36. def __init__(self):
  37. super(myMetric, self).__init__()
  38. self.clear()
  39. def clear(self):
  40. self.total_num = 0
  41. self.acc_num = 0
  42. def update(self, *inputs):
  43. total_num = self._convert_data(inputs[0])
  44. acc_num = self._convert_data(inputs[1])
  45. self.total_num = total_num
  46. self.acc_num = acc_num
  47. def eval(self):
  48. return self.acc_num/self.total_num
  49. class GetLogProbs(nn.Cell):
  50. '''
  51. Get MaskedLM prediction scores
  52. '''
  53. def __init__(self, config):
  54. super(GetLogProbs, self).__init__()
  55. self.bert = BertModel(config, False)
  56. self.cls1 = GetMaskedLMOutput(config)
  57. def construct(self, input_ids, input_mask, token_type_id, masked_pos):
  58. sequence_output, _, embedding_table = self.bert(input_ids, token_type_id, input_mask)
  59. prediction_scores = self.cls1(sequence_output, embedding_table, masked_pos)
  60. return prediction_scores
  61. class BertPretrainEva(nn.Cell):
  62. '''
  63. Evaluate MaskedLM prediction scores
  64. '''
  65. def __init__(self, config):
  66. super(BertPretrainEva, self).__init__()
  67. self.bert = GetLogProbs(config)
  68. self.argmax = P.Argmax(axis=-1, output_type=mstype.int32)
  69. self.equal = P.Equal()
  70. self.mean = P.ReduceMean()
  71. self.sum = P.ReduceSum()
  72. self.total = Parameter(Tensor([0], mstype.float32), name='total')
  73. self.acc = Parameter(Tensor([0], mstype.float32), name='acc')
  74. self.reshape = P.Reshape()
  75. self.shape = P.Shape()
  76. self.cast = P.Cast()
  77. def construct(self, input_ids, input_mask, token_type_id, masked_pos, masked_ids, masked_weights, nsp_label):
  78. bs, _ = self.shape(input_ids)
  79. probs = self.bert(input_ids, input_mask, token_type_id, masked_pos)
  80. index = self.argmax(probs)
  81. index = self.reshape(index, (bs, -1))
  82. eval_acc = self.equal(index, masked_ids)
  83. eval_acc1 = self.cast(eval_acc, mstype.float32)
  84. real_acc = eval_acc1 * masked_weights
  85. acc = self.sum(real_acc)
  86. total = self.sum(masked_weights)
  87. self.total += total
  88. self.acc += acc
  89. return acc, self.total, self.acc
  90. def get_enwiki_512_dataset(batch_size=1, repeat_count=1, distribute_file=''):
  91. '''
  92. Get enwiki seq_length=512 dataset
  93. '''
  94. ds = de.TFRecordDataset([cfg.data_file], cfg.schema_file, columns_list=["input_ids", "input_mask", "segment_ids",
  95. "masked_lm_positions", "masked_lm_ids",
  96. "masked_lm_weights",
  97. "next_sentence_labels"])
  98. type_cast_op = C.TypeCast(mstype.int32)
  99. ds = ds.map(input_columns="segment_ids", operations=type_cast_op)
  100. ds = ds.map(input_columns="input_mask", operations=type_cast_op)
  101. ds = ds.map(input_columns="input_ids", operations=type_cast_op)
  102. ds = ds.map(input_columns="masked_lm_ids", operations=type_cast_op)
  103. ds = ds.map(input_columns="masked_lm_positions", operations=type_cast_op)
  104. ds = ds.map(input_columns="next_sentence_labels", operations=type_cast_op)
  105. ds = ds.repeat(repeat_count)
  106. # apply batch operations
  107. ds = ds.batch(batch_size, drop_remainder=True)
  108. return ds
  109. def bert_predict():
  110. '''
  111. Predict function
  112. '''
  113. devid = int(os.getenv('DEVICE_ID'))
  114. context.set_context(mode=context.GRAPH_MODE, device_target="Ascend", device_id=devid)
  115. dataset = get_enwiki_512_dataset(bert_net_cfg.batch_size, 1)
  116. net_for_pretraining = BertPretrainEva(bert_net_cfg)
  117. net_for_pretraining.set_train(False)
  118. param_dict = load_checkpoint(cfg.finetune_ckpt)
  119. load_param_into_net(net_for_pretraining, param_dict)
  120. model = Model(net_for_pretraining)
  121. return model, dataset, net_for_pretraining
  122. def MLM_eval():
  123. '''
  124. Evaluate function
  125. '''
  126. _, dataset, net_for_pretraining = bert_predict()
  127. net = Model(net_for_pretraining, eval_network=net_for_pretraining, eval_indexes=[0, 1, 2],
  128. metrics={'name': myMetric()})
  129. res = net.eval(dataset, dataset_sink_mode=False)
  130. print("==============================================================")
  131. for _, v in res.items():
  132. print("Accuracy is: ")
  133. print(v)
  134. print("==============================================================")
  135. if __name__ == "__main__":
  136. MLM_eval()