Skip to content

armgit / txtai

Public Imported from GitHub
0

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

feat: add configurable late pooling centering

morgan-coded75b4ce5c7f56
diff --git a/docs/embeddings/configuration/vectors.md b/docs/embeddings/configuration/vectors.md
index d4d4f88a..e9dd56f1 100644
--- a/docs/embeddings/configuration/vectors.md
+++ b/docs/embeddings/configuration/vectors.md
@@ -145,6 +145,27 @@ vectors: dict
Passes these additional parameters to the underlying vector model.
+### center
+```yaml
+center: boolean | dict
+```
+
+Centers normalized late-interaction token vectors and normalizes them again before MUVERA or LEMUR encoding. Centering is applied to
+both query and document vectors. `true` uses document scope and `false` disables centering. When omitted, centering defaults to document
+scope only for late-interaction models that load more than one `torch.nn.Linear` layer; models with zero or one loaded linear layer keep
+their previous output.
+
+Dictionary configuration supports the following scopes:
+
+```yaml
+center:
+ scope: document | batch | collection
+```
+
+`document` subtracts the mean of each document or query independently. `batch` subtracts the mean of all real token rows in the current
+model batch. `collection` requires a caller-provided, one-dimensional mean vector through either `mean` (an array-like value) or `path`
+(a NumPy `.npy` file), but not both. Zero-padding rows are never centered and remain zero.
+
### muvera
```yaml
muvera:
diff --git a/src/python/txtai/models/pooling/late.py b/src/python/txtai/models/pooling/late.py
index 1bb94d1c..b37f5420 100644
--- a/src/python/txtai/models/pooling/late.py
+++ b/src/python/txtai/models/pooling/late.py
@@ -26,6 +26,8 @@ class LatePooling(Pooling):
modelargs = modelargs.copy() if modelargs else {}
muvera = modelargs.pop("muvera", {})
lemur = modelargs.pop("lemur", None)
+ centerconfigured = "center" in modelargs
+ center = modelargs.pop("center", None)
# Call parent initialization
super().__init__(path, device, tokenizer, maxlength, loadprompts, modelargs)
@@ -49,6 +51,10 @@ class LatePooling(Pooling):
# Load linear model
self.linear = self.loadlinear(path, models)
+ # Configure token centering
+ self.center = self.centersettings(center, self.linear, centerconfigured)
+ self.batches = None
+
def forward(self, **inputs):
"""
Runs late pooling on token embeddings.
@@ -60,10 +66,14 @@ class LatePooling(Pooling):
Late pooled embeddings using output token embeddings (i.e. last hidden state)
"""
- # Track true token counts for encoders that can't consume padding
- if getattr(self.encoder, "unpadded", False):
+ # Track true token counts for centering and encoders that can't consume padding
+ if self.center or getattr(self.encoder, "unpadded", False):
self.lengths.extend(inputs["attention_mask"].sum(dim=1).cpu().tolist())
+ # Track model batch boundaries for batch-scoped centering
+ if self.center and self.center["scope"] == "batch":
+ self.batches.append(inputs["attention_mask"].shape[0])
+
# Run through transformers model
tokens = super().forward(**inputs)
@@ -80,9 +90,12 @@ class LatePooling(Pooling):
"""
# Reset true token counts for this encoding pass
- if getattr(self.encoder, "unpadded", False):
+ if self.center or getattr(self.encoder, "unpadded", False):
self.lengths = []
+ if self.center and self.center["scope"] == "batch":
+ self.batches = []
+
results = []
# Apply prefix
@@ -119,8 +132,15 @@ class LatePooling(Pooling):
vectors /= np.linalg.norm(vectors, axis=1)[:, np.newaxis]
data.append(vectors)
+ if self.center:
+ data = self.centerdata(data)
+
return self.encoder(data, category)
+ # Remove model padding before normalization. Padding is restored as exact zeros below.
+ if self.center:
+ results = [vectors[:length] for vectors, length in zip(results, self.lengths)]
+
length = 0
for vectors in results:
# Get max length
@@ -138,9 +158,105 @@ class LatePooling(Pooling):
# Build NumPy array
data = np.asarray(data)
+ # Center true token rows before fixed dimensional encoding
+ if self.center:
+ data = self.centerdata(data)
+
# Apply fixed dimesional encoder, if necessary
return self.encoder(data, category) if self.encoder else data
+ @staticmethod
+ def centersettings(center, linear, configured):
+ """
+ Validates and resolves token centering settings.
+
+ Args:
+ center: token centering configuration
+ linear: loaded linear model
+ configured: whether center was explicitly configured
+
+ Returns:
+ resolved token centering configuration
+ """
+
+ # Enable document centering by default for multi-linear models
+ if not configured:
+ center = sum(isinstance(module, torch.nn.Linear) for module in linear.modules()) > 1
+
+ if isinstance(center, bool):
+ return {"scope": "document"} if center else None
+
+ if not isinstance(center, dict):
+ raise ValueError("center must be a boolean or dictionary")
+
+ center = center.copy()
+ scope = center.pop("scope", "document")
+ if scope not in ("document", "batch", "collection"):
+ raise ValueError("center scope must be one of: document, batch, collection")
+
+ mean = center.pop("mean", None)
+ path = center.pop("path", None)
+ if center:
+ raise ValueError(f"unknown center setting: {next(iter(center))}")
+
+ if scope != "collection" and (mean is not None or path is not None):
+ raise ValueError("center mean and path are only valid with collection scope")
+
+ if scope == "collection":
+ if (mean is None) == (path is None):
+ raise ValueError("collection center scope requires exactly one of mean or path")
+
+ mean = np.load(path, allow_pickle=False) if path is not None else np.asarray(mean)
+ if mean.ndim != 1 or not np.isfinite(mean).all():
+ raise ValueError("collection center mean must be a finite one-dimensional array")
+
+ return {"scope": scope, "mean": mean} if scope == "collection" else {"scope": scope}
+
+ def centerdata(self, data):
+ """
+ Centers and re-normalizes true token rows.
+
+ Args:
+ data: normalized token vectors, with optional zero padding
+
+ Returns:
+ centered token vectors with zero padding preserved
+ """
+
+ array = isinstance(data, np.ndarray)
+ vectors = [np.array(value, copy=True) for value in data]
+ masks = [np.any(value != 0, axis=1) for value in vectors]
+ scope = self.center["scope"]
+
+ means = [None] * len(vectors)
+ if scope == "batch":
+ batches = getattr(self, "batches", None)
+ sizes = batches if batches and sum(batches) == len(vectors) else [len(vectors)]
+ offset = 0
+ for size in sizes:
+ rows = [vectors[x][masks[x]] for x in range(offset, offset + size) if masks[x].any()]
+ mean = np.concatenate(rows).mean(axis=0) if rows else None
+ means[offset : offset + size] = [mean] * size
+ offset += size
+ elif scope == "collection":
+ means = [self.center["mean"]] * len(vectors)
+
+ for x, (value, mask) in enumerate(zip(vectors, masks)):
+ if not mask.any():
+ continue
+
+ current = value[mask]
+ average = current.mean(axis=0) if scope == "document" else means[x]
+ if average is not None and average.shape != (current.shape[1],):
+ raise ValueError("center mean dimension must match token vector dimension")
+
+ current = current - average
+ norms = np.linalg.norm(current, axis=1, keepdims=True)
+ current = np.divide(current, norms, out=np.zeros_like(current), where=norms != 0)
+ vectors[x][mask] = current
+
+ return np.asarray(vectors) if array else vectors
+
def settings(self, path, config):
"""
Reads model settings.
diff --git a/test/python/testmodels/testpooling.py b/test/python/testmodels/testpooling.py
index d448428f..0fd11e7a 100644
--- a/test/python/testmodels/testpooling.py
+++ b/test/python/testmodels/testpooling.py
@@ -2,6 +2,8 @@
Pooling module tests
"""
+# pylint: disable=too-many-public-methods
+
import json
import os
import tempfile
@@ -10,7 +12,7 @@ import unittest
import numpy as np
import torch
-from txtai.models import Models, ClsPooling, LastPooling, Lemur, MeanPooling, PoolingFactory
+from txtai.models import Models, ClsPooling, LastPooling, LatePooling, Lemur, MeanPooling, PoolingFactory
from txtai.models.pooling.lemur import Activation
from txtai.pipeline import LemurTrainer
@@ -111,6 +113,126 @@ class TestPooling(unittest.TestCase):
)
self.assertEqual(pooling.encode(["test"], category="data").shape, (1, 160))
+ def testLateCenterDefaults(self):
+ """
+ Test late pooling token centering defaults
+ """
+
+ empty = torch.nn.Sequential()
+ single = torch.nn.Sequential(torch.nn.Linear(2, 2, bias=False))
+ multiple = torch.nn.Sequential(torch.nn.Sequential(torch.nn.Linear(2, 2, bias=False), torch.nn.Linear(2, 2, bias=False)))
+
+ self.assertIsNone(LatePooling.centersettings(None, empty, False))
+ self.assertIsNone(LatePooling.centersettings(None, single, False))
+ self.assertEqual(LatePooling.centersettings(None, multiple, False), {"scope": "document"})
+ self.assertIsNone(LatePooling.centersettings(False, multiple, True))
+ self.assertEqual(LatePooling.centersettings(True, empty, True), {"scope": "document"})
+ self.assertEqual(LatePooling.centersettings({"scope": "batch"}, empty, True), {"scope": "batch"})
+
+ def testLateCenterSettings(self):
+ """
+ Test late pooling token centering settings
+ """
+
+ linear = torch.nn.Sequential()
+ mean = np.array([0.25, -0.25], dtype=np.float32)
+ settings = LatePooling.centersettings({"scope": "collection", "mean": mean.tolist()}, linear, True)
+ np.testing.assert_array_equal(settings["mean"], mean)
+
+ with tempfile.TemporaryDirectory() as output:
+ path = os.path.join(output, "mean.npy")
+ np.save(path, mean)
+ settings = LatePooling.centersettings({"scope": "collection", "path": path}, linear, True)
+ np.testing.assert_array_equal(settings["mean"], mean)
+
+ tests = [
+ (None, "center must be a boolean or dictionary"),
+ ({"scope": "invalid"}, "center scope must be one of"),
+ ({"scope": "collection"}, "requires exactly one"),
+ ({"scope": "collection", "mean": mean, "path": "mean.npy"}, "requires exactly one"),
+ ({"scope": "document", "mean": mean}, "only valid with collection scope"),
+ ({"scope": "document", "invalid": True}, "unknown center setting"),
+ ({"scope": "collection", "mean": [[0.0, 1.0]]}, "finite one-dimensional array"),
+ ]
+
+ for center, message in tests:
+ with self.subTest(center=center):
+ with self.assertRaisesRegex(ValueError, message):
+ LatePooling.centersettings(center, linear, True)
+
+ def testLateCenterScopes(self):
+ """
+ Test document, batch and collection token centering
+ """
+
+ data = np.array(
+ [
+ [[1.0, 0.0], [0.0, 1.0], [0.0, 0.0]],
+ [[1.0, 0.0], [-1.0, 0.0], [0.0, 0.0]],
+ ],
+ dtype=np.float32,
+ )
+
+ outputs = {}
+ for scope in ("document", "batch", "collection"):
+ pooling = LatePooling.__new__(LatePooling)
+ object.__setattr__(pooling, "center", {"scope": scope, "mean": np.array([0.25, 0.25])} if scope == "collection" else {"scope": scope})
+ outputs[scope] = pooling.centerdata(data)
+
+ np.testing.assert_array_equal(outputs[scope][:, 2], np.zeros((2, 2), dtype=np.float32))
+ norms = np.linalg.norm(outputs[scope][:, :2], axis=2)
+ self.assertTrue(np.all((norms == 0.0) | np.isclose(norms, 1.0)))
+
+ self.assertFalse(np.array_equal(outputs["document"], outputs["batch"]))
+ self.assertFalse(np.array_equal(outputs["batch"], outputs["collection"]))
+
+ # Document centering is batch-independent and equals batch centering for one item
+ pooling = LatePooling.__new__(LatePooling)
+ object.__setattr__(pooling, "center", {"scope": "document"})
+ separate = np.vstack([pooling.centerdata(data[x : x + 1]) for x in range(len(data))])
+ np.testing.assert_array_equal(outputs["document"], separate)
+
+ object.__setattr__(pooling, "center", {"scope": "batch"})
+ object.__setattr__(pooling, "batches", [1, 1])
+ for x in range(len(data)):
+ np.testing.assert_array_equal(pooling.centerdata(data[x : x + 1]), outputs["document"][x : x + 1])
+ np.testing.assert_array_equal(pooling.centerdata(data), outputs["document"])
+
+ object.__setattr__(pooling, "center", {"scope": "document"})
+ object.__setattr__(pooling, "encoder", None)
+ object.__setattr__(pooling, "lengths", [2, 2])
+ query = pooling.postencode([value.copy() for value in data[:, :2]], "query")
+ documents = pooling.postencode([value.copy() for value in data[:, :2]], "data")
+ np.testing.assert_array_equal(query, documents)
+
+ object.__setattr__(pooling, "center", {"scope": "collection", "mean": np.zeros(3)})
+ with self.assertRaisesRegex(ValueError, "dimension must match"):
+ pooling.centerdata(data)
+
+ def testLateCenterDisabled(self):
+ """
+ Test omitted and explicitly disabled centering are byte-identical
+ """
+
+ base = PoolingFactory.create({"path": "neuml/colbert-bert-tiny", "device": self.device, "modelargs": {"muvera": None}})
+ disabled = PoolingFactory.create({"path": "neuml/colbert-bert-tiny", "device": self.device, "modelargs": {"muvera": None, "center": False}})
+
+ self.assertIsNone(base.center)
+ self.assertIsNone(disabled.center)
+ np.testing.assert_array_equal(base.encode(["test"], category="query"), disabled.encode(["test"], category="query"))
+
+ centered = PoolingFactory.create({"path": "neuml/colbert-bert-tiny", "device": self.device, "modelargs": {"muvera": None, "center": True}})
+ texts = ["Short text.", "A considerably longer text exercises padding behavior."]
+ separate = centered.encode(texts, batch=1, category="data")
+ together = centered.encode(texts, batch=2, category="data")
+ np.testing.assert_allclose(separate, together, rtol=1e-5, atol=1e-6)
+ self.assertTrue(np.any(np.all(together == 0.0, axis=2)))
+
+ centered.center = {"scope": "batch"}
+ batch = centered.encode(texts, batch=1, category="data")
+ self.assertEqual(centered.batches, [1, 1])
+ np.testing.assert_allclose(batch, separate, rtol=1e-5, atol=1e-6)
+
def testLemur(self):
"""
Test late pooling with LEMUR fixed dimensional encoding