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 similarity pipeline, closes #49

davidmezzetti4d502670a064
diff --git a/src/python/txtai/api.py b/src/python/txtai/api.py
index 958e1842..da54f89d 100644
--- a/src/python/txtai/api.py
+++ b/src/python/txtai/api.py
@@ -12,7 +12,7 @@ from fastapi import Body, FastAPI, Request
from .embeddings import Embeddings
from .extractor import Extractor
-from .pipeline import Labels
+from .pipeline import Labels, Similarity
# API instance
app = FastAPI()
@@ -34,7 +34,8 @@ class API(object):
"""
# Initialize member variables
- self.config, self.documents, self.embeddings, self.extractor, self.labels = config, None, None, None, None
+ self.config, self.documents = config, None
+ self.embeddings, self.extractor, self.labels, self.similar = None, None, None, None
# Create/load embeddings index depending on writable flag
if self.config.get("writable"):
@@ -46,17 +47,27 @@ class API(object):
# Create extractor instance
if "extractor" in self.config:
# Extractor settings
- extractor = self.config["extractor"]
+ extractor = self.config["extractor"] if self.config["extractor"] else {}
self.extractor = Extractor(self.embeddings, extractor.get("path"), extractor.get("quantize"),
extractor.get("gpu"))
# Create labels instance
if "labels" in self.config:
- labels = self.config["labels"]
+ labels = self.config["labels"] if self.config["labels"] else {}
self.labels = Labels(labels.get("path"), labels.get("quantize"), labels.get("gpu"))
+ # Creates similarity instance
+ if "similarity" in self.config:
+ similarity = self.config["similarity"] if self.config["similarity"] else {}
+
+ # Share model with labels if separate model not specified
+ if "path" not in similarity and self.labels:
+ self.similar = Similarity(model=self.labels)
+ else:
+ self.similar = Similarity(similarity.get("path"), similarity.get("quantize"), similarity.get("gpu"))
+
def size(self, request):
"""
Parses the number of results to return from the request. Allows range of 1-250, with a default of 10.
@@ -138,6 +149,9 @@ class API(object):
list of similarity scores
"""
+ # Use similarity instance if available otherwise fall back to embeddings model
+ if self.similar:
+ return [float(x) for x in self.similar(search, data)]
if self.embeddings:
return [float(x) for x in self.embeddings.similarity(search, data)]
diff --git a/src/python/txtai/pipeline.py b/src/python/txtai/pipeline.py
index d57d677a..8527d415 100644
--- a/src/python/txtai/pipeline.py
+++ b/src/python/txtai/pipeline.py
@@ -12,7 +12,7 @@ class Pipeline(object):
quantization and minor interface changes.
"""
- def __init__(self, task, path=None, quantize=False, gpu=False):
+ def __init__(self, task, path=None, quantize=False, gpu=False, model=None):
"""
Loads a new pipeline model.
@@ -22,26 +22,31 @@ class Pipeline(object):
uses default model for task if not provided
quantize: if model should be quantized, defaults to False
gpu: if gpu inference should be used (only works if GPUs are available)
+ model: optional existing pipeline model to wrap
"""
- # Enable GPU inference if explicitly set and a GPU is available
- gpu = gpu and torch.cuda.is_available()
+ if model:
+ # Check if input model is a Pipeline or a HF pipeline
+ self.pipeline = model.pipeline if isinstance(model, Pipeline) else model
+ else:
+ # Enable GPU inference if explicitly set and a GPU is available
+ gpu = gpu and torch.cuda.is_available()
- # Transformer pipeline task
- self.pipeline = pipeline(task, model=path, tokenizer=path, device=0 if gpu else -1)
+ # Transformer pipeline task
+ self.pipeline = pipeline(task, model=path, tokenizer=path, device=0 if gpu else -1)
- # Model quantization. Compresses model to int8 precision, improves runtime performance. Only supported on CPU.
- if not gpu and quantize:
- # pylint: disable=E1101
- self.pipeline.model = torch.quantization.quantize_dynamic(self.pipeline.model, {torch.nn.Linear}, dtype=torch.qint8)
+ # Model quantization. Compresses model to int8 precision, improves runtime performance. Only supported on CPU.
+ if not gpu and quantize:
+ # pylint: disable=E1101
+ self.pipeline.model = torch.quantization.quantize_dynamic(self.pipeline.model, {torch.nn.Linear}, dtype=torch.qint8)
class Questions(Pipeline):
"""
Runs extractive QA for a series of questions and contexts.
"""
- def __init__(self, path=None, quantize=False, gpu=False):
- super().__init__("question-answering", path, quantize, gpu)
+ def __init__(self, path=None, quantize=False, gpu=False, model=None):
+ super().__init__("question-answering", path, quantize, gpu, model)
def __call__(self, questions, contexts):
"""
@@ -81,20 +86,52 @@ class Labels(Pipeline):
Applies labels to text sections using a zero shot classifier.
"""
- def __init__(self, path=None, quantize=False, gpu=True):
- super().__init__("zero-shot-classification", path, quantize, gpu)
+ def __init__(self, path=None, quantize=False, gpu=True, model=None):
+ super().__init__("zero-shot-classification", path, quantize, gpu, model)
def __call__(self, section, labels):
"""
Applies a zero shot classifier to a text section using a list of labels.
Args:
- section: text section
+ section: text|list
labels: list of labels
Returns:
- list of (label, score) for section
+ list of (label, score) for each text section
"""
- result = self.pipeline(section, labels)
- return list(zip(result["labels"], result["scores"]))
+ # Run pipeline
+ results = self.pipeline(section, labels)
+
+ # Pipeline returns a dict for single element inputs
+ if not isinstance(results, list):
+ return list(zip(results["labels"], results["scores"]))
+
+ return [list(zip(result["labels"], result["scores"])) for result in results]
+
+class Similarity(Labels):
+ """
+ Computes similarity between a query and a set of documents using a zero shot classifier.
+ """
+
+ def __call__(self, query, documents):
+ """
+ Computes the similarity between a query and a set of documents
+
+ Args:
+ query: query text
+ documents: document text
+
+ Returns:
+ [computed similarity (0 - 1 with 1 being most similar)]
+ """
+
+ # Call Labels pipeline for documents using input query as the candidate label
+ results = super().__call__(documents, [query])
+
+ # Convert results to a list when documents only has a single input
+ if not isinstance(results[0], list):
+ results = [results]
+
+ return [r[0][1] for r in results]
diff --git a/test/python/testapi.py b/test/python/testapi.py
index 97f13062..bc0bd2b0 100644
--- a/test/python/testapi.py
+++ b/test/python/testapi.py
@@ -33,7 +33,10 @@ extractor:
# Labels settings
labels:
- path: squeezebert/squeezebert-mnli
+ path: prajjwal1/bert-medium-mnli
+
+# Enable pipeline similarity backed by zero shot classifier
+similarity:
"""
# Configuration that reads an existing similarity search index
@@ -79,33 +82,33 @@ class TestAPI(unittest.TestCase):
cls.client = TestAPI.start(True)
+ 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 testEmbeddings(self):
"""
Test embeddings via API
"""
- 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"]
-
# Test similarity
uid = np.argmax(self.client.post("similarity", json={
"search": "feel good story",
- "data": data
+ "data": self.data
}).json())
- self.assertEqual(data[uid], data[4])
+ self.assertEqual(self.data[uid], self.data[4])
# Test indexing
- self.client.post("add", json=[{"id": x, "text": row} for x, row in enumerate(data)])
+ self.client.post("add", json=[{"id": x, "text": row} for x, row in enumerate(self.data)])
self.client.get("index")
# Test search
uid = self.client.get("search?q=feel%20good%20story&n=1").json()[0][0]
- self.assertEqual(data[uid], data[4])
+ self.assertEqual(self.data[uid], self.data[4])
# Test embeddings
self.assertIsNotNone(self.client.get("embeddings?t=testembed").json())
@@ -187,3 +190,11 @@ class TestAPI(unittest.TestCase):
# Test search
uid = self.client.get("search?q=feel%20good%20story&n=1").json()[0][0]
self.assertEqual(uid, 4)
+
+ # Test similarity
+ uid = np.argmax(self.client.post("similarity", json={
+ "search": "feel good story",
+ "data": self.data
+ }).json())
+
+ self.assertEqual(uid, 4)
diff --git a/test/python/testextractor.py b/test/python/testextractor.py
index 175c61ac..b6d7a761 100644
--- a/test/python/testextractor.py
+++ b/test/python/testextractor.py
@@ -92,3 +92,10 @@ class TestExtractor(unittest.TestCase):
answers = self.extractor(self.sections, [(question, question, question, True)])
self.assertTrue(answers[0][1].startswith("Giants hit 3 HRs"))
+
+ def testSnippetEmpty(self):
+ """
+ Test snippet method can handle empty parameters
+ """
+
+ self.assertEqual(self.extractor.snippet(None, None), None)
diff --git a/test/python/testlabels.py b/test/python/testlabels.py
index d5f15155..76664fc0 100644
--- a/test/python/testlabels.py
+++ b/test/python/testlabels.py
@@ -4,17 +4,46 @@ Labels module tests
import unittest
-from txtai.pipeline import Labels
+import numpy as np
+
+from txtai.pipeline import Labels, Similarity
class TestLabels(unittest.TestCase):
"""
Labels tests
"""
+ @classmethod
+ def setUpClass(cls):
+ """
+ Create single labels instance
+ """
+
+ cls.labels = Labels("prajjwal1/bert-medium-mnli")
+
def testLabel(self):
"""
Test labels
"""
- labels = Labels("squeezebert/squeezebert-mnli")
- self.assertEqual(labels("This is the best sentence ever", ["positive", "negative"])[0][0], "positive")
+ self.assertEqual(self.labels("This is the best sentence ever", ["positive", "negative"])[0][0], "positive")
+
+ def testSimilarity(self):
+ """
+ Test similarity
+ """
+
+ similarity = Similarity(model=self.labels)
+
+ 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"]
+
+ uid = np.argmax(similarity("feel good story", data))
+ self.assertEqual(data[uid], data[4])
+
+ uid = np.argmax(similarity("feel good story", data[4]))
+ self.assertEqual(uid, 0)