💡 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
Select top results instead of sorting every score in GGML ANN search (#1459)
Serhii Zghama890761187af3
diff --git a/src/python/txtai/ann/dense/ggml.py b/src/python/txtai/ann/dense/ggml.pyindex 8d4c71df..7b5ca42f 100644--- a/src/python/txtai/ann/dense/ggml.py+++ b/src/python/txtai/ann/dense/ggml.py@@ -66,7 +66,7 @@ class GGML(ANN):scores = self.backend.search(queries)# Get topn ids- ids = np.argsort(-scores)[:, :limit]+ ids = self.topn(scores, limit)# Map results to [(id, score)]results = []@@ -76,6 +76,28 @@ class GGML(ANN):return results+ def topn(self, scores, limit):+ """+ Gets the ids of the top scores for each row, ordered from highest to lowest score.++ Args:+ scores: scores array of shape (queries, rows)+ limit: maximum number of ids per row++ Returns:+ topn ids for each row+ """++ # Sort all scores when partitioning isn't possible+ if not 0 < limit < scores.shape[1]:+ return np.argsort(-scores)[:, :limit]++ # Partition to find the topn candidates, then sort only those candidates+ ids = np.argpartition(-scores, limit - 1, axis=1)[:, :limit]+ order = np.argsort(-np.take_along_axis(scores, ids, axis=1), axis=1)++ return np.take_along_axis(ids, order, axis=1)+def count(self):return self.backend.count()diff --git a/test/python/testann/testdense/testggml.py b/test/python/testann/testdense/testggml.pyindex cfb40013..82669c2d 100644--- a/test/python/testann/testdense/testggml.py+++ b/test/python/testann/testdense/testggml.py@@ -54,6 +54,42 @@ class TestGGML(DenseTest):ann.load(index)self.assertEqual(ann.count(), 99)+ def testGGMLTopn(self):+ """+ Test that GGML searches return the same top scores as a full sort for all limit sizes+ """++ rng = np.random.default_rng(0)+ data = rng.random((50, 8), dtype=np.float32)+ data /= np.linalg.norm(data, axis=1, keepdims=True)+ queries = data[:3] + 0.01++ ann = ANNFactory.create({"backend": "ggml", "ggml": {"gpu": False}})+ ann.index(data.copy())++ scores = np.dot(queries, data.T)++ # Limits that are zero, smaller than, equal to and larger than the number of rows+ for limit in (0, 1, 5, 49, 50, 80):+ with self.subTest(limit=limit):+ results = ann.search(queries, limit)++ for x, result in enumerate(results):+ expected = np.sort(scores[x])[::-1][:limit]++ self.assertEqual(len(result), len(expected))+ np.testing.assert_allclose([score for _, score in result], expected, rtol=1e-5)++ # Ids are unique and each id maps to its own score+ ids = [uid for uid, _ in result]+ self.assertEqual(len(set(ids)), len(ids))+ np.testing.assert_allclose([scores[x][uid] for uid in ids], [score for _, score in result], rtol=1e-5)++ # Deleted rows are not returned+ best = ann.search(queries[:1], 1)[0][0][0]+ ann.delete([best])+ self.assertNotIn(best, [uid for uid, _ in ann.search(queries[:1], 5)[0]])+def testGGMLQuantizeDisabled(self):"""Test that quantize: false disables GGML tensor quantization