Skip to content

armgit / txtai

Public Imported from GitHub
0

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

Modify embeddings index/upsert methods only consume input documents once, closes #189

davidmezzetti7fe06052eb08
diff --git a/src/python/txtai/embeddings/base.py b/src/python/txtai/embeddings/base.py
index 10491c7e..64e12e3d 100644
--- a/src/python/txtai/embeddings/base.py
+++ b/src/python/txtai/embeddings/base.py
@@ -17,6 +17,7 @@ from ..vectors import VectorsFactory
from .archive import Archive
from .reducer import Reducer
from .search import Search
+from .transform import Action, Transform
# pylint: disable=R0904
@@ -79,8 +80,18 @@ class Embeddings:
reindex: if this is a reindex operation in which case database creation is skipped, defaults to False
"""
- # Transform documents to embeddings vectors
- ids, dimensions, embeddings = self.vectors(documents)
+ # Create document database, if necessary
+ if not reindex:
+ self.database = self.createdatabase()
+
+ # Reset archive since this is a new index
+ self.archive = None
+
+ # Create transform action
+ transform = Transform(self, Action.REINDEX if reindex else Action.INDEX)
+
+ # Load documents into database and transform to vectors
+ ids, dimensions, embeddings = transform(documents)
# Build LSA model (if enabled). Remove principal components from embeddings.
if self.config.get("pca"):
@@ -96,22 +107,12 @@ class Embeddings:
# Create approximate nearest neighbor index
self.ann = ANNFactory.create(self.config)
- # Build the index
+ # Add embeddings to the index
self.ann.index(embeddings)
- # Keep existing database and archive instances if this is part of a reindex
- if not reindex:
- # Create document database
- self.database = self.createdatabase()
- if self.database:
- # Add documents to database
- self.database.insert(documents)
- else:
- # Save indexids-ids mapping for indexes with no database
- self.config["ids"] = ids
-
- # Reset archive since this is a new index
- self.archive = None
+ # Save indexids-ids mapping for indexes with no database, except when this is a reindex action
+ if not reindex and not self.database:
+ self.config["ids"] = ids
def upsert(self, documents):
"""
@@ -128,26 +129,20 @@ class Embeddings:
self.index(documents)
return
- # Transform documents to embeddings vectors
- ids, _, embeddings = self.vectors(documents)
+ # Create transform action
+ transform = Transform(self, Action.UPSERT)
+
+ # Load documents into database and transform to vectors
+ ids, _, embeddings = transform(documents)
# Normalize embeddings
self.normalize(embeddings)
- # Delete existing elements
- self.delete(ids)
-
- # Get offset before it changes
- offset = self.config.get("offset", 0)
-
- # Append elements the index
+ # Append embeddings to the index
self.ann.append(embeddings)
- if self.database:
- # Add documents to database
- self.database.insert(documents, offset)
- else:
- # Save indexids-ids mapping for indexes with no database
+ # Save indexids-ids mapping for indexes with no database
+ if not self.database:
self.config["ids"] = self.config["ids"] + ids
def delete(self, ids):
@@ -492,57 +487,6 @@ class Embeddings:
return VectorsFactory.create(self.config, self.scoring)
- def vectors(self, documents):
- """
- Transforms documents into embeddings vectors.
-
- Args:
- documents: list of (id, data, tags)
-
- Returns:
- (document ids, dimensions, embeddings)
- """
-
- # Transform documents to embeddings vectors
- ids, dimensions, stream = self.model.index(self.getinputs(documents))
-
- # Load streamed embeddings back to memory
- embeddings = np.empty((len(ids), dimensions), dtype=np.float32)
- with open(stream, "rb") as queue:
- for x in range(embeddings.shape[0]):
- embeddings[x] = pickle.load(queue)
-
- # Remove temporary file
- os.remove(stream)
-
- return (ids, dimensions, embeddings)
-
- def getinputs(self, documents):
- """
- Prepares documents for vector models.
-
- Must be one of the following:
- - dict with the field "text" or "object"
- - not a dict
-
- Otherwise, the document is not passed to the vector models.
-
- Args:
- documents: list of (id, data, tags)
-
- Returns:
- filtered documents
- """
-
- for document in documents:
- if isinstance(document[1], dict):
- if "text" in document[1]:
- yield (document[0], document[1]["text"], document[2])
- elif "object" in document[1]:
- yield (document[0], document[1]["object"], document[2])
- else:
- yield document
-
def checkarchive(self, path):
"""
Checks if path is an archive file.
diff --git a/src/python/txtai/embeddings/documents.py b/src/python/txtai/embeddings/documents.py
index dd736318..4b1f11b7 100644
--- a/src/python/txtai/embeddings/documents.py
+++ b/src/python/txtai/embeddings/documents.py
@@ -1,5 +1,5 @@
"""
-Stream module
+Documents module
"""
import os
@@ -14,7 +14,7 @@ class Documents:
def __init__(self):
"""
- Creates a new DocumentStream.
+ Creates a new documents stream.
"""
self.documents = None
diff --git a/src/python/txtai/embeddings/search.py b/src/python/txtai/embeddings/search.py
index a1edcb9d..10618096 100644
--- a/src/python/txtai/embeddings/search.py
+++ b/src/python/txtai/embeddings/search.py
@@ -12,7 +12,7 @@ class Search:
def __init__(self, embeddings):
"""
- Creates a new search.
+ Creates a new search action.
Args:
embeddings: embeddings instance
diff --git a/src/python/txtai/embeddings/transform.py b/src/python/txtai/embeddings/transform.py
new file mode 100644
index 00000000..dffab0a0
--- /dev/null
+++ b/src/python/txtai/embeddings/transform.py
@@ -0,0 +1,141 @@
+"""
+Transform module
+"""
+
+import os
+import pickle
+
+from enum import Enum
+
+import numpy as np
+
+
+class Transform:
+ """
+ Executes a transform action. Processes a stream of documents, loads batches into a database and vectorizes documents.
+ """
+
+ def __init__(self, embeddings, action):
+ """
+ Creates a new transform action.
+
+ Args:
+ embeddings: embeddings instance
+ action: transform action
+ """
+
+ self.embeddings = embeddings
+ self.action = action
+
+ # Alias embeddings attributes
+ self.delete = self.embeddings.delete
+ self.model = self.embeddings.model
+ self.database = self.embeddings.database
+
+ # Get config parameters
+ self.offset = self.embeddings.config.get("offset", 0) if self.action == Action.UPSERT else 0
+ self.batch = self.embeddings.config.get("batch", 1024)
+
+ # List of deleted ids with this action
+ self.deletes = set()
+
+ def __call__(self, documents):
+ """
+ Processes an iterable collection of documents, handles any iterable including generators.
+
+ This method loads a stream of documents into a database (if applicable) and vectorizes documents into an embeddings array.
+
+ Args:
+ documents: iterable collection of (id, data, tags)
+
+ Returns:
+ (document ids, dimensions, embeddings)
+ """
+
+ # Transform documents to vectors and load into database
+ ids, dimensions, stream = self.model.index(self.stream(documents))
+
+ # Load streamed embeddings back to memory
+ embeddings = np.empty((len(ids), dimensions), dtype=np.float32)
+ with open(stream, "rb") as queue:
+ for x in range(embeddings.shape[0]):
+ embeddings[x] = pickle.load(queue)
+
+ # Remove temporary file
+ os.remove(stream)
+
+ return (ids, dimensions, embeddings)
+
+ def stream(self, documents):
+ """
+ This method does two things:
+
+ 1. Filter and yield data to vectorize
+ 2. Batch and load original documents into a database (if applicable)
+
+ Documents are yielded for vectorization if one of the following is True:
+ - dict with the field "text" or "object"
+ - not a dict
+
+ Otherwise, documents are only batched and inserted into a database
+
+ Args:
+ documents: iterable collection (id, data, tags)
+ """
+
+ batch = []
+
+ # Iterate and process documents stream
+ for document in documents:
+ if isinstance(document[1], dict):
+ if "text" in document[1]:
+ yield (document[0], document[1]["text"], document[2])
+ elif "object" in document[1]:
+ yield (document[0], document[1]["object"], document[2])
+ else:
+ yield document
+
+ # Batch document
+ batch.append(document)
+ if len(batch) == self.batch:
+ self.load(batch)
+ batch = []
+
+ # Final batch
+ if batch:
+ self.load(batch)
+
+ def load(self, batch):
+ """
+ Loads a document batch. This method deletes existing ids from an embeddings index and
+ load into a database, if applicable.
+
+ Args:
+ batch: list of (id, data, tags)
+ """
+
+ # Delete from embeddings index first (which deletes from underlying ANN index and database) if this is an upsert
+ if self.action == Action.UPSERT:
+ # Get list of ids not yet seen and delete
+ deletes = [uid for uid, _, _ in batch if uid not in self.deletes]
+ if deletes:
+ # Execute delete
+ self.delete(deletes)
+
+ # Save deleted ids as a delete must only occur once per action
+ self.deletes.update(deletes)
+
+ # Load batch into database except if this is a reindex
+ if self.database and self.action != Action.REINDEX:
+ self.database.insert(batch, self.offset)
+ self.offset += len(batch)
+
+
+class Action(Enum):
+ """
+ Transform action types
+ """
+
+ INDEX = 1
+ UPSERT = 2
+ REINDEX = 3
diff --git a/test/python/testdatabase/testembeddings.py b/test/python/testdatabase/testembeddings.py
index a3108cac..d36c2fb3 100644
--- a/test/python/testdatabase/testembeddings.py
+++ b/test/python/testdatabase/testembeddings.py
@@ -124,6 +124,23 @@ class TestEmbeddings(unittest.TestCase):
self.assertEqual(self.embeddings.count(), 5)
self.assertEqual(result["text"], self.data[5])
+ def testGenerator(self):
+ """
+ Test index with a generator
+ """
+
+ def documents():
+ for uid, text in enumerate(self.data):
+ yield (uid, text, None)
+
+ # Create an index for the list of text
+ self.embeddings.index(documents())
+
+ # Search for best match
+ result = self.embeddings.search("feel good story", 1)[0]
+
+ self.assertEqual(result["text"], self.data[4])
+
def testIndex(self):
"""
Test index
@@ -314,3 +331,33 @@ class TestEmbeddings(unittest.TestCase):
result = self.embeddings.search("feel good story", 1)[0]
self.assertEqual(result["text"], data[0][1])
+
+ def testUpsertBatch(self):
+ """
+ Test upsert batch
+ """
+
+ try:
+ # Build data array
+ data = [(uid, text, None) for uid, text in enumerate(self.data)]
+
+ # Reset embeddings for test
+ self.embeddings.ann = None
+
+ # Create an index for the list of text
+ self.embeddings.upsert(data)
+
+ # Set batch size to 1
+ self.embeddings.config["batch"] = 1
+
+ # Update data
+ data[0] = (0, "Feel good story: baby panda born", None)
+ data[1] = (0, "Not good news", None)
+ self.embeddings.upsert([data[0], data[1]])
+
+ # Search for best match
+ result = self.embeddings.search("feel good story", 1)[0]
+
+ self.assertEqual(result["text"], data[0][1])
+ finally:
+ del self.embeddings.config["batch"]