💡 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 custom Questions pipeline implementation, closes #1087
davidmezzetti676b997f57e6
diff --git a/src/python/txtai/pipeline/text/questions.py b/src/python/txtai/pipeline/text/questions.pyindex 9f813ea1..4e785735 100644--- a/src/python/txtai/pipeline/text/questions.py+++ b/src/python/txtai/pipeline/text/questions.py@@ -2,25 +2,35 @@Questions module"""-from ..hfpipeline import HFPipeline+import torch+import torch.nn.functional as F+from ..hfmodel import HFModel-class Questions(HFPipeline):++class Questions(HFModel):"""Runs extractive QA for a series of questions and contexts."""- def __init__(self, path=None, quantize=False, gpu=True, model=None, **kwargs):- super().__init__("question-answering", path, quantize, gpu, model, **kwargs)+ def __init__(self, path=None, quantize=False, gpu=True, batch=64, **kwargs):+ # Default model+ path = path if path else "distilbert-base-cased-distilled-squad"++ # Call parent constructor+ super().__init__(path, quantize, gpu, batch)- def __call__(self, questions, contexts, workers=0):+ # Load model and tokenizer+ self.model, self.tokenizer = self.load(path, "question-answering", **kwargs)++ def __call__(self, questions, contexts, **kwargs):"""Runs a extractive question-answering model against each question-context pair, finding the best answers.Args:questions: list of questionscontexts: list of contexts to pull answers from- workers: number of concurrent workers to use for processing data, defaults to None+ kwargs: additional keyword argumentsReturns:list of answers@@ -30,11 +40,25 @@ class Questions(HFPipeline):for x, question in enumerate(questions):if question and contexts[x]:- # Run the QA pipeline- result = self.pipeline(question=question, context=contexts[x], num_workers=workers)+ # Tokenize inputs+ tokens = self.tokenizer(question, contexts[x], truncation="only_second", return_tensors="pt").to(self.device)++ # Generate outputs+ with torch.no_grad():+ outputs = self.model(**tokens)- # Get answer and score- answer, score = result["answer"], result["score"]+ # Unpack results+ startlogits, endlogits = (outputs.start_logits, outputs.end_logits) if hasattr(outputs, "start_logits") else outputs++ # Get best span as answer+ start = startlogits.argmax()+ end = endlogits.argmax()+ answer = self.answer(contexts[x], tokens, start, end)++ # Calculate span score+ startprob = F.softmax(startlogits, dim=-1)[0]+ endprob = F.softmax(endlogits, dim=-1)[0]+ score = startprob[start] * endprob[end]# Require score to be at least 0.05if score < 0.05:@@ -46,3 +70,24 @@ class Questions(HFPipeline):answers.append(None)return answers++ def answer(self, context, tokens, start, end):+ """+ Extracts an answer snippet from context.++ Args:+ context: context+ tokens: tokenized inputs+ start: start index of answer+ end: end index of answer++ Returns:+ answer+ """++ startword = tokens.token_to_word(start)+ endword = tokens.token_to_word(end)+ startindex = tokens.word_to_chars(startword, sequence_index=1)[0]+ endindex = tokens.word_to_chars(endword, sequence_index=1)[1]++ return context[startindex:endindex]diff --git a/test/python/testpipeline/testimage/testcaption.py b/test/python/testpipeline/testimage/testcaption.pyindex 6bf1bd06..02241b9a 100644--- a/test/python/testpipeline/testimage/testcaption.py+++ b/test/python/testpipeline/testimage/testcaption.py@@ -6,6 +6,7 @@ import unittestfrom PIL import Image+from transformers import AutoModelForImageTextToText, AutoImageProcessor, AutoTokenizerfrom txtai.pipeline import Caption# pylint: disable=C0411@@ -24,3 +25,12 @@ class TestCaption(unittest.TestCase):caption = Caption()self.assertEqual(caption(Image.open(Utils.PATH + "/books.jpg")), "a book shelf filled with books and a stack of books")++ # Load passing models directly+ path = "ydshieh/vit-gpt2-coco-en"+ model = AutoModelForImageTextToText.from_pretrained(path)+ tokenizer = AutoTokenizer.from_pretrained(path)+ processor = AutoImageProcessor.from_pretrained(path)++ caption = Caption((model, tokenizer, processor))+ self.assertEqual(caption(Image.open(Utils.PATH + "/books.jpg")), "a book shelf filled with books and a stack of books")