Skip to content

armgit / txtai

Public Imported from GitHub
0

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

Add support for Safetensors storage to NumPy/Torch ANN backend, closes #969

davidmezzetti8dcab1addcee
diff --git a/src/python/txtai/ann/dense/numpy.py b/src/python/txtai/ann/dense/numpy.py
index e8fb433e..6ab79f2f 100644
--- a/src/python/txtai/ann/dense/numpy.py
+++ b/src/python/txtai/ann/dense/numpy.py
@@ -4,6 +4,8 @@ NumPy module
import numpy as np
+from safetensors.numpy import load_file, save_file
+
from ...serialize import SerializeFactory
from ..base import ANN
@@ -28,7 +30,12 @@ class NumPy(ANN):
def load(self, path):
# Load array from file
try:
- self.backend = self.tensor(np.load(path, allow_pickle=False))
+ if self.setting("safetensors"):
+ data = load_file(path).get("data")
+ else:
+ data = np.load(path, allow_pickle=False)
+
+ self.backend = self.tensor(data)
except ValueError:
# Backwards compatible support for previously pickled data
self.backend = self.tensor(SerializeFactory.create("pickle").load(path))
@@ -81,8 +88,11 @@ class NumPy(ANN):
def save(self, path):
# Save array to file. Use stream to prevent ".npy" suffix being added.
- with open(path, "wb") as handle:
- np.save(handle, self.numpy(self.backend), allow_pickle=False)
+ if self.setting("safetensors"):
+ save_file({"data": self.numpy(self.backend)}, path)
+ else:
+ with open(path, "wb") as handle:
+ np.save(handle, self.numpy(self.backend), allow_pickle=False)
def tensor(self, array):
"""
diff --git a/test/python/testann/testdense.py b/test/python/testann/testdense.py
index 5f689a11..a90310ae 100644
--- a/test/python/testann/testdense.py
+++ b/test/python/testann/testdense.py
@@ -159,6 +159,25 @@ class TestDense(unittest.TestCase):
# Validate count
self.assertEqual(ann.count(), 100)
+ def testNumPySafetensors(self):
+ """
+ Test NumPy backend with safetensors storage
+ """
+
+ ann = ANNFactory.create({"backend": "numpy", "numpy": {"safetensors": True}})
+
+ # Generate and index dummy data
+ data = np.random.rand(100, 240).astype(np.float32)
+ ann.index(data)
+
+ # Test save and load
+ index = os.path.join(tempfile.gettempdir(), "ann.safetensors")
+ ann.save(index)
+ ann.load(index)
+
+ # Validate count
+ self.assertEqual(ann.count(), 100)
+
@patch("sqlalchemy.orm.Query.limit")
def testPGVector(self, query):
"""