💡 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 sparse vector scoring, closes #924. Update default Embeddings parameters, closes #925
davidmezzettid9c50c84b78d
diff --git a/docs/embeddings/configuration/general.md b/docs/embeddings/configuration/general.mdindex 27fd3dac..3401ba99 100644--- a/docs/embeddings/configuration/general.md+++ b/docs/embeddings/configuration/general.md@@ -1,15 +1,35 @@# General-General configuration options that don't fit elsewhere.+General configuration options.## keyword```yaml-keyword: boolean+keyword: boolean|string```Enables sparse keyword indexing for this embeddings.-When enabled, this parameter creates a BM25 index for full text search. It also implicitly disables the [defaults](../vectors/#defaults) setting for vector search.+When set to a boolean, this parameter creates a BM25 index for full text search. When set to a string, it expects a [keyword method](../scoring#method).++It also implicitly disables the [defaults](#defaults) setting for vector search.++## sparse+```yaml+sparse: boolean|path+```++Enables sparse vector indexing for this embeddings.++When set to `True`, this parameter creates a sparse vector index using the [default sparse index model](https://huggingface.co/prithivida/Splade_PP_en_v2). When set to a string, it expects a local or Hugging Face model path.++It also implicitly disables the [defaults](#defaults) setting for vector search.++## dense+```yaml+dense: boolean|string+```++Alias for the [vector model path](../vectors/#path). When set to `True`, the [default transformers vector model](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2) is used.## hybrid```yaml@@ -18,7 +38,14 @@ hybrid: booleanEnables hybrid (sparse + dense) indexing for this embeddings.-When enabled, this parameter creates a BM25 index for full text search. It has no effect on the [defaults](../vectors/#defaults) or [path](../vectors/#path) settings.+When enabled, this parameter creates a BM25 index for full text search. It has no effect on the [defaults](#defaults) or [path](../vectors/#path) settings.++## defaults+```yaml+defaults: boolean+```++Uses default vector model path when enabled (default setting is True) and `path` is not provided. See [this link](../) for an example.## indexes```yamldiff --git a/docs/embeddings/configuration/scoring.md b/docs/embeddings/configuration/scoring.mdindex 0cd97f6e..945df33f 100644--- a/docs/embeddings/configuration/scoring.md+++ b/docs/embeddings/configuration/scoring.md@@ -12,7 +12,7 @@ The following covers the available options.## method```yaml-method: bm25|tfidf|sif|pgtext|custom+method: bm25|tfidf|sif|pgtext|sparse|custom```Sets the scoring method. Add custom scoring via setting this parameter to the fully resolvable class string.@@ -25,6 +25,17 @@ schema: database schema to store keyword index - defaults to beingAdditional settings for Postgres full-text keyword indexes.+### sparse+```yaml+path: sparse vector model path+gpu: boolean|int|string|device+encodebatch: int+modelargs: additional model init args+encodeargs: additional encode() args+```++Sparse vector scoring options.+## terms```yamlterms: boolean|dictdiff --git a/docs/embeddings/configuration/vectors.md b/docs/embeddings/configuration/vectors.mdindex 519322b6..e4c10175 100644--- a/docs/embeddings/configuration/vectors.md+++ b/docs/embeddings/configuration/vectors.md@@ -10,13 +10,6 @@ path: stringSets the path for a vectors model. When using a transformers/sentence-transformers model, this can be any model on the[Hugging Face Hub](https://huggingface.co/models) or a local file path. Otherwise, it must be a local file path to a word embeddings model.-## defaults-```yaml-defaults: boolean-```--Uses default vector model path when enabled (default setting is True) and `path` is not provided. See [this link](../) for an example.-## method```yamlmethod: transformers|sentence-transformers|llama.cpp|litellm|model2vec|external|wordsdiff --git a/docs/embeddings/indexing.md b/docs/embeddings/indexing.mdindex 8a5c0f07..c651d24d 100644--- a/docs/embeddings/indexing.md+++ b/docs/embeddings/indexing.md@@ -112,7 +112,7 @@ Graphs are persisted alongside an embeddings index. Each save and load will also## Sparse vectors-Scoring instances can create a standalone [keyword](../configuration/general#keyword) or sparse index (BM25, TF-IDF). This enables [hybrid](../configuration/general/#hybrid) search when there is an available dense vector index.+Scoring instances can create a standalone [sparse keyword indexes](../configuration/general#keyword) (BM25, TF-IDF) and [sparse vector indexes](../configuration/general#sparse) (SPLADE). This enables [hybrid](../configuration/general/#hybrid) search when there is an available dense vector index.The terms `sparse vector index`, `keyword index`, `terms index` and `scoring index` are used interchangeably throughout txtai's documentation.diff --git a/src/python/txtai/embeddings/base.py b/src/python/txtai/embeddings/base.pyindex be49cc6e..8868503f 100644--- a/src/python/txtai/embeddings/base.py+++ b/src/python/txtai/embeddings/base.py@@ -813,20 +813,44 @@ class Embeddings:self.config = self.config if self.config else {}# Expand sparse index shortcuts- if not self.config.get("scoring") and any(self.config.get(key) for key in ["keyword", "hybrid"]):- self.config["scoring"] = {"method": "bm25", "terms": True, "normalize": True}+ if not self.config.get("scoring") and any(self.config.get(key) for key in ["keyword", "sparse", "hybrid"]):+ self.defaultsparse()# Expand graph shortcutsif self.config.get("graph") is True:self.config["graph"] = {}# Check if default model should be loaded- if not self.model and self.defaultallowed():+ if not self.model and (self.defaultallowed() or self.config.get("dense")):self.config["path"] = "sentence-transformers/all-MiniLM-L6-v2"# Load dense vectors modelself.model = self.loadvectors()+ def defaultsparse(self):+ """+ Logic to derive default sparse index configuration.+ """++ # Get sparse index configuration+ index, method = None, None+ for x in ["keyword", "sparse", "hybrid"]:+ value = self.config.get(x)+ if value:+ index, method = (x, value if isinstance(value, str) else "bm25")++ # Default scoring configuration+ self.config["scoring"] = {"method": method, "terms": True, "normalize": True}++ # Sparse vector models+ if index == "sparse" or "/" in method:+ # Derive sparse model path+ path = self.config["sparse"] if index == "sparse" else method+ path = path if isinstance(path, str) else "prithivida/Splade_PP_en_v2"++ # Merge in sparse parameters+ self.config["scoring"] = {**self.config["scoring"], **{"method": "sparse", "path": path}}+def defaultallowed(self):"""Tests if this embeddings instance can use a default model if not otherwise provided.@@ -835,7 +859,7 @@ class Embeddings:True if a default model is allowed, False otherwise"""- params = [("keyword", False), ("defaults", True)]+ params = [("keyword", False), ("sparse", False), ("defaults", True)]return all(self.config.get(key, default) == default for key, default in params)def loadvectors(self):@@ -850,6 +874,11 @@ class Embeddings:if "indexes" in self.config and self.models is None:self.models = {}+ # Support path via dense parameter+ dense = self.config.get("dense")+ if not self.config.get("path") and dense and isinstance(dense, str):+ self.config["path"] = dense+# Load vector modelreturn VectorsFactory.create(self.config, self.scoring, self.models)@@ -1018,7 +1047,7 @@ class Embeddings:# Create configuration with custom columns, if necessaryconfig = self.columns(config)- return ScoringFactory.create(config)+ return ScoringFactory.create(config, self.models)return Nonediff --git a/src/python/txtai/scoring/factory.py b/src/python/txtai/scoring/factory.pyindex 0246ec4c..868db626 100644--- a/src/python/txtai/scoring/factory.py+++ b/src/python/txtai/scoring/factory.py@@ -5,8 +5,9 @@ Factory modulefrom ..util import Resolverfrom .bm25 import BM25-from .sif import SIFfrom .pgtext import PGText+from .sif import SIF+from .sparse import Sparsefrom .tfidf import TFIDF@@ -16,12 +17,13 @@ class ScoringFactory:"""@staticmethod- def create(config):+ def create(config, models=None):"""Factory method to construct a Scoring instance.Args:config: scoring configuration parameters - supports bm25, sif, tfidf+ models: models cacheReturns:Scoring@@ -39,10 +41,12 @@ class ScoringFactory:if method == "bm25":scoring = BM25(config)- elif method == "sif":- scoring = SIF(config)elif method == "pgtext":scoring = PGText(config)+ elif method == "sif":+ scoring = SIF(config)+ elif method == "sparse":+ scoring = Sparse(config, models)elif method == "tfidf":scoring = TFIDF(config)else:diff --git a/src/python/txtai/scoring/sparse.py b/src/python/txtai/scoring/sparse.pynew file mode 100644index 00000000..3b1396cb--- /dev/null+++ b/src/python/txtai/scoring/sparse.py@@ -0,0 +1,194 @@+"""+Sparse module+"""++import numpy as np+import torch++# Conditional import+try:+ from sentence_transformers import SparseEncoder++ SPARSE = True+except ImportError:+ SPARSE = False++from ..models import Models++from .base import Scoring+++class Sparse(Scoring):+ """+ Sparse vector scoring.+ """++ def __init__(self, config=None, models=None):+ super().__init__(config)++ if not SPARSE:+ raise ImportError('Sparse encoder is not available - install "scoring" extra to enable')++ # Models cache+ self.models = models++ # Pool parameter+ self.pool = None++ # Sparse encoder+ self.model = self.loadmodel()++ # Encode batch size - controls underlying model batch size when encoding vectors+ self.encodebatch = config.get("encodebatch", 32)++ # Sparse data backend+ self.backend = None++ # Deleted rows+ self.deletes = []++ def insert(self, documents, index=None):+ data = []+ for _, document, _ in documents:+ # Extract text, if necessary+ if isinstance(document, dict):+ document = document.get(self.text, document.get(self.object))++ if document is not None:+ # Add data+ data.append(" ".join(document) if isinstance(document, list) else document)++ # Encode batch and append to data+ data = self.encode(data)+ self.backend = torch.cat((self.backend, data)) if self.backend is not None else data++ def delete(self, ids):+ self.deletes.append(ids)++ def weights(self, tokens):+ # Not supported+ return None++ def search(self, query, limit=3):+ return self.batchsearch([query], limit)[0]++ def batchsearch(self, queries, limit=3, threads=True):+ queries = self.encode(queries)+ scores = self.model.similarity(queries, self.backend).cpu().numpy()++ # Clear deletes+ scores[:, self.deletes] = 0++ # Get top n scores+ indices = np.argpartition(-scores, limit if limit < scores.shape[0] else scores.shape[0] - 1)[:, :limit]+ scores = np.clip(np.take_along_axis(scores, indices, axis=1), 0.0, 1.0)++ # Get top n results+ results = []+ for x, index in enumerate(indices):+ results.append(list(zip(index.tolist(), scores[x].tolist())))++ return results++ def count(self):+ return self.backend.shape[0] - len(self.deletes) if self.backend is not None else 0++ def load(self, path):+ with open(path, "rb") as f:+ # Load sparse index+ indices, values, size = np.load(f), np.load(f), np.load(f)++ # Load deletes+ self.deletes = np.load(f).tolist()++ # Create backend - load on same device as model+ self.backend = torch.sparse_coo_tensor(indices, values, size=torch.Size(size), device=self.model.device)++ def save(self, path):+ if self.backend is not None:+ with open(path, "wb") as f:+ # Save sparse index+ data = self.backend.coalesce().cpu()+ np.save(f, data.indices())+ np.save(f, data.values())+ np.save(f, data.size())++ # Save deletes+ np.save(f, np.array(self.deletes))++ def close(self):+ # Close pool before model is closed+ if self.pool:+ self.model.stop_multi_process_pool(self.pool)+ self.pool = None++ self.model, self.backend = None, None++ def hasterms(self):+ return True++ def isnormalized(self):+ return True++ def loadmodel(self):+ """+ Loads the sparse encoder model.++ Returns:+ SparseEncoder+ """++ # Model path+ path = self.config.get("path")++ # Check if model is cached+ if self.models and path in self.models:+ return self.models[path]++ # Get target device+ gpu, pool = self.config.get("gpu", True), False++ # Default mode uses a single GPU. Setting to all spawns a process per GPU.+ if isinstance(gpu, str) and gpu == "all":+ # Get number of accelerator devices available+ devices = Models.acceleratorcount()++ # Enable multiprocessing pooling only when multiple devices are available+ gpu, pool = devices <= 1, devices > 1++ # Tensor device id+ deviceid = Models.deviceid(gpu)++ # Additional model arguments+ modelargs = self.config.get("modelargs", {})++ # Build embeddings with sentence-transformers+ model = SparseEncoder(path, device=Models.device(deviceid), similarity_fn_name="cosine", **modelargs)++ # Start process pool for multiple GPUs+ if pool:+ self.pool = model.start_multi_process_pool()++ # Store model in cache+ if self.models is not None and path:+ self.models[path] = model++ # Return model+ return model++ def encode(self, data):+ """+ Encodes a batch of data using the Sparse Encoder model.++ Args:+ data: input data++ Returns:+ encoded data+ """++ # Additional encoding arguments+ encodeargs = self.config.get("encodeargs", {})++ # Encode data+ return self.model.encode(data, pool=self.pool, batch_size=self.encodebatch, **encodeargs)diff --git a/test/python/testembeddings.py b/test/python/testembeddings.pyindex 86b07a9c..8e70bdf5 100644--- a/test/python/testembeddings.py+++ b/test/python/testembeddings.py@@ -124,6 +124,17 @@ class TestEmbeddings(unittest.TestCase):self.assertEqual(self.embeddings.count(), 5)self.assertEqual(uid, 5)+ def testDense(self):+ """+ Test dense alias+ """++ # Dense flag is an alias for path+ embeddings = Embeddings(dense="sentence-transformers/nli-mpnet-base-v2")+ embeddings.index([(uid, text, None) for uid, text in enumerate(self.data)])++ self.assertEqual(embeddings.count(), 6)+def testEmpty(self):"""Test empty index@@ -314,7 +325,7 @@ class TestEmbeddings(unittest.TestCase):# Build data arraydata = [(uid, text, None) for uid, text in enumerate(self.data)]- # Index data with sparse + dense vectors+ # Index data with sparse keyword vectorsembeddings = Embeddings({"keyword": True})embeddings.index(data)@@ -445,6 +456,45 @@ class TestEmbeddings(unittest.TestCase):self.assertEqual(uid, 4)+ def testSparse(self):+ """+ Test sparse vector search+ """++ # Build data array+ data = [(uid, text, None) for uid, text in enumerate(self.data)]++ # Index data with sparse vectors+ embeddings = Embeddings({"sparse": "sparse-encoder-testing/splade-bert-tiny-nq"})+ embeddings.index(data)++ # Run search+ uid = embeddings.search("lottery ticket", 1)[0][0]+ print(uid)+ self.assertEqual(uid, 4)++ # Test count method+ self.assertEqual(embeddings.count(), len(data))++ # Generate temp file path+ index = os.path.join(tempfile.gettempdir(), "embeddings.sparse")++ # Test load/save+ embeddings.save(index)+ embeddings.load(index)++ # Run search+ uid = embeddings.search("lottery ticket", 1)[0][0]+ self.assertEqual(uid, 4)++ # Update data+ data[0] = (0, "Feel good story: baby panda born", None)+ embeddings.upsert([data[0]])++ # Search for best match+ uid = embeddings.search("feel good story", 1)[0][0]+ self.assertEqual(uid, 0)+def testSubindex(self):"""Test subindexdiff --git a/test/python/testoptional.py b/test/python/testoptional.pyindex 84c7551f..6934b1e0 100644--- a/test/python/testoptional.py+++ b/test/python/testoptional.py@@ -298,6 +298,9 @@ class TestOptional(unittest.TestCase):with self.assertRaises(ImportError):ScoringFactory.create({"method": "pgtext"})+ with self.assertRaises(ImportError):+ ScoringFactory.create({"method": "sparse"})+def testVectors(self):"""Test missing vector dependenciesdiff --git a/test/python/testscoring.py b/test/python/testscoring.pyindex 11c54e77..ace10806 100644--- a/test/python/testscoring.py+++ b/test/python/testscoring.py@@ -11,6 +11,7 @@ from unittest.mock import patchfrom txtai.scoring import ScoringFactory, Scoring+# pylint: disable=R0904class TestScoring(unittest.TestCase):"""Scoring tests.@@ -122,6 +123,61 @@ class TestScoring(unittest.TestCase):self.runTests("sif")+ @patch("torch.cuda.device_count")+ def testSparse(self, count):+ """+ Test sparse vectors+ """++ # Mock accelerator count+ count.return_value = 1++ # Models cache+ models = {}++ # Test sparse scoring+ scoring = ScoringFactory.create({"method": "sparse", "path": "sparse-encoder-testing/splade-bert-tiny-nq"}, models=models)+ scoring.index((uid, {"text": text}, tags) for uid, text, tags in self.data)++ # Run search and validate correct result returned+ index, _ = scoring.search("lottery ticket", 1)[0]+ self.assertEqual(index, 4)++ # Run batch search+ index, _ = scoring.batchsearch(["lottery ticket"], 1)[0][0]+ self.assertEqual(index, 4)++ # Validate count+ self.assertEqual(scoring.count(), len(self.data))++ # Test delete+ scoring.delete([4])+ self.assertEqual(scoring.count(), len(self.data) - 1)++ # Run search after delete+ index, _ = scoring.search("lottery ticket", 1)[0]+ self.assertEqual(index, 5)++ # Sparse vectors is a normalized terms index+ self.assertTrue(scoring.hasterms() and scoring.isnormalized())+ self.assertIsNone(scoring.weights("This is a test".split()))++ # Close scoring+ scoring.close()++ # Mock accelerator count+ count.return_value = 2++ # Test multiple gpus+ scoring = ScoringFactory.create({"method": "sparse", "path": "sparse-encoder-testing/splade-bert-tiny-nq", "gpu": "all"})+ self.assertIsNotNone(scoring)+ scoring.close()++ # Test model caching+ scoring = ScoringFactory.create({"method": "sparse", "path": "sparse-encoder-testing/splade-bert-tiny-nq"}, models=models)+ self.assertIsNotNone(scoring.model)+ scoring.close()+def testTFIDF(self):"""Test tfidf