Skip to content

armgit / txtai

Public Imported from GitHub
0

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

Add max pooling

Aryan Pardeshi438ade31b631
diff --git a/docs/embeddings/configuration/vectors.md b/docs/embeddings/configuration/vectors.md
index bdaa3ee9..0c945b51 100644
--- a/docs/embeddings/configuration/vectors.md
+++ b/docs/embeddings/configuration/vectors.md
@@ -25,8 +25,8 @@ Embeddings method to use. If the method is not provided, it is inferred using th
Builds embeddings using a transformers model. While this can be any transformers model, it works best with
[models trained](https://huggingface.co/models?pipeline_tag=sentence-similarity) to build embeddings.
-`mean`, `cls`, `last` and `late` pooling are supported and automatically inferred from the model. The pooling method can be overwritten by changing the method
-from `transformers` to `meanpooling`, `clspooling`, `lastpooling` or `latepooling` respectively.
+`mean`, `cls`, `max`, `last` and `late` pooling are supported and automatically inferred from the model. The pooling method can be overwritten by changing the method
+from `transformers` to `meanpooling`, `clspooling`, `maxpooling`, `lastpooling` or `latepooling` respectively.
Setting `maxlength` to `True` enables truncating inputs to the `max_seq_length`. Setting `maxlength` to an integer will truncate inputs to that value. When omitted (default), the `maxlength` will be set to either the model or tokenizer maxlength.
diff --git a/src/python/txtai/models/pooling/__init__.py b/src/python/txtai/models/pooling/__init__.py
index 0f82ba2a..fe8d1974 100644
--- a/src/python/txtai/models/pooling/__init__.py
+++ b/src/python/txtai/models/pooling/__init__.py
@@ -8,5 +8,6 @@ from .factory import PoolingFactory
from .last import LastPooling
from .late import LatePooling
from .lemur import Lemur
+from .max import MaxPooling
from .mean import MeanPooling
from .muvera import Muvera
diff --git a/src/python/txtai/models/pooling/factory.py b/src/python/txtai/models/pooling/factory.py
index 0e635e7f..3e4d800f 100644
--- a/src/python/txtai/models/pooling/factory.py
+++ b/src/python/txtai/models/pooling/factory.py
@@ -9,6 +9,7 @@ from .base import Pooling
from .cls import ClsPooling
from .last import LastPooling
from .late import LatePooling
+from .max import MaxPooling
from .mean import MeanPooling
from ...util import Download, DownloadError
@@ -44,13 +45,17 @@ class PoolingFactory:
return Pooling(path, device, tokenizer, maxlength, loadprompts, modelargs)
# Derive pooling method if it's not specified and path is a string
- if (not method or method not in ("clspooling", "meanpooling", "lastpooling", "latepooling")) and isinstance(path, str):
+ if (not method or method not in ("clspooling", "meanpooling", "maxpooling", "lastpooling", "latepooling")) and isinstance(path, str):
method = PoolingFactory.method(path)
# Check for cls pooling
if method == "clspooling":
return ClsPooling(path, device, tokenizer, maxlength, loadprompts, modelargs)
+ # Check for max pooling
+ if method == "maxpooling":
+ return MaxPooling(path, device, tokenizer, maxlength, loadprompts, modelargs)
+
# Check for last pooling
if method == "lastpooling":
return LastPooling(path, device, tokenizer, maxlength, loadprompts, modelargs)
@@ -84,6 +89,10 @@ class PoolingFactory:
if config and config.get("pooling_mode_cls_token") and not config["pooling_mode_mean_tokens"]:
method = "clspooling"
+ # Set to max pooling if it's enabled and mean pooling is disabled
+ if config and config.get("pooling_mode_max_tokens") and not config["pooling_mode_mean_tokens"]:
+ method = "maxpooling"
+
# Set to last token pooling if it's enabled and mean pooling is disabled
if config and config.get("pooling_mode_lasttoken") and not config["pooling_mode_mean_tokens"]:
method = "lastpooling"
diff --git a/src/python/txtai/models/pooling/max.py b/src/python/txtai/models/pooling/max.py
new file mode 100644
index 00000000..f2b173d7
--- /dev/null
+++ b/src/python/txtai/models/pooling/max.py
@@ -0,0 +1,36 @@
+"""
+Max module
+"""
+
+from .base import Pooling
+
+# Core library imports
+from ...util import Library
+
+torch = Library().torch()
+
+
+class MaxPooling(Pooling):
+ """
+ Builds max pooled vectors usings outputs from a transformers model.
+ """
+
+ def forward(self, **inputs):
+ """
+ Runs max pooling on token embeddings taking the input mask into account.
+
+ Args:
+ inputs: model inputs
+
+ Returns:
+ max pooled embeddings using output token embeddings (i.e. last hidden state)
+ """
+
+ # Run through transformers model
+ tokens = super().forward(**inputs)
+ mask = inputs["attention_mask"]
+
+ # Max pooling
+ # pylint: disable=E1101
+ mask = mask.unsqueeze(-1).expand(tokens.size()).bool()
+ return torch.max(tokens.masked_fill(~mask, torch.finfo(tokens.dtype).min), 1).values
diff --git a/src/python/txtai/vectors/dense/huggingface.py b/src/python/txtai/vectors/dense/huggingface.py
index cd2fc248..05fa1066 100644
--- a/src/python/txtai/vectors/dense/huggingface.py
+++ b/src/python/txtai/vectors/dense/huggingface.py
@@ -24,7 +24,7 @@ class HFVectors(Vectors):
True if this is a local transformers-based model, False otherwise
"""
- return method in ("transformers", "pooling", "clspooling", "meanpooling")
+ return method in ("transformers", "pooling", "clspooling", "meanpooling", "maxpooling")
def loadmodel(self, path):
# Build embeddings with transformers pooling
diff --git a/test/python/testmodels/testpooling.py b/test/python/testmodels/testpooling.py
index 89dd27ea..992d6374 100644
--- a/test/python/testmodels/testpooling.py
+++ b/test/python/testmodels/testpooling.py
@@ -6,12 +6,14 @@ import os
import tempfile
import unittest
+from unittest.mock import patch
+
import numpy as np
import torch
from safetensors.numpy import save_file
-from txtai.models import Models, ClsPooling, LastPooling, LatePooling, Lemur, MeanPooling, Muvera, PoolingFactory
+from txtai.models import Models, ClsPooling, LastPooling, LatePooling, Lemur, MaxPooling, MeanPooling, Muvera, PoolingFactory
from txtai.models.pooling.lemur import Activation
from txtai.pipeline import LemurTrainer
@@ -379,6 +381,31 @@ class TestPooling(unittest.TestCase):
pooling = PoolingFactory.create({"path": "hf-internal-testing/tiny-random-gpt2", "device": self.device, "maxlength": True})
self.assertEqual(pooling.maxlength, 1024)
+ def testMax(self):
+ """
+ Test max pooling
+ """
+
+ # Test max pooling
+ pooling = PoolingFactory.create({"method": "maxpooling", "path": "sentence-transformers/nli-mpnet-base-v2", "device": self.device})
+ self.assertEqual(type(pooling), MaxPooling)
+
+ # Test max pooling encoding
+ self.assertEqual(pooling.encode(["test"])[0].shape, (768,))
+
+ # Padding tokens must be excluded from the max, otherwise a short text changes when batched with a longer one
+ texts = ["Short text.", "A considerably longer text exercises padding behavior."]
+ self.assertTrue(np.allclose(pooling.encode([texts[0]])[0], pooling.encode(texts, batch=2)[0], atol=1e-4))
+
+ def testMaxMethod(self):
+ """
+ Test max pooling is derived from the sentence transformers pooling config
+ """
+
+ config = {"pooling_mode_max_tokens": True, "pooling_mode_mean_tokens": False}
+ with patch.object(PoolingFactory, "load", return_value=config):
+ self.assertEqual(PoolingFactory.method("sentence-transformers/nli-mpnet-base-v2"), "maxpooling")
+
def testMean(self):
"""
Test mean pooling