-
Notifications
You must be signed in to change notification settings - Fork 3
/
rerank.py
280 lines (250 loc) · 11.1 KB
/
rerank.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import copy
import os
import re
import time
import json
from tqdm import tqdm
import argparse
from datasets import load_dataset
import torch
from sentence_transformers import CrossEncoder
from retrievers import calculate_retrieval_metrics
import functools
import logging
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
datefmt='%m/%d/%Y %H:%M:%S')
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
def extract_program(a_string,lan='python',first_block_only=False):
indices_object = re.finditer(pattern="```", string=a_string)
indices = [index.start() for index in indices_object]
contents = ''
if len(indices) == 0:
contents = a_string
elif len(indices) % 2 == 0:
for i in range(0, len(indices), 2):
cur_str = a_string[indices[i]:indices[i + 1]]
if cur_str.startswith(f"```{lan}"):
cur_str = cur_str[len(f"```{lan}"):]
elif cur_str.startswith(f"```\n{lan}"):
cur_str = cur_str[len(f"```\n{lan}"):]
elif cur_str.startswith("```"):
cur_str = cur_str[len("```"):]
contents += cur_str
if first_block_only:
break
else:
contents = a_string.replace(f"```{lan}", '').replace("```", '').replace(f"{lan}\n", '')
lines = contents.strip().split('\n')
if lines[-1].isidentifier():
contents = '\n'.join(lines[:-1])
return contents.replace(f"{lan}\n", '')
def call_api(func):
count = 0
while True:
try:
count += 1
output = func()
break
except Exception as e:
logger.info(f"Exception while using api: {e}")
if "rate limit" in str(e).lower() or "rate_limit" in str(e).lower():
logger.info("Rate limit exceeded, waiting 10 secs and retrying...")
time.sleep(10)
elif count < 5:
logger.info("Encountered error, retrying...")
time.sleep(5)
else:
logger.info("Skipping generation due to unknown error after 5 retries.")
output = None
break
return output
def format_chat(message, include_system=True, system_message="You are a helpful assistant."):
if include_system:
chat = [{"role": "system", "content": system_message}, {"role": "user", "content": message}]
else:
chat = [{"role": "user", "content": message}]
return chat
class ClaudeModel:
def __init__(self, version):
from anthropic import AnthropicVertex
PROJECT_ID = "xxx" # @param
LOCATION = "xxx" # @param
self.model = AnthropicVertex(region=LOCATION, project_id=PROJECT_ID)
self.version = version
def rerank(self, docs, query, topk):
doc_string = ''
indices_map = {}
for doc_idx,doc in enumerate(docs):
assert isinstance(doc,list)
doc_string += "[{}]. {}\n\n".format(doc_idx + 1, re.sub('\n+', ' ', doc[1]))
indices_map[doc_idx + 1] = doc[0]
cur_query = query.replace('\n',' ')
prompt = (f'The following passages are related to query: {cur_query}\n\n'
f'{doc_string}'
f'First identify the essential problem in the query.\n'
f'Think step by step to reason about why each document is relevant or irrelevant.\n'
f'Rank these passages based on their relevance to the query.\n'
f'Please output the ranking result of passages as a list, where the first element is the id of the most relevant '
f'passage, the second element is the id of the second most element, etc.\n'
f'Please strictly follow the format to output a list of {topk} ids corresponding to the most relevant {topk} passages:\n'
f'```json\n'
f'[...]\n'
f'```')
func = functools.partial(
self.model.messages.create,
max_tokens=2048,
messages=[
{
"role": "user",
"content": prompt,
}
],
model=self.version,
temperature=0.8,
top_p=0.8
)
message = call_api(func)
response = json.loads(message.model_dump_json(indent=2))
ranks = extract_program(response['content'][0]['text'],lan='json')
return [indices_map[r] for r in ranks]
class OpenAIModel:
def __init__(self, model_name, temperature=0.8, top_p=0.8):
import openai
if "azure" in model_name:
# env var: AZURE_OPENAI_API_KEY, AZURE_OPENAI_ENDPOINT, and OPENAI_API_VERSION
self.model = openai.AzureOpenAI()
model_name = model_name[model_name.index("/")+1:]
else:
# make sure to set the OPENAI_API_KEY environment variable
self.model = openai.OpenAI()
self.model_name = model_name
self.temperature = temperature
self.top_p = top_p
self.max_tokens = 2048
def rerank(self, docs, query, topk):
doc_string = ''
indices_map = {}
for doc_idx,doc in enumerate(docs):
assert isinstance(doc,list)
doc_string += "[{}]. {}\n\n".format(doc_idx + 1, re.sub('\n+', ' ', doc[1]))
indices_map[doc_idx + 1] = doc[0]
cur_query = query.replace('\n',' ')
prompt = (f'The following passages are related to query: {cur_query}\n\n'
f'{doc_string}'
f'First identify the essential problem in the query.\n'
f'Think step by step to reason about why each document is relevant or irrelevant.\n'
f'Rank these passages based on their relevance to the query.\n'
f'Please output the ranking result of passages as a list, where the first element is the id of the most relevant '
f'passage, the second element is the id of the second most element, etc.\n'
f'Please strictly follow the format to output a list of {topk} ids corresponding to the most relevant {topk} passages, sorted from the most to least relevant passage. First think step by step and write the reasoning process, then output the ranking results as a list of ids in a json format.'
)
inputs = format_chat(prompt, system_message="You are a helpful assistant")
func = functools.partial(
self.model.chat.completions.create,
model=self.model_name,
messages=inputs,
max_tokens=self.max_tokens,
temperature=self.temperature,
top_p=self.top_p,
)
def parse_json(text):
matches = re.findall(r"(?:```json\s*)(.+)(?:```)", text, re.DOTALL)
if len(matches) > 0:
try:
return json.loads(matches[-1].strip())
except:
return None
return None
output = call_api(func)
if output is not None:
response = parse_json(output.choices[0].message.content)
if response is None:
return None
return [indices_map[r] for r in response if r in indices_map]
# return output.choices[0].message.content
return None
class STReranker:
def __init__(self, model_name, batch_size=8):
self.model = CrossEncoder(model_name)
self.batch_size = batch_size
@torch.no_grad()
def rerank(self, docs, query, topk):
inputs = [(query, doc["text"]) for doc in docs]
scores = self.model.predict(inputs, batch_size=self.batch_size)
ranking = {doc["id"]: score.item() for doc, score in zip(docs, scores)}
ranking = dict(sorted(ranking.items(), key=lambda item: item[1], reverse=True)[:topk])
return ranking
if __name__=='__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--task', type=str, required=True,
choices=['biology','earth_science','economics','pony','psychology','robotics','theoremqa_questions', "theoremqa_theorems",
'stackoverflow','sustainable_living','aops','leetcode'])
parser.add_argument('--long_context', action='store_true')
parser.add_argument('--llm', type=str, default=None)
parser.add_argument('--score_file', type=str, default=None)
parser.add_argument('--rerank_score_file', type=str, default=None)
parser.add_argument('--input_k', type=int)
parser.add_argument('--k', type=int)
args = parser.parse_args()
if os.path.exists(args.rerank_score_file):
print(f"Rerank score file {args.rerank_score_file} already exists.")
exit()
raw_examples = load_dataset('xlangai/bright', 'examples')[args.task]
examples = {}
for e in raw_examples:
examples[e['id']] = e
if args.long_context:
doc_pairs = load_dataset('xlangai/bright', 'long_documents')[args.task]
else:
doc_pairs = load_dataset('xlangai/bright', 'documents')[args.task]
documents = {}
for d in doc_pairs:
documents[d['id']] = d['content']
with open(args.score_file) as f:
all_scores = json.load(f)
new_scores = copy.deepcopy(all_scores)
if 'claude' in args.llm:
model = ClaudeModel(version=args.llm)
elif "gpt" in args.llm:
model = OpenAIModel(model_name=args.llm)
else:
model = STReranker(model_name=args.llm)
for qid,scores in tqdm(all_scores.items()):
docs = []
sorted_scores = sorted(scores.items(),key=lambda x:x[1],reverse=True)[:args.input_k]
for did, _ in sorted_scores:
docs.append([did, documents[did]])
if 'claude' in args.llm or "gpt" in args.llm:
new_rank = model.rerank(docs=docs, query=examples[qid]['query'], topk=args.k)
cur_score = {}
if new_rank is None:
# use the original ranks if fail
for rank_id, (did, _) in enumerate(sorted_scores):
cur_score[did] = args.k - rank_id
else:
for rank_id, r in enumerate(new_rank):
cur_score[r] = args.k - rank_id
new_scores[qid] = cur_score
else:
ctxs = [{'id': did, 'text': documents[did]} for did, _ in sorted_scores]
cur_score = model.rerank(query=examples[qid]['query'], docs=ctxs, topk=args.k)
new_scores[qid] = cur_score
os.makedirs(os.path.dirname(args.rerank_score_file), exist_ok=True)
with open(args.rerank_score_file, 'w') as f:
json.dump(new_scores, f, indent=2)
if args.long_context:
key = 'gold_ids_long'
else:
key = 'gold_ids'
ground_truth = {}
for e in raw_examples:
ground_truth[e['id']] = {}
for gid in e[key]:
ground_truth[e['id']][gid] = 1
for i in e["excluded_ids"]:
if i in documents:
ground_truth[e['id']][i] = 0
results = calculate_retrieval_metrics(results=new_scores, qrels=ground_truth)
with open(args.rerank_score_file.replace(".json", "_results.json"), 'w') as f:
json.dump(results, f, indent=2)