Skip to content

armgit / txtai

Public Imported from GitHub
0

💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows

Improve efficiency of vector transformations, closes #191

davidmezzetti1b5a18022120
diff --git a/src/python/txtai/embeddings/base.py b/src/python/txtai/embeddings/base.py
index 64e12e3d..730be18c 100644
--- a/src/python/txtai/embeddings/base.py
+++ b/src/python/txtai/embeddings/base.py
@@ -6,6 +6,7 @@ import json
import pickle
import os
import shutil
+import types
import numpy as np
@@ -114,6 +115,9 @@ class Embeddings:
if not reindex and not self.database:
self.config["ids"] = ids
+ # Delete mmap buffer file
+ os.remove(embeddings.filename)
+
def upsert(self, documents):
"""
Runs an embeddings upsert operation. If the index exists, new data is
@@ -145,6 +149,9 @@ class Embeddings:
if not self.database:
self.config["ids"] = self.config["ids"] + ids
+ # Delete mmap buffer file
+ os.remove(embeddings.filename)
+
def delete(self, ids):
"""
Deletes from an embeddings index. Returns list of ids deleted.
@@ -452,7 +459,19 @@ class Embeddings:
Prints the current embeddings index configuration.
"""
- print(json.dumps(self.config, sort_keys=True, indent=2))
+ # Copy and edit config
+ config = self.config.copy()
+
+ # Remove ids array if present
+ config.pop("ids", None)
+
+ # Format functions
+ for key in config:
+ if isinstance(config[key], types.FunctionType):
+ config[key] = "<function>"
+
+ # Print configuration
+ print(json.dumps(config, sort_keys=True, indent=2))
def configure(self, config):
"""
diff --git a/src/python/txtai/embeddings/transform.py b/src/python/txtai/embeddings/transform.py
index dffab0a0..3c074124 100644
--- a/src/python/txtai/embeddings/transform.py
+++ b/src/python/txtai/embeddings/transform.py
@@ -4,6 +4,7 @@ Transform module
import os
import pickle
+import tempfile
from enum import Enum
@@ -53,13 +54,20 @@ class Transform:
"""
# Transform documents to vectors and load into database
- ids, dimensions, stream = self.model.index(self.stream(documents))
+ ids, dimensions, batches, stream = self.model.index(self.stream(documents))
+
+ # Generate buffer file name
+ # pylint: disable=R1732
+ buffer = tempfile.NamedTemporaryFile(mode="wb", suffix=".npy", delete=False)
# Load streamed embeddings back to memory
- embeddings = np.empty((len(ids), dimensions), dtype=np.float32)
+ embeddings = np.memmap(buffer, dtype=np.float32, shape=(len(ids), dimensions), mode="w+")
with open(stream, "rb") as queue:
- for x in range(embeddings.shape[0]):
- embeddings[x] = pickle.load(queue)
+ x = 0
+ for _ in range(batches):
+ batch = pickle.load(queue)
+ embeddings[x : x + batch.shape[0]] = batch
+ x += batch.shape[0]
# Remove temporary file
os.remove(stream)
diff --git a/src/python/txtai/vectors/transformers.py b/src/python/txtai/vectors/transformers.py
index 4f437101..2bb10b49 100644
--- a/src/python/txtai/vectors/transformers.py
+++ b/src/python/txtai/vectors/transformers.py
@@ -46,7 +46,7 @@ class TransformersVectors(Vectors):
return SentenceTransformer(path, device=Models.reference(deviceid))
def index(self, documents):
- ids, dimensions, stream = [], None, None
+ 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:
@@ -59,6 +59,7 @@ class TransformersVectors(Vectors):
# Convert batch to embeddings
uids, dimensions = self.batch(batch, output)
ids.extend(uids)
+ batches += 1
batch = []
@@ -66,8 +67,9 @@ class TransformersVectors(Vectors):
if batch:
uids, dimensions = self.batch(batch, output)
ids.extend(uids)
+ batches += 1
- return (ids, dimensions, stream)
+ return (ids, dimensions, batches, stream)
def transform(self, document):
# Prepare input document for transformers model and build embeddings
@@ -92,12 +94,9 @@ class TransformersVectors(Vectors):
# Build embeddings
embeddings = self.model.encode(documents)
- for embedding in embeddings:
- if not dimensions:
- # Set number of dimensions for embeddings
- dimensions = embedding.shape[0]
-
- pickle.dump(embedding, output, protocol=4)
+ 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/words.py b/src/python/txtai/vectors/words.py
index 36439d18..f783960e 100644
--- a/src/python/txtai/vectors/words.py
+++ b/src/python/txtai/vectors/words.py
@@ -118,7 +118,7 @@ class WordVectors(Vectors):
ids.append(uid)
pickle.dump(embedding, output, protocol=4)
- return (ids, dimensions, stream)
+ return (ids, dimensions, len(ids), stream)
def transform(self, document):
# Convert to tokens if necessary
diff --git a/test/python/testvectors/testtransformers.py b/test/python/testvectors/testtransformers.py
index 05223ef7..85c065dd 100644
--- a/test/python/testvectors/testtransformers.py
+++ b/test/python/testvectors/testtransformers.py
@@ -31,10 +31,11 @@ class TestTransformersVectors(unittest.TestCase):
# Generate enough volume to test batching
documents = [(x, "This is a test", None) for x in range(1000)]
- ids, dimension, stream = self.model.index(documents)
+ 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))
def testSentenceTransformers(self):
diff --git a/test/python/testvectors/testwordvectors.py b/test/python/testvectors/testwordvectors.py
index 2255ffd2..269c4ad7 100644
--- a/test/python/testvectors/testwordvectors.py
+++ b/test/python/testvectors/testwordvectors.py
@@ -55,10 +55,11 @@ class TestWordVectors(unittest.TestCase):
model = VectorsFactory.create({"path": self.path, "parallel": True}, None)
- ids, dimension, stream = model.index(documents)
+ ids, dimension, batches, stream = model.index(documents)
self.assertEqual(len(ids), 1000)
self.assertEqual(dimension, 10)
+ self.assertEqual(batches, 1000)
self.assertIsNotNone(os.path.exists(stream))
def testIndexSerial(self):
@@ -71,10 +72,11 @@ class TestWordVectors(unittest.TestCase):
model = VectorsFactory.create({"path": self.path, "parallel": False}, None)
- ids, dimension, stream = model.index(documents)
+ ids, dimension, batches, stream = model.index(documents)
self.assertEqual(len(ids), 1000)
self.assertEqual(dimension, 10)
+ self.assertEqual(batches, 1000)
self.assertIsNotNone(os.path.exists(stream))
def testLookup(self):