quantization.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. from __future__ import annotations
  2. import logging
  3. import time
  4. from typing import TYPE_CHECKING, Literal
  5. import numpy as np
  6. from torch import Tensor
  7. logger = logging.getLogger(__name__)
  8. if TYPE_CHECKING:
  9. import faiss
  10. import usearch
  11. def semantic_search_faiss(
  12. query_embeddings: np.ndarray,
  13. corpus_embeddings: np.ndarray | None = None,
  14. corpus_index: faiss.Index | None = None,
  15. corpus_precision: Literal["float32", "uint8", "ubinary"] = "float32",
  16. top_k: int = 10,
  17. ranges: np.ndarray | None = None,
  18. calibration_embeddings: np.ndarray | None = None,
  19. rescore: bool = True,
  20. rescore_multiplier: int = 2,
  21. exact: bool = True,
  22. output_index: bool = False,
  23. ) -> tuple[list[list[dict[str, int | float]]], float, faiss.Index]:
  24. """
  25. Performs semantic search using the FAISS library.
  26. Rescoring will be performed if:
  27. 1. `rescore` is True
  28. 2. The query embeddings are not quantized
  29. 3. The corpus is quantized, i.e. the corpus precision is not float32
  30. Only if these conditions are true, will we search for `top_k * rescore_multiplier` samples and then rescore to only
  31. keep `top_k`.
  32. Args:
  33. query_embeddings: Embeddings of the query sentences. Ideally not
  34. quantized to allow for rescoring.
  35. corpus_embeddings: Embeddings of the corpus sentences. Either
  36. `corpus_embeddings` or `corpus_index` should be used, not
  37. both. The embeddings can be quantized to "int8" or "binary"
  38. for more efficient search.
  39. corpus_index: FAISS index for the corpus sentences. Either
  40. `corpus_embeddings` or `corpus_index` should be used, not
  41. both.
  42. corpus_precision: Precision of the corpus embeddings. The
  43. options are "float32", "int8", or "binary". Default is
  44. "float32".
  45. top_k: Number of top results to retrieve. Default is 10.
  46. ranges: Ranges for quantization of embeddings. This is only used
  47. for int8 quantization, where the ranges refers to the
  48. minimum and maximum values for each dimension. So, it's a 2D
  49. array with shape (2, embedding_dim). Default is None, which
  50. means that the ranges will be calculated from the
  51. calibration embeddings.
  52. calibration_embeddings: Embeddings used for calibration during
  53. quantization. This is only used for int8 quantization, where
  54. the calibration embeddings can be used to compute ranges,
  55. i.e. the minimum and maximum values for each dimension.
  56. Default is None, which means that the ranges will be
  57. calculated from the query embeddings. This is not
  58. recommended.
  59. rescore: Whether to perform rescoring. Note that rescoring still
  60. will only be used if the query embeddings are not quantized
  61. and the corpus is quantized, i.e. the corpus precision is
  62. not "float32". Default is True.
  63. rescore_multiplier: Oversampling factor for rescoring. The code
  64. will now search `top_k * rescore_multiplier` samples and
  65. then rescore to only keep `top_k`. Default is 2.
  66. exact: Whether to use exact search or approximate search.
  67. Default is True.
  68. output_index: Whether to output the FAISS index used for the
  69. search. Default is False.
  70. Returns:
  71. A tuple containing a list of search results and the time taken
  72. for the search. If `output_index` is True, the tuple will also
  73. contain the FAISS index used for the search.
  74. Raises:
  75. ValueError: If both `corpus_embeddings` and `corpus_index` are
  76. provided or if neither is provided.
  77. The list of search results is in the format: [[{"corpus_id": int, "score": float}, ...], ...]
  78. The time taken for the search is a float value.
  79. """
  80. import faiss
  81. if corpus_embeddings is not None and corpus_index is not None:
  82. raise ValueError("Only corpus_embeddings or corpus_index should be used, not both.")
  83. if corpus_embeddings is None and corpus_index is None:
  84. raise ValueError("Either corpus_embeddings or corpus_index should be used.")
  85. # If corpus_index is not provided, create a new index
  86. if corpus_index is None:
  87. if corpus_precision in ("float32", "uint8"):
  88. if exact:
  89. corpus_index = faiss.IndexFlatIP(corpus_embeddings.shape[1])
  90. else:
  91. corpus_index = faiss.IndexHNSWFlat(corpus_embeddings.shape[1], 16)
  92. elif corpus_precision == "ubinary":
  93. if exact:
  94. corpus_index = faiss.IndexBinaryFlat(corpus_embeddings.shape[1] * 8)
  95. else:
  96. corpus_index = faiss.IndexBinaryHNSW(corpus_embeddings.shape[1] * 8, 16)
  97. corpus_index.add(corpus_embeddings)
  98. # If rescoring is enabled and the query embeddings are in float32, we need to quantize them
  99. # to the same precision as the corpus embeddings. Also update the top_k value to account for the
  100. # rescore_multiplier
  101. rescore_embeddings = None
  102. k = top_k
  103. if query_embeddings.dtype not in (np.uint8, np.int8):
  104. if rescore:
  105. if corpus_precision != "float32":
  106. rescore_embeddings = query_embeddings
  107. k *= rescore_multiplier
  108. else:
  109. logger.warning(
  110. "Rescoring is enabled but the corpus is not quantized. Either pass `rescore=False` or "
  111. 'quantize the corpus embeddings with `quantize_embeddings(embeddings, precision="...") `'
  112. 'and pass `corpus_precision="..."` to `semantic_search_faiss`.'
  113. )
  114. query_embeddings = quantize_embeddings(
  115. query_embeddings,
  116. precision=corpus_precision,
  117. ranges=ranges,
  118. calibration_embeddings=calibration_embeddings,
  119. )
  120. elif rescore:
  121. logger.warning(
  122. "Rescoring is enabled but the query embeddings are quantized. Either pass `rescore=False` or don't quantize the query embeddings."
  123. )
  124. # Perform the search using the usearch index
  125. start_t = time.time()
  126. scores, indices = corpus_index.search(query_embeddings, k)
  127. # If rescoring is enabled, we need to rescore the results using the rescore_embeddings
  128. if rescore_embeddings is not None:
  129. top_k_embeddings = np.array(
  130. [[corpus_index.reconstruct(idx.item()) for idx in query_indices] for query_indices in indices]
  131. )
  132. # If the corpus precision is binary, we need to unpack the bits
  133. if corpus_precision == "ubinary":
  134. top_k_embeddings = np.unpackbits(top_k_embeddings, axis=-1).astype(int)
  135. else:
  136. top_k_embeddings = top_k_embeddings.astype(int)
  137. # rescore_embeddings: [num_queries, embedding_dim]
  138. # top_k_embeddings: [num_queries, top_k, embedding_dim]
  139. # updated_scores: [num_queries, top_k]
  140. # We use einsum to calculate the dot product between the query and the top_k embeddings, equivalent to looping
  141. # over the queries and calculating 'rescore_embeddings[i] @ top_k_embeddings[i].T'
  142. rescored_scores = np.einsum("ij,ikj->ik", rescore_embeddings, top_k_embeddings)
  143. rescored_indices = np.argsort(-rescored_scores)[:, :top_k]
  144. indices = indices[np.arange(len(query_embeddings))[:, None], rescored_indices]
  145. scores = rescored_scores[np.arange(len(query_embeddings))[:, None], rescored_indices]
  146. delta_t = time.time() - start_t
  147. outputs = (
  148. [
  149. [
  150. {"corpus_id": int(neighbor), "score": float(score)}
  151. for score, neighbor in zip(scores[query_id], indices[query_id])
  152. ]
  153. for query_id in range(len(query_embeddings))
  154. ],
  155. delta_t,
  156. )
  157. if output_index:
  158. outputs = (*outputs, corpus_index)
  159. return outputs
  160. def semantic_search_usearch(
  161. query_embeddings: np.ndarray,
  162. corpus_embeddings: np.ndarray | None = None,
  163. corpus_index: usearch.index.Index | None = None,
  164. corpus_precision: Literal["float32", "int8", "binary"] = "float32",
  165. top_k: int = 10,
  166. ranges: np.ndarray | None = None,
  167. calibration_embeddings: np.ndarray | None = None,
  168. rescore: bool = True,
  169. rescore_multiplier: int = 2,
  170. exact: bool = True,
  171. output_index: bool = False,
  172. ) -> tuple[list[list[dict[str, int | float]]], float, usearch.index.Index]:
  173. """
  174. Performs semantic search using the usearch library.
  175. Rescoring will be performed if:
  176. 1. `rescore` is True
  177. 2. The query embeddings are not quantized
  178. 3. The corpus is quantized, i.e. the corpus precision is not float32
  179. Only if these conditions are true, will we search for `top_k * rescore_multiplier` samples and then rescore to only
  180. keep `top_k`.
  181. Args:
  182. query_embeddings: Embeddings of the query sentences. Ideally not
  183. quantized to allow for rescoring.
  184. corpus_embeddings: Embeddings of the corpus sentences. Either
  185. `corpus_embeddings` or `corpus_index` should be used, not
  186. both. The embeddings can be quantized to "int8" or "binary"
  187. for more efficient search.
  188. corpus_index: usearch index for the corpus sentences. Either
  189. `corpus_embeddings` or `corpus_index` should be used, not
  190. both.
  191. corpus_precision: Precision of the corpus embeddings. The
  192. options are "float32", "int8", "ubinary" or "binary". Default
  193. is "float32".
  194. top_k: Number of top results to retrieve. Default is 10.
  195. ranges: Ranges for quantization of embeddings. This is only used
  196. for int8 quantization, where the ranges refers to the
  197. minimum and maximum values for each dimension. So, it's a 2D
  198. array with shape (2, embedding_dim). Default is None, which
  199. means that the ranges will be calculated from the
  200. calibration embeddings.
  201. calibration_embeddings: Embeddings used for calibration during
  202. quantization. This is only used for int8 quantization, where
  203. the calibration embeddings can be used to compute ranges,
  204. i.e. the minimum and maximum values for each dimension.
  205. Default is None, which means that the ranges will be
  206. calculated from the query embeddings. This is not
  207. recommended.
  208. rescore: Whether to perform rescoring. Note that rescoring still
  209. will only be used if the query embeddings are not quantized
  210. and the corpus is quantized, i.e. the corpus precision is
  211. not "float32". Default is True.
  212. rescore_multiplier: Oversampling factor for rescoring. The code
  213. will now search `top_k * rescore_multiplier` samples and
  214. then rescore to only keep `top_k`. Default is 2.
  215. exact: Whether to use exact search or approximate search.
  216. Default is True.
  217. output_index: Whether to output the usearch index used for the
  218. search. Default is False.
  219. Returns:
  220. A tuple containing a list of search results and the time taken
  221. for the search. If `output_index` is True, the tuple will also
  222. contain the usearch index used for the search.
  223. Raises:
  224. ValueError: If both `corpus_embeddings` and `corpus_index` are
  225. provided or if neither is provided.
  226. The list of search results is in the format: [[{"corpus_id": int, "score": float}, ...], ...]
  227. The time taken for the search is a float value.
  228. """
  229. from usearch.compiled import ScalarKind
  230. from usearch.index import Index
  231. if corpus_embeddings is not None and corpus_index is not None:
  232. raise ValueError("Only corpus_embeddings or corpus_index should be used, not both.")
  233. if corpus_embeddings is None and corpus_index is None:
  234. raise ValueError("Either corpus_embeddings or corpus_index should be used.")
  235. if corpus_precision not in ["float32", "int8", "ubinary", "binary"]:
  236. raise ValueError('corpus_precision must be "float32", "int8", "ubinary", "binary" for usearch')
  237. # If corpus_index is not provided, create a new index
  238. if corpus_index is None:
  239. if corpus_precision == "float32":
  240. corpus_index = Index(
  241. ndim=corpus_embeddings.shape[1],
  242. metric="cos",
  243. dtype="f32",
  244. )
  245. elif corpus_precision == "int8":
  246. corpus_index = Index(
  247. ndim=corpus_embeddings.shape[1],
  248. metric="ip",
  249. dtype="i8",
  250. )
  251. elif corpus_precision == "binary":
  252. corpus_index = Index(
  253. ndim=corpus_embeddings.shape[1],
  254. metric="hamming",
  255. dtype="i8",
  256. )
  257. elif corpus_precision == "ubinary":
  258. corpus_index = Index(
  259. ndim=corpus_embeddings.shape[1] * 8,
  260. metric="hamming",
  261. dtype="b1",
  262. )
  263. corpus_index.add(np.arange(len(corpus_embeddings)), corpus_embeddings)
  264. # If rescoring is enabled and the query embeddings are in float32, we need to quantize them
  265. # to the same precision as the corpus embeddings. Also update the top_k value to account for the
  266. # rescore_multiplier
  267. rescore_embeddings = None
  268. k = top_k
  269. if query_embeddings.dtype not in (np.uint8, np.int8):
  270. if rescore:
  271. if corpus_index.dtype != ScalarKind.F32:
  272. rescore_embeddings = query_embeddings
  273. k *= rescore_multiplier
  274. else:
  275. logger.warning(
  276. "Rescoring is enabled but the corpus is not quantized. Either pass `rescore=False` or "
  277. 'quantize the corpus embeddings with `quantize_embeddings(embeddings, precision="...") `'
  278. 'and pass `corpus_precision="..."` to `semantic_search_usearch`.'
  279. )
  280. query_embeddings = quantize_embeddings(
  281. query_embeddings,
  282. precision=corpus_precision,
  283. ranges=ranges,
  284. calibration_embeddings=calibration_embeddings,
  285. )
  286. elif rescore:
  287. logger.warning(
  288. "Rescoring is enabled but the query embeddings are quantized. Either pass `rescore=False` or don't quantize the query embeddings."
  289. )
  290. # Perform the search using the usearch index
  291. start_t = time.time()
  292. matches = corpus_index.search(query_embeddings, count=k, exact=exact)
  293. scores = matches.distances
  294. indices = matches.keys
  295. if scores.ndim < 2:
  296. scores = np.atleast_2d(scores)
  297. if indices.ndim < 2:
  298. indices = np.atleast_2d(indices)
  299. # If rescoring is enabled, we need to rescore the results using the rescore_embeddings
  300. if rescore_embeddings is not None:
  301. top_k_embeddings = np.array([corpus_index.get(query_indices) for query_indices in indices])
  302. # If the corpus precision is binary, we need to unpack the bits
  303. if corpus_precision in ("ubinary", "binary"):
  304. top_k_embeddings = np.unpackbits(top_k_embeddings.astype(np.uint8), axis=-1)
  305. top_k_embeddings = top_k_embeddings.astype(int)
  306. # rescore_embeddings: [num_queries, embedding_dim]
  307. # top_k_embeddings: [num_queries, top_k, embedding_dim]
  308. # updated_scores: [num_queries, top_k]
  309. # We use einsum to calculate the dot product between the query and the top_k embeddings, equivalent to looping
  310. # over the queries and calculating 'rescore_embeddings[i] @ top_k_embeddings[i].T'
  311. rescored_scores = np.einsum("ij,ikj->ik", rescore_embeddings, top_k_embeddings)
  312. rescored_indices = np.argsort(-rescored_scores)[:, :top_k]
  313. indices = indices[np.arange(len(query_embeddings))[:, None], rescored_indices]
  314. scores = rescored_scores[np.arange(len(query_embeddings))[:, None], rescored_indices]
  315. delta_t = time.time() - start_t
  316. outputs = (
  317. [
  318. [
  319. {"corpus_id": int(neighbor), "score": float(score)}
  320. for score, neighbor in zip(scores[query_id], indices[query_id])
  321. ]
  322. for query_id in range(len(query_embeddings))
  323. ],
  324. delta_t,
  325. )
  326. if output_index:
  327. outputs = (*outputs, corpus_index)
  328. return outputs
  329. def quantize_embeddings(
  330. embeddings: Tensor | np.ndarray,
  331. precision: Literal["float32", "int8", "uint8", "binary", "ubinary"],
  332. ranges: np.ndarray | None = None,
  333. calibration_embeddings: np.ndarray | None = None,
  334. ) -> np.ndarray:
  335. """
  336. Quantizes embeddings to a lower precision. This can be used to reduce the memory footprint and increase the
  337. speed of similarity search. The supported precisions are "float32", "int8", "uint8", "binary", and "ubinary".
  338. Args:
  339. embeddings: Unquantized (e.g. float) embeddings with to quantize
  340. to a given precision
  341. precision: The precision to convert to. Options are "float32",
  342. "int8", "uint8", "binary", "ubinary".
  343. ranges (Optional[np.ndarray]): Ranges for quantization of
  344. embeddings. This is only used for int8 quantization, where
  345. the ranges refers to the minimum and maximum values for each
  346. dimension. So, it's a 2D array with shape (2,
  347. embedding_dim). Default is None, which means that the ranges
  348. will be calculated from the calibration embeddings.
  349. calibration_embeddings (Optional[np.ndarray]): Embeddings used
  350. for calibration during quantization. This is only used for
  351. int8 quantization, where the calibration embeddings can be
  352. used to compute ranges, i.e. the minimum and maximum values
  353. for each dimension. Default is None, which means that the
  354. ranges will be calculated from the query embeddings. This is
  355. not recommended.
  356. Returns:
  357. Quantized embeddings with the specified precision
  358. """
  359. if isinstance(embeddings, Tensor):
  360. embeddings = embeddings.cpu().numpy()
  361. elif isinstance(embeddings, list):
  362. if isinstance(embeddings[0], Tensor):
  363. embeddings = [embedding.cpu().numpy() for embedding in embeddings]
  364. embeddings = np.array(embeddings)
  365. if embeddings.dtype in (np.uint8, np.int8):
  366. raise Exception("Embeddings to quantize must be float rather than int8 or uint8.")
  367. if precision == "float32":
  368. return embeddings.astype(np.float32)
  369. if precision.endswith("int8"):
  370. # Either use the 1. provided ranges, 2. the calibration dataset or 3. the provided embeddings
  371. if ranges is None:
  372. if calibration_embeddings is not None:
  373. ranges = np.vstack((np.min(calibration_embeddings, axis=0), np.max(calibration_embeddings, axis=0)))
  374. else:
  375. if embeddings.shape[0] < 100:
  376. logger.warning(
  377. f"Computing {precision} quantization buckets based on {len(embeddings)} embedding{'s' if len(embeddings) != 1 else ''}."
  378. f" {precision} quantization is more stable with `ranges` calculated from more embeddings "
  379. "or a `calibration_embeddings` that can be used to calculate the buckets."
  380. )
  381. ranges = np.vstack((np.min(embeddings, axis=0), np.max(embeddings, axis=0)))
  382. starts = ranges[0, :]
  383. steps = (ranges[1, :] - ranges[0, :]) / 255
  384. if precision == "uint8":
  385. return ((embeddings - starts) / steps).astype(np.uint8)
  386. elif precision == "int8":
  387. return ((embeddings - starts) / steps - 128).astype(np.int8)
  388. if precision == "binary":
  389. return (np.packbits(embeddings > 0).reshape(embeddings.shape[0], -1) - 128).astype(np.int8)
  390. if precision == "ubinary":
  391. return np.packbits(embeddings > 0).reshape(embeddings.shape[0], -1)
  392. raise ValueError(f"Precision {precision} is not supported")