mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-06 19:48:19 +08:00
Merge #2336 from remote-controlled-man
This commit is contained in:
@@ -24,6 +24,10 @@ from .rerank import rerank_nodes
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
BM25_PERSIST_DIRNAME = "bm25_retriever"
|
||||
_BM25_TOKEN_PATTERN_FILENAME = "token_pattern.txt"
|
||||
# Split word runs before adjacent dotted numbers, retaining single-character terms.
|
||||
# Check for an identifier only at the start of a digit run to avoid quadratic scans.
|
||||
BM25_TOKEN_PATTERN = r"(?u)\d+(?:\.\d+)+|(?:(?!(?<!\d)\d+\.\d)\w)+"
|
||||
|
||||
|
||||
class _MatchedOnlyRetriever(BaseRetriever):
|
||||
@@ -93,6 +97,14 @@ def effective_retrieval_profile(profile: str | None) -> str:
|
||||
return normalized
|
||||
|
||||
|
||||
@lru_cache(maxsize=4)
|
||||
def _rebuilt_bm25_retriever(bm25_cls: Any, index: Any, top_k: int) -> Any:
|
||||
"""Reuse a rebuild for this loaded index; published versions load new identities."""
|
||||
return bm25_cls.from_defaults(
|
||||
index=index, similarity_top_k=top_k, token_pattern=BM25_TOKEN_PATTERN
|
||||
)
|
||||
|
||||
|
||||
def build_bm25_retriever(index: Any, storage_dir: Path, *, top_k: int) -> Any | None:
|
||||
"""Build or load LlamaIndex's official BM25 retriever if available."""
|
||||
top_k = max(1, int(top_k))
|
||||
@@ -119,13 +131,21 @@ def build_bm25_retriever(index: Any, storage_dir: Path, *, top_k: int) -> Any |
|
||||
persist_dir = _bm25_persist_dir(storage_dir)
|
||||
if persist_dir.exists():
|
||||
try:
|
||||
retriever = bm25_cls.from_persist_dir(str(persist_dir))
|
||||
return _set_similarity_top_k(retriever, top_k)
|
||||
pattern_path = persist_dir / _BM25_TOKEN_PATTERN_FILENAME
|
||||
if (
|
||||
pattern_path.is_file()
|
||||
and pattern_path.read_text(encoding="utf-8") == BM25_TOKEN_PATTERN
|
||||
):
|
||||
retriever = bm25_cls.from_persist_dir(str(persist_dir))
|
||||
# The upstream adapter does not persist its token_pattern.
|
||||
retriever.token_pattern = BM25_TOKEN_PATTERN
|
||||
return _set_similarity_top_k(retriever, top_k)
|
||||
logger.info("Using document-based BM25 for outdated persisted tokenization")
|
||||
except Exception as exc:
|
||||
logger.warning("Failed to load persisted BM25 retriever from %s: %s", persist_dir, exc)
|
||||
|
||||
try:
|
||||
return bm25_cls.from_defaults(index=index, similarity_top_k=top_k)
|
||||
return _rebuilt_bm25_retriever(bm25_cls, index, top_k)
|
||||
except Exception as exc:
|
||||
logger.warning("Failed to build BM25 retriever; falling back to vector retrieval: %s", exc)
|
||||
return None
|
||||
@@ -147,7 +167,9 @@ def persist_bm25_retriever(index: Any, storage_dir: Path, *, top_k: int) -> bool
|
||||
shutil.rmtree(persist_dir, ignore_errors=True)
|
||||
|
||||
try:
|
||||
retriever = bm25_cls.from_defaults(index=index, similarity_top_k=top_k)
|
||||
retriever = bm25_cls.from_defaults(
|
||||
index=index, similarity_top_k=top_k, token_pattern=BM25_TOKEN_PATTERN
|
||||
)
|
||||
except Exception as exc:
|
||||
logger.warning("Failed to build BM25 retriever for persistence: %s", exc)
|
||||
return False
|
||||
@@ -158,6 +180,9 @@ def persist_bm25_retriever(index: Any, storage_dir: Path, *, top_k: int) -> bool
|
||||
persist_dir.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
retriever.persist(str(persist_dir))
|
||||
(persist_dir / _BM25_TOKEN_PATTERN_FILENAME).write_text(
|
||||
BM25_TOKEN_PATTERN, encoding="utf-8"
|
||||
)
|
||||
return True
|
||||
except Exception as exc:
|
||||
logger.warning("Failed to persist BM25 retriever to %s: %s", persist_dir, exc)
|
||||
@@ -295,7 +320,9 @@ def retrieve_scoped_nodes(
|
||||
vector = index.as_retriever(similarity_top_k=count)
|
||||
bm25_cls = _import_bm25_retriever()
|
||||
if bm25_cls is not None:
|
||||
lexical = bm25_cls.from_defaults(nodes=nodes, similarity_top_k=count)
|
||||
lexical = bm25_cls.from_defaults(
|
||||
nodes=nodes, similarity_top_k=count, token_pattern=BM25_TOKEN_PATTERN
|
||||
)
|
||||
retriever = QueryFusionRetriever(
|
||||
[vector, _MatchedOnlyRetriever(lexical)],
|
||||
llm=MockLLM(),
|
||||
@@ -330,7 +357,13 @@ class _UnstemmedPageRetriever:
|
||||
def _tokenize(text):
|
||||
import bm25s
|
||||
|
||||
return bm25s.tokenize(text, stopwords="en", stemmer=None, show_progress=False)
|
||||
return bm25s.tokenize(
|
||||
text,
|
||||
stopwords="en",
|
||||
stemmer=None,
|
||||
token_pattern=BM25_TOKEN_PATTERN,
|
||||
show_progress=False,
|
||||
)
|
||||
|
||||
def retrieve(self, query: str) -> list[Any]:
|
||||
from llama_index.core.schema import NodeWithScore
|
||||
@@ -356,7 +389,9 @@ def _legacy_page_retriever(directory: Path) -> Any:
|
||||
cls = _import_bm25_retriever()
|
||||
if cls is None:
|
||||
return _UnstemmedPageRetriever(nodes)
|
||||
return cls.from_defaults(nodes=nodes, similarity_top_k=min(8, len(nodes)))
|
||||
return cls.from_defaults(
|
||||
nodes=nodes, similarity_top_k=min(8, len(nodes)), token_pattern=BM25_TOKEN_PATTERN
|
||||
)
|
||||
|
||||
|
||||
def retrieve_legacy_pages(directory: Path, query: str, *, top_k: int = 8) -> list[Any]:
|
||||
|
||||
@@ -38,6 +38,16 @@ Completed and failed sources are reported separately, including partial success.
|
||||
The durable journal is scoped to the active user/workspace knowledge base;
|
||||
linked/read-only knowledge bases cannot be cancelled through mutation routes.
|
||||
|
||||
LlamaIndex hybrid retrieval keeps dotted identifiers such as `2.6.8` intact
|
||||
and retains single-character terms, subject to the existing English stopword
|
||||
filter, during BM25 indexing and queries. Persisted
|
||||
BM25 sidecars record their token pattern. Older sidecars without that pattern
|
||||
are rebuilt in memory from the stored documents, without new embedding calls.
|
||||
A bounded cache reuses these rebuilds for the loaded index and requested result
|
||||
count; publishing an updated index loads a new identity and rebuilds as needed.
|
||||
Queries leave the old sidecar unchanged; the next successful indexing run
|
||||
persists the updated BM25 cache.
|
||||
|
||||
## Implementation and verification
|
||||
|
||||
- [deeptutor/knowledge/indexing_run.py](../deeptutor/knowledge/indexing_run.py)
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
"""BM25 hits that match no query term must not reach hybrid fusion."""
|
||||
"""BM25 must preserve identifiers and pass only lexical matches to hybrid fusion."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from llama_index.core import VectorStoreIndex
|
||||
from llama_index.core.embeddings import MockEmbedding
|
||||
from llama_index.core.schema import NodeWithScore, QueryBundle, TextNode
|
||||
from llama_index.core.storage.docstore import SimpleDocumentStore
|
||||
import pytest
|
||||
|
||||
from deeptutor.services.rag.pipelines.llamaindex import retrievers as retriever_module
|
||||
@@ -47,3 +52,142 @@ def test_a_query_with_no_shared_term_adds_nothing_from_bm25() -> None:
|
||||
filtered = retriever_module._MatchedOnlyRetriever(bm25)
|
||||
assert filtered.retrieve("中央値と平均の違い") == []
|
||||
assert [hit.node.node_id for hit in filtered.retrieve("median outliers")] == ["n0"]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def identifier_index() -> VectorStoreIndex:
|
||||
if not retriever_module.bm25_available():
|
||||
pytest.skip("llama-index-retrievers-bm25 is not installed")
|
||||
nodes = [
|
||||
TextNode(text="Exercise 2.6.9: solve the equation.", id_="other-exercise"),
|
||||
TextNode(text="The variable y is unknown.", id_="other-variable"),
|
||||
TextNode(text="The variable x is unknown.", id_="variable"),
|
||||
TextNode(text="Exercise 2.6.8: solve the equation.", id_="exercise"),
|
||||
]
|
||||
# Make the exact exercise a poor vector match so hybrid ranking must use BM25.
|
||||
for node in nodes:
|
||||
node.embedding = [-0.5 if node.node_id == "exercise" else 0.5] * 8
|
||||
return VectorStoreIndex(nodes, embed_model=MockEmbedding(embed_dim=8))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("query", "expected_id"), [("2.6.8", "exercise"), ("x", "variable")])
|
||||
def test_bm25_matches_dotted_identifiers_and_single_character_terms(
|
||||
tmp_path: Path, identifier_index: VectorStoreIndex, query: str, expected_id: str
|
||||
) -> None:
|
||||
retriever = retriever_module.build_bm25_retriever(identifier_index, tmp_path, top_k=4)
|
||||
|
||||
assert retriever is not None
|
||||
hits = retriever.retrieve(query)
|
||||
assert [hit.node.node_id for hit in hits if (hit.score or 0) > 0] == [expected_id]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("legacy", [False, True])
|
||||
def test_persisted_bm25_keeps_corpus_and_query_tokenization_consistent(
|
||||
tmp_path: Path, identifier_index: VectorStoreIndex, legacy: bool
|
||||
) -> None:
|
||||
if legacy:
|
||||
bm25_cls = retriever_module._import_bm25_retriever()
|
||||
old = bm25_cls.from_defaults(index=identifier_index, similarity_top_k=4)
|
||||
old.persist(str(tmp_path / retriever_module.BM25_PERSIST_DIRNAME))
|
||||
else:
|
||||
assert retriever_module.persist_bm25_retriever(identifier_index, tmp_path, top_k=4)
|
||||
|
||||
retriever = retriever_module.build_bm25_retriever(identifier_index, tmp_path, top_k=2)
|
||||
|
||||
assert retriever is not None
|
||||
assert len(retriever.retrieve("2.6.8")) == 2
|
||||
for query, expected_id in [("2.6.8", "exercise"), ("x", "variable")]:
|
||||
hits = retriever.retrieve(query)
|
||||
assert [hit.node.node_id for hit in hits if (hit.score or 0) > 0] == [expected_id]
|
||||
|
||||
|
||||
def test_scoped_hybrid_retrieval_promotes_the_matching_identifier(
|
||||
identifier_index: VectorStoreIndex,
|
||||
) -> None:
|
||||
for node in identifier_index.docstore.docs.values():
|
||||
node.metadata.update(document_key="textbook", page_status="searchable")
|
||||
identifier_index.docstore.add_documents([node], allow_update=True)
|
||||
|
||||
hits = retriever_module.retrieve_scoped_nodes(identifier_index, "2.6.8", ["textbook"], top_k=4)
|
||||
|
||||
assert hits[0].node.node_id == "exercise"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("without_adapter", [False, True])
|
||||
def test_legacy_page_lookup_keeps_dotted_identifiers_and_short_terms(
|
||||
tmp_path: Path,
|
||||
identifier_index: VectorStoreIndex,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
without_adapter: bool,
|
||||
) -> None:
|
||||
store = SimpleDocumentStore()
|
||||
store.add_documents(list(identifier_index.docstore.docs.values()))
|
||||
store.persist(str(tmp_path / "docstore.json"))
|
||||
if without_adapter:
|
||||
monkeypatch.setattr(retriever_module, "_import_bm25_retriever", lambda: None)
|
||||
|
||||
for query, expected_id in [("2.6.8", "exercise"), ("x", "variable")]:
|
||||
hits = retriever_module.retrieve_legacy_pages(tmp_path, query)
|
||||
assert [hit.node.node_id for hit in hits if (hit.score or 0) > 0] == [expected_id]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("heading", ["习题2.6.8", "2.6.8解答", "§2.6.8"])
|
||||
def test_bm25_matches_identifiers_adjacent_to_text(
|
||||
tmp_path: Path, identifier_index: VectorStoreIndex, heading: str
|
||||
) -> None:
|
||||
node = identifier_index.docstore.get_node("exercise")
|
||||
node.text = heading
|
||||
identifier_index.docstore.add_documents([node], allow_update=True)
|
||||
|
||||
retriever = retriever_module.build_bm25_retriever(identifier_index, tmp_path, top_k=4)
|
||||
|
||||
assert retriever is not None
|
||||
assert [hit.node.node_id for hit in retriever.retrieve("2.6.8") if (hit.score or 0) > 0] == [
|
||||
"exercise"
|
||||
]
|
||||
|
||||
|
||||
def test_old_bm25_rebuild_is_reused_until_the_index_changes(
|
||||
tmp_path: Path, identifier_index: VectorStoreIndex, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
bm25_cls = retriever_module._import_bm25_retriever()
|
||||
old = bm25_cls.from_defaults(index=identifier_index, similarity_top_k=4)
|
||||
old.persist(str(tmp_path / retriever_module.BM25_PERSIST_DIRNAME))
|
||||
original = bm25_cls.from_defaults
|
||||
builds = []
|
||||
|
||||
def build(**kwargs):
|
||||
builds.append(kwargs["index"])
|
||||
return original(**kwargs)
|
||||
|
||||
monkeypatch.setattr(bm25_cls, "from_defaults", build)
|
||||
for _ in range(2):
|
||||
retriever = retriever_module.build_bm25_retriever(identifier_index, tmp_path, top_k=4)
|
||||
assert retriever is not None
|
||||
assert retriever.retrieve("2.6.8")[0].node.node_id == "exercise"
|
||||
assert len(builds) == 1
|
||||
|
||||
updated = VectorStoreIndex(
|
||||
[TextNode(text="Exercise 2.6.7", id_="updated")],
|
||||
embed_model=MockEmbedding(embed_dim=8),
|
||||
)
|
||||
retriever = retriever_module.build_bm25_retriever(updated, tmp_path, top_k=4)
|
||||
assert retriever is not None
|
||||
assert retriever.retrieve("2.6.7")[0].node.node_id == "updated"
|
||||
assert len(builds) == 2
|
||||
|
||||
|
||||
def test_bm25_keeps_short_cjk_terms_and_existing_english_stopwords(
|
||||
tmp_path: Path, identifier_index: VectorStoreIndex
|
||||
) -> None:
|
||||
node = identifier_index.docstore.get_node("exercise")
|
||||
node.text = "第3.4節 a"
|
||||
identifier_index.docstore.add_documents([node], allow_update=True)
|
||||
retriever = retriever_module.build_bm25_retriever(identifier_index, tmp_path, top_k=4)
|
||||
|
||||
assert retriever is not None
|
||||
for query in ["§3.4", "第", "節"]:
|
||||
assert [hit.node.node_id for hit in retriever.retrieve(query) if (hit.score or 0) > 0] == [
|
||||
"exercise"
|
||||
]
|
||||
assert all(not hit.score for hit in retriever.retrieve("a"))
|
||||
|
||||
@@ -150,7 +150,7 @@ def test_hybrid_retriever_uses_official_query_fusion_when_bm25_available(
|
||||
|
||||
class _FakeBM25:
|
||||
@classmethod
|
||||
def from_defaults(cls, index, similarity_top_k: int):
|
||||
def from_defaults(cls, index, similarity_top_k: int, token_pattern: str):
|
||||
captured["bm25_top_k"] = similarity_top_k
|
||||
return cls()
|
||||
|
||||
@@ -209,6 +209,9 @@ def test_bm25_retriever_overrides_persisted_top_k(
|
||||
|
||||
persist_dir = tmp_path / retriever_module.BM25_PERSIST_DIRNAME
|
||||
persist_dir.mkdir()
|
||||
(persist_dir / "token_pattern.txt").write_text(
|
||||
retriever_module.BM25_TOKEN_PATTERN, encoding="utf-8"
|
||||
)
|
||||
|
||||
class _FakeBM25:
|
||||
def __init__(self) -> None:
|
||||
@@ -237,7 +240,7 @@ def test_bm25_persistence_drops_stale_sidecar_on_rebuild_failure(
|
||||
|
||||
class _FailingBM25:
|
||||
@classmethod
|
||||
def from_defaults(cls, index, similarity_top_k: int):
|
||||
def from_defaults(cls, index, similarity_top_k: int, token_pattern: str):
|
||||
raise RuntimeError("boom")
|
||||
|
||||
monkeypatch.setattr(retriever_module, "_import_bm25_retriever", lambda: _FailingBM25)
|
||||
|
||||
Reference in New Issue
Block a user