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 8.1 kB

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