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.5KB

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