Skip to content

armgit / txtai

Public Imported from GitHub
0

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

Refactor NumPy/Torch ANN backends to consolidate common code

davidmezzettia2a4ff344890
diff --git a/docs/embeddings/configuration/index.md b/docs/embeddings/configuration/index.md
index 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 the
diff --git a/src/python/txtai/ann/base.py b/src/python/txtai/ann/base.py
index 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 None
return 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.py
index 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 metadata
self.config["offset"] += new
- self.metadata(None)
+ self.metadata()
def delete(self, ids):
# Remove specified ids
diff --git a/src/python/txtai/ann/hnsw.py b/src/python/txtai/ann/hnsw.py
index 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 metadata
self.config["offset"] += new
- self.metadata(None)
+ self.metadata()
def delete(self, ids):
# Mark elements as deleted to omit from search results
diff --git a/src/python/txtai/ann/numpy.py b/src/python/txtai/ann/numpy.py
index 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 file
with 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 metadata
self.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 metadata
self.config["offset"] += new
+ self.metadata()
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] = 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 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[~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 file
with 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.py
index 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 np
import torch
from .. 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.zeros
def tensor(self, array):
- """
- Loads array as a Tensor. Loads to GPU device, if available.
-
- Args:
- array: data array
-
- Returns:
- Tensor
- """
-
# Convert array to Tensor
if isinstance(array, np.ndarray):
array = torch.from_numpy(array)
# Load to GPU device, if available
return array.cuda() if torch.cuda.is_available() else array
+
+ def settings(self):
+ return {"torch": torch.__version__}