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 pipeline model for generic HF models and tensor backed frameworks #70. Add support for GPU device id #64.

davidmezzetti4e089125073d
diff --git a/src/python/txtai/pipeline/hfmodel.py b/src/python/txtai/pipeline/hfmodel.py
new file mode 100644
index 00000000..50f01d31
--- /dev/null
+++ b/src/python/txtai/pipeline/hfmodel.py
@@ -0,0 +1,117 @@
+"""
+Hugging Face model wrapper module
+"""
+
+from .tensors import Tensors
+
+
+class HFModel(Tensors):
+ """
+ Pipeline backed by a Hugging Face model.
+ """
+
+ def __init__(self, path=None, quantize=False, gpu=False, batch=64):
+ """
+ Creates a new HFModel.
+
+ Args:
+ path: optional path to model, accepts Hugging Face model hub id or local path,
+ uses default model for task if not provided
+ quantize: if model should be quantized, defaults to False
+ gpu: True/False if GPU should be enabled, also supports a GPU device id
+ batch: batch size used to incrementally process content
+ """
+
+ # Default model path
+ self.path = path
+
+ # Quantization flag
+ self.quantization = quantize
+
+ # Get tensor device reference
+ self.deviceid = self.deviceid(gpu)
+ self.device = self.reference(self.deviceid)
+
+ # Process batch size
+ self.batchsize = batch
+
+ def prepare(self, model):
+ """
+ Prepares a model for processing. Applies dynamice quantization if necessary.
+
+ Args:
+ model: input model
+
+ Returns:
+ model
+ """
+
+ if self.deviceid == -1 and self.quantization:
+ model = self.quantize(model)
+
+ return model
+
+ def tokenize(self, tokenizer, texts):
+ """
+ Tokenizes text using tokenizer. This method handles overflowing tokens and automatically splits
+ them into separate elements. Indices of each element is returned to allow reconstructing the
+ transformed elements after running through the model.
+
+ Args:
+ tokenizer: Tokenizer
+ texts: list of text
+
+ Returns:
+ (tokenization result, indices)
+ """
+
+ # Run tokenizer
+ tokens = tokenizer(texts, padding=True)
+
+ inputids, attention, indices = [], [], []
+ for x, ids in enumerate(tokens["input_ids"]):
+ if len(ids) > tokenizer.model_max_length:
+ # Remove padding characters, if any
+ ids = [i for i in ids if i != tokenizer.pad_token_id]
+
+ # Split into model_max_length chunks
+ for chunk in self.batch(ids, tokenizer.model_max_length - 1):
+ # Append EOS token if necessary
+ if chunk[-1] != tokenizer.eos_token_id:
+ chunk.append(tokenizer.eos_token_id)
+
+ # Set attention mask
+ mask = [1] * len(chunk)
+
+ # Append padding if necessary
+ if len(chunk) < tokenizer.model_max_length:
+ pad = tokenizer.model_max_length - len(chunk)
+ chunk.extend([tokenizer.pad_token_id] * pad)
+ mask.extend([0] * pad)
+
+ inputids.append(chunk)
+ attention.append(mask)
+ indices.append(x)
+ else:
+ inputids.append(ids)
+ attention.append(tokens["attention_mask"][x])
+ indices.append(x)
+
+ tokens = {"input_ids": inputids, "attention_mask": attention}
+
+ # pylint: disable=E1102
+ return ({name: self.tensor(tensor).to(self.device) for name, tensor in tokens.items()}, indices)
+
+ def batch(self, texts, size):
+ """
+ Splits texts into separate batch sizes specified by size.
+
+ Args:
+ texts: text elements
+ size: batch size
+
+ Returns:
+ list of evenly sized batches with the last batch having the remaining elements
+ """
+
+ return [texts[x : x + size] for x in range(0, len(texts), size)]
diff --git a/src/python/txtai/pipeline/hfpipeline.py b/src/python/txtai/pipeline/hfpipeline.py
index c701d3d3..1fa1631a 100644
--- a/src/python/txtai/pipeline/hfpipeline.py
+++ b/src/python/txtai/pipeline/hfpipeline.py
@@ -2,14 +2,12 @@
Hugging Face pipeline wrapper module
"""
-import torch
-
from transformers import pipeline
-from .base import Pipeline
+from .tensors import Tensors
-class HFPipeline(Pipeline):
+class HFPipeline(Tensors):
"""
Light wrapper around Hugging Face's pipeline component for selected tasks. Adds support for model
quantization and minor interface changes.
@@ -24,21 +22,21 @@ class HFPipeline(Pipeline):
path: optional path to model, accepts Hugging Face model hub id or local path,
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)
+ gpu: True/False if GPU should be enabled, also supports a GPU device id
model: optional existing pipeline model to wrap
"""
if model:
# Check if input model is a Pipeline or a HF pipeline
- self.pipeline = model.pipeline if isinstance(model, Pipeline) else model
+ self.pipeline = model.pipeline if isinstance(model, HFPipeline) else model
else:
- # Enable GPU inference if explicitly set and a GPU is available
- gpu = gpu and torch.cuda.is_available()
+ # Get device id
+ deviceid = self.deviceid(gpu)
# Transformer pipeline task
- self.pipeline = pipeline(task, model=path, tokenizer=path, device=0 if gpu else -1)
+ self.pipeline = pipeline(task, model=path, tokenizer=path, device=deviceid)
# Model quantization. Compresses model to int8 precision, improves runtime performance. Only supported on CPU.
- if not gpu and quantize:
+ if deviceid == -1 and quantize:
# pylint: disable=E1101
- self.pipeline.model = torch.quantization.quantize_dynamic(self.pipeline.model, {torch.nn.Linear}, dtype=torch.qint8)
+ self.pipeline.model = self.quantize(self.pipeline.model)
diff --git a/src/python/txtai/pipeline/tensors.py b/src/python/txtai/pipeline/tensors.py
new file mode 100644
index 00000000..d4d360d1
--- /dev/null
+++ b/src/python/txtai/pipeline/tensors.py
@@ -0,0 +1,114 @@
+"""
+Tensor processing framework module
+"""
+
+import torch
+
+from .base import Pipeline
+
+
+class Tensors(Pipeline):
+ """
+ Pipeline backed by a tensor processing framework. Currently supports PyTorch.
+ """
+
+ def deviceid(self, gpu):
+ """
+ Translates a gpu flag into a device id.
+
+ Args:
+ gpu: True/False if GPU should be enabled, also supports a GPU device id
+
+ Returns:
+ device id
+ """
+
+ # Always return -1 if gpu is None or CUDA is unavailable
+ if gpu is None or not torch.cuda.is_available():
+ return -1
+
+ # Default to device 0 if gpu is True and not otherwise specified
+ if isinstance(gpu, bool):
+ return 0 if gpu else -1
+
+ # Return gpu as device id if gpu flag is an int
+ return int(gpu)
+
+ def reference(self, device):
+ """
+ Gets a tensor device reference.
+
+ Args:
+ device: device id
+
+ Returns:
+ tensor device
+ """
+
+ # Torch device
+ # pylint: disable=E1101
+ return torch.device("cpu" if device < 0 else "cuda:{}".format(device))
+
+ def quantize(self, model):
+ """
+ Quantizes input model and returns. This only is supported for CPU devices.
+
+ Args:
+ model: torch model
+
+ Returns:
+ quantized torch model
+ """
+
+ # pylint: disable=E1101
+ return torch.quantization.quantize_dynamic(model, {torch.nn.Linear}, dtype=torch.qint8)
+
+ def tensor(self, data):
+ """
+ Creates a tensor array.
+
+ Args:
+ data: input data
+
+ Returns:
+ tensor
+ """
+
+ # pylint: disable=E1102
+ return torch.tensor(data)
+
+ def tensortype(self):
+ """
+ Returns the tensor processing framework code.
+
+ Returns:
+ tensor processing framework code
+ """
+
+ return "pt"
+
+ def argmax(self, data, dimension):
+ """
+ Calls argmax on data using the tensor processing framework.
+
+ Args:
+ data: input data
+ dimension: dimension to derive argmax
+
+ Returns:
+ argmax
+ """
+
+ # pylint: disable=E1101
+ return torch.argmax(data, dim=dimension)
+
+ def context(self):
+ """
+ Defines a context used to wrap processing with the tensor processing framework.
+
+ Returns:
+ processing context
+ """
+
+ # pylint: disable=E1101
+ return torch.no_grad()