Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

rerank_model.py 5.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import re
  17. import threading
  18. import requests
  19. import torch
  20. from FlagEmbedding import FlagReranker
  21. from huggingface_hub import snapshot_download
  22. import os
  23. from abc import ABC
  24. import numpy as np
  25. from api.utils.file_utils import get_home_cache_dir
  26. from rag.utils import num_tokens_from_string, truncate
  27. def sigmoid(x):
  28. return 1 / (1 + np.exp(-x))
  29. class Base(ABC):
  30. def __init__(self, key, model_name):
  31. pass
  32. def similarity(self, query: str, texts: list):
  33. raise NotImplementedError("Please implement encode method!")
  34. class DefaultRerank(Base):
  35. _model = None
  36. _model_lock = threading.Lock()
  37. def __init__(self, key, model_name, **kwargs):
  38. """
  39. If you have trouble downloading HuggingFace models, -_^ this might help!!
  40. For Linux:
  41. export HF_ENDPOINT=https://hf-mirror.com
  42. For Windows:
  43. Good luck
  44. ^_-
  45. """
  46. if not DefaultRerank._model:
  47. with DefaultRerank._model_lock:
  48. if not DefaultRerank._model:
  49. try:
  50. DefaultRerank._model = FlagReranker(os.path.join(get_home_cache_dir(), re.sub(r"^[a-zA-Z]+/", "", model_name)), use_fp16=torch.cuda.is_available())
  51. except Exception as e:
  52. model_dir = snapshot_download(repo_id= model_name,
  53. local_dir=os.path.join(get_home_cache_dir(), re.sub(r"^[a-zA-Z]+/", "", model_name)),
  54. local_dir_use_symlinks=False)
  55. DefaultRerank._model = FlagReranker(model_dir, use_fp16=torch.cuda.is_available())
  56. self._model = DefaultRerank._model
  57. def similarity(self, query: str, texts: list):
  58. pairs = [(query,truncate(t, 2048)) for t in texts]
  59. token_count = 0
  60. for _, t in pairs:
  61. token_count += num_tokens_from_string(t)
  62. batch_size = 4096
  63. res = []
  64. for i in range(0, len(pairs), batch_size):
  65. scores = self._model.compute_score(pairs[i:i + batch_size], max_length=2048)
  66. scores = sigmoid(np.array(scores)).tolist()
  67. if isinstance(scores, float): res.append(scores)
  68. else: res.extend(scores)
  69. return np.array(res), token_count
  70. class JinaRerank(Base):
  71. def __init__(self, key, model_name="jina-reranker-v1-base-en",
  72. base_url="https://api.jina.ai/v1/rerank"):
  73. self.base_url = "https://api.jina.ai/v1/rerank"
  74. self.headers = {
  75. "Content-Type": "application/json",
  76. "Authorization": f"Bearer {key}"
  77. }
  78. self.model_name = model_name
  79. def similarity(self, query: str, texts: list):
  80. texts = [truncate(t, 8196) for t in texts]
  81. data = {
  82. "model": self.model_name,
  83. "query": query,
  84. "documents": texts,
  85. "top_n": len(texts)
  86. }
  87. res = requests.post(self.base_url, headers=self.headers, json=data).json()
  88. return np.array([d["relevance_score"] for d in res["results"]]), res["usage"]["total_tokens"]
  89. class YoudaoRerank(DefaultRerank):
  90. _model = None
  91. _model_lock = threading.Lock()
  92. def __init__(self, key=None, model_name="maidalun1020/bce-reranker-base_v1", **kwargs):
  93. from BCEmbedding import RerankerModel
  94. if not YoudaoRerank._model:
  95. with YoudaoRerank._model_lock:
  96. if not YoudaoRerank._model:
  97. try:
  98. print("LOADING BCE...")
  99. YoudaoRerank._model = RerankerModel(model_name_or_path=os.path.join(
  100. get_home_cache_dir(),
  101. re.sub(r"^[a-zA-Z]+/", "", model_name)))
  102. except Exception as e:
  103. YoudaoRerank._model = RerankerModel(
  104. model_name_or_path=model_name.replace(
  105. "maidalun1020", "InfiniFlow"))
  106. self._model = YoudaoRerank._model
  107. def similarity(self, query: str, texts: list):
  108. pairs = [(query, truncate(t, self._model.max_length)) for t in texts]
  109. token_count = 0
  110. for _, t in pairs:
  111. token_count += num_tokens_from_string(t)
  112. batch_size = 32
  113. res = []
  114. for i in range(0, len(pairs), batch_size):
  115. scores = self._model.compute_score(pairs[i:i + batch_size], max_length=self._model.max_length)
  116. scores = sigmoid(np.array(scores)).tolist()
  117. if isinstance(scores, float): res.append(scores)
  118. else: res.extend(scores)
  119. return np.array(res), token_count
  120. class XInferenceRerank(Base):
  121. def __init__(self, key="xxxxxxx", model_name="", base_url=""):
  122. self.model_name = model_name
  123. self.base_url = base_url
  124. self.headers = {
  125. "Content-Type": "application/json",
  126. "accept": "application/json"
  127. }
  128. def similarity(self, query: str, texts: list):
  129. data = {
  130. "model": self.model_name,
  131. "query": query,
  132. "return_documents": "true",
  133. "return_len": "true",
  134. "documents": texts
  135. }
  136. res = requests.post(self.base_url, headers=self.headers, json=data).json()
  137. return np.array([d["relevance_score"] for d in res["results"]]), res["tokens"]["input_tokens"] + res["tokens"][
  138. "output_tokens"]