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 custom Summary pipeline implementation, closes #1085

davidmezzetti688734136c5f
diff --git a/src/python/txtai/pipeline/hfmodel.py b/src/python/txtai/pipeline/hfmodel.py
index 04444e87..71f8b7dd 100644
--- a/src/python/txtai/pipeline/hfmodel.py
+++ b/src/python/txtai/pipeline/hfmodel.py
@@ -2,6 +2,8 @@
Hugging Face Transformers model wrapper module
"""
+from transformers import AutoTokenizer
+
from ..models import Models
from .tensors import Tensors
@@ -36,6 +38,30 @@ class HFModel(Tensors):
# Process batch size
self.batchsize = batch
+ def load(self, path, task, **kwargs):
+ """
+ Loads a HuggingFace model and tokenizer.
+
+ Args:
+ path: model path
+ task: model task
+ kwargs: additional keyword args
+ """
+
+ # Unpack path
+ if isinstance(path, tuple):
+ model, tokenizer = path
+ else:
+ model, tokenizer = path, path
+
+ # Load model
+ model = Models.load(model, task=task, modelargs=kwargs).to(self.device)
+
+ # Load tokenizer
+ tokenizer = AutoTokenizer.from_pretrained(tokenizer) if isinstance(tokenizer, str) else tokenizer
+
+ return model, tokenizer
+
def prepare(self, model):
"""
Prepares a model for processing. Applies dynamic quantization if necessary.
diff --git a/src/python/txtai/pipeline/hfpipeline.py b/src/python/txtai/pipeline/hfpipeline.py
index 2e12d59a..64d2b461 100644
--- a/src/python/txtai/pipeline/hfpipeline.py
+++ b/src/python/txtai/pipeline/hfpipeline.py
@@ -84,13 +84,3 @@ class HFPipeline(Tensors):
# Split into modelargs and kwargs
return ({arg: value for arg, value in kwargs.items() if arg not in args}, {arg: value for arg, value in kwargs.items() if arg in args})
-
- def maxlength(self):
- """
- Gets the max length to use for generate calls.
-
- Returns:
- max length
- """
-
- return Models.maxlength(self.pipeline.model, self.pipeline.tokenizer)
diff --git a/src/python/txtai/pipeline/text/summary.py b/src/python/txtai/pipeline/text/summary.py
index 3901108a..bf7ba2f2 100644
--- a/src/python/txtai/pipeline/text/summary.py
+++ b/src/python/txtai/pipeline/text/summary.py
@@ -4,18 +4,26 @@ Summary module
import re
-from ..hfpipeline import HFPipeline
+from ...models import Models
+from ..hfmodel import HFModel
-class Summary(HFPipeline):
+class Summary(HFModel):
"""
Summarizes text.
"""
- def __init__(self, path=None, quantize=False, gpu=True, model=None, **kwargs):
- super().__init__("summarization", path, quantize, gpu, model, **kwargs)
+ def __init__(self, path=None, quantize=False, gpu=True, batch=64, **kwargs):
+ # Default model
+ path = path if path else "sshleifer/distilbart-cnn-12-6"
- def __call__(self, text, minlength=None, maxlength=None, workers=0):
+ # Call parent constructor
+ super().__init__(path, quantize, gpu, batch)
+
+ # Load model and tokenizer
+ self.model, self.tokenizer = self.load(path, "summarization", **kwargs)
+
+ def __call__(self, text, minlength=None, maxlength=None, **kwargs):
"""
Runs a summarization model against a block of text.
@@ -26,7 +34,7 @@ class Summary(HFPipeline):
text: text|list
minlength: minimum length for summary
maxlength: maximum length for summary
- workers: number of concurrent workers to use for processing data, defaults to None
+ kwargs: additional keyword arguments
Returns:
summary text
@@ -44,11 +52,11 @@ class Summary(HFPipeline):
inputs = [text for _, text in params if text]
if inputs:
- # Run summarization pipeline
- results = self.pipeline(inputs, num_workers=workers, **kwargs)
+ # Run summarization
+ results = self.generate(inputs, **kwargs)
# Pull out summary text
- results = iter([self.clean(x["summary_text"]) for x in results])
+ results = iter([self.clean(x) for x in results])
results = [next(results) if text else texts[x] for x, text in params]
else:
# Return original
@@ -56,6 +64,42 @@ class Summary(HFPipeline):
return results[0] if isinstance(text, str) else results
+ def maxlength(self):
+ """
+ Gets the max length to use for generate calls.
+
+ Returns:
+ max length
+ """
+
+ return Models.maxlength(self.model, self.tokenizer)
+
+ def generate(self, inputs, **kwargs):
+ """
+ Generates outputs.
+
+ Args:
+ input: tokenized input
+ kwargs: additional keyword arguments
+
+ Returns:
+ generated output
+ """
+
+ # Prepend prefix, if necessary
+ prefix = kwargs.pop("prefix", None)
+ if prefix:
+ inputs = [prefix + x for x in inputs]
+
+ # Tokenize inputs
+ tokens = self.tokenizer(inputs, truncation=kwargs.pop("truncation", False), return_tensors="pt").to(self.device)
+
+ # Generate outputs
+ outputs = self.model.generate(**tokens, **kwargs)
+
+ # Decode and return
+ return [self.tokenizer.decode(x, skip_special_tokens=True) for x in outputs]
+
def clean(self, text):
"""
Applies a series of rules to clean extracted text.
@@ -84,7 +128,17 @@ class Summary(HFPipeline):
keyword arguments
"""
- kwargs = {"truncation": True}
+ # Defaults
+ kwargs = {"truncation": True, "num_beams": 4, "max_new_tokens": 256}
+
+ # Get default summary task parameters
+ params = getattr(self.model.config, "task_specific_params", None)
+ if params:
+ params = params.get("summarization", {})
+
+ # Ignore max length
+ kwargs.update({k: v for k, v in params.items() if k not in ["max_length"]})
+
if minlength:
kwargs["min_length"] = minlength
if maxlength: