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 ONNX vectors backend (#1212)

Joe Bergin007d61077abc
diff --git a/setup.py b/setup.py
index a4c86e5a..20b01bd0 100644
--- a/setup.py
+++ b/setup.py
@@ -142,6 +142,7 @@ extras["vectors"] = [
"litellm>=1.37.16",
"llama-cpp-python>=0.2.75",
"model2vec>=0.3.0",
+ "onnxruntime>=1.11.0",
"scikit-learn>=0.23.1",
"scipy>=1.4.1",
"sentence-transformers>=5.0.0",
diff --git a/src/python/txtai/vectors/dense/factory.py b/src/python/txtai/vectors/dense/factory.py
index bfa41e5b..d81e596e 100644
--- a/src/python/txtai/vectors/dense/factory.py
+++ b/src/python/txtai/vectors/dense/factory.py
@@ -11,6 +11,7 @@ from .litellm import LiteLLM
from .litert import LiteRT
from .llama import LlamaCpp
from .m2v import Model2Vec
+from .onnx import ONNX
from .sbert import STVectors
from .words import WordVectors
@@ -57,6 +58,10 @@ class VectorsFactory:
if method == "model2vec":
return Model2Vec(config, scoring, models)
+ # ONNX vectors
+ if method == "onnx":
+ return ONNX(config, scoring, models)
+
# Sentence Transformers vectors
if method == "sentence-transformers":
return STVectors(config, scoring, models) if config and config.get("path") else None
@@ -99,6 +104,8 @@ class VectorsFactory:
method = "llama.cpp"
elif Model2Vec.ismodel(path):
method = "model2vec"
+ elif ONNX.ismodel(path):
+ method = "onnx"
elif WordVectors.ismodel(path):
method = "words"
else:
diff --git a/src/python/txtai/vectors/dense/onnx.py b/src/python/txtai/vectors/dense/onnx.py
new file mode 100644
index 00000000..d5e8aa63
--- /dev/null
+++ b/src/python/txtai/vectors/dense/onnx.py
@@ -0,0 +1,160 @@
+"""
+ONNX module
+"""
+
+import os
+
+# Conditional import
+try:
+ import onnxruntime as ort
+
+ from tokenizers import Tokenizer
+
+ ONNX_RUNTIME = True
+except ImportError:
+ ONNX_RUNTIME = False
+
+from ...util import Download, Library
+
+from ..base import Vectors
+
+# Core library imports
+np = Library().numpy()
+
+
+class ONNX(Vectors):
+ """
+ Builds vectors using ONNX Runtime.
+ """
+
+ @staticmethod
+ def ismodel(path):
+ """
+ Checks if path is an ONNX model.
+
+ Args:
+ path: input path
+
+ Returns:
+ True if this is an ONNX model, False otherwise
+ """
+
+ return isinstance(path, str) and path.lower().endswith(".onnx")
+
+ def __init__(self, config, scoring, models):
+ # Check before parent constructor since it calls loadmodel
+ if not ONNX_RUNTIME:
+ raise ImportError('onnxruntime is not available - install "vectors" extra to enable')
+
+ super().__init__(config, scoring, models)
+
+ def loadmodel(self, path):
+ # Check if this is a local path, otherwise download from the HF Hub
+ model = path if os.path.exists(path) else Download()(path)
+
+ # Create ONNX session
+ session = ort.InferenceSession(model, ort.SessionOptions(), self.providers())
+
+ # Load tokenizer. ONNX supports dynamic shapes, so pad to the longest sequence in each batch
+ tokenizer = self.loadtokenizer(path)
+ tokenizer.enable_padding()
+
+ maxlength = self.config.get("maxlength")
+ if maxlength:
+ tokenizer.enable_truncation(max_length=maxlength)
+
+ return (session, tokenizer)
+
+ def loadtokenizer(self, path):
+ """
+ Loads the tokenizer for a model. Reads the `tokenizer` configuration option when set,
+ otherwise falls back to a tokenizer.json file stored alongside the model.
+
+ Args:
+ path: model path
+
+ Returns:
+ Tokenizer
+ """
+
+ tokenizer = self.config.get("tokenizer")
+ if not tokenizer:
+ tokenizer = os.path.dirname(path) + "/" + "tokenizer.json"
+ tokenizer = tokenizer if os.path.exists(tokenizer) else Download()(tokenizer)
+
+ # Local tokenizer file vs a model id resolved through the HF Hub
+ return Tokenizer.from_file(tokenizer) if os.path.exists(tokenizer) else Tokenizer.from_pretrained(tokenizer)
+
+ def providers(self):
+ """
+ Returns a list of available and usable providers.
+
+ Returns:
+ list of available and usable providers
+ """
+
+ # Prefer the CUDA provider when it's available, it requires onnxruntime-gpu
+ if self.config.get("gpu", True) and "CUDAExecutionProvider" in ort.get_available_providers():
+ return ["CUDAExecutionProvider", "CPUExecutionProvider"]
+
+ return ["CPUExecutionProvider"]
+
+ def encode(self, data, category=None):
+ # Unpack model
+ session, tokenizer = self.model
+
+ results = []
+ for start in range(0, len(data), self.encodebatch):
+ batch = data[start : start + self.encodebatch]
+
+ inputs, masks = self.inputs(session, tokenizer.encode_batch(batch))
+
+ # Run model and pool the outputs into a single vector per input
+ results.append(self.pool(session.run(None, inputs)[0], masks))
+
+ return np.vstack(results)
+
+ def inputs(self, session, encoding):
+ """
+ Builds model inputs from a tokenized batch. Only inputs declared by the model are set,
+ since not every exported model takes token_type_ids.
+
+ Args:
+ session: inference session
+ encoding: tokenized batch
+
+ Returns:
+ (model inputs, attention masks)
+ """
+
+ masks = np.array([x.attention_mask for x in encoding], dtype=np.int64)
+ available = {x.name for x in session.get_inputs()}
+
+ features = {
+ "input_ids": np.array([x.ids for x in encoding], dtype=np.int64),
+ "attention_mask": masks,
+ "token_type_ids": np.array([x.type_ids for x in encoding], dtype=np.int64),
+ }
+
+ return {name: value for name, value in features.items() if name in available}, masks
+
+ def pool(self, outputs, masks):
+ """
+ Builds a single vector per input. Token-level outputs are mean pooled with the attention
+ mask, outputs that are already pooled are returned as is.
+
+ Args:
+ outputs: model outputs
+ masks: attention masks
+
+ Returns:
+ embeddings
+ """
+
+ # Model already returns a vector per input
+ if outputs.ndim == 2:
+ return outputs
+
+ # Mean pooling, ignoring padding tokens
+ masks = np.expand_dims(masks, -1).astype(outputs.dtype)
+ return np.sum(outputs * masks, axis=1) / np.clip(masks.sum(axis=1), a_min=1e-9, a_max=None)
diff --git a/test/python/testoptional.py b/test/python/testoptional.py
index 028c876a..0a7d74df 100644
--- a/test/python/testoptional.py
+++ b/test/python/testoptional.py
@@ -379,6 +379,9 @@ class TestOptional(unittest.TestCase):
with self.assertRaises(ImportError):
VectorsFactory.create({"method": "model2vec", "path": "minishlab/M2V_base_output"}, None)
+ with self.assertRaises(ImportError):
+ VectorsFactory.create({"method": "onnx", "path": "sentence-transformers/all-MiniLM-L6-v2/onnx/model.onnx"}, None)
+
with self.assertRaises(ImportError):
VectorsFactory.create({"method": "sentence-transformers", "path": "sentence-transformers/nli-mpnet-base-v2"}, None)
diff --git a/test/python/testvectors/testdense/testonnx.py b/test/python/testvectors/testdense/testonnx.py
new file mode 100644
index 00000000..7f73f653
--- /dev/null
+++ b/test/python/testvectors/testdense/testonnx.py
@@ -0,0 +1,253 @@
+"""
+ONNX module tests
+"""
+
+import os
+import shutil
+import tempfile
+import unittest
+
+from unittest.mock import patch
+
+import numpy as np
+import onnx
+
+from onnx import helper, TensorProto
+from tokenizers import Tokenizer, models, pre_tokenizers
+
+from txtai.pipeline import HFOnnx
+from txtai.vectors import VectorsFactory
+from txtai.vectors.dense.onnx import ONNX
+
+
+class TestONNX(unittest.TestCase):
+ """
+ ONNX vectors tests
+ """
+
+ @classmethod
+ def setUpClass(cls):
+ """
+ Export a model to ONNX and create an ONNX vectors instance.
+ """
+
+ path = "sentence-transformers/paraphrase-MiniLM-L3-v2"
+
+ # Export model to ONNX
+ cls.path = os.path.join(tempfile.gettempdir(), "vectors", "model.onnx")
+ os.makedirs(os.path.dirname(cls.path), exist_ok=True)
+ HFOnnx()(path, "pooling", cls.path)
+
+ cls.model = VectorsFactory.create({"path": cls.path, "tokenizer": path, "gpu": False}, None)
+
+ def testMethod(self):
+ """
+ Test that an .onnx path resolves to the onnx method
+ """
+
+ self.assertEqual(VectorsFactory.method({"path": self.path}), "onnx")
+ self.assertEqual(VectorsFactory.method({"path": "model.tflite"}), "litert")
+
+ def testIndex(self):
+ """
+ Test indexing with ONNX vectors
+ """
+
+ ids, dimension, batches, stream = self.model.index([(0, "test", None)])
+
+ self.assertEqual(len(ids), 1)
+ self.assertEqual(dimension, 384)
+ self.assertEqual(batches, 1)
+ self.assertIsNotNone(os.path.exists(stream))
+
+ # Test shape of serialized embeddings
+ with open(stream, "rb") as queue:
+ self.assertEqual(np.load(queue).shape, (1, 384))
+
+ def testEncodeBatch(self):
+ """
+ Test that results are stable when a batch spans multiple encode batches
+ """
+
+ data = ["dog", "puppy", "quantum chromodynamics", "cat", "kitten"]
+
+ single = self.model.encode(data)
+
+ self.model.encodebatch = 2
+ batched = self.model.encode(data)
+ self.model.encodebatch = 32
+
+ self.assertEqual(single.shape, (5, 384))
+
+ # Each input sees a different amount of padding depending on how the data is batched,
+ # so compare direction rather than exact values
+ single = single / np.linalg.norm(single, axis=1, keepdims=True)
+ batched = batched / np.linalg.norm(batched, axis=1, keepdims=True)
+ self.assertTrue(np.all(np.sum(single * batched, axis=1) > 0.99))
+
+ def testSimilarity(self):
+ """
+ Test that pooled embeddings carry semantics
+ """
+
+ embeddings = self.model.encode(["dog", "puppy", "quantum chromodynamics"])
+ embeddings = embeddings / np.linalg.norm(embeddings, axis=1, keepdims=True)
+
+ self.assertGreater(float(embeddings[0] @ embeddings[1]), float(embeddings[0] @ embeddings[2]))
+
+
+class TestONNXModels(unittest.TestCase):
+ """
+ ONNX vectors tests covering model shapes and configuration a single exported model doesn't reach.
+ These build small ONNX graphs locally, no model download required.
+ """
+
+ @classmethod
+ def setUpClass(cls):
+ """
+ Create a working directory and a small tokenizer.
+ """
+
+ cls.directory = os.path.join(tempfile.gettempdir(), "onnxvectors")
+ os.makedirs(cls.directory, exist_ok=True)
+
+ vocab = {"[PAD]": 0, "[UNK]": 1, "dog": 2, "puppy": 3, "quantum": 4, "physics": 5}
+ tokenizer = Tokenizer(models.WordLevel(vocab=vocab, unk_token="[UNK]"))
+ tokenizer.pre_tokenizer = pre_tokenizers.Whitespace()
+
+ cls.tokenizer = os.path.join(cls.directory, "tokenizer.json")
+ tokenizer.save(cls.tokenizer)
+
+ cls.vocab = len(vocab)
+
+ def build(self, name, pooled=False, types=False):
+ """
+ Builds a small ONNX model that maps input ids to hidden states.
+
+ Args:
+ name: model file name
+ pooled: True to output a single vector per input, False for token level output
+ types: True to declare a token_type_ids input
+
+ Returns:
+ model path
+ """
+
+ table = np.eye(self.vocab, 4, dtype=np.float32)
+ initializers = [helper.make_tensor("table", TensorProto.FLOAT, table.shape, table.flatten())]
+
+ inputs = [
+ helper.make_tensor_value_info("input_ids", TensorProto.INT64, ["batch", "sequence"]),
+ helper.make_tensor_value_info("attention_mask", TensorProto.INT64, ["batch", "sequence"]),
+ ]
+ if types:
+ inputs.append(helper.make_tensor_value_info("token_type_ids", TensorProto.INT64, ["batch", "sequence"]))
+
+ nodes = [helper.make_node("Gather", ["table", "input_ids"], ["hidden"], axis=0)]
+ if pooled:
+ nodes.append(helper.make_node("ReduceMean", ["hidden"], ["output"], axes=[1], keepdims=0))
+ outputs = [helper.make_tensor_value_info("output", TensorProto.FLOAT, ["batch", 4])]
+ else:
+ nodes.append(helper.make_node("Identity", ["hidden"], ["output"]))
+ outputs = [helper.make_tensor_value_info("output", TensorProto.FLOAT, ["batch", "sequence", 4])]
+
+ graph = helper.make_graph(nodes, "model", inputs, outputs, initializer=initializers)
+
+ # Pin the opset, the default tracks the installed onnx package and can run ahead of onnxruntime
+ model = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 14)])
+ model.ir_version = 9
+
+ path = os.path.join(self.directory, name)
+ onnx.save(model, path)
+
+ return path
+
+ def model(self, path, **config):
+ """
+ Creates an ONNX vectors instance.
+
+ Args:
+ path: model path
+ config: additional configuration
+
+ Returns:
+ ONNX
+ """
+
+ return ONNX({"path": path, "tokenizer": self.tokenizer, "gpu": False, **config}, None, None)
+
+ def testTokenOutput(self):
+ """
+ Test that token level output is pooled into a single vector per input
+ """
+
+ model = self.model(self.build("tokens.onnx"))
+ self.assertEqual(model.encode(["dog puppy", "quantum"]).shape, (2, 4))
+
+ def testPooledOutput(self):
+ """
+ Test that output which is already pooled passes through
+ """
+
+ model = self.model(self.build("pooled.onnx", pooled=True))
+ self.assertEqual(model.encode(["dog puppy"]).shape, (1, 4))
+
+ def testTokenTypeIds(self):
+ """
+ Test that token_type_ids is set only when the model declares it
+ """
+
+ self.assertEqual(self.model(self.build("types.onnx", types=True)).encode(["dog", "quantum physics"]).shape, (2, 4))
+ self.assertEqual(self.model(self.build("notypes.onnx")).encode(["dog", "quantum physics"]).shape, (2, 4))
+
+ def testPadding(self):
+ """
+ Test that padding is excluded when pooling
+ """
+
+ model = self.model(self.build("padding.onnx"))
+
+ # An input padded to a longer sequence must produce the same vector as that input alone
+ self.assertTrue(np.allclose(model.encode(["dog"])[0], model.encode(["dog", "quantum physics"])[0], atol=1e-6))
+
+ def testMaxLength(self):
+ """
+ Test that maxlength truncates long inputs
+ """
+
+ model = self.model(self.build("maxlength.onnx"), maxlength=1)
+ self.assertTrue(np.allclose(model.encode(["dog quantum physics"])[0], model.encode(["dog"])[0], atol=1e-6))
+
+ def testTokenizerPath(self):
+ """
+ Test that a tokenizer stored alongside the model is found when one isn't configured
+ """
+
+ directory = os.path.join(self.directory, "sibling")
+ os.makedirs(directory, exist_ok=True)
+ shutil.copy(self.tokenizer, os.path.join(directory, "tokenizer.json"))
+
+ path = self.build(os.path.join("sibling", "model.onnx"))
+ model = ONNX({"path": path, "gpu": False}, None, None)
+
+ self.assertEqual(model.encode(["dog"]).shape, (1, 4))
+
+ def testProviders(self):
+ """
+ Test provider selection
+ """
+
+ model = self.model(self.build("providers.onnx"))
+
+ with patch("txtai.vectors.dense.onnx.ort.get_available_providers") as providers:
+ providers.return_value = ["CUDAExecutionProvider", "CPUExecutionProvider"]
+
+ model.config["gpu"] = True
+ self.assertEqual(model.providers(), ["CUDAExecutionProvider", "CPUExecutionProvider"])
+
+ model.config["gpu"] = False
+ self.assertEqual(model.providers(), ["CPUExecutionProvider"])
+
+ providers.return_value = ["CPUExecutionProvider"]
+ model.config["gpu"] = True
+ self.assertEqual(model.providers(), ["CPUExecutionProvider"])