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.

raptor.py 6.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  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 logging
  17. import re
  18. import umap
  19. import numpy as np
  20. from sklearn.mixture import GaussianMixture
  21. import trio
  22. from api.utils.api_utils import timeout
  23. from graphrag.utils import (
  24. get_llm_cache,
  25. get_embed_cache,
  26. set_embed_cache,
  27. set_llm_cache,
  28. chat_limiter,
  29. )
  30. from rag.utils import truncate
  31. class RecursiveAbstractiveProcessing4TreeOrganizedRetrieval:
  32. def __init__(
  33. self, max_cluster, llm_model, embd_model, prompt, max_token=512, threshold=0.1
  34. ):
  35. self._max_cluster = max_cluster
  36. self._llm_model = llm_model
  37. self._embd_model = embd_model
  38. self._threshold = threshold
  39. self._prompt = prompt
  40. self._max_token = max_token
  41. @timeout(60*20)
  42. async def _chat(self, system, history, gen_conf):
  43. response = await trio.to_thread.run_sync(
  44. lambda: get_llm_cache(self._llm_model.llm_name, system, history, gen_conf)
  45. )
  46. if response:
  47. return response
  48. response = await trio.to_thread.run_sync(
  49. lambda: self._llm_model.chat(system, history, gen_conf)
  50. )
  51. response = re.sub(r"^.*</think>", "", response, flags=re.DOTALL)
  52. if response.find("**ERROR**") >= 0:
  53. raise Exception(response)
  54. await trio.to_thread.run_sync(
  55. lambda: set_llm_cache(self._llm_model.llm_name, system, response, history, gen_conf)
  56. )
  57. return response
  58. @timeout(20)
  59. async def _embedding_encode(self, txt):
  60. response = await trio.to_thread.run_sync(
  61. lambda: get_embed_cache(self._embd_model.llm_name, txt)
  62. )
  63. if response is not None:
  64. return response
  65. embds, _ = await trio.to_thread.run_sync(lambda: self._embd_model.encode([txt]))
  66. if len(embds) < 1 or len(embds[0]) < 1:
  67. raise Exception("Embedding error: ")
  68. embds = embds[0]
  69. await trio.to_thread.run_sync(lambda: set_embed_cache(self._embd_model.llm_name, txt, embds))
  70. return embds
  71. def _get_optimal_clusters(self, embeddings: np.ndarray, random_state: int):
  72. max_clusters = min(self._max_cluster, len(embeddings))
  73. n_clusters = np.arange(1, max_clusters)
  74. bics = []
  75. for n in n_clusters:
  76. gm = GaussianMixture(n_components=n, random_state=random_state)
  77. gm.fit(embeddings)
  78. bics.append(gm.bic(embeddings))
  79. optimal_clusters = n_clusters[np.argmin(bics)]
  80. return optimal_clusters
  81. async def __call__(self, chunks, random_state, callback=None):
  82. if len(chunks) <= 1:
  83. return []
  84. chunks = [(s, a) for s, a in chunks if s and len(a) > 0]
  85. layers = [(0, len(chunks))]
  86. start, end = 0, len(chunks)
  87. @timeout(60*20)
  88. async def summarize(ck_idx: list[int]):
  89. nonlocal chunks
  90. texts = [chunks[i][0] for i in ck_idx]
  91. len_per_chunk = int(
  92. (self._llm_model.max_length - self._max_token) / len(texts)
  93. )
  94. cluster_content = "\n".join(
  95. [truncate(t, max(1, len_per_chunk)) for t in texts]
  96. )
  97. async with chat_limiter:
  98. cnt = await self._chat(
  99. "You're a helpful assistant.",
  100. [
  101. {
  102. "role": "user",
  103. "content": self._prompt.format(
  104. cluster_content=cluster_content
  105. ),
  106. }
  107. ],
  108. {"max_tokens": self._max_token},
  109. )
  110. cnt = re.sub(
  111. "(······\n由于长度的原因,回答被截断了,要继续吗?|For the content length reason, it stopped, continue?)",
  112. "",
  113. cnt,
  114. )
  115. logging.debug(f"SUM: {cnt}")
  116. embds = await self._embedding_encode(cnt)
  117. chunks.append((cnt, embds))
  118. labels = []
  119. while end - start > 1:
  120. embeddings = [embd for _, embd in chunks[start:end]]
  121. if len(embeddings) == 2:
  122. await summarize([start, start + 1])
  123. if callback:
  124. callback(
  125. msg="Cluster one layer: {} -> {}".format(
  126. end - start, len(chunks) - end
  127. )
  128. )
  129. labels.extend([0, 0])
  130. layers.append((end, len(chunks)))
  131. start = end
  132. end = len(chunks)
  133. continue
  134. n_neighbors = int((len(embeddings) - 1) ** 0.8)
  135. reduced_embeddings = umap.UMAP(
  136. n_neighbors=max(2, n_neighbors),
  137. n_components=min(12, len(embeddings) - 2),
  138. metric="cosine",
  139. ).fit_transform(embeddings)
  140. n_clusters = self._get_optimal_clusters(reduced_embeddings, random_state)
  141. if n_clusters == 1:
  142. lbls = [0 for _ in range(len(reduced_embeddings))]
  143. else:
  144. gm = GaussianMixture(n_components=n_clusters, random_state=random_state)
  145. gm.fit(reduced_embeddings)
  146. probs = gm.predict_proba(reduced_embeddings)
  147. lbls = [np.where(prob > self._threshold)[0] for prob in probs]
  148. lbls = [lbl[0] if isinstance(lbl, np.ndarray) else lbl for lbl in lbls]
  149. async with trio.open_nursery() as nursery:
  150. for c in range(n_clusters):
  151. ck_idx = [i + start for i in range(len(lbls)) if lbls[i] == c]
  152. assert len(ck_idx) > 0
  153. nursery.start_soon(summarize, ck_idx)
  154. assert len(chunks) - end == n_clusters, "{} vs. {}".format(
  155. len(chunks) - end, n_clusters
  156. )
  157. labels.extend(lbls)
  158. layers.append((end, len(chunks)))
  159. if callback:
  160. callback(
  161. msg="Cluster one layer: {} -> {}".format(
  162. end - start, len(chunks) - end
  163. )
  164. )
  165. start = end
  166. end = len(chunks)
  167. return chunks