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 support for vision models to HF LLM pipeline, closes #884

davidmezzetti186e58a1149d
diff --git a/src/python/txtai/models/models.py b/src/python/txtai/models/models.py
index 5f4ad8ee..beef9aa1 100644
--- a/src/python/txtai/models/models.py
+++ b/src/python/txtai/models/models.py
@@ -14,6 +14,7 @@ from transformers import (
AutoModelForSequenceClassification,
AutoTokenizer,
)
+from transformers.models.auto.modeling_auto import MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES
from .onnx import OnnxModel
@@ -255,7 +256,9 @@ class Models:
if config:
architecture = config.architectures[0] if config.architectures else None
if architecture:
- if any(x for x in ["LMHead", "CausalLM"] if x in architecture):
+ if architecture in MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES.values():
+ task = "vision"
+ elif any(x for x in ["LMHead", "CausalLM"] if x in architecture):
task = "language-generation"
elif "QuestionAnswering" in architecture:
task = "question-answering"
diff --git a/src/python/txtai/pipeline/llm/huggingface.py b/src/python/txtai/pipeline/llm/huggingface.py
index 833903bd..ccead9ab 100644
--- a/src/python/txtai/pipeline/llm/huggingface.py
+++ b/src/python/txtai/pipeline/llm/huggingface.py
@@ -69,42 +69,48 @@ class HFLLM(HFPipeline):
texts = [f"{prefix}{x}" for x in texts]
# Combine all keyword arguments
- kwargs = self.parameters(maxlength, workers, stop, **kwargs)
+ args, kwargs = self.parameters(texts, maxlength, workers, stop, **kwargs)
# Stream response
if stream:
return StreamingResponse(self.pipeline, texts, stop, **kwargs)()
- # Run pipeline
- results = self.pipeline(texts, stop_strings=stop, **kwargs)
-
- # Extract generated text
- results = [self.extract(result) for result in results]
+ # Run pipeline and extract generated text
+ results = [self.extract(result) for result in self.pipeline(*args, **kwargs)]
return results[0] if isinstance(text, str) else results
- def parameters(self, maxlength, workers, stop, **kwargs):
+ def parameters(self, texts, maxlength, workers, stop, **kwargs):
"""
- Builds a combined parameter dictionary.
+ Builds a list of arguments and a combined parameter dictionary to use as keyword arguments.
Args:
+ texts: input texts
maxlength: maximum sequence length
workers: number of concurrent workers to use for processing data, defaults to None
stop: list of stop strings
kwargs: additional generation keyword arguments
Returns:
- dict of parameters
+ args, kwargs
"""
- # Default parameters
- defaults = {
- "max_length": maxlength,
- "num_workers": workers,
- }
+ # Set defaults and get underlying model
+ defaults, model = {"max_length": maxlength, "num_workers": workers}, self.pipeline.model
+
+ # Set parameters for vision models and return
+ if self.pipeline.task == "image-text-to-text":
+ # Maxlength has to be large enough to accomodate images
+ defaults["max_length"] = max(maxlength, 2048)
+
+ # Set default token id
+ tokenid = model.generation_config.pad_token_id
+ model.generation_config.pad_token_id = tokenid if tokenid else model.generation_config.eos_token_id
+
+ # Vision models take all arguments as keyword arguments
+ return [], {**{"text": texts, "truncation": True}, **defaults, **kwargs}
# Add pad token if it's missing from model config
- model = self.pipeline.model
if not model.config.pad_token_id:
tokenid = model.config.eos_token_id
tokenid = tokenid[0] if isinstance(tokenid, list) else tokenid
@@ -121,7 +127,7 @@ class HFLLM(HFPipeline):
if stop:
defaults["tokenizer"] = self.pipeline.tokenizer
- return {**defaults, **kwargs}
+ return [texts], {**defaults, **kwargs}
def extract(self, result):
"""
@@ -153,7 +159,7 @@ class HFLLM(HFPipeline):
"""
# Mapping from txtai to Hugging Face pipeline tasks
- mapping = {"language-generation": "text-generation", "sequence-sequence": "text2text-generation"}
+ mapping = {"language-generation": "text-generation", "sequence-sequence": "text2text-generation", "vision": "image-text-to-text"}
# Attempt to resolve task
if path and not task:
diff --git a/test/python/testapi/testapipipeline.py b/test/python/testapi/testapipipeline.py
index a05b086f..e4d60b0e 100644
--- a/test/python/testapi/testapipipeline.py
+++ b/test/python/testapi/testapipipeline.py
@@ -59,11 +59,17 @@ tabular:
# Text extraction
textractor:
+# Text to speech
+texttospeech:
+
# Transcription
transcription:
# Translation:
translation:
+
+# Enable file uploads
+upload:
"""
@@ -316,6 +322,15 @@ class TestPipeline(unittest.TestCase):
texts = self.client.post("batchtextract", json=[path, path]).json()
self.assertEqual((len(texts[0]), len(texts[1])), (2471, 2471))
+ def testTextToSpeech(self):
+ """
+ Test text to speech
+ """
+
+ # Generate audio and check for WAV signature
+ audio = self.client.get("texttospeech?text=hello&encoding=wav").content
+ self.assertTrue(audio[0:4] == b"RIFF")
+
def testTranscribe(self):
"""
Test transcribe via API
@@ -352,3 +367,13 @@ class TestPipeline(unittest.TestCase):
text = "This is a test translation into Spanish"
translations = self.client.post("batchtranslate", json={"texts": [text, text], "target": "es"}).json()
self.assertEqual(translations, ["Esta es una traducción de prueba al español"] * 2)
+
+ def testUpload(self):
+ """
+ Test file upload
+ """
+
+ path = Utils.PATH + "/article.pdf"
+ with open(path, "rb") as f:
+ path = self.client.post("upload", files={"files": f}).json()[0]
+ self.assertTrue(os.path.exists(path))
diff --git a/test/python/testpipeline/testllm/testllm.py b/test/python/testpipeline/testllm/testllm.py
index 7c07e200..d6da25db 100644
--- a/test/python/testpipeline/testllm/testllm.py
+++ b/test/python/testpipeline/testllm/testllm.py
@@ -10,6 +10,9 @@ from transformers import AutoModelForCausalLM, AutoTokenizer
from txtai.pipeline import LLM, Generation
+# pylint: disable = C0411
+from utils import Utils
+
class TestLLM(unittest.TestCase):
"""
@@ -107,3 +110,15 @@ class TestLLM(unittest.TestCase):
model = LLM("sshleifer/tiny-gpt2")
self.assertIsInstance(" ".join(x for x in model("Hello, how are", stream=True)), str)
+
+ def testVision(self):
+ """
+ Test vision LLM
+ """
+
+ model = LLM("hf-internal-testing/tiny-random-Qwen2VLForConditionalGeneration")
+ result = model(
+ [{"role": "user", "content": [{"type": "text", "text": "What is in this image?"}, {"type": "image", "image": Utils.PATH + "/books.jpg"}]}]
+ )
+
+ self.assertIsNotNone(result)