mirror of
https://github.com/lancedb/lancedb.git
synced 2026-12-03 07:45:17 +00:00
feat: support vector-only and FTS-only reranking (#3024)
Add rerank_vector() and rerank_fts() methods to Reranker trait, allowing rerankers to work with single search modes instead of only hybrid search. Implemented for: - RRFReranker (Rust and Python) - LinearCombinationReranker (Python) Resolves TODO at rust/lancedb/src/rerankers.rs:55 Changes: - Extended Reranker trait with default implementations - Added unit tests for new methods - Updated documentation with examples --------- Co-authored-by: Xuanwo <github@xuanwo.io>
This commit is contained in:
@@ -34,6 +34,7 @@ from pydantic_core import PydanticUndefined
|
||||
from typing_extensions import Annotated
|
||||
|
||||
from lancedb._lancedb import (
|
||||
_parse_field_path,
|
||||
_share_hybrid_subquery_filter,
|
||||
_uses_sql_subquery_filter,
|
||||
fts_query_to_json,
|
||||
@@ -47,7 +48,13 @@ from .rerankers.base import Reranker
|
||||
from .rerankers.rrf import RRFReranker
|
||||
from .rerankers.util import check_reranker_result
|
||||
from .schema import blob_column_paths, is_blob_like_field, schema_has_blob_field
|
||||
from .util import _validate_query_vector, add_note, flatten_columns, get_uri_scheme
|
||||
from .util import (
|
||||
_validate_query_vector,
|
||||
add_note,
|
||||
flatten_columns,
|
||||
get_uri_scheme,
|
||||
inf_vector_column_query,
|
||||
)
|
||||
from . import _wal_hybrid # WAL-PK-FUSION: delete.
|
||||
from ._blob import (
|
||||
BLOB_MODE_TO_HANDLING,
|
||||
@@ -181,6 +188,32 @@ def _rows_to_models(model: type[T], rows: List[dict]) -> List[T]:
|
||||
AnalyzePlanDistributedMetrics = Literal["aggregate", "per_worker", "full"]
|
||||
_SYNC_VECTOR_QUERY_TYPES = (list, tuple, np.ndarray, pa.Array, pa.ChunkedArray)
|
||||
|
||||
|
||||
def _uses_single_list_rrf(reranker: Optional[Reranker]) -> bool:
|
||||
# A subclass can supply its own vector callback with batch semantics.
|
||||
return (
|
||||
isinstance(reranker, RRFReranker)
|
||||
and getattr(reranker.rerank_vector, "__func__", None)
|
||||
is RRFReranker.rerank_vector
|
||||
)
|
||||
|
||||
|
||||
def _check_rrf_multivector_column(
|
||||
schema: Optional[pa.Schema], column: Optional[str], dimension: int
|
||||
) -> None:
|
||||
if schema is not None:
|
||||
if column is None:
|
||||
column = inf_vector_column_query(schema, dim=dimension)
|
||||
column_type = schema
|
||||
for name in _parse_field_path(column):
|
||||
column_type = column_type.field(name).type
|
||||
if pa.types.is_list(column_type):
|
||||
return
|
||||
raise NotImplementedError(
|
||||
"RRF does not support batched vector searches. Run one query per vector."
|
||||
)
|
||||
|
||||
|
||||
# Number of rows a hybrid query returns when no limit was set on it. This
|
||||
# mirrors the default the Rust query builder applies to its sub-queries.
|
||||
DEFAULT_HYBRID_LIMIT = 10
|
||||
@@ -2779,6 +2812,24 @@ class LanceVectorQueryBuilder(LanceQueryBuilder):
|
||||
schema=schema,
|
||||
)
|
||||
|
||||
def _query_for_scan(
|
||||
self,
|
||||
blob_sources: Optional[dict[str, str]] = None,
|
||||
schema: Optional[pa.Schema] = None,
|
||||
) -> Query:
|
||||
query = super()._query_for_scan(blob_sources, schema)
|
||||
vectors = query.vector
|
||||
if (
|
||||
_uses_single_list_rrf(self._reranker)
|
||||
and vectors
|
||||
and len(vectors) > 1
|
||||
and isinstance(vectors[0], list)
|
||||
):
|
||||
if schema is None:
|
||||
schema = self._table.schema
|
||||
_check_rrf_multivector_column(schema, query.vector_column, len(vectors[0]))
|
||||
return query
|
||||
|
||||
def to_query_object(self) -> Query:
|
||||
"""
|
||||
Build a Query object
|
||||
@@ -5881,11 +5932,25 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
|
||||
AsyncHybridQuery(self._inner.nearest_to_text({"query": query}), self._table)
|
||||
)
|
||||
|
||||
def _rrf_multivector_input(self) -> Optional[tuple[Optional[str], int]]:
|
||||
if _uses_single_list_rrf(self._reranker):
|
||||
request = self._inner.to_query_request()
|
||||
vectors = request.query_vector
|
||||
if vectors and len(vectors) > 1:
|
||||
return request.column, len(vectors[0])
|
||||
return None
|
||||
|
||||
async def _check_rrf_vector_query(self) -> None:
|
||||
if (vector_input := self._rrf_multivector_input()) is not None:
|
||||
schema = await self._table.schema() if self._table is not None else None
|
||||
_check_rrf_multivector_column(schema, *vector_input)
|
||||
|
||||
async def _execute_eager(
|
||||
self,
|
||||
*,
|
||||
timeout: Optional[timedelta] = None,
|
||||
) -> pa.Table:
|
||||
await self._check_rrf_vector_query()
|
||||
if self._force_local_namespace and self._table is not None:
|
||||
# Preserve local execution for the vector leg so it uses the same
|
||||
# embedded table snapshot as the FTS leg.
|
||||
@@ -5905,6 +5970,9 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
|
||||
*,
|
||||
timeout: Optional[timedelta] = None,
|
||||
) -> pa.Table:
|
||||
if (vector_input := self._rrf_multivector_input()) is not None:
|
||||
schema = self._table._schema_sync() if self._table is not None else None
|
||||
_check_rrf_multivector_column(schema, *vector_input)
|
||||
results = super()._execute_eager_sync(timeout=timeout)
|
||||
if self._reranker:
|
||||
source = results
|
||||
@@ -5919,6 +5987,7 @@ class AsyncVectorQuery(AsyncStandardQuery, AsyncVectorQueryBase):
|
||||
timeout: Optional[timedelta] = None,
|
||||
blob_sources: Optional[dict[str, str]] = None,
|
||||
) -> AsyncRecordBatchReader:
|
||||
await self._check_rrf_vector_query()
|
||||
reader = await super()._execute_batches(
|
||||
max_batch_length=max_batch_length,
|
||||
timeout=timeout,
|
||||
|
||||
@@ -14,20 +14,38 @@ if TYPE_CHECKING:
|
||||
|
||||
class RRFReranker(Reranker):
|
||||
"""
|
||||
Reranks the results using Reciprocal Rank Fusion(RRF) algorithm based
|
||||
on the scores of vector and FTS search.
|
||||
Rerank vector, full-text, or hybrid search results using Reciprocal Rank
|
||||
Fusion (RRF). Each list contributes `1 / (K + rank)` per row, with ranks
|
||||
starting at 1. A single list keeps its input order.
|
||||
|
||||
For vector reranking, run independent searches one query vector at a time.
|
||||
Multiple query vectors against a multivector column form one ranked list.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
K : int, default 60
|
||||
A constant used in the RRF formula (default is 60). Experiments
|
||||
indicate that k = 60 was near-optimal, but that the choice is
|
||||
not critical. See paper:
|
||||
https://plg.uwaterloo.ca/~gvcormac/cormacksigir09-rrf.pdf
|
||||
The constant used in RRF formula. Research suggests K=60 is
|
||||
near-optimal, but the choice is not critical.
|
||||
return_score : str, default "relevance"
|
||||
opntions are "relevance" or "all"
|
||||
The type of score to return. If "relevance", will return only the relevance
|
||||
score. If "all", will return all scores from the vector and FTS search along
|
||||
with the relevance score.
|
||||
Whether to return only "_relevance_score" or "all" scores
|
||||
including "_distance" and "_score".
|
||||
|
||||
Examples
|
||||
--------
|
||||
For a vector query, pass the query text to the builder when supplying a
|
||||
precomputed vector. Full-text and hybrid queries already have query text.
|
||||
|
||||
```python
|
||||
reranker = RRFReranker(K=60)
|
||||
vector = table.search(query_vector).rerank(reranker, query_string=query).to_arrow()
|
||||
fts = table.search(query, query_type="fts").rerank(reranker).to_arrow()
|
||||
```
|
||||
|
||||
References
|
||||
----------
|
||||
Cormack et al. (2009). "Reciprocal rank fusion outperforms condorcet
|
||||
and individual rank learning methods." SIGIR '09.
|
||||
https://plg.uwaterloo.ca/~gvcormac/cormacksigir09-rrf.pdf
|
||||
"""
|
||||
|
||||
def __init__(self, K: int = 60, return_score="relevance"):
|
||||
@@ -39,6 +57,23 @@ class RRFReranker(Reranker):
|
||||
def __str__(self):
|
||||
return f"RRFReranker(K={self.K})"
|
||||
|
||||
def _rerank_list(self, results: pa.Table) -> pa.Table:
|
||||
scores = pa.array(
|
||||
[1 / (rank + self.K) for rank in range(1, len(results) + 1)],
|
||||
type=pa.float32(),
|
||||
)
|
||||
return self._keep_relevance_score(
|
||||
results.append_column("_relevance_score", scores)
|
||||
)
|
||||
|
||||
def rerank_vector(self, query: str, vector_results: pa.Table) -> pa.Table:
|
||||
"""Score vector search results in rank order."""
|
||||
return self._rerank_list(vector_results)
|
||||
|
||||
def rerank_fts(self, query: str, fts_results: pa.Table) -> pa.Table:
|
||||
"""Score full-text search results in rank order."""
|
||||
return self._rerank_list(fts_results)
|
||||
|
||||
def rerank_hybrid(
|
||||
self,
|
||||
query: str, # noqa: F821
|
||||
@@ -81,10 +116,7 @@ class RRFReranker(Reranker):
|
||||
deduplicate: bool = True,
|
||||
):
|
||||
"""
|
||||
Overridden method to rerank the results from multiple vector searches.
|
||||
This leverages the RRF hybrid reranking algorithm to combine the
|
||||
results from multiple vector searches as it doesn't support reranking
|
||||
vector results individually.
|
||||
Combine the ranked lists from multiple vector searches using RRF.
|
||||
|
||||
Set `deduplicate=False` to keep all result rows with their fused scores.
|
||||
"""
|
||||
|
||||
@@ -13,6 +13,7 @@ import pyarrow.compute as pc
|
||||
import pytest
|
||||
from lancedb.conftest import MockTextEmbeddingFunction # noqa
|
||||
from lancedb.embeddings import EmbeddingFunctionRegistry
|
||||
from lancedb.index import FTS
|
||||
from lancedb.pydantic import LanceModel, Vector
|
||||
from lancedb.rerankers import (
|
||||
LinearCombinationReranker,
|
||||
@@ -440,6 +441,153 @@ def test_mrr_multivector_rewards_consensus():
|
||||
assert result["_rowid"].to_pylist()[0] == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"])
|
||||
@pytest.mark.parametrize("query_type", ["vector", "fts"])
|
||||
@pytest.mark.parametrize(
|
||||
"return_score,with_row_id,empty",
|
||||
[
|
||||
("relevance", False, False),
|
||||
("all", False, False),
|
||||
("relevance", True, True),
|
||||
("all", True, True),
|
||||
],
|
||||
)
|
||||
async def test_rrf_single_mode_query(
|
||||
tmp_path, asynchronous, query_type, return_score, with_row_id, empty
|
||||
):
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table(
|
||||
"docs",
|
||||
[
|
||||
{"id": 1, "text": "dog dog", "vector": [0.0, 0.0]},
|
||||
{"id": 2, "text": "cat", "vector": [1.0, 1.0]},
|
||||
{"id": 3, "text": "dog in a garden", "vector": [2.0, 2.0]},
|
||||
],
|
||||
)
|
||||
table.create_index("text", config=FTS())
|
||||
term = "absent" if empty else "dog"
|
||||
reranker = RRFReranker(return_score=return_score)
|
||||
|
||||
if asynchronous:
|
||||
async_db = await lancedb.connect_async(tmp_path)
|
||||
async_table = await async_db.open_table("docs")
|
||||
if query_type == "vector":
|
||||
query = async_table.query().nearest_to([0.0, 0.0])
|
||||
else:
|
||||
query = async_table.query().nearest_to_text(term)
|
||||
elif query_type == "vector":
|
||||
query = table.search([0.0, 0.0])
|
||||
else:
|
||||
query = table.search(term, query_type="fts")
|
||||
|
||||
query = query.select(["id"]).limit(2)
|
||||
if with_row_id:
|
||||
query = query.with_row_id() if asynchronous else query.with_row_id(True)
|
||||
if empty and query_type == "vector":
|
||||
query = query.where("id < 0")
|
||||
if query_type == "vector":
|
||||
query = query.rerank(reranker, query_string="dog")
|
||||
else:
|
||||
query = query.rerank(reranker)
|
||||
result = await query.to_arrow() if asynchronous else query.to_arrow()
|
||||
|
||||
expected_ids = [] if empty else [1, 2 if query_type == "vector" else 3]
|
||||
assert result["id"].to_pylist() == expected_ids
|
||||
assert result.column_names.count("_relevance_score") == 1
|
||||
assert result["_relevance_score"].type == pa.float32()
|
||||
assert result["_relevance_score"].to_pylist() == pytest.approx(
|
||||
[1 / (61 + index) for index in range(len(expected_ids))]
|
||||
)
|
||||
source_score = "_distance" if query_type == "vector" else "_score"
|
||||
assert (source_score in result.column_names) == (return_score == "all")
|
||||
# The synchronous builder also requests row IDs for return_score="all".
|
||||
assert ("_rowid" in result.column_names) == (
|
||||
with_row_id or (not asynchronous and return_score == "all")
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"])
|
||||
async def test_rrf_rejects_independent_vector_batches(tmp_path, asynchronous):
|
||||
rows = [
|
||||
{"id": index, "vector": [x, 0.0]}
|
||||
for index, x in enumerate([0.0, 1.0, 3.0, 4.0])
|
||||
]
|
||||
vectors = [[0.0, 0.0], [4.0, 0.0]]
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
table = await db.create_table("docs", rows)
|
||||
query = table.query().nearest_to(vectors)
|
||||
else:
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("docs", rows)
|
||||
query = table.search(vectors)
|
||||
|
||||
query = query.select(["id"]).limit(2)
|
||||
raw = await query.to_arrow() if asynchronous else query.to_arrow()
|
||||
assert sorted(zip(raw["query_index"].to_pylist(), raw["id"].to_pylist())) == [
|
||||
(0, 0),
|
||||
(0, 1),
|
||||
(1, 2),
|
||||
(1, 3),
|
||||
]
|
||||
|
||||
reranked = query.rerank(RRFReranker(), query_string="dog")
|
||||
with pytest.raises(NotImplementedError, match="RRF does not support batched"):
|
||||
if asynchronous:
|
||||
await reranked.to_arrow()
|
||||
else:
|
||||
reranked.to_arrow()
|
||||
with pytest.raises(NotImplementedError, match="RRF does not support batched"):
|
||||
if asynchronous:
|
||||
await reranked.to_batches()
|
||||
else:
|
||||
reranked.to_batches()
|
||||
|
||||
class CustomReranker(RRFReranker):
|
||||
def rerank_vector(self, query, results):
|
||||
return results.append_column(
|
||||
"_relevance_score", pa.array([1.0] * len(results), type=pa.float32())
|
||||
)
|
||||
|
||||
custom = query.rerank(CustomReranker(), query_string="dog")
|
||||
result = await custom.to_arrow() if asynchronous else custom.to_arrow()
|
||||
assert result["_relevance_score"].to_pylist() == [1.0] * 4
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"])
|
||||
async def test_rrf_multivector_projected_query_index(tmp_path, asynchronous):
|
||||
tokens = pa.FixedSizeListArray.from_arrays(
|
||||
pa.array([1.0, 0.0, 0.0, 1.0], type=pa.float32()), 2
|
||||
)
|
||||
data = pa.table(
|
||||
{
|
||||
"vector": pa.ListArray.from_arrays([0, 2], tokens),
|
||||
"query_index": ["user data"],
|
||||
}
|
||||
)
|
||||
vectors = [[1.0, 0.0], [0.0, 1.0]]
|
||||
if asynchronous:
|
||||
db = await lancedb.connect_async(tmp_path)
|
||||
table = await db.create_table("docs", data)
|
||||
query = table.query().nearest_to(vectors).column("vector")
|
||||
else:
|
||||
db = lancedb.connect(tmp_path)
|
||||
table = db.create_table("docs", data)
|
||||
query = table.search(vectors, vector_column_name="vector")
|
||||
|
||||
query = (
|
||||
query.distance_type("cosine")
|
||||
.select(["query_index"])
|
||||
.rerank(RRFReranker(), query_string="dog")
|
||||
)
|
||||
result = await query.to_arrow() if asynchronous else query.to_arrow()
|
||||
assert result["query_index"].to_pylist() == ["user data"]
|
||||
assert result["_relevance_score"].to_pylist() == pytest.approx([1 / 61])
|
||||
|
||||
|
||||
def test_rrf_multivector_ranks_each_result_list():
|
||||
# RRF scores a document by its rank *within each* result list. The top hit
|
||||
# of the second list must score the same as the top hit of the first list,
|
||||
|
||||
Reference in New Issue
Block a user