💡 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 ability to merge late interaction vectors into fixed dimensional MUVERA vectors, closes #952
davidmezzetti0e54ad3c3f9b
diff --git a/src/python/txtai/models/pooling/base.py b/src/python/txtai/models/pooling/base.pyindex 44804c7a..e0f57987 100644--- a/src/python/txtai/models/pooling/base.py+++ b/src/python/txtai/models/pooling/base.py@@ -42,13 +42,14 @@ class Pooling(nn.Module):# Move to deviceself.to(self.device)- def encode(self, documents, batch=32):+ def encode(self, documents, batch=32, category=None):"""Builds an array of pooled embeddings for documents.Args:documents: list of documents used to build embeddingsbatch: model batch size+ category: embeddings category (query or data)Returns:pooled embeddings@@ -57,6 +58,9 @@ class Pooling(nn.Module):# Split documents into batches and processresults = []+ # Apply pre encoding transformation logic+ documents = self.preencode(documents, category)+# Sort document indices from largest to smallest to enable efficient batching# This performance tweak matches logic in sentence-transformerslengths = np.argsort([-len(x) if x else 0 for x in documents])@@ -74,10 +78,10 @@ class Pooling(nn.Module):outputs = self.forward(**inputs)# Add batch result- results.extend(outputs.cpu().numpy())+ results.extend(outputs.cpu().to(torch.float32).numpy())# Apply post encoding transformation logic- results = self.postencode(results)+ results = self.postencode(results, category)# Restore original order and return arrayreturn np.asarray([results[x] for x in np.argsort(lengths)])@@ -109,12 +113,26 @@ class Pooling(nn.Module):return self.model(**inputs)[0]- def postencode(self, results):+ # pylint: disable=W0613+ def preencode(self, documents, category):+ """+ Applies pre encoding transformation logic.++ Args:+ documents: list of documents used to build embeddings+ category: embeddings category (query or data)+ """++ return documents++ # pylint: disable=W0613+ def postencode(self, results, category):"""Applies post encoding transformation logic.Args:results: list of results+ category: embeddings category (query or data)Returns:results with transformation logic applieddiff --git a/src/python/txtai/models/pooling/factory.py b/src/python/txtai/models/pooling/factory.pyindex 9501683c..906a30ad 100644--- a/src/python/txtai/models/pooling/factory.py+++ b/src/python/txtai/models/pooling/factory.py@@ -43,8 +43,8 @@ class PoolingFactory:if isinstance(path, bytes) or (isinstance(path, str) and os.path.isfile(path)) or method == "pooling":return Pooling(path, device, tokenizer, maxlength, modelargs)- # Derive pooling method if it's not specified, path is a string and path is not a local path- if (not method or method not in ("clspooling", "meanpooling", "latepooling")) and (isinstance(path, str) and not os.path.exists(path)):+ # Derive pooling method if it's not specified and path is a string+ if (not method or method not in ("clspooling", "meanpooling", "latepooling")) and isinstance(path, str):method = PoolingFactory.method(path)# Check for cls poolingdiff --git a/src/python/txtai/models/pooling/late.py b/src/python/txtai/models/pooling/late.pyindex 5d65af76..2d1741cd 100644--- a/src/python/txtai/models/pooling/late.py+++ b/src/python/txtai/models/pooling/late.py@@ -13,6 +13,7 @@ from torch import nnfrom transformers.utils import cached_filefrom .base import Pooling+from .muvera import Muveraclass LatePooling(Pooling):@@ -21,6 +22,12 @@ class LatePooling(Pooling):"""def __init__(self, path, device, tokenizer=None, maxlength=None, modelargs=None):+ # Check if fixed dimensional encoder is enabled+ modelargs = modelargs.copy() if modelargs else {}+ muvera = modelargs.pop("muvera", {})+ self.encoder = Muvera(**muvera) if muvera is not None else None++ # Call parent initializationsuper().__init__(path, device, tokenizer, maxlength, modelargs)# Get linear weights path@@ -32,6 +39,9 @@ class LatePooling(Pooling):# Stanford weights formatname = "model.safetensors"+ # Read model settings+ self.qprefix, self.qlength, self.dprefix, self.dlength = self.settings(path, config)+# Load linear layerpath = cached_file(path_or_repo_id=path, filename=name)with safe_open(filename=path, framework="pt") as f:@@ -59,7 +69,33 @@ class LatePooling(Pooling):# Run through final linear layer and returnreturn self.linear(tokens)- def postencode(self, results):+ def preencode(self, documents, category):+ """+ Apply prefixes and lengths to data.++ Args:+ documents: list of documents used to build embeddings+ category: embeddings category (query or data)+ """++ results = []++ # Apply prefix+ for text in documents:+ prefix = self.qprefix if category == "query" else self.dprefix+ if prefix:+ text = f"{prefix}{text}"++ results.append(text)++ # Set maxlength+ maxlength = self.qlength if category == "query" else self.dlength+ if maxlength:+ self.maxlength = maxlength++ return results++ def postencode(self, results, category):"""Normalizes and pads results.@@ -84,7 +120,31 @@ class LatePooling(Pooling):for vectors in results:data.append(np.pad(vectors, [(0, length - vectors.shape[0]), (0, 0)]))- return np.asarray(data)+ # Build NumPy array+ data = np.asarray(data)++ # Apply fixed dimesional encoder, if necessary+ return self.encoder(data, category) if self.encoder else data++ def settings(self, path, config):+ """+ Reads model settings.++ Args:+ path: model path+ config: PyLate model format if provided, otherwise read from Stanford format+ """++ if config:+ # PyLate format+ config = self.load(path, "config_sentence_transformers.json")+ params = ["query_prefix", "query_length", "document_prefix", "document_length"]+ else:+ # Stanford format+ config = self.load(path, "artifact.metadata")+ params = ["query_token_id", "query_maxlen", "doc_token_id", "doc_maxlen"]++ return [config.get(p) for p in params]def load(self, path, name):"""diff --git a/src/python/txtai/models/pooling/muvera.py b/src/python/txtai/models/pooling/muvera.pynew file mode 100644index 00000000..3a59e8ed--- /dev/null+++ b/src/python/txtai/models/pooling/muvera.py@@ -0,0 +1,164 @@+"""+Muvera module+"""++import numpy as np+++class Muvera:+ """+ Implements the MUVERA (Multi-Vector Retrieval via Fixed Dimensional Encodings) algorithm. This reduces late interaction multi-vector+ outputs to a single fixed vector.++ The size of the output vectors are set using the following parameters++ output dimensions = repetitions * 2^hashes * projected++ For example, the default parameters create vectors with the following output dimensions.++ output dimensions = 20 * 2^5 * 16 = 10240++ This code is based on the following:+ - Paper: https://arxiv.org/abs/2405.19504+ - GitHub: https://github.com/google/graph-mining/tree/main/sketching/point_cloud+ - Python port of the original C++ code: https://github.com/sigridjineth/muvera-py+ """++ def __init__(self, repetitions=20, hashes=5, projection=16, seed=42):+ """+ Creates a Muvera instance.++ Args:+ repetitions: number of iterations+ hashes: number of simhash partitions as 2^hashes+ projection: dimensionality reduction, uses an identity projection when set to None+ seed: random seed+ """++ # Number of repetitions+ self.repetitions = repetitions++ # Number of simhash projections+ self.hashes = hashes++ # Optional number of projected dimensions+ self.projection = projection++ # Seed+ self.seed = seed++ def __call__(self, data, category):+ """+ Transforms a list of multi-vector collections into single fixed vector outputs.++ Args:+ data: array of multi-vector vectors+ category: embeddings category (query or data)+ """++ # Get stats+ dimension, length = data[0].shape[1], len(data)++ # Determine projection dimension+ identity = not self.projection+ projection = dimension if identity else self.projection++ # Number of simhash partitions+ partitions = 2**self.hashes++ # Document tracking+ lengths = np.array([len(doc) for doc in data], dtype=np.int32)+ total = np.sum(lengths)+ documents = np.repeat(np.arange(length), lengths)++ # Stack all vectors+ points = np.vstack(data).astype(np.float32)++ # Output vectors+ size = self.repetitions * partitions * projection+ vectors = np.zeros((length, size), dtype=np.float32)++ # Process each repetition+ for number in range(self.repetitions):+ seed = self.seed + number++ # Calculate the simhash+ sketches = points @ self.random(dimension, self.hashes, seed)++ # Dimensionality reduction, if necessary+ projected = points if identity else (points @ self.reducer(dimension, projection, seed))++ # Get partition indices+ bits = (sketches > 0).astype(np.uint32)+ indices = np.zeros(total, dtype=np.uint32)++ # Calculate vector indices+ for x in range(self.hashes):+ indices = (indices << 1) + (bits[:, x] ^ (indices & 1))++ # Initialize storage+ fdesum = np.zeros((length * partitions * projection,), dtype=np.float32)+ counts = np.zeros((length, partitions), dtype=np.int32)++ # Count vectors per partition per document+ np.add.at(counts, (documents, indices), 1)++ # Aggregate vectors using flattened indexing for efficiency+ part = documents * partitions + indices+ base = part * projection++ for d in range(projection):+ flat = base + d+ np.add.at(fdesum, flat, projected[:, d])++ # Reshape for easier manipulation+ # pylint: disable=E1121+ fdesum = fdesum.reshape(length, partitions, projection)++ # Convert sums to averages for data category+ if category == "data":+ # Safe division (avoid divide by zero)+ counts = counts[:, :, np.newaxis]+ np.divide(fdesum, counts, out=fdesum, where=counts > 0)++ # Save results+ start = number * partitions * projection+ vectors[:, start : start + partitions * projection] = fdesum.reshape(length, -1)++ return vectors++ def random(self, dimension, projection, seed):+ """+ Generates a random matrix for simhash projections.++ Args:+ dimensions: number of dimensions for input vectors+ projections: number of projection dimensions+ seed: random seed++ Returns:+ random matrix for simhash projections+ """++ rng = np.random.default_rng(seed)+ return rng.normal(loc=0.0, scale=1.0, size=(dimension, projection)).astype(np.float32)++ def reducer(self, dimension, projection, seed):+ """+ Generates a random matrix for dimensionality reduction using the AMS sketch algorithm.++ Args:+ dimension: number of input dimensions+ projected: number of dimensions to project inputs to++ Returns:+ Dimensionality reduced matrix+ """++ rng = np.random.default_rng(seed)+ out = np.zeros((dimension, projection), dtype=np.float32)+ indices = rng.integers(0, projection, size=dimension)+ signs = rng.choice([-1.0, 1.0], size=dimension)+ out[np.arange(dimension), indices] = signs++ return outdiff --git a/src/python/txtai/pipeline/text/lateencoder.py b/src/python/txtai/pipeline/text/lateencoder.pyindex 4f264a89..f970df60 100644--- a/src/python/txtai/pipeline/text/lateencoder.py+++ b/src/python/txtai/pipeline/text/lateencoder.py@@ -26,11 +26,11 @@ class LateEncoder(Pipeline):"device": self.device,"tokenizer": kwargs.get("tokenizer"),"maxlength": kwargs.get("maxlength"),- "modelargs": kwargs.get("vectors", {}),+ "modelargs": {**kwargs.get("vectors", {}), **{"muvera": None}},})- def __call__(self, query, texts, limit=None, **kwargs):+ def __call__(self, query, texts, limit=None):"""Computes the similarity between query and list of text. Returns a list of(id, score) sorted by highest score, where id is the index in texts.@@ -51,8 +51,8 @@ class LateEncoder(Pipeline):queries = [query] if isinstance(query, str) else query# Encode text to vectors- queries = torch.from_numpy(self.model.encode(queries)).to(self.device)- data = torch.from_numpy(self.model.encode(texts)).to(self.device)+ queries = self.encode(queries, "query")+ data = self.encode(texts, "data") if isinstance(texts[0], str) else texts# Compute maximum similarity scorescores = []@@ -61,6 +61,20 @@ class LateEncoder(Pipeline):return scores[0] if isinstance(query, str) else scores+ def encode(self, data, category):+ """+ Encodes a batch of data using the underlying model.++ Args:+ data: input data+ category: encoding category++ Returns:+ encoded data+ """++ return torch.from_numpy(self.model.encode(data, category=category)).to(self.device)+def score(self, queries, data, limit):"""Computes the maximum similarity score between query vectors and data vectors.diff --git a/src/python/txtai/vectors/dense/huggingface.py b/src/python/txtai/vectors/dense/huggingface.pyindex bbb563d9..47772f5f 100644--- a/src/python/txtai/vectors/dense/huggingface.py+++ b/src/python/txtai/vectors/dense/huggingface.py@@ -41,4 +41,4 @@ class HFVectors(Vectors):def encode(self, data, category=None):# Encode data using vectors model- return self.model.encode(data, batch=self.encodebatch)+ return self.model.encode(data, batch=self.encodebatch, category=category)diff --git a/test/python/testmodels/testpooling.py b/test/python/testmodels/testpooling.pyindex 8f47e4d5..186e20c8 100644--- a/test/python/testmodels/testpooling.py+++ b/test/python/testmodels/testpooling.py@@ -70,3 +70,20 @@ class TestPooling(unittest.TestCase):{"method": "meanpooling", "path": "flax-sentence-embeddings/multi-qa_v1-MiniLM-L6-cls_dot", "device": self.device})self.assertEqual(type(pooling), MeanPooling)++ def testMuvera(self):+ """+ Test late pooling with MUVERA fixed dimensional encoding+ """++ # Test MUVERA encoding+ for model in ["neuml/colbert-bert-tiny", "neuml/pylate-bert-tiny"]:+ # Test defaults+ pooling = PoolingFactory.create({"path": model, "device": self.device})+ self.assertEqual(pooling.encode(["test"], category="query").shape, (1, 10240))++ # Test custom settings+ pooling = PoolingFactory.create(+ {"path": model, "device": self.device, "modelargs": {"muvera": {"repetitions": 5, "hashes": 2, "projection": 8}}}+ )+ self.assertEqual(pooling.encode(["test"], category="data").shape, (1, 160))