This repository implements a
custom
task for
sentence-embeddings
for 🤗 Inference Endpoints for accelerated inference using
🤗 Optimum
. The code for the customized pipeline is in the
pipeline.py
.
from optimum.onnxruntime import ORTModelForFeatureExtraction
from transformers import AutoTokenizer
from pathlib import Path
model_id="sentence-transformers/all-MiniLM-L6-v2"
onnx_path = Path(".")
# load vanilla transformers and convert to onnx
model = ORTModelForFeatureExtraction.from_pretrained(model_id, from_transformers=True)
tokenizer = AutoTokenizer.from_pretrained(model_id)
# save onnx checkpoint and tokenizer
model.save_pretrained(onnx_path)
tokenizer.save_pretrained(onnx_path)
2. Optimize & quantize model with Optimum
from optimum.onnxruntime import ORTOptimizer, ORTQuantizer
from optimum.onnxruntime.configuration import OptimizationConfig, AutoQuantizationConfig
# create ORTOptimizer and define optimization configuration
optimizer = ORTOptimizer.from_pretrained(model_id, feature=model.pipeline_task)
optimization_config = OptimizationConfig(optimization_level=99) # enable all optimizations# apply the optimization configuration to the model
optimizer.export(
onnx_model_path=onnx_path / "model.onnx",
onnx_optimized_model_output_path=onnx_path / "model-optimized.onnx",
optimization_config=optimization_config,
)
# create ORTQuantizer and define quantization configuration
dynamic_quantizer = ORTQuantizer.from_pretrained(model_id, feature=model.pipeline_task)
dqconfig = AutoQuantizationConfig.avx512_vnni(is_static=False, per_channel=False)
# apply the quantization configuration to the model
model_quantized_path = dynamic_quantizer.export(
onnx_model_path=onnx_path / "model-optimized.onnx",
onnx_quantized_model_output_path=onnx_path / "model-quantized.onnx",
quantization_config=dqconfig,
)
3. Create Custom Handler for Inference Endpoints
%%writefile pipeline.py
from typing importDict, List, Anyfrom optimum.onnxruntime import ORTModelForFeatureExtraction
from transformers import AutoTokenizer
import torch.nn.functional as F
import torch
# copied from the model carddefmean_pooling(model_output, attention_mask):
token_embeddings = model_output[0] #First element of model_output contains all token embeddings
input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(input_mask_expanded.sum(1), min=1e-9)
classPreTrainedPipeline():
def__init__(self, path=""):
# load the optimized model
self.model = ORTModelForFeatureExtraction.from_pretrained(path, file_name="model-quantized.onnx")
self.tokenizer = AutoTokenizer.from_pretrained(path)
def__call__(self, data: Any) -> List[List[Dict[str, float]]]:
""" Args: data (:obj:): includes the input data and the parameters for the inference. Return: A :obj:`list`:. The list contains the embeddings of the inference inputs """
inputs = data.get("inputs", data)
# tokenize the input
encoded_inputs = self.tokenizer(inputs, padding=True, truncation=True, return_tensors='pt')
# run the model
outputs = self.model(**encoded_inputs)
# Perform pooling
sentence_embeddings = mean_pooling(outputs, encoded_inputs['attention_mask'])
# Normalize embeddings
sentence_embeddings = F.normalize(sentence_embeddings, p=2, dim=1)
# postprocess the predictionreturn {"embeddings": sentence_embeddings.tolist()}
test custom pipeline
from pipeline import PreTrainedPipeline
# init handler
my_handler = PreTrainedPipeline(path=".")
# prepare sample payload
request = {"inputs": "I am quite excited how this will turn out"}
# test the handler
%timeit my_handler(request)
results
1.55 ms ± 2.04 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
Runs of philschmid all-MiniLM-L6-v2-optimum-embeddings on huggingface.co
37
Total runs
0
24-hour runs
1
3-day runs
3
7-day runs
28
30-day runs
More Information About all-MiniLM-L6-v2-optimum-embeddings huggingface.co Model
More all-MiniLM-L6-v2-optimum-embeddings license Visit here:
all-MiniLM-L6-v2-optimum-embeddings huggingface.co is an AI model on huggingface.co that provides all-MiniLM-L6-v2-optimum-embeddings's model effect (), which can be used instantly with this philschmid all-MiniLM-L6-v2-optimum-embeddings model. huggingface.co supports a free trial of the all-MiniLM-L6-v2-optimum-embeddings model, and also provides paid use of the all-MiniLM-L6-v2-optimum-embeddings. Support call all-MiniLM-L6-v2-optimum-embeddings model through api, including Node.js, Python, http.
all-MiniLM-L6-v2-optimum-embeddings huggingface.co is an online trial and call api platform, which integrates all-MiniLM-L6-v2-optimum-embeddings's modeling effects, including api services, and provides a free online trial of all-MiniLM-L6-v2-optimum-embeddings, you can try all-MiniLM-L6-v2-optimum-embeddings online for free by clicking the link below.
philschmid all-MiniLM-L6-v2-optimum-embeddings online free url in huggingface.co:
all-MiniLM-L6-v2-optimum-embeddings is an open source model from GitHub that offers a free installation service, and any user can find all-MiniLM-L6-v2-optimum-embeddings on GitHub to install. At the same time, huggingface.co provides the effect of all-MiniLM-L6-v2-optimum-embeddings install, users can directly use all-MiniLM-L6-v2-optimum-embeddings installed effect in huggingface.co for debugging and trial. It also supports api for free installation.
all-MiniLM-L6-v2-optimum-embeddings install url in huggingface.co: