mrinjera commited on
Commit
21a3280
·
verified ·
1 Parent(s): e6fb7a8

Update reranker/rank_listwise_os_vllm.py

Browse files
Files changed (1) hide show
  1. reranker/rank_listwise_os_vllm.py +258 -0
reranker/rank_listwise_os_vllm.py CHANGED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import random
4
+ from typing import Optional, Tuple, List, Dict, Union
5
+ from concurrent.futures import ThreadPoolExecutor
6
+ from tqdm import tqdm
7
+ import torch
8
+ import numpy as np
9
+ import unicodedata
10
+ from ftfy import fix_text
11
+ from transformers.generation import GenerationConfig
12
+ from vllm import LLM, SamplingParams, RequestOutput
13
+ from rankllm import Prompt
14
+
15
+ from .rankllm import PromptMode, RankLLM
16
+ from .result import Result
17
+
18
+ ALPH_START_IDX = ord('A') - 1
19
+
20
+ class RankListwiseOSLLM(RankLLM):
21
+ def __init__(
22
+ self,
23
+ model: str,
24
+ context_size: int = 4096,
25
+ prompt_mode: PromptMode = PromptMode.RANK_GPT,
26
+ num_few_shot_examples: int = 0,
27
+ device: str = "cuda",
28
+ num_gpus: int = 1,
29
+ variable_passages: bool = False,
30
+ window_size: int = 20,
31
+ system_message: Optional[str] = None,
32
+ batched: bool = False,
33
+ rerank_type: str = "text",
34
+ code_prompt_type: str = "docstring",
35
+ ) -> None:
36
+ super().__init__(model, context_size, prompt_mode, num_few_shot_examples)
37
+ self._device = device
38
+ if self._device == "cuda":
39
+ assert torch.cuda.is_available(), "CUDA is not available on this device"
40
+ self.world_size = torch.cuda.device_count()
41
+ print(f"WORLD SIZE: {self.world_size}")
42
+ if self.world_size > 1:
43
+ os.environ['NCCL_P2P_DISABLE']='1'
44
+ os.environ['VLLM_WORKER_MULTIPROC_METHOD']='spawn'
45
+ if prompt_mode != PromptMode.RANK_GPT:
46
+ raise ValueError(
47
+ f"Unsupported prompt mode: {prompt_mode}. Only RANK_GPT is supported."
48
+ )
49
+
50
+ self._llm = LLM(model=model, max_logprobs=30, enforce_eager=False, gpu_memory_utilization=0.9, max_model_len=32768, trust_remote_code=True, enable_chunked_prefill=True, tensor_parallel_size=1)
51
+ self._tokenizer = self._llm.get_tokenizer()
52
+ self.system_message_supported = "system" in self._tokenizer.chat_template
53
+ self._batched = batched
54
+ self._variable_passages = variable_passages
55
+ self._window_size = window_size
56
+ self._system_message = system_message
57
+ self._output_token_estimate = None
58
+ self._rerank_type = rerank_type
59
+ self._code_prompt_type = code_prompt_type
60
+
61
+ if num_few_shot_examples > 0:
62
+ with open("data/output_v2_aug_filtered.jsonl", "r") as json_file:
63
+ self._examples = list(json_file)[1:-1]
64
+
65
+ def run_llm(
66
+ self, prompt: Prompt, current_window_size: Optional[int] = None
67
+ ) -> Tuple[str, int]:
68
+ """Run the language model with appropriate restrictions for code vs text reranking"""
69
+ temp = 0.
70
+ if current_window_size is None:
71
+ current_window_size = self._window_size
72
+ params = SamplingParams(
73
+ temperature=temp,
74
+ max_tokens=self.get_total_output_tokens(current_window_size),
75
+ )
76
+ output = self._llm.generate([prompt], sampling_params=params, use_tqdm=True)[0]
77
+ output_text = output.outputs[0].text.replace(self._tokenizer.eos_token, "")
78
+ self._history.append({
79
+ "prompt": prompt,
80
+ "response": output_text,
81
+ "second_run": {}
82
+ })
83
+
84
+ return output_text, len(output_text)
85
+
86
+ def run_llm_batched(
87
+ self,
88
+ prompts: List[Union[str, List[Dict[str, str]]]],
89
+ current_window_size: Optional[int] = None,
90
+ ) -> List[Tuple[str, int]]:
91
+ """Run batched inference with appropriate restrictions for code vs text reranking"""
92
+
93
+ temp = 0.
94
+ if current_window_size is None:
95
+ current_window_size = self._window_size
96
+ max_new_tokens = self.get_total_output_tokens(current_window_size)
97
+ min_new_tokens = self.get_total_output_tokens(current_window_size)
98
+ params = SamplingParams(
99
+ temperature=temp,
100
+ max_tokens=max_new_tokens,
101
+ min_tokens=min_new_tokens,
102
+ )
103
+ outputs = self._llm.generate(prompts, sampling_params=params, use_tqdm=True)
104
+ return [
105
+ (output.outputs[0].text, len(output.outputs[0].token_ids))
106
+ for output in outputs
107
+ ]
108
+
109
+ def num_output_tokens(self, current_window_size: Optional[int] = None) -> int:
110
+ if current_window_size is None:
111
+ current_window_size = self._window_size
112
+
113
+ if self._output_token_estimate and self._window_size == current_window_size:
114
+ return self._output_token_estimate
115
+
116
+ token_str = " > ".join([f"[{chr(ALPH_START_IDX+i+1)}]" for i in range(current_window_size)])
117
+
118
+ _output_token_estimate = len(self._tokenizer.encode(token_str)) + 2
119
+
120
+ if self._window_size == current_window_size:
121
+ self._output_token_estimate = _output_token_estimate
122
+ return _output_token_estimate
123
+
124
+ def get_total_output_tokens(self, current_window_size: Optional[int] = None) -> int:
125
+ """Get total number of output tokens"""
126
+ base_tokens = self.num_output_tokens(current_window_size)
127
+ return base_tokens
128
+
129
+ def _add_prefix_prompt(self, query: str, num: int) -> str:
130
+ if self._code_prompt_type == "docstring":
131
+ return self._add_prefix_prompt_doc_string(query, num)
132
+ else:
133
+ raise ValueError(f"Invalid code_prompt_type: {self._code_prompt_type}")
134
+
135
+ def _add_post_prompt(self, query: str, num: int) -> str:
136
+ if self._code_prompt_type == "docstring":
137
+ return self._add_post_prompt_doc_string(query, num)
138
+ else:
139
+ raise ValueError(f"Invalid code_prompt_type: {self._code_prompt_type}")
140
+
141
+ def _add_prefix_prompt_doc_string(self, query: str, num: int) -> str:
142
+ return f"I will provide you with {num} code snippets, each indicated by a numerical identifier []. Rank the code snippets based on their relevance to the functionality described by the following doc string: {query}.\n"
143
+
144
+ def _add_post_prompt_doc_string(self, query: str, num: int) -> str:
145
+ example_ordering = "[2] > [1]" if self._variable_passages else "[4] > [2]"
146
+ return f"Doc String: {query}.\nRank the {num} code snippets above based on their relevance to the functionality described by the doc string. All the code snippets should be included and listed using identifiers, in descending order of relevance. The output format should be [] > [], e.g., {example_ordering}. Only respond with the ranking results, do not say any word or explain."
147
+
148
+ def _add_prefix_prompt_github_issue(self, query: str, num: int) -> str:
149
+ prefix_prompt = f"I will provide you with {num} code functions, each indicated by a numerical identifier []."
150
+ prefix_prompt += f" Rank the code functions based on their relevance to contain the faults causing the GitHub issue: {query}.\n"
151
+ return prefix_prompt
152
+
153
+ def _add_few_shot_examples(self, conv):
154
+ for _ in range(self._num_few_shot_examples):
155
+ ex = random.choice(self._examples)
156
+ obj = json.loads(ex)
157
+ prompt = obj["conversations"][0]["value"]
158
+ response = obj["conversations"][1]["value"]
159
+ conv.append_message(conv.roles[0], prompt)
160
+ conv.append_message(conv.roles[1], response)
161
+ return conv
162
+
163
+ def _add_few_shot_examples_messages(self, messages):
164
+ for _ in range(self._num_few_shot_examples):
165
+ ex = random.choice(self._examples)
166
+ obj = json.loads(ex)
167
+ prompt = obj["conversations"][0]["value"]
168
+ response = obj["conversations"][1]["value"]
169
+ messages.append({"role": "user", "content": prompt})
170
+ messages.append({"role": "assistant", "content": response})
171
+ return messages
172
+
173
+ def create_prompt(self, result: Result, rank_start: int, rank_end: int) -> Tuple[str, int]:
174
+ query = result.query
175
+ max_query_len = self.get_num_tokens(query)
176
+ num = len(result.hits[rank_start:rank_end])
177
+ max_doc_length = 1024 if (self._rerank_type == "code") else 300
178
+ min_doc_length = 300
179
+ while True:
180
+ messages = list()
181
+ if self._system_message and self.system_message_supported:
182
+ messages.append({"role": "system", "content": self._system_message})
183
+ messages = self._add_few_shot_examples_messages(messages)
184
+ query_tokens = self._tokenizer.tokenize(query)[:int(max_query_len)]
185
+ truncated_query = self._tokenizer.convert_tokens_to_string(query_tokens)
186
+ prefix = self._add_prefix_prompt(truncated_query, num)
187
+ rank = 0
188
+ input_context = f"{prefix}\n"
189
+ for hit in result.hits[rank_start:rank_end]:
190
+ rank += 1
191
+ if self._rerank_type == "code":
192
+ content = hit["content"]
193
+ content = content.replace("Title: Content: ", "")
194
+ tokenized_content = self._tokenizer.tokenize(content)
195
+ content_tokens = tokenized_content[:int(max_doc_length)]
196
+ truncated_content = self._tokenizer.convert_tokens_to_string(content_tokens)
197
+ identifier = str(rank)
198
+ input_context += f"[{identifier}] {self._replace_number(truncated_content)}\n"
199
+ else:
200
+ content = hit["content"].replace("Title: Content: ", "").strip()
201
+ content = " ".join(content.split()[:max_doc_length])
202
+ identifier = str(rank)
203
+ input_context += f"[{identifier}] {self._replace_number(content)}\n"
204
+ input_context += self._add_post_prompt(truncated_query, num)
205
+ messages.append({"role": "user", "content": input_context})
206
+ if self._system_message and not self.system_message_supported:
207
+ messages[0]["content"] = self._system_message + "\n " + messages[0]["content"]
208
+ prompt = self._tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
209
+ prompt = fix_text(prompt)
210
+ num_tokens = self.get_num_tokens(prompt)
211
+ if num_tokens <= self.max_tokens() - self.get_total_output_tokens(rank_end - rank_start):
212
+ break
213
+ else:
214
+ prefix_len = len(self._tokenizer.encode(prefix))
215
+ if (len(query_tokens) + prefix_len) > (self.max_tokens() - min_doc_length *(rank_end - rank_start) - self.get_total_output_tokens(rank_end - rank_start)):
216
+ # Query truncation to ensure min doc length for each candidate document/code
217
+ offset = num_tokens - (self.max_tokens() - self.get_total_output_tokens(rank_end - rank_start))
218
+ max_query_len -= (offset//2 + 1)
219
+ else:
220
+ # Document truncation
221
+ max_doc_length -= max(
222
+ 1,
223
+ (
224
+ num_tokens - self.max_tokens() + self.get_total_output_tokens(rank_end - rank_start)
225
+ ) // ((rank_end - rank_start) * 4),
226
+ )
227
+ return prompt, num_tokens
228
+
229
+ def create_prompt_batched(
230
+ self,
231
+ results: List[Result],
232
+ rank_start: int,
233
+ rank_end: int,
234
+ batch_size: int = 32,
235
+ ) -> List[Tuple[Prompt, int]]:
236
+ def chunks(lst, n):
237
+ """Yield successive n-sized chunks from lst."""
238
+ for i in range(0, len(lst), n):
239
+ yield lst[i : i + n]
240
+
241
+ all_completed_prompts = []
242
+
243
+ with ThreadPoolExecutor() as executor:
244
+ for batch in chunks(results, batch_size):
245
+ completed_prompts = list(
246
+ executor.map(
247
+ lambda result: self.create_prompt(result, rank_start, rank_end),
248
+ batch,
249
+ )
250
+ )
251
+ all_completed_prompts.extend(completed_prompts)
252
+ return all_completed_prompts
253
+
254
+ def get_num_tokens(self, prompt: str) -> int:
255
+ return len(self._tokenizer.encode(prompt))
256
+
257
+ def cost_per_1k_token(self, input_token: bool) -> float:
258
+ return 0