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.

retriever_eval.py 7.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. # Copyright 2021 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. Retriever Evaluation.
  17. """
  18. import time
  19. import json
  20. import numpy as np
  21. from mindspore import Tensor
  22. import mindspore.context as context
  23. from mindspore.ops import operations as P
  24. from mindspore.common import dtype as mstype
  25. from mindspore import load_checkpoint, load_param_into_net
  26. from src.onehop import OneHopBert
  27. from src.twohop import TwoHopBert
  28. from src.process_data import DataGen
  29. from src.onehop_bert import ModelOneHop
  30. from src.twohop_bert import ModelTwoHop
  31. from src.config import ThinkRetrieverConfig
  32. from src.utils import read_query, split_queries, get_new_title, get_raw_title, save_json
  33. def eval_output(out_2, last_out, path_raw, gold_path, val, true_count):
  34. """evaluation output"""
  35. y_pred_raw = out_2.asnumpy()
  36. last_out_raw = last_out.asnumpy()
  37. path = []
  38. y_pred = []
  39. last_out_list = []
  40. topk_titles = []
  41. index_list_raw = np.argsort(y_pred_raw)
  42. for index_r in index_list_raw[::-1]:
  43. tag = 1
  44. for raw_path in path:
  45. if path_raw[index_r][0] in raw_path and path_raw[index_r][1] in raw_path:
  46. tag = 0
  47. break
  48. if tag:
  49. path.append(path_raw[index_r])
  50. y_pred.append(y_pred_raw[index_r])
  51. last_out_list.append(last_out_raw[index_r])
  52. index_list = np.argsort(y_pred)
  53. for path_index in index_list:
  54. if gold_path[0] in path[path_index] and gold_path[1] in path[path_index]:
  55. true_count += 1
  56. break
  57. for path_index in index_list[-8:][::-1]:
  58. topk_titles.append(list(path[path_index]))
  59. for path_index in index_list[-8:]:
  60. if gold_path[0] in path[path_index] and gold_path[1] in path[path_index]:
  61. val += 1
  62. break
  63. return val, true_count, topk_titles
  64. def evaluation():
  65. """evaluation"""
  66. print('********************** loading corpus ********************** ')
  67. s_lc = time.time()
  68. data_generator = DataGen(config)
  69. queries = read_query(config)
  70. print("loading corpus time (h):", (time.time() - s_lc) / 3600)
  71. print('********************** loading model ********************** ')
  72. s_lm = time.time()
  73. model_onehop_bert = ModelOneHop()
  74. param_dict = load_checkpoint(config.onehop_bert_path)
  75. load_param_into_net(model_onehop_bert, param_dict)
  76. model_twohop_bert = ModelTwoHop()
  77. param_dict2 = load_checkpoint(config.twohop_bert_path)
  78. load_param_into_net(model_twohop_bert, param_dict2)
  79. onehop = OneHopBert(config, model_onehop_bert)
  80. twohop = TwoHopBert(config, model_twohop_bert)
  81. print("loading model time (h):", (time.time() - s_lm) / 3600)
  82. print('********************** evaluation ********************** ')
  83. s_tr = time.time()
  84. f_dev = open(config.dev_path, 'rb')
  85. dev_data = json.load(f_dev)
  86. q_gold = {}
  87. q_2id = {}
  88. for onedata in dev_data:
  89. if onedata["question"] not in q_gold:
  90. q_gold[onedata["question"]] = [get_new_title(get_raw_title(item)) for item in onedata['path']]
  91. q_2id[onedata["question"]] = onedata['_id']
  92. val, true_count, count, step = 0, 0, 0, 0
  93. batch_queries = split_queries(config, queries)[:-1]
  94. output_path = []
  95. for _, batch in enumerate(batch_queries):
  96. print("###step###: ", step)
  97. query = batch[0]
  98. temp_dict = {}
  99. temp_dict['q_id'] = q_2id[query]
  100. temp_dict['question'] = query
  101. gold_path = q_gold[query]
  102. input_ids_1, token_type_ids_1, input_mask_1 = data_generator.convert_onehop_to_features(batch)
  103. start = 0
  104. TOTAL = len(input_ids_1)
  105. split_chunk = 8
  106. while start < TOTAL:
  107. end = min(start + split_chunk - 1, TOTAL - 1)
  108. chunk_len = end - start + 1
  109. input_ids_1_ = input_ids_1[start:start + chunk_len]
  110. input_ids_1_ = Tensor(input_ids_1_, mstype.int32)
  111. token_type_ids_1_ = token_type_ids_1[start:start + chunk_len]
  112. token_type_ids_1_ = Tensor(token_type_ids_1_, mstype.int32)
  113. input_mask_1_ = input_mask_1[start:start + chunk_len]
  114. input_mask_1_ = Tensor(input_mask_1_, mstype.int32)
  115. cls_out = onehop(input_ids_1_, token_type_ids_1_, input_mask_1_)
  116. if start == 0:
  117. out = cls_out
  118. else:
  119. out = P.Concat(0)((out, cls_out))
  120. start = end + 1
  121. out = P.Squeeze(1)(out)
  122. onehop_prob, onehop_index = P.TopK(sorted=True)(out, config.topk)
  123. onehop_prob = P.Softmax()(onehop_prob)
  124. sample, path_raw, last_out = data_generator.get_samples(query, onehop_index, onehop_prob)
  125. input_ids_2, token_type_ids_2, input_mask_2 = data_generator.convert_twohop_to_features(sample)
  126. start_2 = 0
  127. TOTAL_2 = len(input_ids_2)
  128. split_chunk = 8
  129. while start_2 < TOTAL_2:
  130. end_2 = min(start_2 + split_chunk - 1, TOTAL_2 - 1)
  131. chunk_len = end_2 - start_2 + 1
  132. input_ids_2_ = input_ids_2[start_2:start_2 + chunk_len]
  133. input_ids_2_ = Tensor(input_ids_2_, mstype.int32)
  134. token_type_ids_2_ = token_type_ids_2[start_2:start_2 + chunk_len]
  135. token_type_ids_2_ = Tensor(token_type_ids_2_, mstype.int32)
  136. input_mask_2_ = input_mask_2[start_2:start_2 + chunk_len]
  137. input_mask_2_ = Tensor(input_mask_2_, mstype.int32)
  138. cls_out = twohop(input_ids_2_, token_type_ids_2_, input_mask_2_)
  139. if start_2 == 0:
  140. out_2 = cls_out
  141. else:
  142. out_2 = P.Concat(0)((out_2, cls_out))
  143. start_2 = end_2 + 1
  144. out_2 = P.Softmax()(out_2)
  145. last_out = Tensor(last_out, mstype.float32)
  146. out_2 = P.Mul()(out_2, last_out)
  147. val, true_count, topk_titles = eval_output(out_2, last_out, path_raw, gold_path, val, true_count)
  148. temp_dict['topk_titles'] = topk_titles
  149. output_path.append(temp_dict)
  150. count += 1
  151. print("val:", val)
  152. print("count:", count)
  153. print("true count:", true_count)
  154. if count:
  155. print("PEM:", val / count)
  156. if true_count:
  157. print("true top8 PEM:", val / true_count)
  158. step += 1
  159. save_json(output_path, config.save_path, config.save_name)
  160. print("evaluation time (h):", (time.time() - s_tr) / 3600)
  161. if __name__ == "__main__":
  162. config = ThinkRetrieverConfig()
  163. context.set_context(mode=context.GRAPH_MODE,
  164. device_target='Ascend',
  165. device_id=config.device_id,
  166. save_graphs=False)
  167. evaluation()