💡 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
Refactor NumPy/Torch ANN backends to consolidate common code
davidmezzettia2a4ff344890
diff --git a/docs/embeddings/configuration/index.md b/docs/embeddings/configuration/index.mdindex 516330be..d184cfb5 100644--- a/docs/embeddings/configuration/index.md+++ b/docs/embeddings/configuration/index.md@@ -106,7 +106,7 @@ Instruction-based models use prefixes to modify how embeddings are computed. Thi## backend```yaml-backend: faiss|hnsw|annoy|custom+backend: faiss|hnsw|annoy|numpy|torch|custom```Approximate Nearest Neighbor (ANN) index backend for storing generated sentence embeddings. `Defaults to faiss`. Additional backends require thediff --git a/src/python/txtai/ann/base.py b/src/python/txtai/ann/base.pyindex b27e99b2..7993d8bd 100644--- a/src/python/txtai/ann/base.py+++ b/src/python/txtai/ann/base.py@@ -121,7 +121,7 @@ class ANN:setting = backend.get(name) if backend else Nonereturn setting if setting else default- def metadata(self, settings):+ def metadata(self, settings=None):"""Adds index build metadata.diff --git a/src/python/txtai/ann/faiss.py b/src/python/txtai/ann/faiss.pyindex 47cb74a9..56c08f9b 100644--- a/src/python/txtai/ann/faiss.py+++ b/src/python/txtai/ann/faiss.py@@ -49,7 +49,7 @@ class Faiss(ANN):# Update id offset and index metadataself.config["offset"] += new- self.metadata(None)+ self.metadata()def delete(self, ids):# Remove specified idsdiff --git a/src/python/txtai/ann/hnsw.py b/src/python/txtai/ann/hnsw.pyindex 3f029f44..a5d36c6a 100644--- a/src/python/txtai/ann/hnsw.py+++ b/src/python/txtai/ann/hnsw.py@@ -64,7 +64,7 @@ class HNSW(ANN):# Update id offset and index metadataself.config["offset"] += new- self.metadata(None)+ self.metadata()def delete(self, ids):# Mark elements as deleted to omit from search resultsdiff --git a/src/python/txtai/ann/numpy.py b/src/python/txtai/ann/numpy.pyindex ca8bac6b..7a3937d9 100644--- a/src/python/txtai/ann/numpy.py+++ b/src/python/txtai/ann/numpy.py@@ -16,46 +16,77 @@ class NumPy(ANN):Builds an ANN index backed by a NumPy array."""+ def __init__(self, config):+ super().__init__(config)++ # Array function definitions+ self.all, self.cat, self.dot, self.zeros = np.all, np.concatenate, np.dot, np.zeros+def load(self, path):# Load array from filewith open(path, "rb") as handle:- self.backend = pickle.load(handle)+ self.backend = self.tensor(pickle.load(handle))def index(self, embeddings):# Create index- self.backend = embeddings+ self.backend = self.tensor(embeddings)# Add id offset and index build metadataself.config["offset"] = embeddings.shape[0]+ self.metadata(self.settings())def append(self, embeddings):new = embeddings.shape[0]# Append new data to array- self.backend = np.concatenate((self.backend, embeddings), axis=0)+ self.backend = self.cat((self.backend, self.tensor(embeddings)), axis=0)- # Update id offset+ # Update id offset and index metadataself.config["offset"] += new+ self.metadata()def delete(self, ids):# Filter any index greater than size of arrayids = [x for x in ids if x < self.backend.shape[0]]# Clear specified ids- self.backend[ids] = np.zeros((len(ids), self.backend.shape[1]))+ self.backend[ids] = self.tensor(self.zeros((len(ids), self.backend.shape[1])))def search(self, queries, limit):# Dot product on normalized vectors is equal to cosine similarity- scores = np.dot(queries, self.backend.T).tolist()+ scores = self.dot(self.tensor(queries), self.backend.T).tolist()# Add index and sort desc based on scorereturn [sorted(enumerate(score), key=lambda x: x[1], reverse=True)[:limit] for score in scores]def count(self):# Get count of non-zero rows (ignores deleted rows)- return self.backend[~np.all(self.backend == 0, axis=1)].shape[0]+ return self.backend[~self.all(self.backend == 0, axis=1)].shape[0]def save(self, path):# Save array to filewith open(path, "wb") as handle:pickle.dump(self.backend, handle, protocol=__pickle__)++ def tensor(self, array):+ """+ Handles backend-specific code such as loading to a GPU device.++ Args:+ array: data array++ Returns:+ array with backend-specific logic applied+ """++ return array++ def settings(self):+ """+ Returns settings for this array.++ Returns:+ dict+ """++ return {"numpy": np.__version__}diff --git a/src/python/txtai/ann/torch.py b/src/python/txtai/ann/torch.pyindex e0552f69..6bc2f046 100644--- a/src/python/txtai/ann/torch.py+++ b/src/python/txtai/ann/torch.py@@ -2,79 +2,32 @@PyTorch module"""-import pickle-import numpy as npimport torchfrom .. import __pickle__-from .base import ANN+from .numpy import NumPy-class Torch(ANN):+class Torch(NumPy):"""Builds an ANN index backed by a PyTorch array."""- def load(self, path):- # Load array from file- with open(path, "rb") as handle:- self.backend = self.tensor(pickle.load(handle))-- def index(self, embeddings):- # Create index- self.backend = self.tensor(embeddings)-- # Add id offset and index build metadata- self.config["offset"] = embeddings.shape[0]-- def append(self, embeddings):- new = embeddings.shape[0]-- # Append new data to array- self.backend = torch.cat((self.backend, self.tensor(embeddings)), 0)-- # Update id offset- self.config["offset"] += new-- def delete(self, ids):- # Filter any index greater than size of array- ids = [x for x in ids if x < self.backend.shape[0]]-- # Clear specified ids- self.backend[ids] = self.tensor(torch.zeros((len(ids), self.backend.shape[1])))+ def __init__(self, config):+ super().__init__(config)- def search(self, queries, limit):- # Dot product on normalized vectors is equal to cosine similarity- scores = torch.mm(self.tensor(queries), self.backend.T).tolist()-- # Add index and sort desc based on score- return [sorted(enumerate(score), key=lambda x: x[1], reverse=True)[:limit] for score in scores]-- def count(self):- # Get count of non-zero rows (ignores deleted rows)- return self.backend[~torch.all(self.backend == 0, axis=1)].shape[0]-- def save(self, path):- # Save array to file- with open(path, "wb") as handle:- pickle.dump(self.backend, handle, protocol=__pickle__)+ # Define array functions+ self.all, self.cat, self.dot, self.zeros = torch.all, torch.cat, torch.mm, torch.zerosdef tensor(self, array):- """- Loads array as a Tensor. Loads to GPU device, if available.-- Args:- array: data array-- Returns:- Tensor- """-# Convert array to Tensorif isinstance(array, np.ndarray):array = torch.from_numpy(array)# Load to GPU device, if availablereturn array.cuda() if torch.cuda.is_available() else array++ def settings(self):+ return {"torch": torch.__version__}