💡 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
Score cross-encoder labels by class probability instead of raw logit (#1436)
digit504e61cd282d1f
diff --git a/src/python/txtai/pipeline/text/crossencoder.py b/src/python/txtai/pipeline/text/crossencoder.pyindex 7fc9b0e9..108cbdb7 100644--- a/src/python/txtai/pipeline/text/crossencoder.py+++ b/src/python/txtai/pipeline/text/crossencoder.py@@ -36,7 +36,8 @@ class CrossEncoder(Labels):labels: optional list of labels to score by, resolved by name/id via the model config the same wayLabels.limit() does. Restricts ranking to a fixed label so multi-class models (e.g. NLIcross-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.+ candidate happened to score highest on. Each candidate is scored by that label's probability+ over the model's classes. Defaults to that original top-scored label when None.Returns:list of (id, score)@@ -71,7 +72,13 @@ class CrossEncoder(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]+ score = matches[0][1]++ # Score a requested label of a multi-class model by its probability over the classes of the pair+ if labels and len(result) > 1:+ score = np.exp(score) / np.sum(np.exp([x["score"] for x in result]))++ return scoredef function(self, scores, multilabel):"""diff --git a/test/python/testpipeline/testtext/testsimilarity.py b/test/python/testpipeline/testtext/testsimilarity.pyindex 8a38e536..963e19e4 100644--- a/test/python/testpipeline/testtext/testsimilarity.py+++ b/test/python/testpipeline/testtext/testsimilarity.py@@ -69,6 +69,25 @@ class TestSimilarity(unittest.TestCase):uid = similarity(premise, [entailment, contradiction], labels=["1"])[0][0]self.assertEqual(uid, 0)+ def testCrossEncoderProbability(self):+ """+ Test cross-encoder labels rank candidates by the requested label's probability, not its raw logit+ """++ similarity = Similarity("prajjwal1/bert-medium-mnli", crossencode=True)++ premise = "A dog is running in the park."+ texts = ["The dog is chasing a ball in the park.", "It is raining.", "Nobody is running."]++ # "Nobody is running." has the highest entailment logit but the lowest entailment probability+ for multilabel in [True, None, False]:+ result = similarity(premise, texts, multilabel=multilabel, labels=["1"])+ self.assertEqual([uid for uid, _ in result], [0, 1, 2])++ # Raw scores are the entailment probabilities+ result = similarity(premise, texts, multilabel=None, labels=["1"])+ self.assertAlmostEqual(result[0][1], 0.052, places=3)+def testCrossEncoderLabelsOrder(self):"""Test cross-encoder labels resolve to label ids when the model config's label order differs from id order