💡 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 serial execution mode for building word vectors, addresses #62
davidmezzetti006f8346093d
diff --git a/src/python/txtai/vectors/words.py b/src/python/txtai/vectors/words.pyindex 1cac062e..d73f11d2 100644--- a/src/python/txtai/vectors/words.py+++ b/src/python/txtai/vectors/words.py@@ -53,6 +53,34 @@ def transform(document):return (document[0], VECTORS.transform(document))+class SerialPool:+ """+ Custom pool to execute vector transforms serially.+ """++ def __init__(self, vectors):+ global VECTORS+ VECTORS = vectors++ def __enter__(self):+ return self++ def __exit__(self, exc_type, exc_val, exc_tb):+ pass++ def imap(self, func, iterable):+ """+ Single process version of imap.++ Args:+ func: function to run+ iterable: iterable to use+ """++ for x in iterable:+ yield func(x)++class WordVectors(Vectors):"""Builds sentence embeddings/vectors using weighted word embeddings.@@ -73,7 +101,9 @@ class WordVectors(Vectors):args = (self.config, self.scoring)# Convert all documents to embedding arrays, stream embeddings to disk to control memory usage- with Pool(os.cpu_count(), initializer=create, initargs=args) as pool:+ with SerialPool(self) if "parallel" in self.config and not self.config["parallel"] else Pool(+ os.cpu_count(), initializer=create, initargs=args+ ) as pool:with tempfile.NamedTemporaryFile(mode="wb", suffix=".npy", delete=False) as output:stream = output.namefor uid, embedding in pool.imap(transform, documents):diff --git a/test/python/testwordvectors.py b/test/python/testwordvectors.pyindex 0093d0c6..d51133b8 100644--- a/test/python/testwordvectors.py+++ b/test/python/testwordvectors.py@@ -61,6 +61,22 @@ class TestWordVectors(unittest.TestCase):self.assertEqual(dimension, 10)self.assertIsNotNone(os.path.exists(stream))+ def testIndexSerial(self):+ """+ Test word vector indexing in single process mode+ """++ # Generate data+ documents = [(x, "This is a test", None) for x in range(1000)]++ model = VectorsFactory.create({"path": self.path, "parallel": False}, None)++ ids, dimension, stream = model.index(documents)++ self.assertEqual(len(ids), 1000)+ self.assertEqual(dimension, 10)+ self.assertIsNotNone(os.path.exists(stream))+def testLookup(self):"""Test word vector lookup