Skip to content

armgit / txtai

Public Imported from GitHub
0

💡 All-in-one AI framework for semantic search, LLM orchestration and language model workflows

Change sparse vector normalization logic, closes #946

davidmezzettib53c966fa7df
diff --git a/docs/embeddings/configuration/scoring.md b/docs/embeddings/configuration/scoring.md
index 2c579d12..2b4eef25 100644
--- a/docs/embeddings/configuration/scoring.md
+++ b/docs/embeddings/configuration/scoring.md
@@ -29,7 +29,9 @@ Additional settings for Postgres full-text keyword indexes.
```yaml
path: sparse vector model path
vectormethod: vector embeddings method
+vectornormalize: enable vector embeddings normalization (boolean)
gpu: boolean|int|string|device
+normalize: enable score normalization (boolean | float)
batch: Sets the transform batch size
encodebatch: Sets the encode batch size
vectors: additional model init args
@@ -37,14 +39,20 @@ encodeargs: additional encode() args
backend: ivfsparse|pgsparse
```
-Sparse vector scoring options. The sparse scoring instance combines a sparse vector model with a sparse approximate nearest neighbor index (ANN).
+Sparse vector scoring options. The sparse scoring instance combines a sparse vector model with a sparse approximate nearest neighbor index (ANN). This method supports both vector normalization and score normalization.
+
+Vector normalization normalizes all vectors to have a magnitude of 1. By extension, all generated scores will be 0 to 1.
+
+Score normalization scales output scores by a scale factor. When `normalize` is set to `True` it uses a default scale factor. If `normalize` is an integer, then that is used as the scale factor. This scales the scores from 0 to 1.
#### ivfsparse
```yaml
ivfsparse:
sample: percent of data to use for model training (0.0 - 1.0)
+ nfeatures: top n features to use for model training (int)
nlist: desired number of clusters (int)
nprobe: search probe setting (int)
+ minpoints: minimum number of points for a cluster (int)
```
Inverted file (IVF) index with flat vector file storage and sparse array support.
diff --git a/src/python/txtai/ann/sparse/ivfsparse.py b/src/python/txtai/ann/sparse/ivfsparse.py
index 54351ee3..0824417e 100644
--- a/src/python/txtai/ann/sparse/ivfsparse.py
+++ b/src/python/txtai/ann/sparse/ivfsparse.py
@@ -212,16 +212,15 @@ class IVFSparse(ANN):
kmeans = MiniBatchKMeans(n_clusters=clusters, random_state=0, n_init=5).fit(data)
# Find closest points to each cluster center and use those as centroids
- # Filter out duplicate centroids
- indices, _ = pairwise_distances_argmin_min(kmeans.cluster_centers_, data, metric="cosine")
+ indices, _ = pairwise_distances_argmin_min(kmeans.cluster_centers_, data, metric="l2")
- # Return cluster centroids
+ # Filter out duplicate centroids and return cluster centroids
return train[np.unique(indices)]
def aggregate(self, data):
"""
Aggregates input data array into clusters. This method sorts each data element into the
- cluster with the highest cosine similarity centroid.
+ cluster with the highest L2 similarity centroid.
Args:
data: input data
@@ -235,7 +234,7 @@ class IVFSparse(ANN):
return {0: list(range(data.shape[0]))}
# Map data to closest centroids
- indices, _ = pairwise_distances_argmin_min(data, self.centroids, metric="cosine")
+ indices, _ = pairwise_distances_argmin_min(data, self.centroids, metric="l2")
# Sort into clusters
ids = {}
@@ -262,7 +261,7 @@ class IVFSparse(ANN):
list of matching (indices, scores)
"""
- # Dot product similarity (assumes all data is normalized)
+ # Dot product similarity
scores = safe_sparse_dot(queries, data.T, dense_output=True)
# Clear deletes
@@ -271,7 +270,7 @@ class IVFSparse(ANN):
# Get top n matching indices and 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)
+ scores = np.take_along_axis(scores, indices, axis=1)
return indices, scores
diff --git a/src/python/txtai/scoring/sparse.py b/src/python/txtai/scoring/sparse.py
index 717a0909..4f0c7357 100644
--- a/src/python/txtai/scoring/sparse.py
+++ b/src/python/txtai/scoring/sparse.py
@@ -23,13 +23,19 @@ class Sparse(Scoring):
super().__init__(config)
# Vector configuration
- config = {k: v for k, v in config.items() if k != "method"}
- if "vectormethod" in config:
- config["method"] = config["vectormethod"]
+ mapping = {"vectormethod": "method", "vectornormalize": "normalize"}
+ config = {k: v for k, v in config.items() if k not in mapping.values()}
+ for k, v in mapping.items():
+ if k in config:
+ config[v] = config[k]
# Load the SparseVectors model
self.model = SparseVectorsFactory.create(config, models)
+ # Normalize search outputs if vectors are not normalized already
+ # A float can also be provided to set the normalization factor (defaults to 30.0)
+ self.isnormalize = self.config.get("normalize", True)
+
# Sparse ANN
self.ann = None
@@ -93,7 +99,10 @@ class Sparse(Scoring):
embeddings = self.model.batchtransform((None, query, None) for query in queries)
# Run ANN search
- return self.ann.search(embeddings, limit)
+ scores = self.ann.search(embeddings, limit)
+
+ # Normalize scores if normalization IS enabled AND vector normalization IS NOT enabled
+ return self.normalize(embeddings, scores) if self.isnormalize and not self.model.isnormalize else scores
def count(self):
return self.ann.count()
@@ -119,7 +128,7 @@ class Sparse(Scoring):
return True
def isnormalized(self):
- return True
+ return self.isnormalize or self.model.isnormalize
def start(self, checkpoint):
"""
@@ -179,3 +188,31 @@ class Sparse(Scoring):
while batch != Sparse.COMPLETE:
yield from batch
batch = self.queue.get()
+
+ def normalize(self, queries, scores):
+ """
+ Normalize query result using the max query score.
+
+ Args:
+ queries: query vectors
+ scores: query results
+
+ Returns:
+ normalized query results
+ """
+
+ # Get normalize scale factor
+ scale = 30.0 if isinstance(self.isnormalize, bool) else self.isnormalize
+
+ # Normalize scores using max scores
+ maxscores = self.model.dot(queries, queries)
+
+ # Normalize results and return
+ results = []
+ for x, result in enumerate(scores):
+ maxscore = max(maxscores[x][x] / scale, scale)
+ maxscore = max(maxscore, result[0][1]) if result else maxscore
+
+ results.append([(uid, score / maxscore) for uid, score in result])
+
+ return results
diff --git a/src/python/txtai/vectors/sparse/base.py b/src/python/txtai/vectors/sparse/base.py
index 11736919..b0be71c0 100644
--- a/src/python/txtai/vectors/sparse/base.py
+++ b/src/python/txtai/vectors/sparse/base.py
@@ -29,6 +29,9 @@ class SparseVectors(Vectors):
super().__init__(config, scoring, models)
+ # Get normalization setting
+ self.isnormalize = self.config.get("normalize", self.defaultnormalize()) if self.config else None
+
def encode(self, data, category=None):
# Encode data to embeddings
embeddings = super().encode(data, category)
@@ -69,8 +72,19 @@ class SparseVectors(Vectors):
raise ValueError("Truncate is not supported for sparse vectors")
def normalize(self, embeddings):
- # Normalize in place using method that supports sparse vectors
- return normalize(embeddings, copy=False)
+ # Optionally normalize embeddings using method that supports sparse vectors
+ return normalize(embeddings, copy=False) if self.isnormalize else embeddings
def quantize(self, embeddings):
raise ValueError("Quantize is not supported for sparse vectors")
+
+ def defaultnormalize(self):
+ """
+ Returns the default normalization setting.
+
+ Returns:
+ default normalization setting
+ """
+
+ # Sparse vector embeddings typically perform better as unnormalized
+ return False
diff --git a/src/python/txtai/vectors/sparse/sbert.py b/src/python/txtai/vectors/sparse/sbert.py
index 4c76e0a6..b387ffc4 100644
--- a/src/python/txtai/vectors/sparse/sbert.py
+++ b/src/python/txtai/vectors/sparse/sbert.py
@@ -28,3 +28,7 @@ class SparseSTVectors(SparseVectors, STVectors):
def loadencoder(self, path, device, **kwargs):
return SparseEncoder(path, device=device, **kwargs)
+
+ def defaultnormalize(self):
+ # Enable normalization by default if similarity function is cosine
+ return self.model and self.model.similarity_fn_name == "cosine"
diff --git a/test/python/testscoring/testsparse.py b/test/python/testscoring/testsparse.py
index 7471b212..329429e2 100644
--- a/test/python/testscoring/testsparse.py
+++ b/test/python/testscoring/testsparse.py
@@ -29,7 +29,6 @@ class TestSparse(unittest.TestCase):
"Beijing mobilises invasion craft along coast as Taiwan tensions escalate",
"The National Park Service warns against sacrificing slower friends in a bear attack",
"Maine man wins $1M from $25 lottery ticket",
- "wins wins wins",
"Make huge profits without work, earn up to $100,000 a day",
]
diff --git a/test/python/testvectors/testsparse/testvectors.py b/test/python/testvectors/testsparse/testvectors.py
index 63e18ade..6fc114aa 100644
--- a/test/python/testvectors/testsparse/testvectors.py
+++ b/test/python/testvectors/testsparse/testvectors.py
@@ -21,6 +21,14 @@ class TestSparseVectors(unittest.TestCase):
SparseVectorsFactory.create({"method": "txtai.vectors.SparseSTVectors", "path": "sparse-encoder-testing/splade-bert-tiny-nq"})
)
+ def testDefaultNormalize(self):
+ """
+ Test defaultnormalize method
+ """
+
+ vectors = SparseVectors(None, None, None)
+ self.assertFalse(vectors.defaultnormalize())
+
def testNotSupported(self):
"""
Test exceptions for unsupported methods