faisser.py 12 KB

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