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 cross-encoder pipeline, closes #372

davidmezzetti30f82a62b028
diff --git a/src/python/txtai/pipeline/text/__init__.py b/src/python/txtai/pipeline/text/__init__.py
index e1ac9b54..261439d4 100644
--- a/src/python/txtai/pipeline/text/__init__.py
+++ b/src/python/txtai/pipeline/text/__init__.py
@@ -2,6 +2,7 @@
Text imports
"""
+from .crossencoder import CrossEncoder
from .entity import Entity
from .extractor import Extractor
from .labels import Labels
diff --git a/src/python/txtai/pipeline/text/crossencoder.py b/src/python/txtai/pipeline/text/crossencoder.py
new file mode 100644
index 00000000..09d4842e
--- /dev/null
+++ b/src/python/txtai/pipeline/text/crossencoder.py
@@ -0,0 +1,69 @@
+"""
+CrossEncoder module
+"""
+
+import numpy as np
+
+from ..hfpipeline import HFPipeline
+
+
+class CrossEncoder(HFPipeline):
+ """
+ Computes similarity between query and list of text using a cross-encoder model
+ """
+
+ def __init__(self, path=None, quantize=False, gpu=True, model=None):
+ super().__init__("text-classification", path, quantize, gpu, model)
+
+ def __call__(self, query, texts, multilabel=True, workers=0):
+ """
+ Computes the similarity between query and list of text. Returns a list of
+ (id, score) sorted by highest score, where id is the index in texts.
+
+ This method supports query as a string or a list. If the input is a string,
+ the return type is a 1D list of (id, score). If text is a list, a 2D list
+ of (id, score) is returned with a row per string.
+
+ Args:
+ query: query text|list
+ texts: list of text
+ multilabel: labels are independent if True, scores are normalized to sum to 1 per text item if False, raw scores returned if None
+ workers: number of concurrent workers to use for processing data, defaults to None
+
+ Returns:
+ list of (id, score)
+ """
+
+ scores = []
+ for q in [query] if isinstance(query, str) else query:
+ # Pass (query, text) pairs to model
+ result = self.pipeline([{"text": q, "text_pair": t} for t in texts], top_k=None, function_to_apply="none", num_workers=workers)
+
+ # Apply score transform function
+ scores.append(self.function([r[0]["score"] for r in result], multilabel))
+
+ # Build list of (id, score) per query sorted by highest score
+ 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 function(self, scores, multilabel):
+ """
+ Applys an output transformation function based on value of multilabel.
+
+ Args:
+ scores: input scores
+ multilabel: labels are independent if True, scores are normalized to sum to 1 per text item if False, raw scores returned if None
+
+ Returns:
+ transformed scores
+ """
+
+ # Output functions
+ identity = lambda x: x
+ sigmoid = lambda x: 1.0 / (1.0 + np.exp(-x))
+ softmax = lambda x: np.exp(x) / np.sum(np.exp(x))
+ function = identity if multilabel is None else sigmoid if multilabel else softmax
+
+ # Apply output function
+ return function(np.array(scores))
diff --git a/src/python/txtai/pipeline/text/similarity.py b/src/python/txtai/pipeline/text/similarity.py
index f8f9cb5b..b862b463 100644
--- a/src/python/txtai/pipeline/text/similarity.py
+++ b/src/python/txtai/pipeline/text/similarity.py
@@ -4,6 +4,7 @@ Similarity module
import numpy as np
+from .crossencoder import CrossEncoder
from .labels import Labels
@@ -12,6 +13,12 @@ class Similarity(Labels):
Computes similarity between query and list of text using a text classifier.
"""
+ def __init__(self, path=None, quantize=False, gpu=True, model=None, dynamic=True, crossencode=False):
+ super().__init__(path, quantize, gpu, model, False if crossencode else dynamic)
+
+ # Load as a cross-encoder if crossencode set to True
+ self.crossencoder = CrossEncoder(model=self.pipeline) if crossencode else None
+
# pylint: disable=W0222
def __call__(self, query, texts, multilabel=True):
"""
@@ -25,11 +32,16 @@ class Similarity(Labels):
Args:
query: query text|list
texts: list of text
+ multilabel: labels are independent if True, scores are normalized to sum to 1 per text item if False, raw scores returned if None
Returns:
list of (id, score)
"""
+ if self.crossencoder:
+ # pylint: disable=E1102
+ return self.crossencoder(query, texts, multilabel)
+
# Call Labels pipeline for texts using input query as the candidate label
scores = super().__call__(texts, [query] if isinstance(query, str) else query, multilabel)
diff --git a/test/python/testpipeline/testlabels.py b/test/python/testpipeline/testlabels.py
index cb46599b..aff9458f 100644
--- a/test/python/testpipeline/testlabels.py
+++ b/test/python/testpipeline/testlabels.py
@@ -30,6 +30,24 @@ class TestLabels(unittest.TestCase):
cls.labels = Labels("prajjwal1/bert-medium-mnli")
cls.similarity = Similarity(model=cls.labels)
+ def testCrossEncoder(self):
+ """
+ Test cross-encoder similarity model
+ """
+
+ similarity = Similarity("cross-encoder/ms-marco-MiniLM-L-2-v2", crossencode=True)
+ uid = similarity("Who won the lottery?", self.data)[0][0]
+ self.assertEqual(self.data[uid], self.data[4])
+
+ def testCrossEncoderBatch(self):
+ """
+ Test cross-encoder similarity model with multiple inputs
+ """
+
+ similarity = Similarity("cross-encoder/ms-marco-MiniLM-L-2-v2", crossencode=True)
+ results = [r[0][0] for r in similarity(["Who won the lottery?", "Where did an iceberg collapse?"], self.data)]
+ self.assertEqual(results, [4, 1])
+
def testLabel(self):
"""
Test labels with single text input