Blame view

reranker/backends/qwen3_vllm.py 12.3 KB
701ae503   tangwang   docs
1
2
3
4
5
6
7
8
9
10
11
  """
  Qwen3-Reranker-0.6B backend using vLLM.
  
  Reference: https://huggingface.co/Qwen/Qwen3-Reranker-0.6B
  Requires: vllm>=0.8.5, transformers; GPU recommended.
  """
  
  from __future__ import annotations
  
  import logging
  import math
9f5994b4   tangwang   reranker
12
  import os
efd435cf   tangwang   tei性能调优:
13
  import threading
701ae503   tangwang   docs
14
  import time
9f5994b4   tangwang   reranker
15
16
  from typing import Any, Dict, List, Tuple
  
701ae503   tangwang   docs
17
18
  logger = logging.getLogger("reranker.backends.qwen3_vllm")
  
3d588bef   tangwang   embeddings
19
20
21
22
  import torch
  from transformers import AutoTokenizer
  from vllm import LLM, SamplingParams
  from vllm.inputs.data import TokensPrompt
701ae503   tangwang   docs
23
24
  
  
985752f5   tangwang   1. 前端调试功能
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
  def deduplicate_with_positions(texts: List[str]) -> Tuple[List[str], List[int]]:
      """
      Deduplicate texts globally while preserving first-seen order.
  
      Returns:
          unique_texts: deduplicated texts in first-seen order
          position_to_unique: mapping from each original position to unique index
      """
      unique_texts: List[str] = []
      position_to_unique: List[int] = []
      seen: Dict[str, int] = {}
  
      for text in texts:
          idx = seen.get(text)
          if idx is None:
              idx = len(unique_texts)
              seen[text] = idx
              unique_texts.append(text)
          position_to_unique.append(idx)
  
      return unique_texts, position_to_unique
  
  
749d78c8   tangwang   支持 reranker精简inst...
48
49
50
51
52
53
54
55
56
57
58
59
60
  def _format_instruction__standard(instruction: str, query: str, doc: str) -> List[Dict[str, str]]:
      """Build chat messages for one (query, doc) pair."""
      return [
          {
              "role": "system",
              "content": "Judge whether the Document meets the requirements based on the Query and the Instruct provided. Note that the answer can only be \"yes\" or \"no\".",
          },
          {
              "role": "user",
              "content": f"<Instruct>: {instruction}\n\n<Query>: {query}\n\n<Document>: {doc}",
          },
      ]
  
701ae503   tangwang   docs
61
62
63
64
65
  def _format_instruction(instruction: str, query: str, doc: str) -> List[Dict[str, str]]:
      """Build chat messages for one (query, doc) pair."""
      return [
          {
              "role": "system",
9de5ef49   tangwang   qwen3_vllm_score ...
66
              "content": instruction,
701ae503   tangwang   docs
67
68
69
          },
          {
              "role": "user",
749d78c8   tangwang   支持 reranker精简inst...
70
              "content": f"<Instruct>: {instruction}\n\n<Query>: {query}\n\n<Document>: {doc}",
701ae503   tangwang   docs
71
72
73
          },
      ]
  
701ae503   tangwang   docs
74
75
76
77
78
79
80
81
82
  class Qwen3VLLMRerankerBackend:
      """
      Qwen3-Reranker-0.6B with vLLM inference.
      Config from services.rerank.backends.qwen3_vllm.
      """
  
      def __init__(self, config: Dict[str, Any]) -> None:
          self._config = config or {}
          model_name = str(self._config.get("model_name") or "Qwen/Qwen3-Reranker-0.6B")
07cf5a93   tangwang   START_EMBEDDING=...
83
          max_model_len = int(self._config.get("max_model_len", 2048))
701ae503   tangwang   docs
84
          tensor_parallel_size = int(self._config.get("tensor_parallel_size", 1))
07cf5a93   tangwang   START_EMBEDDING=...
85
86
87
88
          gpu_memory_utilization = float(self._config.get("gpu_memory_utilization", 0.4))
          enable_prefix_caching = bool(self._config.get("enable_prefix_caching", False))
          enforce_eager = bool(self._config.get("enforce_eager", True))
          dtype = str(self._config.get("dtype", "float16")).strip().lower()
701ae503   tangwang   docs
89
90
          self._instruction = str(
              self._config.get("instruction")
fb973d19   tangwang   configs
91
              or "Given a query, score the product for relevance"
701ae503   tangwang   docs
92
          )
749d78c8   tangwang   支持 reranker精简inst...
93
94
95
96
97
98
99
100
101
102
103
          _fmt = str(self._config.get("instruction_format") or "compact").strip().lower()
          if _fmt not in {"standard", "compact"}:
              raise ValueError(
                  f"instruction_format must be 'standard' or 'compact', got {_fmt!r}"
              )
          self._instruction_format = _fmt
          self._format_messages = (
              _format_instruction__standard
              if self._instruction_format == "standard"
              else _format_instruction
          )
9f5994b4   tangwang   reranker
104
105
106
107
          infer_batch_size = os.getenv("RERANK_VLLM_INFER_BATCH_SIZE") or self._config.get("infer_batch_size", 64)
          sort_by_doc_length = os.getenv("RERANK_VLLM_SORT_BY_DOC_LENGTH")
          if sort_by_doc_length is None:
              sort_by_doc_length = self._config.get("sort_by_doc_length", True)
9f5994b4   tangwang   reranker
108
109
110
  
          self._infer_batch_size = int(infer_batch_size)
          self._sort_by_doc_length = str(sort_by_doc_length).strip().lower() in {"1", "true", "yes", "y", "on"}
07cf5a93   tangwang   START_EMBEDDING=...
111
112
113
114
          if not torch.cuda.is_available():
              raise RuntimeError("qwen3_vllm backend requires CUDA GPU, but torch.cuda.is_available() is False")
          if dtype not in {"float16", "half", "auto"}:
              raise ValueError(f"Unsupported dtype for qwen3_vllm: {dtype!r}. Use float16/half/auto.")
9f5994b4   tangwang   reranker
115
          if self._infer_batch_size <= 0:
985752f5   tangwang   1. 前端调试功能
116
117
118
              raise ValueError(
                  f"infer_batch_size must be > 0, got {self._infer_batch_size}"
              )
701ae503   tangwang   docs
119
120
  
          logger.info(
749d78c8   tangwang   支持 reranker精简inst...
121
122
              "[Qwen3_VLLM] Loading model %s (max_model_len=%s, tp=%s, gpu_mem=%.2f, dtype=%s, prefix_caching=%s, "
              "instruction_format=%s)",
701ae503   tangwang   docs
123
124
125
              model_name,
              max_model_len,
              tensor_parallel_size,
07cf5a93   tangwang   START_EMBEDDING=...
126
127
              gpu_memory_utilization,
              dtype,
701ae503   tangwang   docs
128
              enable_prefix_caching,
749d78c8   tangwang   支持 reranker精简inst...
129
              self._instruction_format,
701ae503   tangwang   docs
130
131
132
133
134
135
136
137
          )
  
          self._llm = LLM(
              model=model_name,
              tensor_parallel_size=tensor_parallel_size,
              max_model_len=max_model_len,
              gpu_memory_utilization=gpu_memory_utilization,
              enable_prefix_caching=enable_prefix_caching,
07cf5a93   tangwang   START_EMBEDDING=...
138
139
              enforce_eager=enforce_eager,
              dtype=dtype,
701ae503   tangwang   docs
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
          )
          self._tokenizer = AutoTokenizer.from_pretrained(model_name)
          self._tokenizer.padding_side = "left"
          self._tokenizer.pad_token = self._tokenizer.eos_token
  
          # Suffix for generation prompt (assistant answer)
          self._suffix = "<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n"
          self._suffix_tokens = self._tokenizer.encode(
              self._suffix, add_special_tokens=False
          )
          self._max_prompt_len = max_model_len - len(self._suffix_tokens)
  
          self._true_token = self._tokenizer("yes", add_special_tokens=False).input_ids[0]
          self._false_token = self._tokenizer("no", add_special_tokens=False).input_ids[0]
          self._sampling_params = SamplingParams(
              temperature=0,
              max_tokens=1,
              logprobs=20,
              allowed_token_ids=[self._true_token, self._false_token],
          )
efd435cf   tangwang   tei性能调优:
160
161
162
          # vLLM generate path is unstable under concurrent calls in this process model.
          # Serialize infer calls to avoid engine-core protocol corruption.
          self._infer_lock = threading.Lock()
701ae503   tangwang   docs
163
164
165
166
167
168
169
170
  
          self._model_name = model_name
          logger.info("[Qwen3_VLLM] Model ready | model=%s", model_name)
  
      def _process_inputs(
          self,
          pairs: List[Tuple[str, str]],
      ) -> List[TokensPrompt]:
bc089b43   tangwang   refactor(reranker...
171
172
          """Build tokenized prompts for vLLM from (query, doc) pairs. Batch apply_chat_template."""
          messages_batch = [
749d78c8   tangwang   支持 reranker精简inst...
173
              self._format_messages(self._instruction, q, d) for q, d in pairs
bc089b43   tangwang   refactor(reranker...
174
175
176
177
178
179
180
181
182
183
184
185
186
          ]
          tokenized = self._tokenizer.apply_chat_template(
              messages_batch,
              tokenize=True,
              add_generation_prompt=False,
              enable_thinking=False,
          )
          # Single conv returns flat list; batch returns list of lists
          if tokenized and not isinstance(tokenized[0], list):
              tokenized = [tokenized]
          prompts = [
              TokensPrompt(
                  prompt_token_ids=ids[: self._max_prompt_len] + self._suffix_tokens
701ae503   tangwang   docs
187
              )
bc089b43   tangwang   refactor(reranker...
188
189
              for ids in tokenized
          ]
701ae503   tangwang   docs
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
          return prompts
  
      def _compute_scores(
          self,
          prompts: List[TokensPrompt],
      ) -> List[float]:
          """Run vLLM generate and compute yes/no probability per prompt."""
          if not prompts:
              return []
          outputs = self._llm.generate(prompts, self._sampling_params, use_tqdm=False)
          scores = []
          for i in range(len(outputs)):
              out = outputs[i]
              if not out.outputs:
                  scores.append(0.0)
                  continue
bc089b43   tangwang   refactor(reranker...
206
207
              final_logits = out.outputs[0].logprobs
              if not final_logits:
701ae503   tangwang   docs
208
209
                  scores.append(0.0)
                  continue
bc089b43   tangwang   refactor(reranker...
210
211
212
213
214
215
216
217
218
219
220
221
222
              last = final_logits[-1]
              # Match official: missing token -> logprob = -10
              if self._true_token not in last:
                  true_logit = -10
              else:
                  true_logit = last[self._true_token].logprob
              if self._false_token not in last:
                  false_logit = -10
              else:
                  false_logit = last[self._false_token].logprob
              true_score = math.exp(true_logit)
              false_score = math.exp(false_logit)
              score = true_score / (true_score + false_score)
701ae503   tangwang   docs
223
224
225
              scores.append(float(score))
          return scores
  
9f5994b4   tangwang   reranker
226
227
228
229
230
231
232
      def _estimate_doc_lengths(self, docs: List[str]) -> List[int]:
          """
          Estimate token lengths for sorting documents into similar-length batches.
          Falls back to character length when tokenizer length output is unavailable.
          """
          if not docs:
              return []
985752f5   tangwang   1. 前端调试功能
233
          # Use simple character length to approximate document length.
9f5994b4   tangwang   reranker
234
235
          return [len(text) for text in docs]
  
701ae503   tangwang   docs
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
      def score_with_meta(
          self,
          query: str,
          docs: List[str],
          normalize: bool = True,
      ) -> Tuple[List[float], Dict[str, Any]]:
          start_ts = time.time()
          total_docs = len(docs) if docs else 0
          output_scores: List[float] = [0.0] * total_docs
  
          query = "" if query is None else str(query).strip()
          indexed: List[Tuple[int, str]] = []
          for i, doc in enumerate(docs or []):
              if doc is None:
                  continue
              text = str(doc).strip()
              if not text:
                  continue
              indexed.append((i, text))
  
          if not query or not indexed:
              elapsed_ms = (time.time() - start_ts) * 1000.0
              return output_scores, {
                  "input_docs": total_docs,
                  "usable_docs": len(indexed),
                  "unique_docs": 0,
                  "dedup_ratio": 0.0,
                  "elapsed_ms": round(elapsed_ms, 3),
                  "model": self._model_name,
                  "backend": "qwen3_vllm",
                  "normalize": normalize,
9f5994b4   tangwang   reranker
267
268
269
                  "infer_batch_size": self._infer_batch_size,
                  "inference_batches": 0,
                  "sort_by_doc_length": self._sort_by_doc_length,
749d78c8   tangwang   支持 reranker精简inst...
270
                  "instruction_format": self._instruction_format,
701ae503   tangwang   docs
271
272
              }
  
9f5994b4   tangwang   reranker
273
274
275
276
277
278
279
          # Deduplicate globally by text, keep mapping to original indices.
          indexed_texts = [text for _, text in indexed]
          unique_texts, position_to_unique = deduplicate_with_positions(indexed_texts)
  
          lengths = self._estimate_doc_lengths(unique_texts)
          order = list(range(len(unique_texts)))
          if self._sort_by_doc_length and len(unique_texts) > 1:
985752f5   tangwang   1. 前端调试功能
280
              order = sorted(order, key=lambda i: lengths[i])
9f5994b4   tangwang   reranker
281
282
283
  
          unique_scores: List[float] = [0.0] * len(unique_texts)
          inference_batches = 0
985752f5   tangwang   1. 前端调试功能
284
285
          for start in range(0, len(order), self._infer_batch_size):
              batch_indices = order[start : start + self._infer_batch_size]
9f5994b4   tangwang   reranker
286
287
              inference_batches += 1
              pairs = [(query, unique_texts[i]) for i in batch_indices]
efd435cf   tangwang   tei性能调优:
288
              prompts = self._process_inputs(pairs)
9f5994b4   tangwang   reranker
289
290
291
292
293
294
295
296
              with self._infer_lock:
                  batch_scores = self._compute_scores(prompts)
              if len(batch_scores) != len(batch_indices):
                  raise RuntimeError(
                      f"Reranker score size mismatch: expected {len(batch_indices)}, got {len(batch_scores)}"
                  )
              for idx, score in zip(batch_indices, batch_scores):
                  unique_scores[idx] = float(score)
701ae503   tangwang   docs
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
  
          for (orig_idx, _), unique_idx in zip(indexed, position_to_unique):
              # Score is already P(yes) in [0,1] from yes/(yes+no)
              output_scores[orig_idx] = float(unique_scores[unique_idx])
  
          elapsed_ms = (time.time() - start_ts) * 1000.0
          dedup_ratio = 0.0
          if indexed:
              dedup_ratio = 1.0 - (len(unique_texts) / float(len(indexed)))
  
          meta = {
              "input_docs": total_docs,
              "usable_docs": len(indexed),
              "unique_docs": len(unique_texts),
              "dedup_ratio": round(dedup_ratio, 4),
              "elapsed_ms": round(elapsed_ms, 3),
              "model": self._model_name,
              "backend": "qwen3_vllm",
              "normalize": normalize,
9f5994b4   tangwang   reranker
316
317
              "infer_batch_size": self._infer_batch_size,
              "inference_batches": inference_batches,
749d78c8   tangwang   支持 reranker精简inst...
318
319
              "sort_by_doc_length": self._sort_by_doc_length,
              "instruction_format": self._instruction_format,
701ae503   tangwang   docs
320
321
          }
          return output_scores, meta