SRK-CobuildX's picture
Release v0.1
5e83015 verified
Raw History Blame Contribute Delete
1.11 kB
"""Run the model with ONNX Runtime instead of PyTorch (CPU).
pip install onnxruntime
python onnx_example.py
onnx/model.onnx takes `input_ids` and `attention_mask` [batch, length] and returns the logits [batch, labels].
SentimentClassifier still does the tokenisation and the decision; only the network call changes.
"""
import os
import numpy as np
import onnxruntime as ort
import torch
from cbx_sentiment import SentimentClassifier
class OnnxNet:
def __init__(self, file):
self.sess = ort.InferenceSession(file, providers=["CPUExecutionProvider"])
def __call__(self, input_ids, attention_mask):
out = self.sess.run(None, {"input_ids": input_ids.cpu().numpy().astype(np.int64),
"attention_mask": attention_mask.cpu().numpy().astype(np.int64)})[0]
return torch.from_numpy(out)
here = os.path.dirname(os.path.abspath(__file__))
name = "model.onnx"
clf = SentimentClassifier(here, device="cpu")
clf.net = OnnxNet(os.path.join(here, "onnx", name))
print(clf.classify('Bahut badhiya phone hai, battery poora din chalti hai.'))