💡 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 numpy and torch ANN search, closes #1455 (#1456)
DEVJHAWAR112cd571d414c8
diff --git a/src/python/txtai/ann/dense/numpy.py b/src/python/txtai/ann/dense/numpy.pyindex f009aa8c..5cdbb26f 100644--- a/src/python/txtai/ann/dense/numpy.py+++ b/src/python/txtai/ann/dense/numpy.py@@ -24,7 +24,7 @@ class NumPy(ANN):# Array function definitionsself.all, self.cat, self.dot, self.zeros = np.all, np.concatenate, np.dot, np.zeros- self.argsort, self.xor, self.clip = np.argsort, np.bitwise_xor, np.clip+ self.xor, self.clip = np.bitwise_xor, np.clip# Scalar quantizationquantize = self.config.get("quantize")@@ -79,7 +79,7 @@ class NumPy(ANN):scores = self.dot(self.tensor(queries), self.backend.T)# Get topn ids- ids = self.argsort(-scores)[:, :limit]+ ids = self.topn(scores, limit)# Map results to [(id, score)]results = []@@ -101,6 +101,29 @@ class NumPy(ANN):with open(path, "wb") as handle:np.save(handle, self.numpy(self.backend), allow_pickle=False)+ def topn(self, scores, limit):+ """+ Gets the ids of the top scores for each row, ordered from highest to lowest score. This partitions+ the scores and only sorts the topn candidates rather than sorting every 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 tensor(self, array):"""Handles backend-specific code such as loading to a GPU device.diff --git a/src/python/txtai/ann/dense/torch.py b/src/python/txtai/ann/dense/torch.pyindex b2961bc6..5957aa57 100644--- a/src/python/txtai/ann/dense/torch.py+++ b/src/python/txtai/ann/dense/torch.py@@ -38,7 +38,7 @@ class Torch(NumPy):# Define array functionsself.all, self.cat, self.dot, self.zeros = torch.all, torch.cat, torch.mm, torch.zeros- self.argsort, self.xor, self.clip = torch.argsort, torch.bitwise_xor, torch.clip+ self.xor, self.clip = torch.bitwise_xor, torch.clip# Quantization parametersself.qstate, self.qdeleted = None, 0@@ -89,6 +89,13 @@ class Torch(NumPy):def numpy(self, array):return array.cpu().numpy()+ def topn(self, scores, limit):+ # Sort all scores when topk isn't possible+ if not 0 < limit < scores.shape[1]:+ return torch.argsort(-scores)[:, :limit]++ return torch.topk(scores, limit, dim=1).indices+def totype(self, array, dtype):return array.long() if dtype == np.int64 else arraydiff --git a/test/python/testann/testdense/testnumpy.py b/test/python/testann/testdense/testnumpy.pyindex 208e1f1c..01e817d1 100644--- a/test/python/testann/testdense/testnumpy.py+++ b/test/python/testann/testdense/testnumpy.py@@ -38,6 +38,39 @@ class TestNumPy(DenseTest):np.testing.assert_array_equal(ann.numpy(ann.backend), expected)self.assertEqual(ann.count(), 2)+ def testTopn(self):+ """+ Test that 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++ for backend in ("numpy", "torch"):+ ann = ANNFactory.create({"backend": backend, "dimensions": data.shape[1]})+ self.addCleanup(ann.close)+ 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(backend=backend, 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)+def testNumPy(self):"""Test NumPy backend