faiss.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import os
  15. import pickle
  16. from pathlib import Path
  17. import faiss
  18. import numpy as np
  19. from ....utils import logging
  20. from ...utils.io import YAMLWriter, YAMLReader
  21. from ..base import BaseComponent
  22. class IndexData:
  23. VECTOR_FN = "vector"
  24. VECTOR_SUFFIX = ".index"
  25. IDMAP_FN = "id_map"
  26. IDMAP_SUFFIX = ".yaml"
  27. def __init__(self, index, index_info):
  28. self._index = index
  29. self._index_info = index_info
  30. self._id_map = index_info["id_map"]
  31. self._metric_type = index_info["metric_type"]
  32. self._index_type = index_info["index_type"]
  33. @property
  34. def index(self):
  35. return self._index
  36. @property
  37. def index_bytes(self):
  38. return faiss.serialize_index(self._index)
  39. @property
  40. def id_map(self):
  41. return self._id_map
  42. @property
  43. def metric_type(self):
  44. return self._metric_type
  45. @property
  46. def index_type(self):
  47. return self._index_type
  48. @property
  49. def index_info(self):
  50. return {
  51. "index_type": self.index_type,
  52. "metric_type": self.metric_type,
  53. "id_map": self._convert_int(self.id_map),
  54. }
  55. def _convert_int(self, id_map):
  56. return {int(k): str(v) for k, v in id_map.items()}
  57. @staticmethod
  58. def _convert_int64(id_map):
  59. return {np.int64(k): str(v) for k, v in id_map.items()}
  60. def save(self, save_dir):
  61. save_dir = Path(save_dir)
  62. save_dir.mkdir(parents=True, exist_ok=True)
  63. vector_path = (save_dir / f"{self.VECTOR_FN}{self.VECTOR_SUFFIX}").as_posix()
  64. index_info_path = (save_dir / f"{self.IDMAP_FN}{self.IDMAP_SUFFIX}").as_posix()
  65. if self.metric_type in FaissBuilder.BINARY_METRIC_TYPE:
  66. faiss.write_index_binary(self.index, vector_path)
  67. else:
  68. faiss.write_index(self.index, vector_path)
  69. yaml_writer = YAMLWriter()
  70. yaml_writer.write(
  71. index_info_path,
  72. self.index_info,
  73. default_flow_style=False,
  74. allow_unicode=True,
  75. )
  76. @classmethod
  77. def load(cls, index):
  78. if isinstance(index, str):
  79. index_root = Path(index)
  80. vector_path = index_root / f"{cls.VECTOR_FN}{cls.VECTOR_SUFFIX}"
  81. index_info_path = index_root / f"{cls.IDMAP_FN}{cls.IDMAP_SUFFIX}"
  82. assert (
  83. vector_path.exists()
  84. ), f"Not found the {cls.VECTOR_FN}{cls.VECTOR_SUFFIX} file in {index}!"
  85. assert (
  86. index_info_path.exists()
  87. ), f"Not found the {cls.IDMAP_FN}{cls.IDMAP_SUFFIX} file in {index}!"
  88. yaml_reader = YAMLReader()
  89. index_info = yaml_reader.read(index_info_path)
  90. assert (
  91. "id_map" in index_info
  92. and "metric_type" in index_info
  93. and "index_type" in index_info
  94. ), f"The index_info file({index_info_path}) may have been damaged, `id_map` or `metric_type` or `index_type` not found in `index_info`."
  95. id_map = IndexData._convert_int64(index_info["id_map"])
  96. if index_info["metric_type"] in FaissBuilder.BINARY_METRIC_TYPE:
  97. index = faiss.read_index_binary(vector_path.as_posix())
  98. else:
  99. index = faiss.read_index(vector_path.as_posix())
  100. assert index.ntotal == len(
  101. id_map
  102. ), "data number in index is not equal in in id_map"
  103. return index, id_map, index_info["metric_type"], index_info["index_type"]
  104. else:
  105. assert isinstance(index, IndexData)
  106. return index.index, index.id_map, index.metric_type, index.index_type
  107. class FaissIndexer(BaseComponent):
  108. INPUT_KEYS = "feature"
  109. OUTPUT_KEYS = ["label", "score"]
  110. DEAULT_INPUTS = {"feature": "feature"}
  111. DEAULT_OUTPUTS = {"label": "label", "score": "score"}
  112. ENABLE_BATCH = True
  113. def __init__(
  114. self,
  115. index,
  116. return_k=1,
  117. score_thres=None,
  118. hamming_radius=None,
  119. ):
  120. super().__init__()
  121. self._indexer, self.id_map, self.metric_type, index_type = IndexData.load(index)
  122. self.return_k = return_k
  123. if self.metric_type in FaissBuilder.BINARY_METRIC_TYPE:
  124. self.hamming_radius = hamming_radius
  125. else:
  126. self.score_thres = score_thres
  127. def apply(self, feature):
  128. """apply"""
  129. scores_list, ids_list = self._indexer.search(np.array(feature), self.return_k)
  130. preds = []
  131. for scores, ids in zip(scores_list, ids_list):
  132. labels = []
  133. for id in ids:
  134. if id > 0:
  135. labels.append(self.id_map[id])
  136. preds.append({"score": scores, "label": labels})
  137. if self.metric_type in FaissBuilder.BINARY_METRIC_TYPE:
  138. idxs = np.where(scores_list[:, 0] > self.hamming_radius)[0]
  139. else:
  140. idxs = np.where(scores_list[:, 0] < self.score_thres)[0]
  141. for idx in idxs:
  142. preds[idx] = {"score": None, "label": None}
  143. return preds
  144. class FaissBuilder:
  145. SUPPORT_METRIC_TYPE = ("hamming", "IP", "L2")
  146. SUPPORT_INDEX_TYPE = ("Flat", "IVF", "HNSW32")
  147. BINARY_METRIC_TYPE = ("hamming",)
  148. BINARY_SUPPORT_INDEX_TYPE = ("Flat", "IVF", "BinaryHash")
  149. @classmethod
  150. def _get_index_type(cls, metric_type, index_type, num=None):
  151. # if IVF method, cal ivf number automaticlly
  152. if index_type == "IVF":
  153. index_type = index_type + str(min(int(num // 8), 65536))
  154. if metric_type in cls.BINARY_METRIC_TYPE:
  155. index_type += ",BFlat"
  156. else:
  157. index_type += ",Flat"
  158. # for binary index, add B at head of index_type
  159. if metric_type in cls.BINARY_METRIC_TYPE:
  160. assert (
  161. index_type in cls.BINARY_SUPPORT_INDEX_TYPE
  162. ), f"The metric type({metric_type}) only support {cls.BINARY_SUPPORT_INDEX_TYPE} index types!"
  163. index_type = "B" + index_type
  164. if index_type == "HNSW32":
  165. logging.warning("The HNSW32 method dose not support 'remove' operation")
  166. index_type = "HNSW32"
  167. if index_type == "Flat":
  168. index_type = "Flat"
  169. return index_type
  170. @classmethod
  171. def _get_metric_type(cls, metric_type):
  172. if metric_type == "hamming":
  173. return faiss.METRIC_Hamming
  174. elif metric_type == "jaccard":
  175. return faiss.METRIC_Jaccard
  176. elif metric_type == "IP":
  177. return faiss.METRIC_INNER_PRODUCT
  178. elif metric_type == "L2":
  179. return faiss.METRIC_L2
  180. @classmethod
  181. def build(
  182. cls,
  183. gallery_imgs,
  184. gallery_label,
  185. predict_func,
  186. metric_type="IP",
  187. index_type="HNSW32",
  188. ):
  189. assert (
  190. index_type in cls.SUPPORT_INDEX_TYPE
  191. ), f"Supported index types only: {cls.SUPPORT_INDEX_TYPE}!"
  192. assert (
  193. metric_type in cls.SUPPORT_METRIC_TYPE
  194. ), f"Supported metric types only: {cls.SUPPORT_METRIC_TYPE}!"
  195. if isinstance(gallery_label, str):
  196. gallery_docs, gallery_list = cls.load_gallery(gallery_label, gallery_imgs)
  197. else:
  198. gallery_docs, gallery_list = gallery_label, gallery_imgs
  199. features = [res["feature"] for res in predict_func(gallery_list)]
  200. dtype = np.uint8 if metric_type in cls.BINARY_METRIC_TYPE else np.float32
  201. features = np.array(features).astype(dtype)
  202. vector_num, vector_dim = features.shape
  203. if metric_type in cls.BINARY_METRIC_TYPE:
  204. index = faiss.index_binary_factory(
  205. vector_dim,
  206. cls._get_index_type(metric_type, index_type, vector_num),
  207. cls._get_metric_type(metric_type),
  208. )
  209. else:
  210. index = faiss.index_factory(
  211. vector_dim,
  212. cls._get_index_type(metric_type, index_type, vector_num),
  213. cls._get_metric_type(metric_type),
  214. )
  215. index = faiss.IndexIDMap2(index)
  216. ids = {}
  217. # calculate id for new data
  218. index, ids = cls._add_gallery(
  219. metric_type, index, ids, features, gallery_docs, mode="new"
  220. )
  221. return IndexData(
  222. index, {"id_map": ids, "metric_type": metric_type, "index_type": index_type}
  223. )
  224. @classmethod
  225. def remove(
  226. cls,
  227. remove_ids,
  228. index,
  229. ):
  230. index, ids, metric_type, index_type = IndexData.load(index)
  231. if index_type == "HNSW32":
  232. raise RuntimeError(
  233. "The index_type: HNSW32 dose not support 'remove' operation"
  234. )
  235. if isinstance(remove_ids, str):
  236. lines = []
  237. with open(remove_ids) as f:
  238. lines = f.readlines()
  239. remove_ids = []
  240. for line in lines:
  241. id_ = int(line.strip().split(" ")[0])
  242. remove_ids.append(id_)
  243. remove_ids = np.asarray(remove_ids)
  244. else:
  245. remove_ids = np.asarray(remove_ids)
  246. # remove ids in id_map, remove index data in faiss index
  247. index.remove_ids(remove_ids)
  248. ids = {k: v for k, v in ids.items() if k not in remove_ids}
  249. return IndexData(
  250. index, {"id_map": ids, "metric_type": metric_type, "index_type": index_type}
  251. )
  252. @classmethod
  253. def append(cls, gallery_imgs, gallery_label, predict_func, index):
  254. index, ids, metric_type, index_type = IndexData.load(index)
  255. assert (
  256. metric_type in cls.SUPPORT_METRIC_TYPE
  257. ), f"Supported metric types only: {cls.SUPPORT_METRIC_TYPE}!"
  258. if isinstance(gallery_label, str):
  259. gallery_docs, gallery_list = cls.load_gallery(gallery_label, gallery_imgs)
  260. else:
  261. gallery_docs, gallery_list = gallery_label, gallery_imgs
  262. features = [res["feature"] for res in predict_func(gallery_list)]
  263. dtype = np.uint8 if metric_type in cls.BINARY_METRIC_TYPE else np.float32
  264. features = np.array(features).astype(dtype)
  265. # calculate id for new data
  266. index, ids = cls._add_gallery(
  267. metric_type, index, ids, features, gallery_docs, mode="append"
  268. )
  269. return IndexData(
  270. index, {"id_map": ids, "metric_type": metric_type, "index_type": index_type}
  271. )
  272. @classmethod
  273. def _add_gallery(
  274. cls, metric_type, index, ids, gallery_features, gallery_docs, mode
  275. ):
  276. start_id = max(ids.keys()) + 1 if ids else 0
  277. ids_now = (np.arange(0, len(gallery_docs)) + start_id).astype(np.int64)
  278. # only train when new index file
  279. if mode == "new":
  280. if metric_type in cls.BINARY_METRIC_TYPE:
  281. index.add(gallery_features)
  282. else:
  283. index.train(gallery_features)
  284. if not metric_type in cls.BINARY_METRIC_TYPE:
  285. index.add_with_ids(gallery_features, ids_now)
  286. for i, d in zip(list(ids_now), gallery_docs):
  287. ids[i] = d
  288. return index, ids
  289. @classmethod
  290. def load_gallery(cls, gallery_label_path, gallery_imgs_root="", delimiter=" "):
  291. lines = []
  292. files = []
  293. labels = []
  294. root = Path(gallery_imgs_root)
  295. with open(gallery_label_path, "r", encoding="utf-8") as f:
  296. lines = f.readlines()
  297. for line in lines:
  298. path, label = line.strip().split(delimiter)
  299. file_path = root / path
  300. files.append(file_path.as_posix())
  301. labels.append(label)
  302. return labels, files