Skip to content

armgit / txtai

Public Imported from GitHub
0

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

Embeddings vector batch improvements, closes #309

davidmezzetti332b232349a8
diff --git a/src/python/txtai/embeddings/transform.py b/src/python/txtai/embeddings/transform.py
index 55d7f238..7237da23 100644
--- a/src/python/txtai/embeddings/transform.py
+++ b/src/python/txtai/embeddings/transform.py
@@ -54,7 +54,7 @@ class Transform:
"""
# Transform documents to vectors and load into database
- ids, dimensions, batches, stream = self.model.index(self.stream(documents))
+ ids, dimensions, batches, stream = self.model.index(self.stream(documents), self.batch)
# Check that embeddings are available and load as a memmap
embeddings = None
diff --git a/src/python/txtai/models/pooling.py b/src/python/txtai/models/pooling.py
index 0af85f38..5f4d2c2d 100644
--- a/src/python/txtai/models/pooling.py
+++ b/src/python/txtai/models/pooling.py
@@ -17,7 +17,7 @@ class Pooling(nn.Module):
Builds pooled vectors usings outputs from a transformers model.
"""
- def __init__(self, path, device, tokenizer=None, batch=32, maxlength=None):
+ def __init__(self, path, device, tokenizer=None, maxlength=None):
"""
Creates a new Pooling model.
@@ -25,7 +25,6 @@ class Pooling(nn.Module):
path: path to model, accepts Hugging Face model hub id or local path
device: tensor device id
tokenizer: optional path to tokenizer
- batch: batch size
maxlength: max sequence length
"""
@@ -38,19 +37,19 @@ class Pooling(nn.Module):
# Detect unbounded tokenizer typically found in older models
Models.checklength(self.model, self.tokenizer)
- # Set batch and max length
- self.batch = batch
+ # Set max length
self.maxlength = maxlength if maxlength else self.tokenizer.model_max_length
# Move to device
self.to(self.device)
- def encode(self, documents):
+ def encode(self, documents, batch=32):
"""
Builds an array of pooled embeddings for documents.
Args:
documents: list of documents used to build embeddings
+ batch: model batch size
Returns:
pooled embeddings
@@ -64,7 +63,7 @@ class Pooling(nn.Module):
lengths = np.argsort([-len(x) for x in documents])
documents = [documents[x] for x in lengths]
- for chunk in self.chunk(documents, self.batch):
+ for chunk in self.chunk(documents, batch):
# Tokenize input
inputs = self.tokenizer(chunk, padding=True, truncation="longest_first", return_tensors="pt", max_length=self.maxlength)
diff --git a/src/python/txtai/vectors/base.py b/src/python/txtai/vectors/base.py
index 239e0101..b6a66c81 100644
--- a/src/python/txtai/vectors/base.py
+++ b/src/python/txtai/vectors/base.py
@@ -23,9 +23,12 @@ class Vectors:
# Enables optional string tokenization
self.tokenize = config.get("tokenize")
- # pylint: disable=E1111
+ # Load model
self.model = self.load(config.get("path"))
+ # Encode batch size - controls underlying model batch size when encoding vectors
+ self.encodebatch = config.get("encodebatch", 32)
+
def load(self, path):
"""
Loads vector model at path.
diff --git a/src/python/txtai/vectors/transformers.py b/src/python/txtai/vectors/transformers.py
index 57b4fc6f..ccdff1d4 100644
--- a/src/python/txtai/vectors/transformers.py
+++ b/src/python/txtai/vectors/transformers.py
@@ -45,7 +45,7 @@ class TransformersVectors(Vectors):
def encode(self, data):
# Encode data using vectors model
- return self.model.encode(data)
+ return self.model.encode(data, self.encodebatch)
def prepare(self, data):
# Optional string tokenization
diff --git a/src/python/txtai/vectors/words.py b/src/python/txtai/vectors/words.py
index 5aae632e..01cfafb5 100644
--- a/src/python/txtai/vectors/words.py
+++ b/src/python/txtai/vectors/words.py
@@ -99,7 +99,7 @@ class WordVectors(Vectors):
return super().index(documents, batchsize)
# Customize indexing logic with multiprocessing pool to efficiently build vectors
- ids, dimensions, stream = [], None, None
+ ids, dimensions, batches, stream = [], None, 0, None
# Shared objects with Pool
args = (self.config, self.scoring)
@@ -108,15 +108,27 @@ class WordVectors(Vectors):
with Pool(os.cpu_count(), initializer=create, initargs=args) as pool:
with tempfile.NamedTemporaryFile(mode="wb", suffix=".npy", delete=False) as output:
stream = output.name
+ embeddings = []
for uid, embedding in pool.imap(transform, documents):
if not dimensions:
# Set number of dimensions for embeddings
dimensions = embedding.shape[0]
ids.append(uid)
- pickle.dump(embedding.reshape(1, -1), output, protocol=4)
+ embeddings.append(embedding)
- return (ids, dimensions, len(ids), stream)
+ if len(embeddings) == batchsize:
+ pickle.dump(np.array(embeddings, dtype=np.float32), output, protocol=4)
+ batches += 1
+
+ embeddings = []
+
+ # Final embeddings batch
+ if embeddings:
+ pickle.dump(np.array(embeddings, dtype=np.float32), output, protocol=4)
+ batches += 1
+
+ return (ids, dimensions, batches, stream)
def lookup(self, tokens):
"""
diff --git a/test/python/testvectors/testwordvectors.py b/test/python/testvectors/testwordvectors.py
index 6e25dd11..75a6ce5f 100644
--- a/test/python/testvectors/testwordvectors.py
+++ b/test/python/testvectors/testwordvectors.py
@@ -73,6 +73,32 @@ class TestWordVectors(unittest.TestCase):
with open(stream, "rb") as queue:
self.assertEqual(pickle.load(queue).shape, (1, 10))
+ @patch("os.cpu_count")
+ def testIndexBatch(self, cpucount):
+ """
+ Test word vectors indexing with batch size set
+ """
+
+ # Mock CPU count
+ cpucount.return_value = 1
+
+ # Generate data
+ documents = [(x, "This is a test", None) for x in range(1000)]
+
+ model = VectorsFactory.create({"path": self.path, "parallel": True}, None)
+
+ ids, dimension, batches, stream = model.index(documents, 512)
+
+ self.assertEqual(len(ids), 1000)
+ self.assertEqual(dimension, 10)
+ self.assertEqual(batches, 2)
+ self.assertIsNotNone(os.path.exists(stream))
+
+ # Test shape of serialized embeddings
+ with open(stream, "rb") as queue:
+ self.assertEqual(pickle.load(queue).shape, (512, 10))
+ self.assertEqual(pickle.load(queue).shape, (488, 10))
+
def testIndexSerial(self):
"""
Test word vector indexing in single process mode
@@ -94,6 +120,28 @@ class TestWordVectors(unittest.TestCase):
with open(stream, "rb") as queue:
self.assertEqual(pickle.load(queue).shape, (1, 10))
+ def testIndexSerialBatch(self):
+ """
+ Test word vector indexing in single process mode with batch size set
+ """
+
+ # 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, batches, stream = model.index(documents, 512)
+
+ self.assertEqual(len(ids), 1000)
+ self.assertEqual(dimension, 10)
+ self.assertEqual(batches, 2)
+ self.assertIsNotNone(os.path.exists(stream))
+
+ # Test shape of serialized embeddings
+ with open(stream, "rb") as queue:
+ self.assertEqual(pickle.load(queue).shape, (512, 10))
+ self.assertEqual(pickle.load(queue).shape, (488, 10))
+
def testLookup(self):
"""
Test word vector lookup