💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows
Python agentsaiai-agentsembeddingsinformation-retrievallanguage-modellarge-language-modelsllmnlppythonragretrieval-augmented-generationsearchsearch-enginesemantic-searchsentence-embeddingstransformerstxtaivector-databasevector-search
Merge pull request #1195 from St4r4x/fix/crossencoder-multiclass-labels
Arnaud Theryadbcccda46a8
diff --git a/src/python/txtai/pipeline/text/crossencoder.py b/src/python/txtai/pipeline/text/crossencoder.pyindex 3a80278b..7fc9b0e9 100644--- a/src/python/txtai/pipeline/text/crossencoder.py+++ b/src/python/txtai/pipeline/text/crossencoder.py@@ -2,23 +2,24 @@CrossEncoder module"""-from ..hfpipeline import HFPipeline-# Core library importsfrom ...util import Library+from .labels import Labels+np = Library().numpy()-class CrossEncoder(HFPipeline):+class CrossEncoder(Labels):"""Computes similarity between query and list of text using a cross-encoder model"""def __init__(self, path=None, quantize=False, gpu=True, model=None, **kwargs):- super().__init__("text-classification", path, quantize, gpu, model, **kwargs)+ super().__init__(path, quantize, gpu, model, False, **kwargs)- def __call__(self, query, texts, multilabel=True, workers=0):+ # pylint: disable=W0222+ def __call__(self, query, texts, multilabel=True, workers=0, labels=None):"""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.@@ -32,6 +33,10 @@ class CrossEncoder(HFPipeline):texts: list of textmultilabel: labels are independent if True, scores are normalized to sum to 1 per text item if False, raw scores returned if Noneworkers: number of concurrent workers to use for processing data, defaults to None+ labels: optional list of labels to score by, resolved by name/id via the model config the same way+ Labels.limit() does. Restricts ranking to a fixed label so multi-class models (e.g. NLI+ cross-encoders) compare every candidate on the same class, instead of whichever one each+ candidate happened to score highest on. Defaults to that original top-scored label when None.Returns:list of (id, score)@@ -43,13 +48,31 @@ class CrossEncoder(HFPipeline):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))+ scores.append(self.function([self.score(r, labels) for r in result], multilabel))# Build list of (id, score) per query sorted by highest scorescores = [sorted(enumerate(row), key=lambda x: x[1], reverse=True) for row in scores]return scores[0] if isinstance(query, str) else scores+ def score(self, result, labels):+ """+ Resolves the score to use for a single (query, text) pair.++ Args:+ result: pipeline result for a single (query, text) pair, sorted by score descending+ labels: list of labels to restrict scoring to, or None to keep the top-scored label++ Returns:+ score+ """++ matches = self.limit(result, labels)+ if labels and not matches:+ raise ValueError(f"None of the requested labels {labels} matched model labels {list(self.pipeline.model.config.label2id.keys())}")++ return matches[0][1]+def function(self, scores, multilabel):"""Applys an output transformation function based on value of multilabel.diff --git a/src/python/txtai/pipeline/text/similarity.py b/src/python/txtai/pipeline/text/similarity.pyindex d1f815a7..0dd1566c 100644--- a/src/python/txtai/pipeline/text/similarity.py+++ b/src/python/txtai/pipeline/text/similarity.py@@ -31,7 +31,7 @@ class Similarity(Labels):self.crossencoder = CrossEncoder(model=self.pipeline) if crossencode else None# pylint: disable=W0222- def __call__(self, query, texts, multilabel=True, **kwargs):+ def __call__(self, query, texts, multilabel=True, labels=None, **kwargs):"""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.@@ -44,6 +44,8 @@ class Similarity(Labels):query: query text|listtexts: list of textmultilabel: labels are independent if True, scores are normalized to sum to 1 per text item if False, raw scores returned if None+ labels: optional list of labels to score by, only used with a cross-encoder model (crossencode=True) -+ see CrossEncoder.__call__. Ignored otherwise.kwargs: additional keyword argsReturns:@@ -52,7 +54,7 @@ class Similarity(Labels):if self.crossencoder:# pylint: disable=E1102- return self.crossencoder(query, texts, multilabel)+ return self.crossencoder(query, texts, multilabel, labels=labels)if self.lateencoder:return self.lateencoder(query, texts)diff --git a/test/python/testpipeline/testtext/testsimilarity.py b/test/python/testpipeline/testtext/testsimilarity.pyindex 145d5f09..b23ead0a 100644--- a/test/python/testpipeline/testtext/testsimilarity.py+++ b/test/python/testpipeline/testtext/testsimilarity.py@@ -47,6 +47,37 @@ class TestSimilarity(unittest.TestCase):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 testCrossEncoderLabels(self):+ """+ Test cross-encoder ranking with a multi-class model, restricted to a single label via labels+ """++ similarity = Similarity("prajjwal1/bert-medium-mnli", crossencode=True)++ premise = "A dog is running in the park."+ entailment = "An animal is outside."+ contradiction = "The park is empty and there are no animals."++ # Without labels, each candidate is scored by whichever label it individually scored highest+ # on - here the contradiction's own top score outscores the entailment's own top score, so+ # the less relevant candidate wins+ uid = similarity(premise, [entailment, contradiction])[0][0]+ self.assertEqual(uid, 1)++ # Restricting to a single label (LABEL_1 = entailment for this model) compares every+ # candidate on that same label instead, fixing the ranking+ uid = similarity(premise, [entailment, contradiction], labels=["1"])[0][0]+ self.assertEqual(uid, 0)++ def testCrossEncoderLabelsInvalid(self):+ """+ Test cross-encoder raises an error when no requested label matches the model+ """++ similarity = Similarity("prajjwal1/bert-medium-mnli", crossencode=True)+ with self.assertRaises(ValueError):+ similarity("A dog is running in the park.", ["An animal is outside."], labels=["not-a-real-label"])+def testLateEncoder(self):"""Test late-encoder similarity model