💡 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 new vector method and fix performance regression, closes #101, closes #102
davidmezzetti68d2477f4f99
diff --git a/docs/embeddings.md b/docs/embeddings.mdindex f846bcde..3a403e24 100644--- a/docs/embeddings.md+++ b/docs/embeddings.md@@ -21,27 +21,35 @@ Embeddings({"method": "words",### method```yaml-method: transformers|words+method: transformers|sentence-transformers|words```-Sets the sentence embeddings method to use. When set to _transformers_, the embeddings object builds sentence embeddings using a sentence transformers model.-Otherwise a word embeddings model is used. The method is inferred using the _path_ if not provided.+Sentence embeddings method to use. Options listed below.-### path-```yaml-path: string-```+#### transformers-Required field that sets the path for a vectors model. When method set to _transformers_, this must be a path to a Hugging Face Transformers model. Otherwise,-it must be a path to a local word embeddings model.+Builds sentence embeddings using a transformers model. While this can be any transformers model, it works best with+[models trained](https://huggingface.co/models?search=sentence-transformers) to build sentence embeddings.-### tokenize+#### sentence-transformers++Same as transformers but loads models with the sentence-transformers library.++#### words++Builds sentence embeddings using a word embeddings model.++sentence-transformers and words require the [similarity](https://neuml.github.io/txtai/install/#similarity) extras package to be installed.++The method is inferred using the _path_ if not provided.++### path```yaml-tokenize: boolean+path: string```-Enables string tokenization (defaults to false). This method applies tokenization rules that only work with English language text and may increase the quality of-English language sentence embeddings in some situations.+Required field that sets the path for a vectors model. When using a transformers/sentence-transformers model, this can be any model on the+[Hugging Face Model Hub](https://huggingface.co/models) or a local file path. Otherwise, it must be a local file path to a word embeddings model.### backend```yaml@@ -90,6 +98,16 @@ quantize: booleanEnables quanitization of generated sentence embeddings. If the index backend supports it, sentence embeddings will be stored with 8-bit precision vs 32-bit.Only Faiss currently supports quantization.+## Additional configuration for Transformers models++### tokenize+```yaml+tokenize: boolean+```++Enables string tokenization (defaults to false). This method applies tokenization rules that only work with English language text and may increase the quality of+English language sentence embeddings in some situations.+## Additional configuration for Word embedding modelsWord embeddings provide a good tradeoff of performance to functionality for a similarity search system. With that being said, Transformers models are making great progress in scaling performance down to smaller models and are the preferred vector backend in txtai for most cases.diff --git a/src/python/txtai/vectors/base.py b/src/python/txtai/vectors/base.pyindex a56a0343..cbc1eeaa 100644--- a/src/python/txtai/vectors/base.py+++ b/src/python/txtai/vectors/base.py@@ -28,7 +28,7 @@ class Vectors:Loads vector model at path.Args:- path: path to word vector model+ path: path to vector modelReturns:vector modeldiff --git a/src/python/txtai/vectors/pooling.py b/src/python/txtai/vectors/pooling.pynew file mode 100644index 00000000..24daef18--- /dev/null+++ b/src/python/txtai/vectors/pooling.py@@ -0,0 +1,135 @@+"""+Pooling module+"""++import numpy as np+import torch++from torch import nn++from transformers import AutoModel, AutoTokenizer++from ..models import Models+++class Pooling(nn.Module):+ """+ Builds pooled vectors usings outputs from a transformers model.+ """++ def __init__(self, path, device, batch=32, maxlength=None):+ """+ Creates a new Pooling model.++ Args:+ path: path to transformers model+ device: tensor device id+ batch: batch size+ maxlength: max sequence length+ """++ super().__init__()++ self.model = AutoModel.from_pretrained(path)+ self.tokenizer = AutoTokenizer.from_pretrained(path)+ self.device = Models.device(device)++ # Detect unbounded tokenizer typically found in older models+ Models.checklength(self.model, self.tokenizer)++ # Set batch and max length+ self.batch = batch+ self.maxlength = maxlength if maxlength else self.tokenizer.model_max_length++ # Move to device+ self.to(device)++ def encode(self, documents):+ """+ Builds an array of pooled embeddings for documents.++ Args:+ documents: list of documents used to build embeddings++ Returns:+ pooled embeddings+ """++ # Split documents into batches and process+ results = []++ # Sort document indices from largest to smallest to enable efficient batching+ # This performance tweak matches logic in sentence-transformers+ lengths = np.argsort([-len(x) for x in documents])+ documents = [documents[x] for x in lengths]++ for chunk in self.chunk(documents, self.batch):+ # Tokenize input+ inputs = self.tokenizer(chunk, padding=True, truncation="longest_first", return_tensors="pt", max_length=self.maxlength)++ # Move inputs to device+ inputs = inputs.to(self.device)++ # Run inputs through model+ with torch.no_grad():+ outputs = self.forward(inputs)++ # Add batch result+ results.extend(outputs.cpu().numpy())++ # Restore original order and return array+ return np.asarray([results[x] for x in np.argsort(lengths)])++ def chunk(self, texts, size):+ """+ Splits texts into separate batch sizes specified by size.++ Args:+ texts: text elements+ size: batch size++ Returns:+ list of evenly sized batches with the last batch having the remaining elements+ """++ return [texts[x : x + size] for x in range(0, len(texts), size)]++ def forward(self, inputs):+ """+ Runs inputs through transformers model and returns outputs.++ Args:+ inputs: model inputs++ Returns:+ model outputs+ """++ return self.model(**inputs)[0]+++class MeanPooling(Pooling):+ """+ Builds mean pooled vectors usings outputs from a transformers model.+ """++ def forward(self, inputs):+ """+ Runs mean pooling on token embeddings taking the input mask into account.++ Args:+ outputs: model outputs+ mask: input attention mask++ Returns:+ mean pooled embeddings using output token embeddings (i.e. last hidden state)+ """++ # Run through transformers model+ tokens = super().forward(inputs)+ mask = inputs["attention_mask"]++ # Mean pooling+ # pylint: disable=E1101+ mask = mask.unsqueeze(-1).expand(tokens.size()).float()+ return torch.sum(tokens * mask, 1) / torch.clamp(mask.sum(1), min=1e-9)diff --git a/src/python/txtai/vectors/transformers.py b/src/python/txtai/vectors/transformers.pyindex 732902c1..137001ac 100644--- a/src/python/txtai/vectors/transformers.py+++ b/src/python/txtai/vectors/transformers.py@@ -5,9 +5,6 @@ Transformers moduleimport pickleimport tempfile-import numpy as np-import torch-# Conditional importtry:from sentence_transformers import SentenceTransformer@@ -16,12 +13,10 @@ try:except ImportError:SENTENCE_TRANSFORMERS = False-from transformers import AutoModel, AutoTokenizer--from ..pipeline.tokenizer import Tokenizer-from .base import Vectorsfrom ..models import Models+from ..pipeline.tokenizer import Tokenizer+from .pooling import MeanPoolingclass TransformersVectors(Vectors):@@ -30,26 +25,20 @@ class TransformersVectors(Vectors):"""def load(self, path):- # Flag that determines if transformers or sentence-transformers should be used to run model- modelhub = self.config.get("modelhub", True)+ # Flag that determines if transformers or sentence-transformers should be used to build embeddings+ transformers = self.config.get("method") != "sentence-transformers"# Tensor device iddeviceid = Models.deviceid(self.config.get("gpu", True))- # Use transformers model directly (default)- if modelhub:- model = AutoModel.from_pretrained(path)- tokenizer = AutoTokenizer.from_pretrained(path)-- # Detect unbounded tokenizer typically found in older models- Models.checklength(model, tokenizer)-- return (model, tokenizer, Models.device(deviceid))+ # Build embeddings with transformers (default)+ if transformers:+ return MeanPooling(path, device=deviceid)if not SENTENCE_TRANSFORMERS:raise ImportError('sentence-transformers is not available - install "similarity" extra to enable')- # Download model directly from sentence transformers if model hub disabled+ # Build embeddings with sentence-transformersreturn SentenceTransformer(path, device=Models.reference(deviceid))def index(self, documents):@@ -78,7 +67,7 @@ class TransformersVectors(Vectors):def transform(self, document):# Convert input document to text and build embeddings- return self.encode([self.text(document[1])])[0]+ return self.model.encode([self.text(document[1])])[0]def batch(self, documents, output):"""@@ -98,7 +87,7 @@ class TransformersVectors(Vectors):dimensions = None# Build embeddings- embeddings = self.encode(documents)+ embeddings = self.model.encode(documents)for embedding in embeddings:if not dimensions:# Set number of dimensions for embeddings@@ -126,76 +115,3 @@ class TransformersVectors(Vectors):text = " ".join(text)return text-- def encode(self, documents):- """- Builds embeddings for input documents.-- Args:- documents: list of text to build embeddings for-- Returns:- embeddings- """-- # Build embeddings using transformers- if isinstance(self.model, tuple):- # Unpack model- model, tokenizer, device = self.model-- # Move model to device- model = model.to(device)-- # Split documents into batches and process- results = []- for chunk in self.chunk(documents, 32):- # Tokenize input- inputs = tokenizer(chunk, padding=True, truncation="longest_first", return_tensors="pt")-- # Move inputs to device- inputs = inputs.to(device)-- # Run inputs through model- with torch.no_grad():- outputs = model(**inputs)-- # Run pooling logic on outputs- outputs = self.pooling(outputs, inputs["attention_mask"])-- # Add batch result- results.extend(outputs.cpu().numpy())-- return np.asarray(results)-- # Build embeddings using sentence transformers- return self.model.encode(documents, show_progress_bar=False)-- def chunk(self, texts, size):- """- Splits texts into separate batch sizes specified by size.-- Args:- texts: text elements- size: batch size-- Returns:- list of evenly sized batches with the last batch having the remaining elements- """-- return [texts[x : x + size] for x in range(0, len(texts), size)]-- def pooling(self, outputs, mask):- """- Runs mean pooling on token embeddings taking the input mask into account.-- Args:- outputs: model outputs- mask: input attention mask-- Returns:- mean pooled vector using output token embeddings (i.e. last hidden state)- """-- # pylint: disable=E1101- mask = mask.unsqueeze(-1).expand(outputs[0].size()).float()- return torch.sum(outputs[0] * mask, 1) / torch.clamp(mask.sum(1), min=1e-9)diff --git a/test/python/testoptional.py b/test/python/testoptional.pyindex 776bb6f3..9e316fbe 100644--- a/test/python/testoptional.py+++ b/test/python/testoptional.py@@ -93,7 +93,7 @@ class TestOptional(unittest.TestCase):VectorsFactory.create({"method": "words"}, None)with self.assertRaises(ImportError):- VectorsFactory.create({"method": "transformers", "path": "", "modelhub": False}, None)+ VectorsFactory.create({"method": "sentence-transformers", "path": ""}, None)def testWorkflow(self):"""diff --git a/test/python/testtransformers.py b/test/python/testtransformers.pyindex 7f4fec3d..343dfd5c 100644--- a/test/python/testtransformers.py+++ b/test/python/testtransformers.py@@ -39,10 +39,10 @@ class TestTransformersVectors(unittest.TestCase):def testSentenceTransformers(self):"""- Test creating a direct sentence transformers model+ Test creating a model with sentence transformers"""- model = VectorsFactory.create({"path": "paraphrase-MiniLM-L3-v2", "modelhub": False}, None)+ model = VectorsFactory.create({"method": "sentence-transformers", "path": "paraphrase-MiniLM-L3-v2"}, None)self.assertIsNotNone(model.transform("This is a test"))def testText(self):