💡 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
Add support for fixed label models, closes #95
davidmezzetti2a50557df18d
diff --git a/docs/pipelines/labels.md b/docs/pipelines/labels.mdindex f80bd37d..402d3fdd 100644--- a/docs/pipelines/labels.md+++ b/docs/pipelines/labels.md@@ -1,12 +1,18 @@# Labels-A Labels pipeline uses a zero shot classification model to apply labels to input text.+A Labels pipeline uses a text classification model to apply labels to input text. This pipeline can classify text using either a zero shot model (dynamic labeling) or a standard text classification model (fixed labeling).Labels parameters are set as constructor arguments. Examples below.```python+# Default configurationLabels()++# Custom model with zero shot classificationLabels("roberta-large-mnli")++# Model with fixed labels+Labels(dynamic=False)```::: txtai.pipeline.Labels.__init__diff --git a/src/python/txtai/pipeline/labels.py b/src/python/txtai/pipeline/labels.pyindex 79dc6180..bebc4cf0 100644--- a/src/python/txtai/pipeline/labels.py+++ b/src/python/txtai/pipeline/labels.py@@ -2,21 +2,27 @@Labels module"""+import numpy as np+from .hfpipeline import HFPipelineclass Labels(HFPipeline):"""- Applies a zero shot classifier to text using a list of labels.+ Applies a text classifier to text. Supports zero shot and standard text classification models"""- def __init__(self, path=None, quantize=False, gpu=True, model=None):- super().__init__("zero-shot-classification", path, quantize, gpu, model)+ def __init__(self, path=None, quantize=False, gpu=True, model=None, dynamic=True):+ super().__init__("zero-shot-classification" if dynamic else "text-classification", path, quantize, gpu, model)++ # Set if labels are dynamic (zero shot) or fixed (standard text classification)+ self.dynamic = dynamic- def __call__(self, text, labels, multilabel=False):+ def __call__(self, text, labels=None, multilabel=False):"""- Applies a zero shot classifier to text using a list of labels. Returns a list of- (id, score) sorted by highest score, where id is the index in labels.+ Applies a text classifier to text. Returns a list of (id, score) sorted by highest score,+ where id is the index in labels. For zero shot classification, a list of labels is required,+ otherwise the labels indices are taken from the trained text classification model.This method supports text as a string or a list. If the input is a string, the returntype is a 1D list of (id, score). If text is a list, a 2D list of (id, score) is@@ -24,14 +30,19 @@ class Labels(HFPipeline):Args:text: text|list- labels: list of labels+ labels: list of labels (zero shot classification only)+ multilabel: labels are independent if True, otherwise scores are normalized to sum to 1 per text itemReturns:list of (id, score)"""- # Run ZSL pipeline- results = self.pipeline(text, labels, multi_label=multilabel, truncation=True)+ if self.dynamic:+ # Run zero shot classification pipeline+ results = self.pipeline(text, labels, multi_label=multilabel, truncation=True)+ else:+ # Run text classification pipeline+ results = self.textclassify(text, multilabel)# Convert results to a list if necessaryif not isinstance(results, list):@@ -40,6 +51,46 @@ class Labels(HFPipeline):# Build list of (id, score)scores = []for result in results:- scores.append([(labels.index(label), result["scores"][x]) for x, label in enumerate(result["labels"])])+ if self.dynamic:+ scores.append([(labels.index(label), result["scores"][x]) for x, label in enumerate(result["labels"])])+ else:+ scores.append(sorted(enumerate(result), key=lambda x: x[1], reverse=True))return scores[0] if isinstance(text, str) else scores++ def textclassify(self, text, multilabel):+ """+ Wrapper of the text-classification pipeline to be more flexible with the logits transformation+ function. While these methods are in later versions of Hugging Face Transformers, this method supports+ older versions.++ Args:+ text: text|list+ multilabel: labels are independent if True, otherwise scores are normalized to sum to 1 per text item++ Returns:+ list of scores for each label in model+ """++ # pylint: disable=W0212+ inputs = self.pipeline._parse_and_tokenize(text, truncation=True)+ outputs = self.pipeline._forward(inputs)++ # Apply sigmoid to outputs+ if multilabel or len(self.labels()) == 1:+ return (1.0 / (1.0 + np.exp(-outputs))).tolist()++ # Apply softmax to outputs+ maxes = np.max(outputs, axis=-1, keepdims=True)+ shift = np.exp(outputs - maxes)+ return (shift / shift.sum(axis=-1, keepdims=True)).tolist()++ def labels(self):+ """+ Returns a list of all text classification model labels sorted in index order.++ Returns:+ list of labels+ """++ return list(self.pipeline.model.config.id2label.values())diff --git a/src/python/txtai/pipeline/similarity.py b/src/python/txtai/pipeline/similarity.pyindex 3140fead..f8f9cb5b 100644--- a/src/python/txtai/pipeline/similarity.py+++ b/src/python/txtai/pipeline/similarity.py@@ -9,9 +9,10 @@ from .labels import Labelsclass Similarity(Labels):"""- Computes similarity between query and list of text using a zero shot classifier.+ Computes similarity between query and list of text using a text classifier."""+ # pylint: disable=W0222def __call__(self, query, texts, multilabel=True):"""Computes the similarity between query and list of text. Returns a list ofdiff --git a/test/python/testlabels.py b/test/python/testlabels.pyindex b7683f91..62cb5cc1 100644--- a/test/python/testlabels.py+++ b/test/python/testlabels.py@@ -45,6 +45,19 @@ class TestLabels(unittest.TestCase):results = [l[0][0] for l in self.labels(["This is the best sentence ever", "This is terrible"], ["positive", "negative"])]self.assertEqual(results, [0, 1])+ def testLabelFixed(self):+ """+ Test labels with a fixed label text classification model+ """++ labels = Labels(dynamic=False)++ # Get index of "POSITIVE" label+ index = labels.labels().index("POSITIVE")++ # Run comparison+ self.assertEqual(labels("This is the best sentence ever")[0][0], index)+def testSimilarity(self):"""Test similarity with single query