2024-05-23 14:31:16 +08:00
|
|
|
#
|
|
|
|
# Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
|
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
|
|
|
#
|
2024-11-14 17:13:48 +08:00
|
|
|
import logging
|
2024-05-23 14:31:16 +08:00
|
|
|
import re
|
|
|
|
import umap
|
|
|
|
import numpy as np
|
|
|
|
from sklearn.mixture import GaussianMixture
|
2025-03-03 18:59:49 +08:00
|
|
|
import trio
|
2024-05-23 14:31:16 +08:00
|
|
|
|
2025-03-10 15:15:06 +08:00
|
|
|
from graphrag.utils import (
|
|
|
|
get_llm_cache,
|
|
|
|
get_embed_cache,
|
|
|
|
set_embed_cache,
|
|
|
|
set_llm_cache,
|
|
|
|
chat_limiter,
|
|
|
|
)
|
2024-11-12 17:35:13 +08:00
|
|
|
from rag.utils import truncate
|
2024-05-23 14:31:16 +08:00
|
|
|
|
|
|
|
|
|
|
|
class RecursiveAbstractiveProcessing4TreeOrganizedRetrieval:
|
2025-03-10 15:15:06 +08:00
|
|
|
def __init__(
|
|
|
|
self, max_cluster, llm_model, embd_model, prompt, max_token=512, threshold=0.1
|
|
|
|
):
|
2024-05-23 14:31:16 +08:00
|
|
|
self._max_cluster = max_cluster
|
|
|
|
self._llm_model = llm_model
|
|
|
|
self._embd_model = embd_model
|
|
|
|
self._threshold = threshold
|
|
|
|
self._prompt = prompt
|
|
|
|
self._max_token = max_token
|
|
|
|
|
2025-03-10 15:15:06 +08:00
|
|
|
async def _chat(self, system, history, gen_conf):
|
2024-12-17 09:48:03 +08:00
|
|
|
response = get_llm_cache(self._llm_model.llm_name, system, history, gen_conf)
|
|
|
|
if response:
|
|
|
|
return response
|
2025-03-10 15:15:06 +08:00
|
|
|
response = await trio.to_thread.run_sync(
|
|
|
|
lambda: self._llm_model.chat(system, history, gen_conf)
|
|
|
|
)
|
2025-04-24 11:44:10 +08:00
|
|
|
response = re.sub(r"^.*</think>", "", response, flags=re.DOTALL)
|
2024-12-17 09:48:03 +08:00
|
|
|
if response.find("**ERROR**") >= 0:
|
|
|
|
raise Exception(response)
|
|
|
|
set_llm_cache(self._llm_model.llm_name, system, response, history, gen_conf)
|
|
|
|
return response
|
|
|
|
|
2025-03-10 15:15:06 +08:00
|
|
|
async def _embedding_encode(self, txt):
|
2024-12-17 09:48:03 +08:00
|
|
|
response = get_embed_cache(self._embd_model.llm_name, txt)
|
2025-02-14 12:00:19 +08:00
|
|
|
if response is not None:
|
2024-12-17 09:48:03 +08:00
|
|
|
return response
|
2025-03-10 15:15:06 +08:00
|
|
|
embds, _ = await trio.to_thread.run_sync(lambda: self._embd_model.encode([txt]))
|
2024-12-17 09:48:03 +08:00
|
|
|
if len(embds) < 1 or len(embds[0]) < 1:
|
|
|
|
raise Exception("Embedding error: ")
|
|
|
|
embds = embds[0]
|
|
|
|
set_embed_cache(self._embd_model.llm_name, txt, embds)
|
|
|
|
return embds
|
|
|
|
|
2024-11-29 11:55:41 +08:00
|
|
|
def _get_optimal_clusters(self, embeddings: np.ndarray, random_state: int):
|
2024-05-23 14:31:16 +08:00
|
|
|
max_clusters = min(self._max_cluster, len(embeddings))
|
|
|
|
n_clusters = np.arange(1, max_clusters)
|
|
|
|
bics = []
|
|
|
|
for n in n_clusters:
|
|
|
|
gm = GaussianMixture(n_components=n, random_state=random_state)
|
|
|
|
gm.fit(embeddings)
|
|
|
|
bics.append(gm.bic(embeddings))
|
|
|
|
optimal_clusters = n_clusters[np.argmin(bics)]
|
|
|
|
return optimal_clusters
|
|
|
|
|
2025-03-03 18:59:49 +08:00
|
|
|
async def __call__(self, chunks, random_state, callback=None):
|
2024-12-08 14:21:12 +08:00
|
|
|
if len(chunks) <= 1:
|
2025-02-24 13:21:05 +08:00
|
|
|
return []
|
2025-01-26 18:45:36 +08:00
|
|
|
chunks = [(s, a) for s, a in chunks if s and len(a) > 0]
|
2025-04-11 17:01:49 +08:00
|
|
|
layers = [(0, len(chunks))]
|
|
|
|
start, end = 0, len(chunks)
|
2024-05-23 14:31:16 +08:00
|
|
|
|
2025-03-10 15:15:06 +08:00
|
|
|
async def summarize(ck_idx: list[int]):
|
2024-05-23 14:31:16 +08:00
|
|
|
nonlocal chunks
|
2025-03-10 15:15:06 +08:00
|
|
|
texts = [chunks[i][0] for i in ck_idx]
|
|
|
|
len_per_chunk = int(
|
|
|
|
(self._llm_model.max_length - self._max_token) / len(texts)
|
|
|
|
)
|
|
|
|
cluster_content = "\n".join(
|
|
|
|
[truncate(t, max(1, len_per_chunk)) for t in texts]
|
|
|
|
)
|
|
|
|
async with chat_limiter:
|
|
|
|
cnt = await self._chat(
|
|
|
|
"You're a helpful assistant.",
|
|
|
|
[
|
|
|
|
{
|
|
|
|
"role": "user",
|
|
|
|
"content": self._prompt.format(
|
|
|
|
cluster_content=cluster_content
|
|
|
|
),
|
|
|
|
}
|
|
|
|
],
|
|
|
|
{"temperature": 0.3, "max_tokens": self._max_token},
|
|
|
|
)
|
|
|
|
cnt = re.sub(
|
|
|
|
"(······\n由于长度的原因,回答被截断了,要继续吗?|For the content length reason, it stopped, continue?)",
|
|
|
|
"",
|
|
|
|
cnt,
|
|
|
|
)
|
|
|
|
logging.debug(f"SUM: {cnt}")
|
|
|
|
embds = await self._embedding_encode(cnt)
|
|
|
|
chunks.append((cnt, embds))
|
2024-05-23 14:31:16 +08:00
|
|
|
|
|
|
|
labels = []
|
|
|
|
while end - start > 1:
|
2025-03-10 15:15:06 +08:00
|
|
|
embeddings = [embd for _, embd in chunks[start:end]]
|
2024-05-23 14:31:16 +08:00
|
|
|
if len(embeddings) == 2:
|
2025-03-10 15:15:06 +08:00
|
|
|
await summarize([start, start + 1])
|
2024-05-23 14:31:16 +08:00
|
|
|
if callback:
|
2025-03-10 15:15:06 +08:00
|
|
|
callback(
|
|
|
|
msg="Cluster one layer: {} -> {}".format(
|
|
|
|
end - start, len(chunks) - end
|
|
|
|
)
|
|
|
|
)
|
2024-11-29 11:55:41 +08:00
|
|
|
labels.extend([0, 0])
|
2024-05-23 14:31:16 +08:00
|
|
|
layers.append((end, len(chunks)))
|
|
|
|
start = end
|
|
|
|
end = len(chunks)
|
|
|
|
continue
|
|
|
|
|
|
|
|
n_neighbors = int((len(embeddings) - 1) ** 0.8)
|
|
|
|
reduced_embeddings = umap.UMAP(
|
2025-03-10 15:15:06 +08:00
|
|
|
n_neighbors=max(2, n_neighbors),
|
|
|
|
n_components=min(12, len(embeddings) - 2),
|
|
|
|
metric="cosine",
|
2024-05-23 14:31:16 +08:00
|
|
|
).fit_transform(embeddings)
|
|
|
|
n_clusters = self._get_optimal_clusters(reduced_embeddings, random_state)
|
|
|
|
if n_clusters == 1:
|
|
|
|
lbls = [0 for _ in range(len(reduced_embeddings))]
|
|
|
|
else:
|
|
|
|
gm = GaussianMixture(n_components=n_clusters, random_state=random_state)
|
|
|
|
gm.fit(reduced_embeddings)
|
|
|
|
probs = gm.predict_proba(reduced_embeddings)
|
|
|
|
lbls = [np.where(prob > self._threshold)[0] for prob in probs]
|
2024-05-27 11:01:20 +08:00
|
|
|
lbls = [lbl[0] if isinstance(lbl, np.ndarray) else lbl for lbl in lbls]
|
2025-03-03 18:59:49 +08:00
|
|
|
|
|
|
|
async with trio.open_nursery() as nursery:
|
2024-05-23 14:31:16 +08:00
|
|
|
for c in range(n_clusters):
|
2024-11-29 11:55:41 +08:00
|
|
|
ck_idx = [i + start for i in range(len(lbls)) if lbls[i] == c]
|
2025-03-10 15:15:06 +08:00
|
|
|
assert len(ck_idx) > 0
|
2025-03-03 18:59:49 +08:00
|
|
|
async with chat_limiter:
|
fix(nursery): Fix Closure Trap Issues in Trio Concurrent Tasks (#7106)
## Problem Description
Multiple files in the RAGFlow project contain closure trap issues when
using lambda functions with `trio.open_nursery()`. This problem causes
concurrent tasks created in loops to reference the same variable,
resulting in all tasks processing the same data (the data from the last
iteration) rather than each task processing its corresponding data from
the loop.
## Issue Details
When using a `lambda` to create a closure function and passing it to
`nursery.start_soon()` within a loop, the lambda function captures a
reference to the loop variable rather than its value. For example:
```python
# Problematic code
async with trio.open_nursery() as nursery:
for d in docs:
nursery.start_soon(lambda: doc_keyword_extraction(chat_mdl, d, topn))
```
In this pattern, when concurrent tasks begin execution, `d` has already
become the value after the loop ends (typically the last element),
causing all tasks to use the same data.
## Fix Solution
Changed the way concurrent tasks are created with `nursery.start_soon()`
by leveraging Trio's API design to directly pass the function and its
arguments separately:
```python
# Fixed code
async with trio.open_nursery() as nursery:
for d in docs:
nursery.start_soon(doc_keyword_extraction, chat_mdl, d, topn)
```
This way, each task uses the parameter values at the time of the
function call, rather than references captured through closures.
## Fixed Files
Fixed closure traps in the following files:
1. `rag/svr/task_executor.py`: 3 fixes, involving document keyword
extraction, question generation, and tag processing
2. `rag/raptor.py`: 1 fix, involving document summarization
3. `graphrag/utils.py`: 2 fixes, involving graph node and edge
processing
4. `graphrag/entity_resolution.py`: 2 fixes, involving entity resolution
and graph node merging
5. `graphrag/general/mind_map_extractor.py`: 2 fixes, involving document
processing
6. `graphrag/general/extractor.py`: 3 fixes, involving content
processing and graph node/edge merging
7. `graphrag/general/community_reports_extractor.py`: 1 fix, involving
community report extraction
## Potential Impact
This fix resolves a serious concurrency issue that could have caused:
- Data processing errors (processing duplicate data)
- Performance degradation (all tasks working on the same data)
- Inconsistent results (some data not being processed)
After the fix, all concurrent tasks should correctly process their
respective data, improving system correctness and reliability.
2025-04-18 18:00:20 +08:00
|
|
|
nursery.start_soon(summarize, ck_idx)
|
2024-05-23 14:31:16 +08:00
|
|
|
|
2025-03-10 15:15:06 +08:00
|
|
|
assert len(chunks) - end == n_clusters, "{} vs. {}".format(
|
|
|
|
len(chunks) - end, n_clusters
|
|
|
|
)
|
2024-05-23 14:31:16 +08:00
|
|
|
labels.extend(lbls)
|
|
|
|
layers.append((end, len(chunks)))
|
|
|
|
if callback:
|
2025-03-10 15:15:06 +08:00
|
|
|
callback(
|
|
|
|
msg="Cluster one layer: {} -> {}".format(
|
|
|
|
end - start, len(chunks) - end
|
|
|
|
)
|
|
|
|
)
|
2024-05-23 14:31:16 +08:00
|
|
|
start = end
|
|
|
|
end = len(chunks)
|
|
|
|
|
2024-11-29 11:55:41 +08:00
|
|
|
return chunks
|