infgrad commited on
Commit
d8f227d
·
verified ·
1 Parent(s): fbc1304

Upload run_evaluate_loco.py

Browse files
Files changed (1) hide show
  1. scripts/evaluate/run_evaluate_loco.py +304 -0
scripts/evaluate/run_evaluate_loco.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import random
3
+
4
+ import pandas as pd
5
+ import torch
6
+ import os
7
+
8
+ os.environ["HF_ENDPOINT"] = "https://hf-mirror.com"
9
+ from sentence_transformers import SentenceTransformer
10
+ import tqdm
11
+ import numpy as np
12
+ import faiss
13
+ from sklearn.metrics import ndcg_score
14
+ from os.path import join
15
+ from sklearn.preprocessing import normalize
16
+ from transformers import AutoTokenizer, AutoModel
17
+
18
+ faiss.omp_set_num_threads(16)
19
+
20
+
21
+ def find_topk_by_vecs(source_vecs: np.ndarray, target_vecs: np.ndarray, topk: int):
22
+ if topk > len(target_vecs):
23
+ topk = len(target_vecs)
24
+ faiss_index = faiss.IndexFlatIP(target_vecs.shape[1])
25
+ faiss_index.add(target_vecs)
26
+
27
+ res_distance, res_index = faiss_index.search(source_vecs, topk)
28
+ return res_index, res_distance
29
+
30
+
31
+ def get_loco_path_info(q_dir, d_dir):
32
+ names = []
33
+ for name in sorted(os.listdir(q_dir)):
34
+ if name.endswith(".jsonl"):
35
+ names.append(name)
36
+ for name in os.listdir(d_dir):
37
+ if name.endswith(".jsonl"):
38
+ assert name in names
39
+ infos = []
40
+ for name in names:
41
+ infos.append(["LOCO-V1", name, join(q_dir, name), join(d_dir, name)])
42
+ infos.sort(key=lambda x: x[1])
43
+ return infos
44
+
45
+
46
+ def get_loco_data(q_path, d_path):
47
+ passage_list, query2passage_list = [], {}
48
+
49
+ original_doc_id2doc = {}
50
+
51
+ with open(d_path, "r", encoding="utf8") as fr:
52
+ for line in fr:
53
+ item = json.loads(line)
54
+ if item["passage"].strip():
55
+ original_doc_id2doc[item["pid"]] = item["passage"].strip()
56
+ passage_list.append(item["passage"].strip())
57
+
58
+ with open(q_path, "r", encoding="utf8") as fr:
59
+ for line in fr:
60
+ item = json.loads(line)
61
+ if item["query"].strip():
62
+ query2passage_list[item["query"].strip()] = [
63
+ original_doc_id2doc[answer_pid]
64
+ for answer_pid in item["answer_pids"]
65
+ if answer_pid in original_doc_id2doc
66
+ ]
67
+ query2passage_list = {k: list(set(v)) for k, v in query2passage_list.items() if list(set(v))}
68
+ passage_list = list(set(passage_list))
69
+ passage2id = {passage: idx for idx, passage in enumerate(passage_list)}
70
+ query2id_list = {k: list(set([passage2id[i] for i in v])) for k, v in query2passage_list.items()}
71
+ query_list = list(query2id_list.keys())
72
+ return query_list, passage_list, query2id_list
73
+
74
+
75
+ def get_ndcg_score(query_list, passage_list, query2passage_id_list, topk=10, error_data_save_path: str = None):
76
+ chunk_id2passage_id = {}
77
+ q_vecs = model.encode(
78
+ sentences=query_list,
79
+ batch_size=batch_size,
80
+ chunk_size=chunk_size,
81
+ chunk_overlap=chunk_overlap,
82
+ max_seq_length=max_seq_length,
83
+ is_q=True,
84
+ )
85
+ p_vecs = model.encode(
86
+ sentences=passage_list,
87
+ batch_size=batch_size,
88
+ chunk_size=chunk_size,
89
+ chunk_overlap=chunk_overlap,
90
+ max_seq_length=max_seq_length,
91
+ is_q=False,
92
+ )
93
+ # according query2id_list get labels_list
94
+ query_id_list = [query2passage_id_list[query] for query in query_list]
95
+ max_doc = max((len(id_list) for id_list in query_id_list))
96
+
97
+ labels = np.array([(id_list * max_doc)[:max_doc] for id_list in query_id_list])
98
+ if isinstance(p_vecs, list):
99
+ for idx, vec in enumerate(p_vecs):
100
+ if multi_vec_strategy == "full_text":
101
+ p_vecs[idx] = normalize(np.mean(vec[1:2, :], axis=0, keepdims=True), axis=1)
102
+ elif multi_vec_strategy == "full_text+chunks":
103
+ n_chunk = (vec.shape[0] - 2) // 2
104
+ if n_chunk > 0:
105
+ p_vecs[idx] = np.vstack(
106
+ (
107
+ normalize(np.mean(vec[:2, :], axis=0, keepdims=True), axis=1),
108
+ vec[2:2 + n_chunk, :],
109
+ )
110
+ )
111
+ else:
112
+ p_vecs[idx] = normalize(np.mean(vec[:2, :], axis=0, keepdims=True), axis=1)
113
+ p_vecs = np.vstack(p_vecs)
114
+
115
+ if isinstance(q_vecs, list):
116
+ for idx, vec in enumerate(q_vecs):
117
+ q_vecs[idx] = normalize(np.mean(vec[0:2, :], axis=0, keepdims=True), axis=1)
118
+ q_vecs = np.vstack(q_vecs)
119
+ print("q_vecs.shape and dtype", q_vecs.shape, q_vecs.dtype)
120
+ print("p_vecs.shape and dtype", p_vecs.shape, p_vecs.dtype)
121
+ # search topk
122
+ # we calculate ndcg@10
123
+ topk_index, topk_scores = find_topk_by_vecs(q_vecs, p_vecs, topk * 100)
124
+ # print("topk_index", topk_index.shape, topk_index)
125
+ # print("topk_scores", topk_scores.shape, topk_scores)
126
+ ### we may use multi vectors, so we should modify topk_index and topk_scores
127
+ if chunk_id2passage_id:
128
+ new_topk_index, new_topk_scores = [], []
129
+ # print("chunk_id2passage_id")
130
+ for chunk_ids, chunk_scores in tqdm.tqdm(zip(topk_index, topk_scores),
131
+ desc="modify topk_index and topk_scores", disable=True):
132
+ # processed by row
133
+ row_ids, row_scores, passage_id_set = [], [], set()
134
+ for idx, chunk_id in enumerate(chunk_ids):
135
+ passage_id = chunk_id2passage_id[chunk_id]
136
+ if passage_id not in passage_id_set:
137
+ passage_id_set.add(passage_id)
138
+ row_ids.append(passage_id)
139
+ row_scores.append(chunk_scores[idx])
140
+ new_topk_index.append(row_ids[:topk])
141
+ new_topk_scores.append(row_scores[:topk])
142
+ topk_index = np.array(new_topk_index)
143
+ # print("topk_index", topk_index)
144
+ topk_scores = np.array(new_topk_scores)
145
+ topk_index, topk_scores = topk_index[:, :topk], topk_scores[:, :topk]
146
+ is_match = (topk_index == labels[:, :1])
147
+ for idx in range(1, max_doc):
148
+ # the or operator means that only one positive doc in pred topk, we think it is recalled
149
+ is_match = is_match | (topk_index == labels[:, idx:idx + 1])
150
+
151
+ # compute recall at topk
152
+ print("is_match.shape", is_match.shape)
153
+ # recall_at_k = is_match.sum(axis=1).astype(bool).mean()
154
+ ndcg = ndcg_score(is_match.astype(dtype=np.float32), topk_scores)
155
+
156
+ if error_data_save_path:
157
+ in_top_k = is_match.sum(axis=1).astype(bool)
158
+ err_data = []
159
+ for idx, pred_res in enumerate(in_top_k):
160
+ if not pred_res:
161
+ query = query_list[idx]
162
+ label_doc = passage_list[query2passage_id_list[query][0]]
163
+ pred_doc = passage_list[topk_index[idx][0]]
164
+ err_data.append([query, label_doc, pred_doc])
165
+ pd.DataFrame(err_data, columns=["Query", "Label", "Pred"]).to_excel(error_data_save_path, index=False)
166
+ return float(ndcg)
167
+
168
+
169
+ class ModelWrapper:
170
+ def __init__(self, model_dir, model_type, max_seq_length):
171
+ assert model_type in ["dewey", "sentence_transformer"]
172
+ self.model_type = model_type
173
+ self.tokenizer = AutoTokenizer.from_pretrained(model_dir)
174
+ if model_type == "dewey":
175
+ self.model = AutoModel.from_pretrained(
176
+ model_dir,
177
+ attn_implementation="flash_attention_2",
178
+ trust_remote_code=True,
179
+ ).cuda().bfloat16().eval()
180
+ self.model.tokenizer = self.tokenizer
181
+ else:
182
+ self.model = SentenceTransformer(
183
+ model_dir,
184
+ trust_remote_code=True,
185
+ device="cpu",
186
+ model_kwargs={
187
+ "torch_dtype": torch.bfloat16, # fp16
188
+ "attn_implementation": "flash_attention_2"
189
+ },
190
+ )
191
+ self.model.max_seq_length = max_seq_length
192
+ if "NV-Embed-v2" in model_dir:
193
+ self.model.tokenizer.padding_side = "right"
194
+ self.pool = self.model.start_multi_process_pool()
195
+
196
+ def encode(
197
+ self,
198
+ sentences,
199
+ batch_size,
200
+ chunk_size,
201
+ chunk_overlap,
202
+ max_seq_length,
203
+ is_q,
204
+ ):
205
+ if self.model_type == "dewey":
206
+ if is_q:
207
+ prompt = "<|START_INSTRUCTION|>Answer the question<|END_INSTRUCTION|>"
208
+ else:
209
+ prompt = "<|START_INSTRUCTION|>Candidate document<|END_INSTRUCTION|>"
210
+ return self.model.encode(
211
+ sentences=sentences,
212
+ batch_size=batch_size,
213
+ use_cuda=True,
214
+ show_progress_bar=True,
215
+ chunk_size=chunk_size,
216
+ chunk_overlap=chunk_overlap,
217
+ convert_to_tensor=False,
218
+ max_seq_length=max_seq_length,
219
+ normalize_embeddings=True,
220
+ prompt=prompt,
221
+ fast_chunk=True,
222
+ )[0]
223
+ self.model.max_seq_length = max_seq_length
224
+ prompt = None
225
+ if is_q and (
226
+ "Linq-Embed-Mistral" in model_dir or "e5-mistral-7b-instruct" in model_dir or "SFR-Embedding-Mistral" in model_dir):
227
+ prompt = PROMPT_E5
228
+ if is_q and ("NV-Embed-v2" in model_dir):
229
+ prompt = PROMPT_NV
230
+ if "chunk_alignment" in model_dir or "dewey" in model_dir:
231
+ if is_q:
232
+ prompt = "<|START_INSTRUCTION|>Answer the question<|END_INSTRUCTION|>"
233
+ else:
234
+ prompt = "<|START_INSTRUCTION|>Candidate document<|END_INSTRUCTION|>"
235
+ vecs = self.model.encode_multi_process(
236
+ add_eos(sentences) if "NV-Embed-v2" in model_dir else sentences,
237
+ pool=self.pool,
238
+ show_progress_bar=True,
239
+ batch_size=batch_size,
240
+ normalize_embeddings=True,
241
+ prompt=prompt
242
+ )
243
+ return vecs
244
+
245
+
246
+ def add_eos(input_examples):
247
+ input_examples = [input_example + model.tokenizer.eos_token for input_example in input_examples]
248
+ return input_examples
249
+
250
+
251
+ PROMPT_BGE = "Represent this sentence for searching relevant passages:"
252
+ PROMPT_E5 = "Instruct: Given a web search query, retrieve relevant passages that answer the query.\nQuery: "
253
+ PROMPT_NV = "Instruct: Given a question, retrieve passages that answer the question\nQuery: "
254
+ if __name__ == "__main__":
255
+ chunk_size = -1
256
+ chunk_overlap = 32
257
+ batch_size = 2
258
+ max_seq_length = 8 * 1024
259
+ multi_vec_strategy = "full_text" # full_text; full_text+chunks
260
+ err_data_save_path = None
261
+ topk = 10
262
+
263
+ model_dir = "infgrad/dewey_en_beta"
264
+ # model_dir = "/home/zd/public_models/Linq-Embed-Mistral/"
265
+ # model_dir = "/home/zd/public_models/SFR-Embedding-Mistral"
266
+ # model_dir = "/home/zd/public_models/e5-mistral-7b-instruct"
267
+ # model_dir = "/home/zd/public_models/bge-m3"
268
+ # model_dir = "/home/zd/public_models/gte-modernbert-base"
269
+ # model_dir = "/home/zd/public_models/NV-Embed-v2"
270
+
271
+ # sentence_transformer dewey
272
+ model_type = "sentence_transformer"
273
+ ## get data info
274
+ # TODO Please download LOCOV1 data first!
275
+ data_info = get_loco_path_info(
276
+ "/home/zd/public_data/LoCoV1-Queries/documents/",
277
+ "/home/zd/public_data/LoCoV1-Documents/documents/",
278
+ )
279
+
280
+ # load model
281
+ model = ModelWrapper(model_dir=model_dir, model_type=model_type, max_seq_length=max_seq_length)
282
+ # model = zd()
283
+ ndcg_score_list = []
284
+ for item in data_info:
285
+ print("\n\n\n\n" + "=" * 20)
286
+ print(f"evaluate {item[:2]}...")
287
+ query_list, passage_list, query2passage_id_list = get_loco_data(*item[2:])
288
+ print("number of all queries", len(query_list))
289
+ print("number of all passages", len(passage_list))
290
+ ndcg = get_ndcg_score(query_list, passage_list, query2passage_id_list, topk=topk,
291
+ error_data_save_path=err_data_save_path)
292
+ print(f"{ndcg}")
293
+ ndcg_score_list.append(ndcg)
294
+
295
+ for i in data_info:
296
+ print(i[0])
297
+ print("\n\n\n")
298
+ for i in data_info:
299
+ print(i[1].replace(".jsonl", ""))
300
+ print("\n\n\n")
301
+
302
+ print(os.path.basename(model_dir))
303
+ for i in ndcg_score_list:
304
+ print(i)