Views
No views yet
onnx/model.onnx is the full precision ONNX versiononnx/model_quantized.onnx is the int8 quantized versionORT) for the main Transformers classes, so these models can be used with the familiar constructs. The only extra property needed is file_name on the model creation, which in the below example specifies the quantized (INT8) model.1sentences = ["ONNX is seriously fast for small batches. Impressive"]
2
3from transformers import AutoTokenizer, pipeline
4from optimum.onnxruntime import ORTModelForSequenceClassification
5
6model_id = "SamLowe/roberta-base-go_emotions-onnx"
7file_name = "onnx/model_quantized.onnx"
8
9model = ORTModelForSequenceClassification.from_pretrained(model_id, file_name=file_name)
10tokenizer = AutoTokenizer.from_pretrained(model_id)
11
12onnx_classifier = pipeline(
13 task="text-classification",
14 model=model,
15 tokenizer=tokenizer,
16 top_k=None,
17 function_to_apply="sigmoid", # optional as is the default for the task
18)
19
20model_outputs = onnx_classifier(sentences)
21# gives a list of outputs, each a list of dicts (one per label)
22
23print(model_outputs)
24# E.g.
25# [[{'label': 'admiration', 'score': 0.9203393459320068},
26# {'label': 'approval', 'score': 0.0560273639857769},
27# {'label': 'neutral', 'score': 0.04265536740422249},
28# {'label': 'gratitude', 'score': 0.015126707963645458},
29# ...tokenizers library,1from tokenizers import Tokenizer
2import onnxruntime as ort
3
4from os import cpu_count
5import numpy as np # only used for the postprocessing sigmoid
6
7sentences = ["hello world"] # for example a batch of 1
8
9# labels as (ordered) list - from the go_emotions dataset
10labels = ['admiration', 'amusement', 'anger', 'annoyance', 'approval', 'caring', 'confusion', 'curiosity', 'desire', 'disappointment', 'disapproval', 'disgust', 'embarrassment', 'excitement', 'fear', 'gratitude', 'grief', 'joy', 'love', 'nervousness', 'optimism', 'pride', 'realization', 'relief', 'remorse', 'sadness', 'surprise', 'neutral']
11
12tokenizer = Tokenizer.from_pretrained("SamLowe/roberta-base-go_emotions")
13
14# Optional - set pad to only pad to longest in batch, not a fixed length.
15# (without this, the model will run slower, esp for shorter input strings)
16params = {**tokenizer.padding, "length": None}
17tokenizer.enable_padding(**params)
18
19tokens_obj = tokenizer.encode_batch(sentences)
20
21def load_onnx_model(model_filepath):
22 _options = ort.SessionOptions()
23 _options.inter_op_num_threads, _options.intra_op_num_threads = cpu_count(), cpu_count()
24 _providers = ["CPUExecutionProvider"] # could use ort.get_available_providers()
25 return ort.InferenceSession(path_or_bytes=model_filepath, sess_options=_options, providers=_providers)
26
27model = load_onnx_model("path_to_model_dot_onnx_or_model_quantized_dot_onnx")
28output_names = [model.get_outputs()[0].name] # E.g. ["logits"]
29
30input_feed_dict = {
31 "input_ids": [t.ids for t in tokens_obj],
32 "attention_mask": [t.attention_mask for t in tokens_obj]
33}
34
35logits = model.run(output_names=output_names, input_feed=input_feed_dict)[0]
36# produces a numpy array, one row per input item, one col per label
37
38def sigmoid(x):
39 return 1.0 / (1.0 + np.exp(-x))
40
41# Post-processing. Gets the scores per label in range.
42# Auto done by Transformers' pipeline, but we must do it manually with ORT.
43model_outputs = sigmoid(logits)
44
45# for example, just to show the top result per input item
46for probas in model_outputs:
47 top_result_index = np.argmax(probas)
48 print(labels[top_result_index], "with score:", probas[top_result_index])