This repository implements a
custom
handler for
question-answering
for 🤗 Inference Endpoints for accelerated inference using
🤗 Optiumum
. The code for the customized handler is in the
handler.py
.
{"inputs":{"question":"As what is Philipp working?","context":"Hello, my name is Philipp and I live in Nuremberg, Germany. Currently I am working as a Technical Lead at Hugging Face to democratize artificial intelligence through open source and open science. In the past I designed and implemented cloud-native machine learning architectures for fin-tech and insurance companies. I found my passion for cloud concepts and machine learning 5 years ago. Since then I never stopped learning. Currently, I am focusing myself in the area NLP and how to leverage models like BERT, Roberta, T5, ViT, and GPT2 to generate business value."}}
below is an example on how to run a request using Python and
requests
.
Run Request
import json
from typing importListimport requests as r
import base64
ENDPOINT_URL = ""
HF_TOKEN = ""defpredict(question:str=None,context:str=None):
payload = {"inputs": {"question": question, "context": context}}
response = r.post(
ENDPOINT_URL, headers={"Authorization": f"Bearer {HF_TOKEN}"}, json=payload
)
return response.json()
prediction = predict(
question="As what is Philipp working?",
context="Hello, my name is Philipp and I live in Nuremberg, Germany. Currently I am working as a Technical Lead at Hugging Face to democratize artificial intelligence through open source and open science."
)
from transformers import pipeline
qa = pipeline("question-answering",model="deepset/roberta-base-squad2")
Okay, let's test the performance (latency) with sequence length of 128.
context="Hello, my name is Philipp and I live in Nuremberg, Germany. Currently I am working as a Technical Lead at Hugging Face to democratize artificial intelligence through open source and open science. In the past I designed and implemented cloud-native machine learning architectures for fin-tech and insurance companies. I found my passion for cloud concepts and machine learning 5 years ago. Since then I never stopped learning. Currently, I am focusing myself in the area NLP and how to leverage models like BERT, Roberta, T5, ViT, and GPT2 to generate business value."
question="As what is Philipp working?"
payload = {"inputs": {"question": question, "context": context}}
from optimum.onnxruntime import ORTModelForQuestionAnswering
from transformers import AutoTokenizer
from pathlib import Path
model_id="deepset/roberta-base-squad2"
onnx_path = Path(".")
# load vanilla transformers and convert to onnx
model = ORTModelForQuestionAnswering.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 the optimizer
optimizer = ORTOptimizer.from_pretrained(model)
# Define the optimization strategy by creating the appropriate configuration
optimization_config = OptimizationConfig(optimization_level=99) # enable all optimizations# Optimize the model
optimizer.optimize(save_dir=onnx_path, optimization_config=optimization_config)
# create ORTQuantizer and define quantization configuration
dynamic_quantizer = ORTQuantizer.from_pretrained(onnx_path, file_name="model_optimized.onnx")
dqconfig = AutoQuantizationConfig.avx512_vnni(is_static=False, per_channel=False)
# apply the quantization configuration to the model
model_quantized_path = dynamic_quantizer.quantize(
save_dir=onnx_path,
quantization_config=dqconfig,
)
3. Create Custom Handler for Inference Endpoints
%%writefile handler.py
from typing importDict, List, Anyfrom optimum.onnxruntime import ORTModelForQuestionAnswering
from transformers import AutoTokenizer, pipeline
classEndpointHandler():
def__init__(self, path=""):
# load the optimized model
self.model = ORTModelForQuestionAnswering.from_pretrained(path, file_name="model_optimized_quantized.onnx")
self.tokenizer = AutoTokenizer.from_pretrained(path)
# create pipeline
self.pipeline = pipeline("question-answering", model=self.model, tokenizer=self.tokenizer)
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 answer and scores of the inference inputs """
inputs = data.get("inputs", data)
# run the model
prediction = self.pipeline(**inputs)
# return predictionreturn prediction
4. Test Custom Handler Locally
from handler import EndpointHandler
# init handler
my_handler = EndpointHandler(path=".")
# prepare sample payload
context="Hello, my name is Philipp and I live in Nuremberg, Germany. Currently I am working as a Technical Lead at Hugging Face to democratize artificial intelligence through open source and open science. In the past I designed and implemented cloud-native machine learning architectures for fin-tech and insurance companies. I found my passion for cloud concepts and machine learning 5 years ago. Since then I never stopped learning. Currently, I am focusing myself in the area NLP and how to leverage models like BERT, Roberta, T5, ViT, and GPT2 to generate business value."
question="As what is Philipp working?"
payload = {"inputs": {"question": question, "context": context}}
# test the handler
my_handler(payload)
roberta-base-squad2-optimized huggingface.co is an AI model on huggingface.co that provides roberta-base-squad2-optimized's model effect (), which can be used instantly with this philschmid roberta-base-squad2-optimized model. huggingface.co supports a free trial of the roberta-base-squad2-optimized model, and also provides paid use of the roberta-base-squad2-optimized. Support call roberta-base-squad2-optimized model through api, including Node.js, Python, http.
roberta-base-squad2-optimized huggingface.co is an online trial and call api platform, which integrates roberta-base-squad2-optimized's modeling effects, including api services, and provides a free online trial of roberta-base-squad2-optimized, you can try roberta-base-squad2-optimized online for free by clicking the link below.
philschmid roberta-base-squad2-optimized online free url in huggingface.co:
roberta-base-squad2-optimized is an open source model from GitHub that offers a free installation service, and any user can find roberta-base-squad2-optimized on GitHub to install. At the same time, huggingface.co provides the effect of roberta-base-squad2-optimized install, users can directly use roberta-base-squad2-optimized installed effect in huggingface.co for debugging and trial. It also supports api for free installation.
roberta-base-squad2-optimized install url in huggingface.co: