模型:
apple/ane-distilbert-base-uncased-finetuned-sst-2-english
这是适用于苹果神经引擎(ANE)的 distilbert-base-uncased-finetuned-sst-2-english 模型,正如文章 Deploying Transformers on the Apple Neural Engine 中描述的那样。
源代码取自苹果的 ml-ane-transformers GitHub 存储库,稍作修改以使其能够从 🤗 Transformers 库中使用。
关于 DistilBERT 的更多细节,请用户查看 this model card 。
使用示例:
import torch
from transformers import AutoModelForSequenceClassification, AutoTokenizer
model_checkpoint = "apple/ane-distilbert-base-uncased-finetuned-sst-2-english"
tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)
model = AutoModelForSequenceClassification.from_pretrained(
model_checkpoint, trust_remote_code=True, return_dict=False,
)
inputs = tokenizer(
["The Neural Engine is really fast"],
return_tensors="pt",
max_length=128,
padding="max_length",
)
with torch.no_grad():
outputs = model(**inputs)
PyTorch 不使用 ANE,并且在 CPU 或 GPU 上运行此版本的模型可能比原始模型更慢。要利用 ANE 的硬件加速功能,请使用 Core ML 版本的模型, DistilBERT_fp16.mlpackage。
Python 中使用 Core ML 的示例:
import coremltools as ct
mlmodel = ct.models.MLModel("DistilBERT_fp16.mlpackage")
inputs = tokenizer(
["The Neural Engine is really fast"],
return_tensors="np",
max_length=128,
padding="max_length",
)
outputs_coreml = mlmodel.predict({
"input_ids": inputs["input_ids"].astype(np.int32),
"attention_mask": inputs["attention_mask"].astype(np.int32),
})
要从 Swift 中使用该模型,您需要根据 BERT 规则自行对输入进行分词。您可以找到一个 Swift 实现版本的 BERT tokenizer here 。