Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

raptor.py 6.5KB

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