microsoft/onnxruntime-extensions

Public

mirrored fromhttps://github.com/microsoft/onnxruntime-extensionsAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
9bd453e0f1fa7966789c228ba8e27fc7023d7063

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

onnxruntime_extensions/_ortapi2.py

128lines · modecode

1# Copyright (c) Microsoft Corporation. All rights reserved.
2# Licensed under the MIT License. See License.txt in the project root for
3# license information.
4###############################################################################
5
6import numpy as np
7import onnxruntime as _ort
8from ._ocos import default_opset_domain, get_library_path # noqa
9from ._cuops import * # noqa
10
11
12def get_opset_version_from_ort():
13 _ORT_OPSET_SUPPORT_TABLE = {
14 "1.5": 11,
15 "1.6": 12,
16 "1.7": 13,
17 "1.8": 14,
18 "1.9": 15
19 }
20
21 ort_ver_string = '.'.join(_ort.__version__.split('.')[0:2])
22 return _ORT_OPSET_SUPPORT_TABLE.get(ort_ver_string, 11)
23
24
25def make_onnx_model(graph, opset_version=0, extra_domain=default_opset_domain(), extra_opset_version=1):
26 if opset_version == 0:
27 opset_version = get_opset_version_from_ort()
28 fn_mm = onnx.helper.make_model_gen_version if hasattr(onnx.helper, 'make_model_gen_version'
29 ) else onnx.helper.make_model
30 model = fn_mm(graph, opset_imports=[
31 onnx.helper.make_operatorsetid('ai.onnx', opset_version)])
32 model.opset_import.extend([onnx.helper.make_operatorsetid(extra_domain, extra_opset_version)])
33 return model
34
35
36class OrtPyFunction:
37
38 @classmethod
39 def get_ort_session_options(cls):
40 # ONNXRuntime has an issue to support reusing the SessionOptions object.
41 # Create a new one every time here
42 so = _ort.SessionOptions()
43 so.register_custom_ops_library(get_library_path())
44 return so
45
46 def __init__(self):
47 self._onnx_model = None
48 self.ort_session = None
49 self.default_inputs = {}
50
51 def create_from_customop(self, op_type, *args, **kwargs):
52 graph = SingleOpGraph.build_my_graph(op_type, *args, **kwargs)
53 self._bind(make_onnx_model(graph))
54 return self
55
56 def add_default_input(self, **kwargs):
57 inputs = {
58 ky_: val_ if isinstance(val_, (np.ndarray, np.generic)) else \
59 np.asarray(list(val_), dtype=np.uint8) for ky_, val_ in kwargs.items()
60 }
61
62 self.default_inputs.update(inputs)
63
64 @property
65 def onnx_model(self):
66 assert self._oxml is not None, "No onnx model attached yet."
67 return self._oxml
68
69 @property
70 def input_names(self):
71 return [vi_.name for vi_ in self.onnx_model.graph.input]
72
73 @property
74 def output_names(self):
75 return [vi_.name for vi_ in self.onnx_model.graph.output]
76
77 def _bind(self, oxml):
78 self.inputs = list(oxml.graph.input)
79 self.output = list(oxml.graph.output)
80 self._oxml = oxml
81 return self
82
83 def _ensure_ort_session(self):
84 if self.ort_session is None:
85 sess = _ort.InferenceSession(self.onnx_model.SerializeToString(), self.get_ort_session_options())
86 self.ort_session = sess
87
88 return self.ort_session
89
90 @classmethod
91 def from_customop(cls, op_type, *args, **kwargs):
92 return cls().create_from_customop(op_type, *args, **kwargs)
93
94 @classmethod
95 def from_model(cls, path_or_model, *args, **kwargs):
96 return cls()._bind(onnx.load_model(path_or_model) if isinstance(path_or_model, str) else path_or_model)
97
98 def _argument_map(self, *args, **kwargs):
99 idx = 0
100 feed = {}
101 for i_ in self.inputs:
102 if i_.name in self.default_inputs:
103 feed[i_.name] = self.default_inputs[i_.name]
104 continue
105
106 x = args[idx]
107 ts_x = np.array(x) if isinstance(x, (int, float, bool)) else x
108 # an annoying bug is numpy by default is int32, while pytorch is int64.
109 # so cast the input here automatically.
110 feed[i_.name] = \
111 ts_x.astype(np.int64) if i_.type.tensor_type.elem_type == onnx_proto.TensorProto.INT64 else ts_x
112 idx += 1
113
114 # feed.update(kwargs)
115 return feed
116
117 def __call__(self, *args, **kwargs):
118 self._ensure_ort_session()
119 outputs = self.ort_session.run(None, self._argument_map(*args, **kwargs))
120 return outputs[0] if len(outputs) == 1 else tuple(outputs)
121
122
123def optimize_model(model_or_file, output_file):
124 sess_options = OrtPyFunction.get_ort_session_options()
125 sess_options.graph_optimization_level = _ort.GraphOptimizationLevel.ORT_ENABLE_BASIC
126 sess_options.optimized_model_filepath = output_file
127 _ort.InferenceSession(model_or_file if isinstance(model_or_file, str)
128 else model_or_file.SerializeToString(), sess_options)
129