💡 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 pre-computed vector support, closes #192
davidmezzetti1e65a3b75e0c
diff --git a/src/python/txtai/vectors/base.py b/src/python/txtai/vectors/base.pyindex ce8398bc..93f036dc 100644--- a/src/python/txtai/vectors/base.py+++ b/src/python/txtai/vectors/base.py@@ -21,7 +21,7 @@ class Vectors:self.tokenize = config.get("tokenize")# pylint: disable=E1111- self.model = self.load(config["path"])+ self.model = self.load(config.get("path"))def load(self, path):"""diff --git a/src/python/txtai/vectors/external.py b/src/python/txtai/vectors/external.pynew file mode 100644index 00000000..8b0873a1--- /dev/null+++ b/src/python/txtai/vectors/external.py@@ -0,0 +1,79 @@+"""+External module+"""++import pickle+import tempfile++import numpy as np++from .base import Vectors+++class ExternalVectors(Vectors):+ """+ Loads pre-computed vectors. Pre-computed vectors allow integrating other vector models. They can also be used to efficiently+ test different model configurations without having to recompute vectors.+ """++ def load(self, path):+ return None++ def index(self, documents):+ ids, dimensions, batches, stream = [], None, 0, None++ # Convert all documents to embedding arrays, stream embeddings to disk to control memory usage+ with tempfile.NamedTemporaryFile(mode="wb", suffix=".npy", delete=False) as output:+ stream = output.name+ batch = []+ for document in documents:+ # Require embeddings vector as input+ if isinstance(document[1], np.ndarray):+ batch.append(document)++ if len(batch) == 500:+ # Convert batch to embeddings+ uids, dimensions = self.batch(batch, output)+ ids.extend(uids)+ batches += 1++ batch = []++ # Final batch+ if batch:+ uids, dimensions = self.batch(batch, output)+ ids.extend(uids)+ batches += 1++ return (ids, dimensions, batches, stream)++ def transform(self, document):+ # Get transform function+ transform = self.config.get("transform")++ # Apply transform function if set, otherwise, assume input is an array+ return transform(document) if transform else document[1].astype(np.float32)++ def batch(self, documents, output):+ """+ Builds a batch of embeddings.++ Args:+ documents: list of documents used to build embeddings+ output: output temp file to store embeddings++ Returns:+ (ids, dimensions) list of ids and number of dimensions in embeddings+ """++ # Extract ids and prepare input documents for transformers model+ ids = [uid for uid, _, _ in documents]+ dimensions = None++ # Build embeddings+ embeddings = np.array([data for _, data, _ in documents])+ if embeddings is not None:+ dimensions = embeddings.shape[1]+ pickle.dump(embeddings, output, protocol=4)++ return (ids, dimensions)diff --git a/src/python/txtai/vectors/factory.py b/src/python/txtai/vectors/factory.pyindex 74f0c051..57864b70 100644--- a/src/python/txtai/vectors/factory.py+++ b/src/python/txtai/vectors/factory.py@@ -2,6 +2,7 @@Factory module"""+from .external import ExternalVectorsfrom .transformers import TransformersVectorsfrom .words import WordVectors, WORDS@@ -26,6 +27,9 @@ class VectorsFactory:# Determine vector methodmethod = VectorsFactory.method(config)+ if method == "external":+ return ExternalVectors(config, scoring)+if method == "words":if not WORDS:# Raise error if trying to create Word Vectors without similarity extradiff --git a/test/python/testembeddings.py b/test/python/testembeddings.pyindex 469859d7..be047ee1 100644--- a/test/python/testembeddings.py+++ b/test/python/testembeddings.py@@ -2,10 +2,14 @@Embeddings module tests"""+import contextlib+import ioimport osimport tempfileimport unittest+import numpy as np+from txtai.embeddings import Embeddingsfrom txtai.vectors import WordVectors@@ -59,6 +63,29 @@ class TestEmbeddings(unittest.TestCase):self.assertEqual(self.embeddings.count(), 5)self.assertEqual(uid, 5)+ def testExternal(self):+ """+ Test embeddings backed by external vectors+ """++ def transform(document):+ return document[1].astype(np.float32)++ # Generate random data and index+ data = np.random.rand(5, 100)+ embeddings = Embeddings({"method": "external", "transform": transform})+ embeddings.index([(x, row, None) for x, row in enumerate(data)])++ # Run search+ self.assertGreaterEqual(len(embeddings.search(data[0])), 1)++ # Run info+ output = io.StringIO()+ with contextlib.redirect_stdout(output):+ embeddings.info()++ self.assertTrue("txtai" in output.getvalue())+def testIndex(self):"""Test indexdiff --git a/test/python/testvectors/testexternal.py b/test/python/testvectors/testexternal.pynew file mode 100644index 00000000..49ebc3b5--- /dev/null+++ b/test/python/testvectors/testexternal.py@@ -0,0 +1,42 @@+"""+External module tests+"""++import os+import unittest++import numpy as np++from txtai.vectors import VectorsFactory+++class TestExternalVectors(unittest.TestCase):+ """+ ExternalVectors tests+ """++ @classmethod+ def setUpClass(cls):+ """+ Create single ExternalVectors instance.+ """++ cls.model = VectorsFactory.create({"method": "external"}, None)++ def testIndex(self):+ """+ Test indexing with external vectors+ """++ # Generate dummy data+ data = np.random.rand(1000, 768)++ # Generate enough volume to test batching+ documents = [(x, data[x], None) for x in range(1000)]++ ids, dimension, batches, stream = self.model.index(documents)++ self.assertEqual(len(ids), 1000)+ self.assertEqual(dimension, 768)+ self.assertEqual(batches, 2)+ self.assertIsNotNone(os.path.exists(stream))