You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

rerank_model.py 4.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  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 requests
  18. import torch
  19. from FlagEmbedding import FlagReranker
  20. from huggingface_hub import snapshot_download
  21. import os
  22. from abc import ABC
  23. import numpy as np
  24. from api.utils.file_utils import get_home_cache_dir
  25. from rag.utils import num_tokens_from_string, truncate
  26. def sigmoid(x):
  27. return 1 / (1 + np.exp(-x))
  28. class Base(ABC):
  29. def __init__(self, key, model_name):
  30. pass
  31. def similarity(self, query: str, texts: list):
  32. raise NotImplementedError("Please implement encode method!")
  33. class DefaultRerank(Base):
  34. _model = None
  35. def __init__(self, key, model_name, **kwargs):
  36. """
  37. If you have trouble downloading HuggingFace models, -_^ this might help!!
  38. For Linux:
  39. export HF_ENDPOINT=https://hf-mirror.com
  40. For Windows:
  41. Good luck
  42. ^_-
  43. """
  44. if not DefaultRerank._model:
  45. try:
  46. self._model = FlagReranker(os.path.join(get_home_cache_dir(), re.sub(r"^[a-zA-Z]+/", "", model_name)),
  47. use_fp16=torch.cuda.is_available())
  48. except Exception as e:
  49. self._model = snapshot_download(repo_id=model_name,
  50. local_dir=os.path.join(get_home_cache_dir(),
  51. re.sub(r"^[a-zA-Z]+/", "", model_name)),
  52. local_dir_use_symlinks=False)
  53. self._model = FlagReranker(os.path.join(get_home_cache_dir(), model_name),
  54. use_fp16=torch.cuda.is_available())
  55. def similarity(self, query: str, texts: list):
  56. pairs = [(query,truncate(t, 2048)) for t in texts]
  57. token_count = 0
  58. for _, t in pairs:
  59. token_count += num_tokens_from_string(t)
  60. batch_size = 4096
  61. res = []
  62. for i in range(0, len(pairs), batch_size):
  63. scores = self._model.compute_score(pairs[i:i + batch_size], max_length=2048)
  64. scores = sigmoid(np.array(scores)).tolist()
  65. if isinstance(scores, float): res.append(scores)
  66. else: res.extend(scores)
  67. return np.array(res), token_count
  68. class JinaRerank(Base):
  69. def __init__(self, key, model_name="jina-reranker-v1-base-en",
  70. base_url="https://api.jina.ai/v1/rerank"):
  71. self.base_url = "https://api.jina.ai/v1/rerank"
  72. self.headers = {
  73. "Content-Type": "application/json",
  74. "Authorization": f"Bearer {key}"
  75. }
  76. self.model_name = model_name
  77. def similarity(self, query: str, texts: list):
  78. texts = [truncate(t, 8196) for t in texts]
  79. data = {
  80. "model": self.model_name,
  81. "query": query,
  82. "documents": texts,
  83. "top_n": len(texts)
  84. }
  85. res = requests.post(self.base_url, headers=self.headers, json=data).json()
  86. return np.array([d["relevance_score"] for d in res["results"]]), res["usage"]["total_tokens"]
  87. class YoudaoRerank(DefaultRerank):
  88. _model = None
  89. def __init__(self, key=None, model_name="maidalun1020/bce-reranker-base_v1", **kwargs):
  90. from BCEmbedding import RerankerModel
  91. if not YoudaoRerank._model:
  92. try:
  93. print("LOADING BCE...")
  94. YoudaoRerank._model = RerankerModel(model_name_or_path=os.path.join(
  95. get_home_cache_dir(),
  96. re.sub(r"^[a-zA-Z]+/", "", model_name)))
  97. except Exception as e:
  98. YoudaoRerank._model = RerankerModel(
  99. model_name_or_path=model_name.replace(
  100. "maidalun1020", "InfiniFlow"))
  101. def similarity(self, query: str, texts: list):
  102. pairs = [(query, truncate(t, self._model.max_length)) for t in texts]
  103. token_count = 0
  104. for _, t in pairs:
  105. token_count += num_tokens_from_string(t)
  106. batch_size = 32
  107. res = []
  108. for i in range(0, len(pairs), batch_size):
  109. scores = self._model.compute_score(pairs[i:i + batch_size], max_length=self._model.max_length)
  110. scores = sigmoid(np.array(scores)).tolist()
  111. if isinstance(scores, float): res.append(scores)
  112. else: res.extend(scores)
  113. return np.array(res), token_count