💡 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
Better default ANN parameters, closes #174
davidmezzetti9ca366398906
diff --git a/docs/embeddings.md b/docs/embeddings.mdindex 3a403e24..aeee6afb 100644--- a/docs/embeddings.md+++ b/docs/embeddings.md@@ -1,5 +1,5 @@# Embeddings-An Embeddings instance is the engine that provides similarity search. Embeddings can be used to run ad-hoc similarity comparisions or build/search large indices.+Embeddings is the engine that delivers semantic search. Text is transformed into embeddings vectors where similar concepts will produce similar vectors. Indexes both large and small are built with these vectors. The indexes are used find results that have the same meaning, not necessarily the same keywords.Embeddings parameters are set through the constructor. Examples below.@@ -29,7 +29,7 @@ Sentence embeddings method to use. Options listed below.#### transformersBuilds sentence embeddings using a transformers model. While this can be any transformers model, it works best with-[models trained](https://huggingface.co/models?search=sentence-transformers) to build sentence embeddings.+[models trained](https://huggingface.co/models?pipeline_tag=sentence-similarity) to build sentence embeddings.#### sentence-transformers@@ -53,7 +53,7 @@ Required field that sets the path for a vectors model. When using a transformers### backend```yaml-backend: faiss|annoy|hnsw+backend: faiss|hnsw|annoy```Approximate Nearest Neighbor (ANN) index backend for storing generated sentence embeddings. Defaults to Faiss. Additional backends require the@@ -64,20 +64,16 @@ Backend-specific settings are set with a corresponding configuration object havi### faiss```yamlfaiss:- components: Comma separated list of components - defaults to None- nprobe: search probe setting (int) - defaults to 6+ components: Comma separated list of components - defaults to "Flat" for small indices and "IVFx,Flat" for larger indexes where x = 4 * sqrt(embeddings count)+ nprobe: search probe setting (int) - defaults to x/16 (as defined above) for larger indexes```-See Faiss documentation on the [index factory](https://github.com/facebookresearch/faiss/wiki/The-index-factory) and [search](https://github.com/facebookresearch/faiss/wiki/Faster-search) for more information on these parameters.+See the following Faiss documentation links for more information.-### annoy-```yaml-annoy:- ntrees: number of trees (int) - defaults to 10- searchk: search_k search setting (int) - defaults to -1-```--See [Annoy documentation](https://github.com/spotify/annoy#full-python-api) for more information on these parameters.+- [Guidelines for choosing an index](https://github.com/facebookresearch/faiss/wiki/Guidelines-to-choose-an-index)+- [Index configuration summary](https://github.com/facebookresearch/faiss/wiki/Faiss-indexes)+- [Index Factory](https://github.com/facebookresearch/faiss/wiki/The-index-factory)+- [Search Tuning](https://github.com/facebookresearch/faiss/wiki/Faster-search)### hnsw```yaml@@ -90,6 +86,15 @@ hnsw:See [Hnswlib documentation](https://github.com/nmslib/hnswlib/blob/master/ALGO_PARAMS.md) for more information on these parameters.+### annoy+```yaml+annoy:+ ntrees: number of trees (int) - defaults to 10+ searchk: search_k search setting (int) - defaults to -1+```++See [Annoy documentation](https://github.com/spotify/annoy#full-python-api) for more information on these parameters. Note that annoy indexes can not be modified after creation, upserts/deletes and other modifications are not supported.+### quantize```yamlquantize: booleandiff --git a/src/python/txtai/ann/annoy.py b/src/python/txtai/ann/annoy.pyindex 8af3293c..89e50bbe 100644--- a/src/python/txtai/ann/annoy.py+++ b/src/python/txtai/ann/annoy.py@@ -35,7 +35,11 @@ class Annoy(ANN):self.model.add_item(x, embeddings[x])# Build index- self.model.build(self.setting("ntrees", 10))+ ntrees = self.setting("ntrees", 10)+ self.model.build(ntrees)++ # Add index build metadata+ self.metadata({"ntrees": ntrees})def search(self, queries, limit):# Lookup search k settingdiff --git a/src/python/txtai/ann/faiss.py b/src/python/txtai/ann/faiss.pyindex ad59a576..05fa93f2 100644--- a/src/python/txtai/ann/faiss.py+++ b/src/python/txtai/ann/faiss.py@@ -2,6 +2,8 @@Faiss module"""+import math+import numpy as npfrom faiss import index_factory, METRIC_INNER_PRODUCT, read_index, write_index@@ -19,17 +21,8 @@ class Faiss(ANN):self.model = read_index(path)def index(self, embeddings):- # Lookup components setting- components = self.setting("components")-- # Create embeddings index. Inner product is equal to cosine similarity on normalized vectors.- if components:- params = components- elif self.config.get("quantize"):- params = "IVF100,SQ8" if embeddings.shape[0] >= 5000 else "IDMap,SQ8"- else:- params = "IVF100,Flat" if embeddings.shape[0] >= 5000 else "IDMap,Flat"-+ # Configure embeddings index. Inner product is equal to cosine similarity on normalized vectors.+ params = self.configure(embeddings.shape[0])self.model = index_factory(embeddings.shape[1], params, METRIC_INNER_PRODUCT)# Train model@@ -38,8 +31,9 @@ class Faiss(ANN):# Add embeddings - position in embeddings is used as the idself.model.add_with_ids(embeddings, np.arange(embeddings.shape[0], dtype=np.int64))- # Update id offset+ # Add id offset and index build metadataself.config["offset"] = embeddings.shape[0]+ self.metadata({"components": params})def append(self, embeddings):new = embeddings.shape[0]@@ -56,7 +50,7 @@ class Faiss(ANN):def search(self, queries, limit):# Run the query- self.model.nprobe = self.setting("nprobe", 6)+ self.model.nprobe = self.nprobe()scores, ids = self.model.search(queries, limit)# Map results to [(id, score)]@@ -72,3 +66,58 @@ class Faiss(ANN):def save(self, path):# Write indexwrite_index(self.model, path)++ def configure(self, count):+ """+ Configures settings for a new index.++ Args:+ count: initial number of embeddings rows++ Returns:+ user-specified or generated components setting+ """++ # Lookup components setting+ components = self.setting("components")++ if components:+ return components++ # Get storage setting+ storage = "SQ8" if self.config.get("quantize") else "Flat"++ # Small index, use storage directly with IDMap+ if count <= 5000:+ return f"IDMap,{storage}"++ x = self.cells(count)+ components = f"IVF{x},{storage}"++ return components++ def cells(self, count):+ """+ Calculates the number of IVF cells for an IVF index.++ Args:+ count: number of embeddings rows++ Returns:+ number of IVF cells+ """++ # Calculate number of IVF cells where x = min(4 * sqrt(embeddings count), embeddings count / 39)+ # Faiss requires at least 39 * x data points+ return min(round(4 * math.sqrt(count)), int(count / 39))++ def nprobe(self):+ """+ Gets or derives the nprobe search parameter+ """++ # Get size of embeddings index+ count = self.count()++ default = 6 if count <= 5000 else round(self.cells(count) / 16)+ return self.setting("nprobe", default)diff --git a/src/python/txtai/ann/hnsw.py b/src/python/txtai/ann/hnsw.pyindex 540e1d1f..2436cb28 100644--- a/src/python/txtai/ann/hnsw.py+++ b/src/python/txtai/ann/hnsw.py@@ -42,9 +42,10 @@ class HNSW(ANN):# Add items - position in embeddings is used as the idself.model.add_items(embeddings, np.arange(embeddings.shape[0]))- # Update id offset and set delete counter+ # Add id offset, delete counter and index build metadataself.config["offset"] = embeddings.shape[0]self.config["deletes"] = 0+ self.metadata({"efconstruction": efconstruction, "m": m, "seed": seed})def append(self, embeddings):new = embeddings.shape[0]