Elffuss BraidHub

kikocis/lancedb public

feat: update default reranker to RRF (#1580)

- Both LinearCombination (the current default) and RRF are pretty fast
compared to model based rerankers. RRF is slightly faster.
- In our tests RRF has also been slightly more accurate.

This PR:
- Makes RRF the default reranker
- Removed duplicate docs for rerankers
Changeseteef1b2e997ef0f62156a1239e97c866626bfa75a9f8bd791b8910ab742e0c3c7
AuthorAyush Chaurasia <ayush.chaurarsia@gmail.com> · 2024-09-03 14:00 +05:30
CommitterGitHub <noreply@github.com> · 2024-09-03 14:00 +05:30
Parents29a0fbeb822f

Browse the files at this changeset

3 files changed

modified docs/src/hybrid_search/hybrid_search.md +4 −185
@@ -57,199 +57,18 @@
5757
5858 ```
5959
60-By default, LanceDB uses `LinearCombinationReranker(weight=0.7)` to combine and rerank the results of semantic and full-text search. You can customize the hyperparameters as needed or write your own custom reranker. Here's how you can use any of the available rerankers:
60+By default, LanceDB uses `RRFReranker()`, which uses reciprocal rank fusion score, to combine and rerank the results of semantic and full-text search. You can customize the hyperparameters as needed or write your own custom reranker. Here's how you can use any of the available rerankers:
6161
6262
6363 ### `rerank()` arguments
6464 * `normalize`: `str`, default `"score"`:
6565 The method to normalize the scores. Can be "rank" or "score". If "rank", the scores are converted to ranks and then normalized. If "score", the scores are normalized directly.
66-* `reranker`: `Reranker`, default `LinearCombinationReranker(weight=0.7)`.
66+* `reranker`: `Reranker`, default `RRF()`.
6767 The reranker to use. If not specified, the default reranker is used.
6868
6969
7070 ## Available Rerankers
71-LanceDB provides a number of re-rankers out of the box. You can use any of these re-rankers by passing them to the `rerank()` method. Here's a list of available re-rankers:
71+LanceDB provides a number of re-rankers out of the box. You can use any of these re-rankers by passing them to the `rerank()` method.
72+Go to [Rerankers](../reranking/index.md) to learn more about using the available rerankers and implementing custom rerankers.
7273
73-### Linear Combination Reranker
74-This is the default re-ranker used by LanceDB. It combines the results of semantic and full-text search using a linear combination of the scores. The weights for the linear combination can be specified. It defaults to 0.7, i.e, 70% weight for semantic search and 30% weight for full-text search.
7574
76-
77-```python
78-from lancedb.rerankers import LinearCombinationReranker
79-
80-reranker = LinearCombinationReranker(weight=0.3) # Use 0.3 as the weight for vector search
81-
82-results = table.search("rebel", query_type="hybrid").rerank(reranker=reranker).to_pandas()
83-```
84-
85-### Arguments
86-----------------
87-* `weight`: `float`, default `0.7`:
88- The weight to use for the semantic search score. The weight for the full-text search score is `1 - weights`.
89-* `fill`: `float`, default `1.0`:
90- The score to give to results that are only in one of the two result sets.This is treated as penalty, so a higher value means a lower score.
91- TODO: We should just hardcode this-- its pretty confusing as we invert scores to calculate final score
92-* `return_score` : str, default `"relevance"`
93- options are "relevance" or "all"
94- 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.
95-
96-### Cohere Reranker
97-This re-ranker uses the [Cohere](https://cohere.ai/) API to combine the results of semantic and full-text search. You can use this re-ranker by passing `CohereReranker()` to the `rerank()` method. Note that you'll need to set the `COHERE_API_KEY` environment variable to use this re-ranker.
98-
99-```python
100-from lancedb.rerankers import CohereReranker
101-
102-reranker = CohereReranker()
103-
104-results = table.search("vampire weekend", query_type="hybrid").rerank(reranker=reranker).to_pandas()
105-```
106-
107-### Arguments
108-----------------
109-* `model_name` : str, default `"rerank-english-v2.0"`
110- The name of the cross encoder model to use. Available cohere models are:
111- - rerank-english-v2.0
112- - rerank-multilingual-v2.0
113-* `column` : str, default `"text"`
114- The name of the column to use as input to the cross encoder model.
115-* `top_n` : str, default `None`
116- The number of results to return. If None, will return all results.
117-
118-!!! Note
119- Only returns `_relevance_score`. Does not support `return_score = "all"`.
120-
121-### Cross Encoder Reranker
122-This reranker uses the [Sentence Transformers](https://www.sbert.net/) library to combine the results of semantic and full-text search. You can use it by passing `CrossEncoderReranker()` to the `rerank()` method.
123-
124-```python
125-from lancedb.rerankers import CrossEncoderReranker
126-
127-reranker = CrossEncoderReranker()
128-
129-results = table.search("harmony hall", query_type="hybrid").rerank(reranker=reranker).to_pandas()
130-```
131-
132-
133-### Arguments
134-----------------
135-* `model` : str, default `"cross-encoder/ms-marco-TinyBERT-L-6"`
136- The name of the cross encoder model to use. Available cross encoder models can be found [here](https://www.sbert.net/docs/pretrained_cross-encoders.html)
137-* `column` : str, default `"text"`
138- The name of the column to use as input to the cross encoder model.
139-* `device` : str, default `None`
140- The device to use for the cross encoder model. If None, will use "cuda" if available, otherwise "cpu".
141-
142-!!! Note
143- Only returns `_relevance_score`. Does not support `return_score = "all"`.
144-
145-
146-### ColBERT Reranker
147-This reranker uses the ColBERT model to combine the results of semantic and full-text search. You can use it by passing `ColbertrReranker()` to the `rerank()` method.
148-
149-ColBERT reranker model calculates relevance of given docs against the query and don't take existing fts and vector search scores into account, so it currently only supports `return_score="relevance"`. By default, it looks for `text` column to rerank the results. But you can specify the column name to use as input to the cross encoder model as described below.
150-
151-```python
152-from lancedb.rerankers import ColbertReranker
153-
154-reranker = ColbertReranker()
155-
156-results = table.search("harmony hall", query_type="hybrid").rerank(reranker=reranker).to_pandas()
157-```
158-
159-### Arguments
160-----------------
161-* `model_name` : `str`, default `"colbert-ir/colbertv2.0"`
162- The name of the cross encoder model to use.
163-* `column` : `str`, default `"text"`
164- The name of the column to use as input to the cross encoder model.
165-* `return_score` : `str`, default `"relevance"`
166- options are `"relevance"` or `"all"`. Only `"relevance"` is supported for now.
167-
168-!!! Note
169- Only returns `_relevance_score`. Does not support `return_score = "all"`.
170-
171-### OpenAI Reranker
172-This reranker uses the OpenAI API to combine the results of semantic and full-text search. You can use it by passing `OpenaiReranker()` to the `rerank()` method.
173-
174-!!! Note
175- This prompts chat model to rerank results which is not a dedicated reranker model. This should be treated as experimental.
176-
177-!!! Tip
178- - You might run out of token limit so set the search `limits` based on your token limit.
179- - It is recommended to use gpt-4-turbo-preview, the default model, older models might lead to undesired behaviour
180-
181-```python
182-from lancedb.rerankers import OpenaiReranker
183-
184-reranker = OpenaiReranker()
185-
186-results = table.search("harmony hall", query_type="hybrid").rerank(reranker=reranker).to_pandas()
187-```
188-
189-### Arguments
190-----------------
191-* `model_name` : `str`, default `"gpt-4-turbo-preview"`
192- The name of the cross encoder model to use.
193-* `column` : `str`, default `"text"`
194- The name of the column to use as input to the cross encoder model.
195-* `return_score` : `str`, default `"relevance"`
196- options are "relevance" or "all". Only "relevance" is supported for now.
197-* `api_key` : `str`, default `None`
198- The API key to use. If None, will use the OPENAI_API_KEY environment variable.
199-
200-
201-## Building Custom Rerankers
202-You can build your own custom reranker by subclassing the `Reranker` class and implementing the `rerank_hybrid()` method. Here's an example of a custom reranker that combines the results of semantic and full-text search using a linear combination of the scores.
203-
204-The `Reranker` base interface comes with a `merge_results()` method that can be used to combine the results of semantic and full-text search. This is a vanilla merging algorithm that simply concatenates the results and removes the duplicates without taking the scores into consideration. It only keeps the first copy of the row encountered. This works well in cases that don't require the scores of semantic and full-text search to combine the results. If you want to use the scores or want to support `return_score="all"`, you'll need to implement your own merging algorithm.
205-
206-```python
207-
208-from lancedb.rerankers import Reranker
209-import pyarrow as pa
210-
211-class MyReranker(Reranker):
212- def __init__(self, param1, param2, ..., return_score="relevance"):
213- super().__init__(return_score)
214- self.param1 = param1
215- self.param2 = param2
216-
217- def rerank_hybrid(self, query: str, vector_results: pa.Table, fts_results: pa.Table):
218- # Use the built-in merging function
219- combined_result = self.merge_results(vector_results, fts_results)
220-
221- # Do something with the combined results
222- # ...
223-
224- # Return the combined results
225- return combined_result
226-
227-```
228-
229-### Example of a Custom Reranker
230-For the sake of simplicity let's build custom reranker that just enchances the Cohere Reranker by accepting a filter query, and accept other CohereReranker params as kwags.
231-
232-```python
233-
234-from typing import List, Union
235-import pandas as pd
236-from lancedb.rerankers import CohereReranker
237-
238-class MofidifiedCohereReranker(CohereReranker):
239- def __init__(self, filters: Union[str, List[str]], **kwargs):
240- super().__init__(**kwargs)
241- filters = filters if isinstance(filters, list) else [filters]
242- self.filters = filters
243-
244- def rerank_hybrid(self, query: str, vector_results: pa.Table, fts_results: pa.Table)-> pa.Table:
245- combined_result = super().rerank_hybrid(query, vector_results, fts_results)
246- df = combined_result.to_pandas()
247- for filter in self.filters:
248- df = df.query("not text.str.contains(@filter)")
249-
250- return pa.Table.from_pandas(df)
251-
252-```
253-
254-!!! tip
255- The `vector_results` and `fts_results` are pyarrow tables. You can convert them to pandas dataframes using `to_pandas()` method and perform any operations you want. After you are done, you can convert the dataframe back to pyarrow table using `pa.Table.from_pandas()` method and return it.
modified docs/src/reranking/index.md +2 −0
@@ -71,6 +71,8 @@
7171 - [OpenAI Reranker](./openai.md)
7272 - [Linear Combination Reranker](./linear_combination.md)
7373 - [Jina Reranker](./jina.md)
74+- [AnswerDotAI Rerankers](./answerdotai.md)
75+- [Reciprocal Rank Fusion Reranker](./rrf.md)
7476
7577 ## Creating Custom Rerankers
7678
modified python/python/lancedb/query.py +6 −5
@@ -35,7 +35,7 @@
3535 from . import __version__
3636 from .arrow import AsyncRecordBatchReader
3737 from .rerankers.base import Reranker
38-from .rerankers.linear_combination import LinearCombinationReranker
38+from .rerankers.rrf import RRFReranker
3939 from .util import safe_import_pandas
4040
4141 if TYPE_CHECKING:
@@ -916,7 +916,8 @@
916916 """
917917 A query builder that performs hybrid vector and full text search.
918918 Results are combined and reranked based on the specified reranker.
919- By default, the results are reranked using the LinearCombinationReranker.
919+ By default, the results are reranked using the RRFReranker, which
920+ uses reciprocal rank fusion score for reranking.
920921
921922 To make the vector and fts results comparable, the scores are normalized.
922923 Instead of normalizing scores, the `normalize` parameter can be set to "rank"
@@ -935,7 +936,7 @@
935936 self._vector_column = vector_column
936937 self._fts_columns = fts_columns
937938 self._norm = "score"
938- self._reranker = LinearCombinationReranker(weight=0.7, fill=1.0)
939+ self._reranker = RRFReranker()
939940 self._nprobes = None
940941 self._refine_factor = None
941942
@@ -1066,7 +1067,7 @@
10661067 def rerank(
10671068 self,
10681069 normalize="score",
1069- reranker: Reranker = LinearCombinationReranker(weight=0.7, fill=1.0),
1070+ reranker: Reranker = RRFReranker(),
10701071 ) -> LanceHybridQueryBuilder:
10711072 """
10721073 Rerank the hybrid search results using the specified reranker. The reranker
@@ -1078,7 +1079,7 @@
10781079 The method to normalize the scores. Can be "rank" or "score". If "rank",
10791080 the scores are converted to ranks and then normalized. If "score", the
10801081 scores are normalized directly.
1081- reranker: Reranker, default LinearCombinationReranker(weight=0.7, fill=1.0)
1082+ reranker: Reranker, default RRFReranker()
10821083 The reranker to use. Must be an instance of Reranker class.
10831084 Returns
10841085 -------