File size: 1,123 Bytes
a4709f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
"""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].
IntentClassifier 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_intent import IntentClassifier


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 = IntentClassifier(here, device="cpu")
clf.net = OnnxNet(os.path.join(here, "onnx", name))
print(clf.classify('कल सुबह सात बजे का अलार्म लगा दो'))