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 support for late interaction models, closes #954

davidmezzetti1b1ab4c9ea7e
diff --git a/src/python/txtai/models/pooling/__init__.py b/src/python/txtai/models/pooling/__init__.py
index f5a8defe..9ba930e5 100644
--- a/src/python/txtai/models/pooling/__init__.py
+++ b/src/python/txtai/models/pooling/__init__.py
@@ -5,4 +5,5 @@ Pooling imports
from .base import Pooling
from .cls import ClsPooling
from .factory import PoolingFactory
+from .late import LatePooling
from .mean import MeanPooling
diff --git a/src/python/txtai/models/pooling/base.py b/src/python/txtai/models/pooling/base.py
index 7e690644..44804c7a 100644
--- a/src/python/txtai/models/pooling/base.py
+++ b/src/python/txtai/models/pooling/base.py
@@ -76,6 +76,9 @@ class Pooling(nn.Module):
# Add batch result
results.extend(outputs.cpu().numpy())
+ # Apply post encoding transformation logic
+ results = self.postencode(results)
+
# Restore original order and return array
return np.asarray([results[x] for x in np.argsort(lengths)])
@@ -105,3 +108,16 @@ class Pooling(nn.Module):
"""
return self.model(**inputs)[0]
+
+ def postencode(self, results):
+ """
+ Applies post encoding transformation logic.
+
+ Args:
+ results: list of results
+
+ Returns:
+ results with transformation logic applied
+ """
+
+ return results
diff --git a/src/python/txtai/models/pooling/factory.py b/src/python/txtai/models/pooling/factory.py
index d61dabb4..9501683c 100644
--- a/src/python/txtai/models/pooling/factory.py
+++ b/src/python/txtai/models/pooling/factory.py
@@ -10,6 +10,7 @@ from transformers.utils import cached_file
from .base import Pooling
from .cls import ClsPooling
+from .late import LatePooling
from .mean import MeanPooling
@@ -43,13 +44,17 @@ class PoolingFactory:
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")) and (isinstance(path, str) and not os.path.exists(path)):
+ if (not method or method not in ("clspooling", "meanpooling", "latepooling")) and (isinstance(path, str) and not os.path.exists(path)):
method = PoolingFactory.method(path)
# Check for cls pooling
if method == "clspooling":
return ClsPooling(path, device, tokenizer, maxlength, modelargs)
+ # Check for late pooling
+ if method == "latepooling":
+ return LatePooling(path, device, tokenizer, maxlength, modelargs)
+
# Default to mean pooling
return MeanPooling(path, device, tokenizer, maxlength, modelargs)
@@ -75,6 +80,19 @@ class PoolingFactory:
if config and config["pooling_mode_cls_token"] and not config["pooling_mode_mean_tokens"]:
method = "clspooling"
+ # Check for late interaction pooling
+ if not config:
+ # Load 1_Dense/config.json
+ config = PoolingFactory.load(path, "1_Dense/config.json")
+ if config:
+ method = "latepooling"
+
+ # Load config.json and check architecture
+ else:
+ config = PoolingFactory.load(path, "config.json")
+ if config and "HF_ColBERT" in config.get("architectures", []):
+ method = "latepooling"
+
return method
@staticmethod
diff --git a/src/python/txtai/models/pooling/late.py b/src/python/txtai/models/pooling/late.py
new file mode 100644
index 00000000..5d65af76
--- /dev/null
+++ b/src/python/txtai/models/pooling/late.py
@@ -0,0 +1,113 @@
+"""
+Late module
+"""
+
+import json
+
+import numpy as np
+import torch
+
+from huggingface_hub.errors import HFValidationError
+from safetensors import safe_open
+from torch import nn
+from transformers.utils import cached_file
+
+from .base import Pooling
+
+
+class LatePooling(Pooling):
+ """
+ Builds late pooled vectors using outputs from a transformers model.
+ """
+
+ def __init__(self, path, device, tokenizer=None, maxlength=None, modelargs=None):
+ super().__init__(path, device, tokenizer, maxlength, modelargs)
+
+ # Get linear weights path
+ config = self.load(path, "1_Dense/config.json")
+ if config:
+ # PyLate weights format
+ name = "1_Dense/model.safetensors"
+ else:
+ # Stanford weights format
+ name = "model.safetensors"
+
+ # Load linear layer
+ path = cached_file(path_or_repo_id=path, filename=name)
+ with safe_open(filename=path, framework="pt") as f:
+ weights = f.get_tensor("linear.weight")
+
+ # Load weights into linear layer
+ self.linear = nn.Linear(weights.shape[1], weights.shape[0], bias=False, device=self.device, dtype=weights.dtype)
+ with torch.no_grad():
+ self.linear.weight.copy_(weights)
+
+ def forward(self, **inputs):
+ """
+ Runs late pooling on token embeddings.
+
+ Args:
+ inputs: model inputs
+
+ Returns:
+ Late pooled embeddings using output token embeddings (i.e. last hidden state)
+ """
+
+ # Run through transformers model
+ tokens = super().forward(**inputs)
+
+ # Run through final linear layer and return
+ return self.linear(tokens)
+
+ def postencode(self, results):
+ """
+ Normalizes and pads results.
+
+ Args:
+ results: input results
+
+ Returns:
+ normalized results with padding
+ """
+
+ length = 0
+ for vectors in results:
+ # Get max length
+ if vectors.shape[0] > length:
+ length = vectors.shape[0]
+
+ # Normalize vectors
+ vectors /= np.linalg.norm(vectors, axis=1)[:, np.newaxis]
+
+ # Pad values
+ data = []
+ for vectors in results:
+ data.append(np.pad(vectors, [(0, length - vectors.shape[0]), (0, 0)]))
+
+ return np.asarray(data)
+
+ def load(self, path, name):
+ """
+ Loads a JSON config file from the Hugging Face Hub.
+
+ Args:
+ path: model path
+ name: file to load
+
+ Returns:
+ config
+ """
+
+ # Download file and parse JSON
+ config = None
+ try:
+ path = cached_file(path_or_repo_id=path, filename=name)
+ if path:
+ with open(path, encoding="utf-8") as f:
+ config = json.load(f)
+
+ # Ignore this error - invalid repo or directory
+ except (HFValidationError, OSError):
+ pass
+
+ return config