Skip to content

armgit / txtai

Public Imported from GitHub
0

💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows

Add Reranker pipeline, closes #960

davidmezzettib8980bc5be0e
diff --git a/docs/pipeline/index.md b/docs/pipeline/index.md
index b5f553a4..859eb2dd 100644
--- a/docs/pipeline/index.md
+++ b/docs/pipeline/index.md
@@ -35,6 +35,7 @@ The `LLM` and `RAG` pipelines also have integrations for [llama.cpp](https://git
- [Labeling](text/labels)
- [LLM](text/llm)
- [RAG](text/rag)
+ - [Reranker](text/reranker)
- [Similarity](text/similarity)
- [Summary](text/summary)
- [Translation](text/translation)
diff --git a/docs/pipeline/text/reranker.md b/docs/pipeline/text/reranker.md
new file mode 100644
index 00000000..2cbf0db1
--- /dev/null
+++ b/docs/pipeline/text/reranker.md
@@ -0,0 +1,76 @@
+# Reranker
+
+![pipeline](../../images/pipeline.png#only-light)
+![pipeline](../../images/pipeline-dark.png#only-dark)
+
+The Reranker pipeline runs embeddings queries and re-ranks them using a similarity pipeline.
+
+## Example
+
+The following shows a simple example using this pipeline.
+
+```python
+from txtai import Embeddings
+from txtai.pipeline import Reranker, Similarity
+
+# Embeddings instance
+embeddings = Embeddings()
+embeddings.load(provider="huggingface-hub", container="neuml/txtai-wikipedia")
+
+# Similarity instance
+similarity = Similarity(path="colbert-ir/colbertv2.0", lateencode=True)
+
+# Reranking pipeline
+reranker = Reranker(embeddings, similarity)
+reranker("Tell me about AI")
+```
+
+_Note: Content must be enabled with the embeddings instance for this to work properly._
+
+## Configuration-driven example
+
+Pipelines are run with Python or configuration. Pipelines can be instantiated in [configuration](../../../api/configuration/#pipeline) using the lower case name of the pipeline. Configuration-driven pipelines are run with [workflows](../../../workflow/#configuration-driven-example) or the [API](../../../api#local-instance).
+
+### config.yml
+```yaml
+embeddings:
+
+similarity:
+
+# Create pipeline using lower case class name
+reranker:
+
+# Run pipeline with workflow
+workflow:
+ translate:
+ tasks:
+ - reranker
+```
+
+### Run with Workflows
+
+```python
+from txtai import Application
+
+# Create and run pipeline with workflow
+app = Application("config.yml")
+list(app.workflow("reranker", ["Tell me about AI"]))
+```
+
+### Run with API
+
+```bash
+CONFIG=config.yml uvicorn "txtai.api:app" &
+
+curl \
+ -X POST "http://localhost:8000/workflow" \
+ -H "Content-Type: application/json" \
+ -d '{"name":"rerank", "elements":["Tell me about AI"]}'
+```
+
+## Methods
+
+Python documentation for the pipeline.
+
+### ::: txtai.pipeline.Reranker.__init__
+### ::: txtai.pipeline.Reranker.__call__
diff --git a/docs/pipeline/text/similarity.md b/docs/pipeline/text/similarity.md
index 8085b3d0..79b49b88 100644
--- a/docs/pipeline/text/similarity.md
+++ b/docs/pipeline/text/similarity.md
@@ -7,7 +7,7 @@ The Similarity pipeline computes similarity between queries and list of text usi
This pipeline supports both standard text classification models and zero-shot classification models. The pipeline uses the queries as labels for the input text. The results are transposed to get scores per query/label vs scores per input text.
-Cross-encoder models are supported via the `crossencode=True` constructor parameter. These models are loaded with a CrossEncoder pipeline that can also be instantiated directly. The CrossEncoder pipeline has the same methods and functionality as described below.
+Cross-encoder models are supported via the `crossencode=True` constructor parameter. Late interaction (i.e. ColBERT) models are also supported via the `lateencode=True` constructor parameter. CrossEncoder and LateEncoder pipelines back each of these models and can be instantiated directly as well.
## Example
diff --git a/mkdocs.yml b/mkdocs.yml
index 1e273f13..6b26f04e 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -99,6 +99,7 @@ nav:
- Labels: pipeline/text/labels.md
- LLM: pipeline/text/llm.md
- RAG: pipeline/text/rag.md
+ - Reranker: pipeline/text/reranker.md
- Similarity: pipeline/text/similarity.md
- Summary: pipeline/text/summary.md
- Translation: pipeline/text/translation.md
diff --git a/src/python/txtai/api/routers/__init__.py b/src/python/txtai/api/routers/__init__.py
index 69021a25..029db1df 100644
--- a/src/python/txtai/api/routers/__init__.py
+++ b/src/python/txtai/api/routers/__init__.py
@@ -12,6 +12,7 @@ from . import llm
from . import objects
from . import openai
from . import rag
+from . import reranker
from . import segmentation
from . import similarity
from . import summary
diff --git a/src/python/txtai/api/routers/reranker.py b/src/python/txtai/api/routers/reranker.py
new file mode 100644
index 00000000..7f938649
--- /dev/null
+++ b/src/python/txtai/api/routers/reranker.py
@@ -0,0 +1,46 @@
+"""
+Defines API paths for reranking endpoints.
+"""
+
+from typing import List, Optional
+
+from fastapi import APIRouter, Body
+
+from .. import application
+from ..route import EncodingAPIRoute
+
+router = APIRouter(route_class=EncodingAPIRoute)
+
+
+def rerank(query: str, limit: Optional[int] = 3, factor: Optional[int] = 10):
+ """
+ Queries an embeddings database and reranks the results with a similarity pipeline.
+
+ Args:
+ query: query text
+ limit: maximum results
+ factor: factor to multiply limit by for the initial embeddings search
+
+ Returns:
+ query results
+ """
+
+ return application.get().pipeline("reranker", (query, limit, factor))
+
+
[email protected]("/batchrerank")
+def batchrerank(queries: List[str] = Body(...), limit: Optional[int] = Body(default=3), factor: Optional[int] = Body(default=10)):
+ """
+ Queries an embeddings database and reranks the results with a similarity pipeline.
+
+ Args:
+ queries: list of queries
+ limit: maximum results
+ factor: factor to multiply limit by for the initial embeddings search
+
+ Returns:
+ query results
+ """
+
+ return application.get().pipeline("reranker", (queries, limit, factor))
diff --git a/src/python/txtai/app/base.py b/src/python/txtai/app/base.py
index 39c00b28..bceb8f87 100644
--- a/src/python/txtai/app/base.py
+++ b/src/python/txtai/app/base.py
@@ -107,7 +107,7 @@ class Application:
pipelines.append(key)
# Move dependent pipelines to end of list
- dependent = ["similarity", "extractor", "rag"]
+ dependent = ["similarity", "extractor", "rag", "reranker"]
pipelines = sorted(pipelines, key=lambda x: dependent.index(x) + 1 if x in dependent else 0)
# Create pipelines
@@ -135,6 +135,10 @@ class Application:
elif pipeline == "similarity" and "path" not in config and "labels" in self.pipelines:
config["model"] = self.pipelines["labels"]
+ elif pipeline == "reranker":
+ config["embeddings"] = None
+ config["similarity"] = self.pipelines["similarity"]
+
self.pipelines[pipeline] = PipelineFactory.create(config, pipeline)
def createworkflows(self):
@@ -235,6 +239,10 @@ class Application:
if pipeline and config is not None and config["similarity"] is None:
pipeline.similarity = self.embeddings
+ # Attach embeddings to reranker
+ if "reranker" in self.pipelines:
+ self.pipelines["reranker"].embeddings = self.embeddings
+
def resolvetask(self, task):
"""
Resolves callable functions for a task.
diff --git a/src/python/txtai/pipeline/text/__init__.py b/src/python/txtai/pipeline/text/__init__.py
index df9cc507..be6b9792 100644
--- a/src/python/txtai/pipeline/text/__init__.py
+++ b/src/python/txtai/pipeline/text/__init__.py
@@ -7,6 +7,7 @@ from .entity import Entity
from .labels import Labels
from .lateencoder import LateEncoder
from .questions import Questions
+from .reranker import Reranker
from .similarity import Similarity
from .summary import Summary
from .translation import Translation
diff --git a/src/python/txtai/pipeline/text/reranker.py b/src/python/txtai/pipeline/text/reranker.py
new file mode 100644
index 00000000..b0ffd9f8
--- /dev/null
+++ b/src/python/txtai/pipeline/text/reranker.py
@@ -0,0 +1,57 @@
+"""
+Reranker module
+"""
+
+from ..base import Pipeline
+
+
+class Reranker(Pipeline):
+ """
+ Runs embeddings queries and re-ranks them using a similarity pipeline. Note that content must be enabled with the
+ embeddings instance for this to work properly.
+ """
+
+ def __init__(self, embeddings, similarity):
+ """
+ Creates a Reranker pipeline.
+
+ Args:
+ embeddings: embeddings instance (content must be enabled)
+ similarity: similarity instance
+ """
+
+ self.embeddings, self.similarity = embeddings, similarity
+
+ # pylint: disable=W0222
+ def __call__(self, query, limit=3, factor=10, **kwargs):
+ """
+ Runs an embeddings search and re-ranks the results using a Similarity pipeline.
+
+ Args:
+ query: query text|list
+ limit: maximum results
+ factor: factor to multiply limit by for the initial embeddings search
+ kwargs: additional arguments to pass to embeddings search
+
+ Returns:
+ list of query results rescored using a Similarity pipeline
+ """
+
+ queries = [query] if not isinstance(query, list) else query
+
+ # Run searches
+ results = self.embeddings.batchsearch(queries, limit * factor, **kwargs)
+
+ # Re-rank using similarity pipeline
+ ranked = []
+ for x, result in enumerate(results):
+ texts = [row["text"] for row in result]
+
+ # Score results and merge
+ for uid, score in self.similarity(queries[x], texts):
+ result[uid]["score"] = score
+
+ # Sort and take top n sorted results
+ ranked.append(sorted(result, key=lambda row: row["score"], reverse=True)[:limit])
+
+ return ranked[0] if isinstance(query, str) else ranked
diff --git a/src/python/txtai/pipeline/text/similarity.py b/src/python/txtai/pipeline/text/similarity.py
index bed805f5..57e8842e 100644
--- a/src/python/txtai/pipeline/text/similarity.py
+++ b/src/python/txtai/pipeline/text/similarity.py
@@ -52,7 +52,7 @@ class Similarity(Labels):
return self.crossencoder(query, texts, multilabel)
if self.lateencoder:
- return self.lateencoder(query, texts, **kwargs)
+ return self.lateencoder(query, texts)
# Call Labels pipeline for texts using input query as the candidate label
scores = super().__call__(texts, [query] if isinstance(query, str) else query, multilabel, **kwargs)
@@ -67,3 +67,17 @@ class Similarity(Labels):
scores = [sorted(enumerate(row), key=lambda x: x[1], reverse=True) for row in scores]
return scores[0] if isinstance(query, str) else scores
+
+ def encode(self, data, category):
+ """
+ Encodes a batch of data using the underlying model.
+
+ Args:
+ data: input data
+ category: encoding category
+
+ Returns:
+ encoded data
+ """
+
+ return self.lateencoder.encode(data, category) if self.lateencoder else data
diff --git a/test/python/testapi/testapiembeddings.py b/test/python/testapi/testapiembeddings.py
index 4e05e4a6..4ad99df1 100644
--- a/test/python/testapi/testapiembeddings.py
+++ b/test/python/testapi/testapiembeddings.py
@@ -92,6 +92,27 @@ rag:
output: flatten
"""
+# Configuration for reranker
+RERANK = """
+# Index file path
+path: %s
+
+# Allow indexing of documents
+writable: True
+
+# Embeddings settings
+embeddings:
+ path: sentence-transformers/nli-mpnet-base-v2
+ content: True
+
+# Similarity and Reranking settings
+similarity:
+ path: neuml/colbert-bert-tiny
+ lateencode: True
+
+reranker:
+"""
+
class TestEmbeddings(unittest.TestCase):
"""
@@ -401,6 +422,26 @@ class TestEmbeddings(unittest.TestCase):
response = self.client.post("batchrag", json={"queries": ["bear", "bear"]}).json()
self.assertEqual(len(response), 2)
+ def testXRerank(self):
+ """
+ Test rerank via API
+ """
+
+ # Re-create model with custom functions
+ self.client = TestEmbeddings.start(RERANK)
+
+ # Index data
+ self.client.post("add", json=[{"id": x, "text": row} for x, row in enumerate(self.data)])
+ self.client.get("index")
+
+ uid = self.client.get("rerank?query=bear").json()[0]["id"]
+ self.assertEqual(uid, "3")
+
+ results = self.client.post("batchrerank", json={"queries": ["bear", "bear"]}).json()
+
+ uids = [result[0]["id"] for result in results]
+ self.assertEqual(uids, ["3", "3"])
+
class Elements:
"""
diff --git a/test/python/testpipeline/testtext/testreranker.py b/test/python/testpipeline/testtext/testreranker.py
new file mode 100644
index 00000000..58505702
--- /dev/null
+++ b/test/python/testpipeline/testtext/testreranker.py
@@ -0,0 +1,42 @@
+"""
+Reranker module tests
+"""
+
+import unittest
+
+from txtai import Embeddings
+from txtai.pipeline import Reranker, Similarity
+
+
+class TestReranker(unittest.TestCase):
+ """
+ Reranker tests.
+ """
+
+ @classmethod
+ def setUpClass(cls):
+ """
+ Create single labels instance.
+ """
+
+ cls.data = [
+ "US tops 5 million confirmed virus cases",
+ "Canada's last fully intact ice shelf has suddenly collapsed, forming a Manhattan-sized iceberg",
+ "Beijing mobilises invasion craft along coast as Taiwan tensions escalate",
+ "The National Park Service warns against sacrificing slower friends in a bear attack",
+ "Maine man wins $1M from $25 lottery ticket",
+ "Make huge profits without work, earn up to $100,000 a day",
+ ]
+
+ def testRanker(self):
+ """
+ Test re-ranking pipeline
+ """
+
+ embeddings = Embeddings(content=True)
+ embeddings.index(self.data)
+
+ similarity = Similarity("neuml/colbert-bert-tiny", lateencode=True)
+
+ ranker = Reranker(embeddings, similarity)
+ self.assertEqual(ranker("lottery winner")[0]["id"], "4")
diff --git a/test/python/testpipeline/testtext/testsimilarity.py b/test/python/testpipeline/testtext/testsimilarity.py
index 5193c738..145d5f09 100644
--- a/test/python/testpipeline/testtext/testsimilarity.py
+++ b/test/python/testpipeline/testtext/testsimilarity.py
@@ -56,6 +56,10 @@ class TestSimilarity(unittest.TestCase):
uid = similarity("Who won the lottery?", self.data)[0][0]
self.assertEqual(self.data[uid], self.data[4])
+ # Test encode method
+ # pylint: disable=E1101
+ self.assertEqual(similarity.encode(["Who won the lottery?"], "data").shape, (1, 8, 128))
+
def testLateEncoderBatch(self):
"""
Test late-encoder similarity model with multiple inputs