ONNX 模型库
返回模型

说明文档

这是 SamLowe/roberta-base-go_emotions-onnx 模型的 ONNX 版本,对应原始模型为 https://huggingface.co/SamLowe/roberta-base-go_emotions

全精度 ONNX 版本

onnx/model.onnx 是全精度 ONNX 版本

  • 具有与原始 Transformers 模型相同的精度/指标
  • 模型大小相同(499MB)
  • 推理速度比普通 Transformers 更快,尤其是在小批次情况下
    • 在我的测试中,使用 ONNXRuntime 在 8 核第 11 代 i7 CPU 上,批次大小为 1 时大约快 2 到 3 倍

指标

使用固定的 0.5 阈值将分数转换为每个标签的二分类预测:

  • 准确率:0.474
  • 精确率:0.575
  • 召回率:0.396
  • F1:0.450

更多详细信息请参阅 SamLowe/roberta-base-go_emotions 模型卡片,了解通过选择特定标签阈值来最大化 F1 分数或其他指标的可能提升。

量化(INT8)ONNX 版本

onnx/model_quantized.onnx 是 int8 量化版本

  • 大小是全精度模型的四分之一(125MB)
  • 但几乎保留了所有精度
  • 推理速度比上面的全精度 ONNX 版本和普通 Transformers 模型都快
    • 在 8 核第 11 代 i7 CPU 上使用 ONNXRuntime,批次大小为 1 时比上面的全精度模型快约 2 倍
    • 因此比全精度普通 Transformers 模型快约 5 倍(在上述 CPU 上,批次大小为 1)

量化(INT8)模型的指标

使用固定的 0.5 阈值将分数转换为每个标签的二分类预测:

  • 准确率:0.475
  • 精确率:0.582
  • 召回率:0.398
  • F1:0.447

注意指标与上面的全精度指标几乎相同。

更多详细信息请参阅 SamLowe/roberta-base-go_emotions 模型卡片,了解通过选择特定标签阈值来最大化 F1 分数或其他指标的可能提升。

如何使用

使用 Optimum Library ONNX 类

Optimum 库有与主要 Transformers 类等效的类(以 ORT 开头),因此这些模型可以使用熟悉的结构来使用。唯一需要的额外属性是模型创建时的 file_name,在下面的示例中指定了量化(INT8)模型。

sentences = ["ONNX is seriously fast for small batches. Impressive"]

from transformers import AutoTokenizer, pipeline
from optimum.onnxruntime import ORTModelForSequenceClassification

model_id = "SamLowe/roberta-base-go_emotions-onnx"
file_name = "onnx/model_quantized.onnx"

model = ORTModelForSequenceClassification.from_pretrained(model_id, file_name=file_name)
tokenizer = AutoTokenizer.from_pretrained(model_id)

onnx_classifier = pipeline(
    task="text-classification",
    model=model,
    tokenizer=tokenizer,
    top_k=None,
    function_to_apply="sigmoid",  # optional as is the default for the task
)

model_outputs = onnx_classifier(sentences)
# gives a list of outputs, each a list of dicts (one per label)

print(model_outputs)
# E.g.
# [[{'label': 'admiration', 'score': 0.9203393459320068},
#   {'label': 'approval', 'score': 0.0560273639857769},
#   {'label': 'neutral', 'score': 0.04265536740422249},
#   {'label': 'gratitude', 'score': 0.015126707963645458},
# ...

使用 ONNXRuntime

  • 分词可以事先用 tokenizers 库完成,
  • 然后将其作为 ONNXRuntime 使用的字典类型输入,
  • 之后只需对模型输出(以 numpy 数组形式返回)进行后处理 sigmoid 即可生成嵌入。
from tokenizers import Tokenizer
import onnxruntime as ort

from os import cpu_count
import numpy as np  # only used for the postprocessing sigmoid

sentences = ["hello world"]  # for example a batch of 1

# labels as (ordered) list - from the go_emotions dataset
labels = ['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']

tokenizer = Tokenizer.from_pretrained("SamLowe/roberta-base-go_emotions")

# Optional - set pad to only pad to longest in batch, not a fixed length.
# (without this, the model will run slower, esp for shorter input strings)
params = {**tokenizer.padding, "length": None}
tokenizer.enable_padding(**params)

tokens_obj = tokenizer.encode_batch(sentences)

def load_onnx_model(model_filepath):
    _options = ort.SessionOptions()
    _options.inter_op_num_threads, _options.intra_op_num_threads = cpu_count(), cpu_count()
    _providers = ["CPUExecutionProvider"]  # could use ort.get_available_providers()
    return ort.InferenceSession(path_or_bytes=model_filepath, sess_options=_options, providers=_providers)

model = load_onnx_model("path_to_model_dot_onnx_or_model_quantized_dot_onnx")
output_names = [model.get_outputs()[0].name]  # E.g. ["logits"]

input_feed_dict = {
  "input_ids": [t.ids for t in tokens_obj],
  "attention_mask": [t.attention_mask for t in tokens_obj]
}

logits = model.run(output_names=output_names, input_feed=input_feed_dict)[0]
# produces a numpy array, one row per input item, one col per label

def sigmoid(x):
  return 1.0 / (1.0 + np.exp(-x))

# Post-processing. Gets the scores per label in range.
# Auto done by Transformers' pipeline, but we must do it manually with ORT.
model_outputs = sigmoid(logits) 

# for example, just to show the top result per input item
for probas in model_outputs:
  top_result_index = np.argmax(probas)
  print(labels[top_result_index], "with score:", probas[top_result_index])

示例笔记本:展示用法、准确率和性能

更多详细信息请参阅后续笔记本。

SamLowe/roberta-base-go_emotions-onnx

作者 SamLowe

text-classification transformers
↓ 99.5K ♥ 26

创建时间: 2023-09-28 14:07:22+00:00

更新时间: 2023-09-29 00:02:20+00:00

在 Hugging Face 上查看

文件 (19)

.gitattributes
README.md
config.json
merges.txt
onnx/config.json
onnx/merges.txt
onnx/model.onnx ONNX
onnx/model_quantized.onnx ONNX
onnx/ort_config.json
onnx/ort_config_quantized.json
onnx/special_tokens_map.json
onnx/tokenizer.json
onnx/tokenizer_config.json
onnx/vocab.json
special_tokens_map.json
tokenizer.json
tokenizer_config.json
trainer_state.json
vocab.json