💡 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
Load instruction prompts for Sentence Transformers models, closes #1004
davidmezzetti86e768bccb9d
diff --git a/docs/embeddings/configuration/vectors.md b/docs/embeddings/configuration/vectors.mdindex fd0e0adb..d409149c 100644--- a/docs/embeddings/configuration/vectors.md+++ b/docs/embeddings/configuration/vectors.md@@ -117,7 +117,7 @@ instructions:Instruction-based models use prefixes to modify how embeddings are computed. This is especially useful with asymmetric search, which is when the query and indexed data are of vastly different lengths. In other words, short queries with long documents.-[E5-base](https://huggingface.co/intfloat/e5-base) is an example of a model that accepts instructions. It takes `query: ` and `passage: ` prefixes and uses those to generate embeddings that work well for asymmetric search.+`txtai` automatically loads prompts stored in `config_sentence_transformers.json` except if this parameter is set. For some older models such as [E5-base](https://huggingface.co/intfloat/e5-base), instructions still need to be provided via this parameter.## models```yamldiff --git a/src/python/txtai/models/pooling/base.py b/src/python/txtai/models/pooling/base.pyindex e0f57987..5a5cd034 100644--- a/src/python/txtai/models/pooling/base.py+++ b/src/python/txtai/models/pooling/base.py@@ -2,10 +2,14 @@Pooling module"""+import json+import numpy as npimport torch+from huggingface_hub.errors import HFValidationErrorfrom torch import nn+from transformers.utils import cached_filefrom ..models import Models@@ -15,7 +19,7 @@ class Pooling(nn.Module):Builds pooled vectors usings outputs from a transformers model."""- def __init__(self, path, device, tokenizer=None, maxlength=None, modelargs=None):+ def __init__(self, path, device, tokenizer=None, maxlength=None, loadprompts=None, modelargs=None):"""Creates a new Pooling model.@@ -24,6 +28,7 @@ class Pooling(nn.Module):device: tensor device idtokenizer: optional path to tokenizermaxlength: max sequence length+ loadprompts: whether instruction prompts should be loadedmodelargs: additional model arguments"""@@ -39,6 +44,9 @@ class Pooling(nn.Module):# Set max lengthself.maxlength = maxlength if maxlength else self.tokenizer.model_max_length if self.tokenizer.model_max_length != int(1e30) else None+ # Load stored prompts+ self.prompts = self.loadprompts(path) if loadprompts else None+# Move to deviceself.to(self.device)@@ -123,6 +131,11 @@ class Pooling(nn.Module):category: embeddings category (query or data)"""+ # Prepend prompt+ prompt = self.prompts.get(category) if self.prompts else None+ if prompt:+ documents = [f"{prompt}{x}" if isinstance(x, str) else x for x in documents]+return documents# pylint: disable=W0613@@ -139,3 +152,50 @@ class Pooling(nn.Module):"""return results++ 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++ def loadprompts(self, path):+ """+ Loads prompts from a sentence transformers configuration file.++ Args:+ path: model path++ Returns:+ prompts dictionary, if available+ """++ prompts = None+ config = self.load(path, "config_sentence_transformers.json")+ if config:+ # Copy document prompt to data+ prompts = config.get("prompts")+ if prompts and "document" in prompts:+ prompts["data"] = prompts["document"]++ return promptsdiff --git a/src/python/txtai/models/pooling/factory.py b/src/python/txtai/models/pooling/factory.pyindex 906a30ad..172fef4b 100644--- a/src/python/txtai/models/pooling/factory.py+++ b/src/python/txtai/models/pooling/factory.py@@ -32,8 +32,8 @@ class PoolingFactory:"""# Unpack parameters- method, path, device, tokenizer, maxlength, modelargs = [- config.get(x) for x in ["method", "path", "device", "tokenizer", "maxlength", "modelargs"]+ method, path, device, tokenizer, maxlength, loadprompts, modelargs = [+ config.get(x) for x in ["method", "path", "device", "tokenizer", "maxlength", "loadprompts", "modelargs"]]# Derive maxlength, if applicable@@ -41,7 +41,7 @@ class PoolingFactory:# Default pooling returns hidden stateif isinstance(path, bytes) or (isinstance(path, str) and os.path.isfile(path)) or method == "pooling":- return Pooling(path, device, tokenizer, maxlength, modelargs)+ return Pooling(path, device, tokenizer, maxlength, loadprompts, modelargs)# Derive pooling method if it's not specified and path is a stringif (not method or method not in ("clspooling", "meanpooling", "latepooling")) and isinstance(path, str):@@ -49,14 +49,14 @@ class PoolingFactory:# Check for cls poolingif method == "clspooling":- return ClsPooling(path, device, tokenizer, maxlength, modelargs)+ return ClsPooling(path, device, tokenizer, maxlength, loadprompts, modelargs)# Check for late poolingif method == "latepooling":- return LatePooling(path, device, tokenizer, maxlength, modelargs)+ return LatePooling(path, device, tokenizer, maxlength, loadprompts, modelargs)# Default to mean pooling- return MeanPooling(path, device, tokenizer, maxlength, modelargs)+ return MeanPooling(path, device, tokenizer, maxlength, loadprompts, modelargs)@staticmethoddef method(path):diff --git a/src/python/txtai/models/pooling/late.py b/src/python/txtai/models/pooling/late.pyindex 2d1741cd..54dfac7a 100644--- a/src/python/txtai/models/pooling/late.py+++ b/src/python/txtai/models/pooling/late.py@@ -2,12 +2,9 @@Late module"""-import json-import numpy as npimport torch-from huggingface_hub.errors import HFValidationErrorfrom safetensors import safe_openfrom torch import nnfrom transformers.utils import cached_file@@ -21,14 +18,14 @@ class LatePooling(Pooling):Builds late pooled vectors using outputs from a transformers model."""- def __init__(self, path, device, tokenizer=None, maxlength=None, modelargs=None):+ def __init__(self, path, device, tokenizer=None, maxlength=None, loadprompts=None, modelargs=None):# Check if fixed dimensional encoder is enabledmodelargs = modelargs.copy() if modelargs else {}muvera = modelargs.pop("muvera", {})self.encoder = Muvera(**muvera) if muvera is not None else None# Call parent initialization- super().__init__(path, device, tokenizer, maxlength, modelargs)+ super().__init__(path, device, tokenizer, maxlength, loadprompts, modelargs)# Get linear weights pathconfig = self.load(path, "1_Dense/config.json")@@ -145,29 +142,3 @@ class LatePooling(Pooling):params = ["query_token_id", "query_maxlen", "doc_token_id", "doc_maxlen"]return [config.get(p) for p in params]-- 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 configdiff --git a/src/python/txtai/vectors/dense/huggingface.py b/src/python/txtai/vectors/dense/huggingface.pyindex 47772f5f..cd2fc248 100644--- a/src/python/txtai/vectors/dense/huggingface.py+++ b/src/python/txtai/vectors/dense/huggingface.py@@ -35,6 +35,7 @@ class HFVectors(Vectors):"device": Models.deviceid(self.config.get("gpu", True)),"tokenizer": self.config.get("tokenizer"),"maxlength": self.config.get("maxlength"),+ "loadprompts": "instructions" not in self.config,"modelargs": self.config.get("vectors", {}),})diff --git a/test/python/testmodels/testpooling.py b/test/python/testmodels/testpooling.pyindex 186e20c8..5681fd0c 100644--- a/test/python/testmodels/testpooling.py+++ b/test/python/testmodels/testpooling.py@@ -87,3 +87,28 @@ class TestPooling(unittest.TestCase):{"path": model, "device": self.device, "modelargs": {"muvera": {"repetitions": 5, "hashes": 2, "projection": 8}}})self.assertEqual(pooling.encode(["test"], category="data").shape, (1, 160))++ def testPrompts(self):+ """+ Test instruction prompts+ """++ # Load model with prompts+ pooling = PoolingFactory.create({"path": "neuml/bert-tiny-prompts", "device": self.device, "loadprompts": True})++ # Test prompts are prepended+ self.assertEqual(pooling.preencode(["abc"], "query")[0], "query: abc")++ self.assertEqual(pooling.preencode(["text"], "data")[0], "document: text")++ # Load model with prompts disabled (default)+ pooling = PoolingFactory.create(+ {+ "path": "neuml/bert-tiny-prompts",+ "device": self.device,+ }+ )++ # Test that prompts are not prepended+ self.assertEqual(pooling.preencode(["abc"], "query")[0], "abc")+ self.assertEqual(pooling.preencode(["text"], "data")[0], "text")