💡 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
Limit pgsparse input vectors to 1000 non-zero elements, closes #939
davidmezzetti6cf12b97a045
diff --git a/src/python/txtai/ann/sparse/pgsparse.py b/src/python/txtai/ann/sparse/pgsparse.pyindex 1a971f21..39726806 100644--- a/src/python/txtai/ann/sparse/pgsparse.py+++ b/src/python/txtai/ann/sparse/pgsparse.py@@ -4,6 +4,8 @@ PGSparse moduleimport os+import numpy as np+# Conditional importtry:from pgvector import SparseVector@@ -37,8 +39,18 @@ class PGSparse(PGVector):return self.setting("url", os.environ.get("SCORING_URL", os.environ.get("ANN_URL")))def column(self):- return SPARSEVEC(self.config["dimensions"]), "sparsevec_ip_ops"+ return SPARSEVEC(self.config["dimensions"])++ def operation(self):+ return "sparsevec_ip_ops"def prepare(self, data):+ # pgvector only allows 1000 non-zero values for sparse vectors+ # Trim to top 1000 values, if necessary+ if data.count_nonzero() > 1000:+ value = -np.sort(-data[0, :].data)[1000]+ data.data = np.where(data.data > value, data.data, 0)+ data.eliminate_zeros()+# Wrap as sparse vectorreturn SparseVector(data)diff --git a/test/python/testann/testsparse.py b/test/python/testann/testsparse.pyindex 403f6f39..6ff1f341 100644--- a/test/python/testann/testsparse.py+++ b/test/python/testann/testsparse.py@@ -83,14 +83,14 @@ class TestSparse(unittest.TestCase):"""# Generate test record- data = self.generate(1, 240)+ data = self.generate(1, 30522)# Mock database queryquery.return_value = [(x, -1.0) for x in range(data.shape[0])]# Create ANNpath = os.path.join(tempfile.gettempdir(), "pgsparse.sqlite")- ann = SparseANNFactory.create({"backend": "pgsparse", "dimensions": 240, "pgsparse": {"url": f"sqlite:///{path}", "schema": "txtai"}})+ ann = SparseANNFactory.create({"backend": "pgsparse", "dimensions": 30522, "pgsparse": {"url": f"sqlite:///{path}", "schema": "txtai"}})# Test indexingann.index(data)@@ -110,6 +110,11 @@ class TestSparse(unittest.TestCase):ann.delete([0])self.assertEqual(ann.count(), 1)+ # Test > 1000 dimensions+ data = random(1, 30522, format="csr", density=0.1)+ ann.index(data)+ self.assertEqual(ann.count(), 1)+# Close ANNann.close()