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

4 years ago
4 years ago
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  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.converted_bert import ModelOneHop
  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(d_id):
  65. """evaluation"""
  66. context.set_context(mode=context.GRAPH_MODE,
  67. device_target='Ascend',
  68. device_id=d_id,
  69. save_graphs=False)
  70. print('********************** loading corpus ********************** ')
  71. s_lc = time.time()
  72. data_generator = DataGen(config)
  73. queries = read_query(config, d_id)
  74. print("loading corpus time (h):", (time.time() - s_lc) / 3600)
  75. print('********************** loading model ********************** ')
  76. s_lm = time.time()
  77. model_onehop_bert = ModelOneHop(256)
  78. param_dict = load_checkpoint(config.onehop_bert_path)
  79. load_param_into_net(model_onehop_bert, param_dict)
  80. model_twohop_bert = ModelOneHop(448)
  81. param_dict2 = load_checkpoint(config.twohop_bert_path)
  82. load_param_into_net(model_twohop_bert, param_dict2)
  83. onehop = OneHopBert(config, model_onehop_bert)
  84. twohop = TwoHopBert(config, model_twohop_bert)
  85. print("loading model time (h):", (time.time() - s_lm) / 3600)
  86. print('********************** evaluation ********************** ')
  87. f_dev = open(config.dev_path, 'rb')
  88. dev_data = json.load(f_dev)
  89. f_dev.close()
  90. q_gold = {}
  91. q_2id = {}
  92. for onedata in dev_data:
  93. if onedata["question"] not in q_gold:
  94. q_gold[onedata["question"]] = [get_new_title(get_raw_title(item)) for item in onedata['path']]
  95. q_2id[onedata["question"]] = onedata['_id']
  96. val, true_count, count, step = 0, 0, 0, 0
  97. batch_queries = split_queries(config, queries)
  98. output_path = []
  99. for _, batch in enumerate(batch_queries):
  100. print("###step###: ", str(step) + "_" + str(d_id))
  101. query = batch[0]
  102. temp_dict = {}
  103. temp_dict['q_id'] = q_2id[query]
  104. temp_dict['question'] = query
  105. gold_path = q_gold[query]
  106. input_ids_1, token_type_ids_1, input_mask_1 = data_generator.convert_onehop_to_features(batch)
  107. start = 0
  108. TOTAL = len(input_ids_1)
  109. split_chunk = 8
  110. while start < TOTAL:
  111. end = min(start + split_chunk - 1, TOTAL - 1)
  112. chunk_len = end - start + 1
  113. input_ids_1_ = input_ids_1[start:start + chunk_len]
  114. input_ids_1_ = Tensor(input_ids_1_, mstype.int32)
  115. token_type_ids_1_ = token_type_ids_1[start:start + chunk_len]
  116. token_type_ids_1_ = Tensor(token_type_ids_1_, mstype.int32)
  117. input_mask_1_ = input_mask_1[start:start + chunk_len]
  118. input_mask_1_ = Tensor(input_mask_1_, mstype.int32)
  119. cls_out = onehop(input_ids_1_, token_type_ids_1_, input_mask_1_)
  120. if start == 0:
  121. out = cls_out
  122. else:
  123. out = P.Concat(0)((out, cls_out))
  124. start = end + 1
  125. out = P.Squeeze(1)(out)
  126. onehop_prob, onehop_index = P.TopK(sorted=True)(out, config.topk)
  127. onehop_prob = P.Softmax()(onehop_prob)
  128. sample, path_raw, last_out = data_generator.get_samples(query, onehop_index, onehop_prob)
  129. input_ids_2, token_type_ids_2, input_mask_2 = data_generator.convert_twohop_to_features(sample)
  130. start_2 = 0
  131. TOTAL_2 = len(input_ids_2)
  132. split_chunk = 8
  133. while start_2 < TOTAL_2:
  134. end_2 = min(start_2 + split_chunk - 1, TOTAL_2 - 1)
  135. chunk_len = end_2 - start_2 + 1
  136. input_ids_2_ = input_ids_2[start_2:start_2 + chunk_len]
  137. input_ids_2_ = Tensor(input_ids_2_, mstype.int32)
  138. token_type_ids_2_ = token_type_ids_2[start_2:start_2 + chunk_len]
  139. token_type_ids_2_ = Tensor(token_type_ids_2_, mstype.int32)
  140. input_mask_2_ = input_mask_2[start_2:start_2 + chunk_len]
  141. input_mask_2_ = Tensor(input_mask_2_, mstype.int32)
  142. cls_out = twohop(input_ids_2_, token_type_ids_2_, input_mask_2_)
  143. if start_2 == 0:
  144. out_2 = cls_out
  145. else:
  146. out_2 = P.Concat(0)((out_2, cls_out))
  147. start_2 = end_2 + 1
  148. out_2 = P.Softmax()(out_2)
  149. last_out = Tensor(last_out, mstype.float32)
  150. out_2 = P.Mul()(out_2, last_out)
  151. val, true_count, topk_titles = eval_output(out_2, last_out, path_raw, gold_path, val, true_count)
  152. temp_dict['topk_titles'] = topk_titles
  153. output_path.append(temp_dict)
  154. step += 1
  155. count += 1
  156. return {'val': val, 'count': count, 'true_count': true_count, 'path': output_path}
  157. if __name__ == "__main__":
  158. t_s = time.time()
  159. config = ThinkRetrieverConfig()
  160. pool = Pool(processes=config.device_num)
  161. results = []
  162. for device_id in range(config.device_num):
  163. results.append(pool.apply_async(evaluation, (device_id,)))
  164. print("Waiting for all subprocess done...")
  165. pool.close()
  166. pool.join()
  167. val_all, true_count_all, count_all = 0, 0, 0
  168. output_path_all = []
  169. for res in results:
  170. output = res.get()
  171. val_all += output['val']
  172. count_all += output['count']
  173. true_count_all += output['true_count']
  174. output_path_all += output['path']
  175. print("val:", val_all)
  176. print("count:", count_all)
  177. print("true count:", true_count_all)
  178. print("PEM:", val_all / count_all)
  179. print("true top8 PEM:", val_all / true_count_all)
  180. save_json(output_path_all, config.save_path, config.save_name)
  181. print("evaluation time (h):", (time.time() - t_s) / 3600)