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 NumPy and Torch ANN components to use np.load/np.save, closes #772

davidmezzetti502db2907e3a
diff --git a/src/python/txtai/ann/numpy.py b/src/python/txtai/ann/numpy.py
index 60b74dd0..2025f23e 100644
--- a/src/python/txtai/ann/numpy.py
+++ b/src/python/txtai/ann/numpy.py
@@ -2,11 +2,9 @@
NumPy module
"""
-import pickle
-
import numpy as np
-from ..version import __pickle__
+from ..serialize import SerializeFactory
from .base import ANN
@@ -29,8 +27,11 @@ class NumPy(ANN):
def load(self, path):
# Load array from file
- with open(path, "rb") as handle:
- self.backend = self.tensor(pickle.load(handle))
+ try:
+ self.backend = self.tensor(np.load(path, allow_pickle=False))
+ except ValueError:
+ # Backwards compatible support for previously pickled data
+ self.backend = self.tensor(SerializeFactory.create("pickle").load(path))
def index(self, embeddings):
# Create index
@@ -81,9 +82,9 @@ class NumPy(ANN):
return self.backend[~self.all(self.backend == 0, axis=1)].shape[0]
def save(self, path):
- # Save array to file
+ # Save array to file. Use stream to prevent ".npy" suffix being added.
with open(path, "wb") as handle:
- pickle.dump(self.backend, handle, protocol=__pickle__)
+ np.save(handle, self.numpy(self.backend), allow_pickle=False)
def tensor(self, array):
"""
@@ -98,6 +99,19 @@ class NumPy(ANN):
return array
+ def numpy(self, array):
+ """
+ Handles backend-specific code to convert an array to numpy
+
+ Args:
+ array: data array
+
+ Returns:
+ numpy array
+ """
+
+ return array
+
def totype(self, array, dtype):
"""
Casts array to dtype.
diff --git a/src/python/txtai/ann/torch.py b/src/python/txtai/ann/torch.py
index ec7a46ea..896e857c 100644
--- a/src/python/txtai/ann/torch.py
+++ b/src/python/txtai/ann/torch.py
@@ -5,8 +5,6 @@ PyTorch module
import numpy as np
import torch
-from ..version import __pickle__
-
from .numpy import NumPy
@@ -30,6 +28,9 @@ class Torch(NumPy):
# Load to GPU device, if available
return array.cuda() if torch.cuda.is_available() else array
+ def numpy(self, array):
+ return array.cpu().numpy()
+
def totype(self, array, dtype):
return array.long() if dtype == np.int64 else array
diff --git a/test/python/testann.py b/test/python/testann.py
index 7fdfc0cd..7e085b9d 100644
--- a/test/python/testann.py
+++ b/test/python/testann.py
@@ -11,8 +11,10 @@ from unittest.mock import patch
import numpy as np
from txtai.ann import ANNFactory, ANN
+from txtai.serialize import SerializeFactory
+# pylint: disable=R0904
class TestANN(unittest.TestCase):
"""
ANN tests.
@@ -110,6 +112,29 @@ class TestANN(unittest.TestCase):
self.runTests("numpy")
+ @patch.dict(os.environ, {"ALLOW_PICKLE": "True"})
+ def testNumPyLegacy(self):
+ """
+ Test NumPy backend with legacy pickled data
+ """
+
+ serializer = SerializeFactory.create("pickle", allowpickle=True)
+
+ # Create output directory
+ output = os.path.join(tempfile.gettempdir(), "ann.npy")
+ path = os.path.join(output, "embeddings")
+ os.makedirs(output, exist_ok=True)
+
+ # Generate data and save as pickle
+ data = np.random.rand(100, 300).astype(np.float32)
+ serializer.save(data, path)
+
+ ann = ANNFactory.create({"backend": "numpy"})
+ ann.load(path)
+
+ # Validate count
+ self.assertEqual(ann.count(), 100)
+
@patch("sqlalchemy.orm.Query.limit")
def testPGVector(self, query):
"""