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 5.3KB

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