💡 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 support for LiteRT vectors, closes #1097
davidmezzetti9d5f82e8249e
diff --git a/src/python/txtai/vectors/dense/factory.py b/src/python/txtai/vectors/dense/factory.pyindex ec6d88b4..859e6cf0 100644--- a/src/python/txtai/vectors/dense/factory.py+++ b/src/python/txtai/vectors/dense/factory.py@@ -7,6 +7,7 @@ from ...util import Resolverfrom .external import Externalfrom .huggingface import HFVectorsfrom .litellm import LiteLLM+from .litert import LiteRTfrom .llama import LlamaCppfrom .m2v import Model2Vecfrom .sbert import STVectors@@ -43,6 +44,10 @@ class VectorsFactory:if method == "litellm":return LiteLLM(config, scoring, models)+ # LiteRT vectors+ if method == "litert":+ return LiteRT(config, scoring, models)+# llama.cpp vectorsif method == "llama.cpp":return LlamaCpp(config, scoring, models)@@ -87,6 +92,8 @@ class VectorsFactory:if path:if LiteLLM.ismodel(path):method = "litellm"+ elif LiteRT.ismodel(path):+ method = "litert"elif LlamaCpp.ismodel(path):method = "llama.cpp"elif Model2Vec.ismodel(path):diff --git a/src/python/txtai/vectors/dense/litert.py b/src/python/txtai/vectors/dense/litert.pynew file mode 100644index 00000000..26c06e22--- /dev/null+++ b/src/python/txtai/vectors/dense/litert.py@@ -0,0 +1,154 @@+"""+LiteRT module+"""++import os++# Conditional import+try:+ from ai_edge_litert.compiled_model import CompiledModel, HardwareAccelerator+ from tokenizers import Tokenizer++ LITERT = True+except ImportError:+ LITERT = False++from ...util import Download, Library++from ..base import Vectors++# Core library imports+np = Library().numpy()+++class LiteRT(Vectors):+ """+ Builds vectors using LiteRT.+ """++ @staticmethod+ def ismodel(path):+ """+ Checks if path is a LiteRT model.++ Args:+ path: input path++ Returns:+ True if this is a LiteRT model, False otherwise+ """++ return isinstance(path, str) and path.lower().endswith(".tflite")++ def __init__(self, config, scoring, models):+ # Check before parent constructor since it calls loadmodel+ if not LITERT:+ raise ImportError('LiteRT is not available - install "vectors" extra to enable')++ super().__init__(config, scoring, models)++ def loadmodel(self, path):+ # Check if this is a local path, otherwise download from the HF Hub+ model = path if os.path.exists(path) else Download()(path)++ # Also local tokenizer file+ tokenizer = os.path.dirname(path) + "/" + "tokenizer.json"+ tokenizer = tokenizer if os.path.exists(tokenizer) else Download()(tokenizer)++ # Load tokenizer and model+ tokenizer = Tokenizer.from_file(tokenizer)+ model = CompiledModel.from_file(+ model,+ HardwareAccelerator.GPU | HardwareAccelerator.NPU | HardwareAccelerator.CPU if self.config.get("gpu", True) else HardwareAccelerator.CPU,+ )++ # Calculate model batch size and max length+ buffers = model.create_input_buffers(0)+ batchsize, maxlength = buffers[0].get_tensor_details()["shape"]++ # Set maxlength on tokenizer+ tokenizer.enable_padding(length=maxlength)+ tokenizer.enable_truncation(max_length=maxlength)++ return (model, tokenizer, batchsize)++ def encode(self, data, category=None):+ # Tokenize input+ ids, masks, types = self.tokenizer(data)++ # Generate embeddings+ return self.embed(ids, masks, types)++ def tokenizer(self, data):+ """+ Tokenizes data.++ Args:+ data: batch of data++ Returns:+ tokenized data+ """++ # Unpack tokenizer+ _, tokenizer, _ = self.model++ encoding = tokenizer.encode_batch(data)+ return (+ np.array([e.ids for e in encoding], dtype=np.int32),+ np.array([e.attention_mask for e in encoding], dtype=np.int32),+ np.array([e.type_ids for e in encoding], dtype=np.int32),+ )++ def embed(self, ids, masks, types):+ """+ Generates embeddings from tokenized input.++ Args:+ ids: token ids+ masks: attention mask+ types: token type ids++ Returns:+ embeddings+ """++ # Unpack model+ model, _, batchsize = self.model++ results = []++ # Create tensor buffers+ inputs = model.create_input_buffers(0)+ outputs = model.create_output_buffers(0)++ # Create batch memory+ bids = np.zeros((batchsize, ids.shape[1]), dtype=np.int32)+ bmasks = np.zeros((batchsize, masks.shape[1]), dtype=np.int32)+ btypes = np.zeros((batchsize, types.shape[1]), dtype=np.int32)++ for start in range(0, len(ids), batchsize):+ # Batch parameters+ end = start + batchsize+ chunk = slice(start, end)+ actual = len(ids[chunk])++ # Copy batch to numpy buffer+ bids[:actual], bmasks[:actual], btypes[:actual] = ids[chunk], masks[chunk], types[chunk]++ # Copy to tensor buffer+ for x, data in enumerate([bids, bmasks, btypes]):+ inputs[x].write(data)++ # Run model+ model.run_by_index(0, inputs, outputs)++ # Get details of output buffer+ details = outputs[0].get_tensor_details()+ count = int(np.prod(details["shape"]))++ # Append result+ result = outputs[0].read(count, details["dtype"])+ results.append(result.reshape(details["shape"])[:actual])++ return np.vstack(results)diff --git a/test/python/testoptional.py b/test/python/testoptional.pyindex bf4af69d..846b9061 100644--- a/test/python/testoptional.py+++ b/test/python/testoptional.py@@ -22,6 +22,7 @@ class TestOptional(unittest.TestCase):"""modules = [+ "ai_edge_litert.compiled_model","annoy","bitsandbytes","bs4",@@ -352,6 +353,9 @@ class TestOptional(unittest.TestCase):with self.assertRaises(ImportError):VectorsFactory.create({"method": "litellm", "path": "huggingface/sentence-transformers/all-MiniLM-L6-v2"}, None)+ with self.assertRaises(ImportError):+ VectorsFactory.create({"method": "litert", "path": "neuml/bert-hash-nano-embeddings-litert/bert-hash-nano-embeddings-int4.tflite"}, None)+with self.assertRaises(ImportError):VectorsFactory.create({"method": "llama.cpp", "path": "nomic-ai/nomic-embed-text-v1.5-GGUF/nomic-embed-text-v1.5.Q2_K.gguf"}, None)diff --git a/test/python/testvectors/testdense/testlitert.py b/test/python/testvectors/testdense/testlitert.pynew file mode 100644index 00000000..05234c5e--- /dev/null+++ b/test/python/testvectors/testdense/testlitert.py@@ -0,0 +1,40 @@+"""+LiteRT module tests+"""++import os+import unittest++import numpy as np++from txtai.vectors import VectorsFactory+++class TestLiteRT(unittest.TestCase):+ """+ LiteRT vectors tests+ """++ @classmethod+ def setUpClass(cls):+ """+ Create LiteRT instance.+ """++ cls.model = VectorsFactory.create({"path": "neuml/bert-hash-nano-embeddings-litert/bert-hash-nano-embeddings-int4.tflite"}, None)++ def testIndex(self):+ """+ Test indexing with LiteRT vectors+ """++ ids, dimension, batches, stream = self.model.index([(0, "test", None)])++ self.assertEqual(len(ids), 1)+ self.assertEqual(dimension, 128)+ self.assertEqual(batches, 1)+ self.assertIsNotNone(os.path.exists(stream))++ # Test shape of serialized embeddings+ with open(stream, "rb") as queue:+ self.assertEqual(np.load(queue).shape, (1, 128))