💡 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
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.pyindex e8fb433e..6ab79f2f 100644--- a/src/python/txtai/ann/dense/numpy.py+++ b/src/python/txtai/ann/dense/numpy.py@@ -4,6 +4,8 @@ NumPy moduleimport numpy as np+from safetensors.numpy import load_file, save_file+from ...serialize import SerializeFactoryfrom ..base import ANN@@ -28,7 +30,12 @@ class NumPy(ANN):def load(self, path):# Load array from filetry:- 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 dataself.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.pyindex 5f689a11..a90310ae 100644--- a/test/python/testann/testdense.py+++ b/test/python/testann/testdense.py@@ -159,6 +159,25 @@ class TestDense(unittest.TestCase):# Validate countself.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):"""