onnx-diagnostic 0.5.0__py3-none-any.whl → 0.6.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- onnx_diagnostic/__init__.py +2 -2
- onnx_diagnostic/_command_lines_parser.py +39 -1
- onnx_diagnostic/api.py +15 -0
- onnx_diagnostic/export/dynamic_shapes.py +14 -5
- onnx_diagnostic/ext_test_case.py +15 -1
- onnx_diagnostic/helpers/args_helper.py +1 -1
- onnx_diagnostic/helpers/graph_helper.py +386 -0
- onnx_diagnostic/helpers/helper.py +30 -5
- onnx_diagnostic/helpers/model_builder_helper.py +349 -0
- onnx_diagnostic/helpers/rt_helper.py +69 -1
- onnx_diagnostic/helpers/torch_helper.py +2 -0
- onnx_diagnostic/reference/__init__.py +1 -0
- onnx_diagnostic/reference/torch_evaluator.py +518 -0
- onnx_diagnostic/reference/torch_ops/__init__.py +55 -0
- onnx_diagnostic/reference/torch_ops/_op_run.py +326 -0
- onnx_diagnostic/reference/torch_ops/access_ops.py +84 -0
- onnx_diagnostic/reference/torch_ops/binary_ops.py +108 -0
- onnx_diagnostic/reference/torch_ops/controlflow_ops.py +118 -0
- onnx_diagnostic/reference/torch_ops/generator_ops.py +35 -0
- onnx_diagnostic/reference/torch_ops/nn_ops.py +176 -0
- onnx_diagnostic/reference/torch_ops/other_ops.py +106 -0
- onnx_diagnostic/reference/torch_ops/reduce_ops.py +130 -0
- onnx_diagnostic/reference/torch_ops/sequence_ops.py +65 -0
- onnx_diagnostic/reference/torch_ops/shape_ops.py +120 -0
- onnx_diagnostic/reference/torch_ops/unary_ops.py +86 -0
- onnx_diagnostic/tasks/__init__.py +22 -1
- onnx_diagnostic/tasks/image_classification.py +2 -2
- onnx_diagnostic/tasks/text_generation.py +3 -3
- onnx_diagnostic/torch_export_patches/eval/__init__.py +690 -0
- onnx_diagnostic/torch_export_patches/eval/model_cases.py +883 -0
- onnx_diagnostic/torch_export_patches/onnx_export_errors.py +34 -1
- onnx_diagnostic/torch_export_patches/onnx_export_serialization.py +6 -1
- onnx_diagnostic/torch_export_patches/patch_module_helper.py +148 -28
- onnx_diagnostic/torch_export_patches/patches/patch_torch.py +91 -0
- onnx_diagnostic/torch_export_patches/patches/patch_transformers.py +117 -1
- onnx_diagnostic/torch_models/hghub/hub_data_cached_configs.py +142 -0
- onnx_diagnostic/torch_models/test_helper.py +225 -22
- onnx_diagnostic/torch_onnx/runtime_info.py +289 -0
- {onnx_diagnostic-0.5.0.dist-info → onnx_diagnostic-0.6.1.dist-info}/METADATA +1 -1
- {onnx_diagnostic-0.5.0.dist-info → onnx_diagnostic-0.6.1.dist-info}/RECORD +43 -24
- {onnx_diagnostic-0.5.0.dist-info → onnx_diagnostic-0.6.1.dist-info}/WHEEL +1 -1
- {onnx_diagnostic-0.5.0.dist-info → onnx_diagnostic-0.6.1.dist-info}/licenses/LICENSE.txt +0 -0
- {onnx_diagnostic-0.5.0.dist-info → onnx_diagnostic-0.6.1.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,518 @@
|
|
|
1
|
+
import functools
|
|
2
|
+
from typing import Dict, List, Optional, Sequence, Tuple, Union
|
|
3
|
+
import numpy as np
|
|
4
|
+
import onnx
|
|
5
|
+
import torch
|
|
6
|
+
from ..helpers.torch_helper import to_tensor
|
|
7
|
+
from ..torch_onnx.runtime_info import first_used_last_used, RuntimeValue
|
|
8
|
+
from . import torch_ops
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@functools.lru_cache
|
|
12
|
+
def get_kernels() -> Dict[Tuple[str, str, int], type[torch_ops.OpRun]]:
|
|
13
|
+
"""
|
|
14
|
+
Retrieves all the available kernels class :class:`TorchOnnxEvaluator`
|
|
15
|
+
can use. The full list is the following.
|
|
16
|
+
|
|
17
|
+
.. runpython::
|
|
18
|
+
:showcode:
|
|
19
|
+
|
|
20
|
+
from onnx_diagnostic.reference.torch_evaluator import get_kernels
|
|
21
|
+
|
|
22
|
+
for k, v in sorted(get_kernels().items()):
|
|
23
|
+
domain, name, version = k
|
|
24
|
+
f = f"{name}({version})" if domain == "" else f"{name}[{domain}]({version})"
|
|
25
|
+
add = " " * max(25 - len(f), 0)
|
|
26
|
+
dd = " -- device dependent" if v.device_dependent() else ""
|
|
27
|
+
print(f"{f}{add} -- {v.__name__}{dd}")
|
|
28
|
+
"""
|
|
29
|
+
res = {}
|
|
30
|
+
for _k, v in torch_ops.__dict__.items():
|
|
31
|
+
if isinstance(v, type) and issubclass(v, torch_ops.OpRun) and "_" in v.__name__:
|
|
32
|
+
name, version = v.__name__.split("_")
|
|
33
|
+
domain = getattr(v, "domain", "")
|
|
34
|
+
res[domain, name, int(version)] = v
|
|
35
|
+
return res
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class TorchOnnxEvaluator:
|
|
39
|
+
"""
|
|
40
|
+
Torch evaluator for onnx models.
|
|
41
|
+
The model does not stores the original proto it evaluates to avoid
|
|
42
|
+
|
|
43
|
+
:param proto: a proto
|
|
44
|
+
:param providers: where to run the model
|
|
45
|
+
:param opsets: needed if proto is a graph
|
|
46
|
+
:param functions: known local functions
|
|
47
|
+
:param verbose: verbosity level
|
|
48
|
+
|
|
49
|
+
The class holds the following attributes:
|
|
50
|
+
|
|
51
|
+
* `providers`: providers
|
|
52
|
+
* `default_device`: default torch device
|
|
53
|
+
* `constants`: all initializers or constants
|
|
54
|
+
* `kernels`: kernels
|
|
55
|
+
* `runtime_info`: produced by :func:`first_used_last_used
|
|
56
|
+
<onnx_diagnostic.torch_onnx.runtime_info.first_used_last_used>`
|
|
57
|
+
* `last_used`: contains the list of intermediate results,
|
|
58
|
+
to remove after every node execution,
|
|
59
|
+
this avoid the memory to grow too much
|
|
60
|
+
* `functions`: local functions
|
|
61
|
+
|
|
62
|
+
The class is not multithreaded. `runtime_info` gets updated
|
|
63
|
+
by the the class. The list of available kernels is returned by function
|
|
64
|
+
:func:`onnx_diagnostic.reference.torch_evaluator.get_kernels`.
|
|
65
|
+
Example:
|
|
66
|
+
|
|
67
|
+
.. runpython::
|
|
68
|
+
:showcode:
|
|
69
|
+
|
|
70
|
+
import onnx
|
|
71
|
+
import onnx.helper as oh
|
|
72
|
+
import torch
|
|
73
|
+
from onnx_diagnostic.helpers import string_type
|
|
74
|
+
from onnx_diagnostic.reference import TorchOnnxEvaluator
|
|
75
|
+
|
|
76
|
+
TFLOAT = onnx.TensorProto.FLOAT
|
|
77
|
+
|
|
78
|
+
proto = oh.make_model(
|
|
79
|
+
oh.make_graph(
|
|
80
|
+
[
|
|
81
|
+
oh.make_node("Sigmoid", ["Y"], ["sy"]),
|
|
82
|
+
oh.make_node("Mul", ["Y", "sy"], ["ysy"]),
|
|
83
|
+
oh.make_node("Mul", ["X", "ysy"], ["final"]),
|
|
84
|
+
],
|
|
85
|
+
"-nd-",
|
|
86
|
+
[
|
|
87
|
+
oh.make_tensor_value_info("X", TFLOAT, [1, "b", "c"]),
|
|
88
|
+
oh.make_tensor_value_info("Y", TFLOAT, ["a", "b", "c"]),
|
|
89
|
+
],
|
|
90
|
+
[oh.make_tensor_value_info("final", TFLOAT, ["a", "b", "c"])],
|
|
91
|
+
),
|
|
92
|
+
opset_imports=[oh.make_opsetid("", 18)],
|
|
93
|
+
ir_version=9,
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
sess = TorchOnnxEvaluator(proto)
|
|
97
|
+
feeds = dict(X=torch.rand((4, 5)), Y=torch.rand((4, 5)))
|
|
98
|
+
result = sess.run(None, feeds)
|
|
99
|
+
print(string_type(result, with_shape=True, with_min_max=True))
|
|
100
|
+
|
|
101
|
+
Adding ``verbose=1`` shows which kernels is executed:
|
|
102
|
+
|
|
103
|
+
.. runpython::
|
|
104
|
+
:showcode:
|
|
105
|
+
|
|
106
|
+
import onnx
|
|
107
|
+
import onnx.helper as oh
|
|
108
|
+
import torch
|
|
109
|
+
from onnx_diagnostic.helpers import string_type
|
|
110
|
+
from onnx_diagnostic.reference import TorchOnnxEvaluator
|
|
111
|
+
|
|
112
|
+
TFLOAT = onnx.TensorProto.FLOAT
|
|
113
|
+
|
|
114
|
+
proto = oh.make_model(
|
|
115
|
+
oh.make_graph(
|
|
116
|
+
[
|
|
117
|
+
oh.make_node("Sigmoid", ["Y"], ["sy"]),
|
|
118
|
+
oh.make_node("Mul", ["Y", "sy"], ["ysy"]),
|
|
119
|
+
oh.make_node("Mul", ["X", "ysy"], ["final"]),
|
|
120
|
+
],
|
|
121
|
+
"-nd-",
|
|
122
|
+
[
|
|
123
|
+
oh.make_tensor_value_info("X", TFLOAT, [1, "b", "c"]),
|
|
124
|
+
oh.make_tensor_value_info("Y", TFLOAT, ["a", "b", "c"]),
|
|
125
|
+
],
|
|
126
|
+
[oh.make_tensor_value_info("final", TFLOAT, ["a", "b", "c"])],
|
|
127
|
+
),
|
|
128
|
+
opset_imports=[oh.make_opsetid("", 18)],
|
|
129
|
+
ir_version=9,
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
sess = TorchOnnxEvaluator(proto, verbose=1)
|
|
133
|
+
feeds = dict(X=torch.rand((4, 5)), Y=torch.rand((4, 5)))
|
|
134
|
+
result = sess.run(None, feeds)
|
|
135
|
+
print(string_type(result, with_shape=True, with_min_max=True))
|
|
136
|
+
|
|
137
|
+
It also shows when a result is not needed anymore. In that case,
|
|
138
|
+
it is deleted to free the memory it takes.
|
|
139
|
+
The runtime can also execute the kernel the onnx model on CUDA.
|
|
140
|
+
It follows the same logic as :class:`onnxruntime.InferenceSession`:
|
|
141
|
+
``providers=["CUDAExecutionProvider"]``.
|
|
142
|
+
It is better in that case to move the input on CUDA. The class
|
|
143
|
+
tries to move every weight on CUDA but tries to keep any tensor
|
|
144
|
+
identified as a shape in CPU. Some bugs may remain as torch
|
|
145
|
+
raises an exception when devices are expected to be the same.
|
|
146
|
+
The runtime was validated with model :epkg:`arnir0/Tiny-LLM`.
|
|
147
|
+
"""
|
|
148
|
+
|
|
149
|
+
class IO:
|
|
150
|
+
"IO"
|
|
151
|
+
|
|
152
|
+
def __init__(self, name: str, type: int, shape: Tuple[Union[str, int], ...]):
|
|
153
|
+
self.name = name
|
|
154
|
+
self.type = type
|
|
155
|
+
self.shape = shape
|
|
156
|
+
|
|
157
|
+
@classmethod
|
|
158
|
+
def _on_cuda(cls, providers) -> int:
|
|
159
|
+
if not providers:
|
|
160
|
+
return -1
|
|
161
|
+
for p in providers:
|
|
162
|
+
if p == "CUDAExecutionProvider":
|
|
163
|
+
return 0
|
|
164
|
+
if isinstance(p, tuple) and p[0] == "CUDAExecutionProvider":
|
|
165
|
+
return p[1]["device_id"]
|
|
166
|
+
return -1
|
|
167
|
+
|
|
168
|
+
def __init__(
|
|
169
|
+
self,
|
|
170
|
+
proto: Union[onnx.FunctionProto, onnx.GraphProto, onnx.ModelProto],
|
|
171
|
+
providers: Tuple[str, ...] = ("CPUExecutionProvider",),
|
|
172
|
+
opsets: Optional[Dict[str, int]] = None,
|
|
173
|
+
local_functions: Optional[Dict[Tuple[str, str], "TorchOnnxEvaluator"]] = None,
|
|
174
|
+
verbose: int = 0,
|
|
175
|
+
):
|
|
176
|
+
self.providers = providers
|
|
177
|
+
self.constants: Dict[str, torch.Tensor] = {}
|
|
178
|
+
self.kernels: List[Optional[torch_ops.OpRun]] = []
|
|
179
|
+
self.functions = local_functions.copy() if local_functions else {}
|
|
180
|
+
self.CPU = torch.tensor([0]).to("cpu").device
|
|
181
|
+
self.verbose = verbose
|
|
182
|
+
dev = self._on_cuda(providers)
|
|
183
|
+
if dev < 0:
|
|
184
|
+
self.default_device = self.CPU
|
|
185
|
+
self.CUDA = None
|
|
186
|
+
else:
|
|
187
|
+
self.CUDA = torch.tensor([0]).to(f"cuda:{dev}").device
|
|
188
|
+
self.default_device = self.CUDA
|
|
189
|
+
|
|
190
|
+
if isinstance(proto, str):
|
|
191
|
+
proto = onnx.load(proto)
|
|
192
|
+
if isinstance(proto, onnx.ModelProto):
|
|
193
|
+
assert opsets is None, "proto is a model, opsets must be None in that case"
|
|
194
|
+
assert not proto.graph.sparse_initializer, "sparse_initializer not support yet"
|
|
195
|
+
self.opsets = {d.domain: d.version for d in proto.opset_import}
|
|
196
|
+
for f in proto.functions:
|
|
197
|
+
self.functions[f.domain, f.name] = self.__class__(
|
|
198
|
+
f,
|
|
199
|
+
providers=providers,
|
|
200
|
+
local_functions=self.functions,
|
|
201
|
+
verbose=self.verbose,
|
|
202
|
+
)
|
|
203
|
+
self._build_initializers(proto.graph.initializer)
|
|
204
|
+
self._build_initializers(proto.graph.node)
|
|
205
|
+
self._build_kernels(proto.graph.node)
|
|
206
|
+
self.input_names = [i.name for i in proto.graph.input]
|
|
207
|
+
self.output_names = [i.name for i in proto.graph.output]
|
|
208
|
+
self._io_input_names = [
|
|
209
|
+
self.IO(
|
|
210
|
+
name=i.name,
|
|
211
|
+
type=i.type.tensor_type.elem_type,
|
|
212
|
+
shape=tuple(
|
|
213
|
+
d.dim_param or d.dim_value for d in i.type.tensor_type.shape.dim
|
|
214
|
+
),
|
|
215
|
+
)
|
|
216
|
+
for i in proto.graph.input
|
|
217
|
+
]
|
|
218
|
+
self._io_output_names = [
|
|
219
|
+
self.IO(
|
|
220
|
+
name=i.name,
|
|
221
|
+
type=i.type.tensor_type.elem_type,
|
|
222
|
+
shape=tuple(
|
|
223
|
+
d.dim_param or d.dim_value for d in i.type.tensor_type.shape.dim
|
|
224
|
+
),
|
|
225
|
+
)
|
|
226
|
+
for i in proto.graph.output
|
|
227
|
+
]
|
|
228
|
+
elif isinstance(proto, onnx.GraphProto):
|
|
229
|
+
assert opsets, "opsets must be specified if proto is a graph"
|
|
230
|
+
assert not proto.sparse_initializer, "sparse_initializer not support yet"
|
|
231
|
+
self.opsets = opsets
|
|
232
|
+
self._build_initializers(proto.initializer)
|
|
233
|
+
self._build_initializers(proto.node)
|
|
234
|
+
self._build_kernels(proto.node)
|
|
235
|
+
self.input_names = [i.name for i in proto.input]
|
|
236
|
+
self.output_names = [i.name for i in proto.output]
|
|
237
|
+
elif isinstance(proto, onnx.FunctionProto):
|
|
238
|
+
assert opsets is None, "proto is a model, opsets must be None in that case"
|
|
239
|
+
self.opsets = {d.domain: d.version for d in proto.opset_import}
|
|
240
|
+
self._build_initializers(proto.node)
|
|
241
|
+
self._build_kernels(proto.node)
|
|
242
|
+
self.input_names = list(proto.input)
|
|
243
|
+
self.output_names = list(proto.output)
|
|
244
|
+
else:
|
|
245
|
+
raise TypeError(f"Unexpected type {type(proto)} for proto")
|
|
246
|
+
|
|
247
|
+
self.runtime_info = first_used_last_used(proto, constant_as_initializer=True)
|
|
248
|
+
self.last_used: List[List[str]] = [[] for _ in self.kernels]
|
|
249
|
+
for name, info in self.runtime_info.items():
|
|
250
|
+
assert isinstance(info.last_used, int) or info.is_input, (
|
|
251
|
+
f"Missing field last_used in {info!r}, last_used={info.last_used!r}, "
|
|
252
|
+
f"This may mean the node is unused and it should be removed."
|
|
253
|
+
)
|
|
254
|
+
if info.last_used is None:
|
|
255
|
+
# Not used.
|
|
256
|
+
self.last_used[0].append(name)
|
|
257
|
+
elif not info.is_output and not info.is_initializer:
|
|
258
|
+
self.last_used[info.last_used].append(name)
|
|
259
|
+
|
|
260
|
+
def get_inputs(self):
|
|
261
|
+
"Same API than onnxruntime."
|
|
262
|
+
assert hasattr(self, "_io_input_names"), "Missing attribute '_io_input_names'."
|
|
263
|
+
return self._io_input_names
|
|
264
|
+
|
|
265
|
+
def get_outputs(self):
|
|
266
|
+
"Same API than onnxruntime."
|
|
267
|
+
assert hasattr(self, "_io_output_names"), "Missing attribute '_io_output_names'."
|
|
268
|
+
return self._io_output_names
|
|
269
|
+
|
|
270
|
+
@property
|
|
271
|
+
def on_cuda(self) -> bool:
|
|
272
|
+
"Tells if the default device is CUDA."
|
|
273
|
+
return self.default_device == self.CUDA
|
|
274
|
+
|
|
275
|
+
def _build_initializers(self, inits: Sequence[Union[onnx.NodeProto, onnx.TensorProto]]):
|
|
276
|
+
for init in inits:
|
|
277
|
+
if isinstance(init, onnx.TensorProto):
|
|
278
|
+
self.constants[init.name] = to_tensor(init).to(self.default_device)
|
|
279
|
+
elif (
|
|
280
|
+
isinstance(init, onnx.NodeProto)
|
|
281
|
+
and init.op_type == "Constant"
|
|
282
|
+
and init.domain == ""
|
|
283
|
+
):
|
|
284
|
+
value = None
|
|
285
|
+
for att in init.attribute:
|
|
286
|
+
if att.name == "value":
|
|
287
|
+
value = to_tensor(att.t).to(self.default_device)
|
|
288
|
+
elif att.name == "value_floats":
|
|
289
|
+
value = torch.tensor(list(att.floats), dtype=torch.float32).to(
|
|
290
|
+
self.default_device
|
|
291
|
+
)
|
|
292
|
+
assert value is not None, f"No attribute value in node {init}"
|
|
293
|
+
self.constants[init.output[0]] = value
|
|
294
|
+
|
|
295
|
+
def _build_kernels(self, nodes: Sequence[onnx.NodeProto]):
|
|
296
|
+
kernels = get_kernels()
|
|
297
|
+
self.kernels.clear()
|
|
298
|
+
for node in nodes:
|
|
299
|
+
if (node.domain, node.op_type) in self.functions:
|
|
300
|
+
kernel = torch_ops.OpRunFunction(
|
|
301
|
+
self.functions[node.domain, node.op_type], node, self.opsets[node.domain]
|
|
302
|
+
)
|
|
303
|
+
self.kernels.append(kernel)
|
|
304
|
+
continue
|
|
305
|
+
|
|
306
|
+
if node.op_type == "Constant" and node.domain == "":
|
|
307
|
+
# Treated as a constant.
|
|
308
|
+
self.kernels.append(None)
|
|
309
|
+
continue
|
|
310
|
+
|
|
311
|
+
opset = self.opsets[node.domain]
|
|
312
|
+
key = node.domain, node.op_type, opset
|
|
313
|
+
while key not in kernels and opset > 0:
|
|
314
|
+
opset -= 1
|
|
315
|
+
key = node.domain, node.op_type, opset
|
|
316
|
+
assert key in kernels, (
|
|
317
|
+
f"Missing kernel for node type {node.op_type!r} from domain {node.domain!r}, "
|
|
318
|
+
f"local functions={sorted(self.functions)}"
|
|
319
|
+
)
|
|
320
|
+
cls = kernels[key]
|
|
321
|
+
ags = [self.default_device] if cls.device_dependent() else []
|
|
322
|
+
kws = dict(parent=self) if cls.has_subgraphs() else {}
|
|
323
|
+
kernel2 = cls(node, opset, *ags, **kws)
|
|
324
|
+
self.kernels.append(kernel2)
|
|
325
|
+
|
|
326
|
+
def run(
|
|
327
|
+
self,
|
|
328
|
+
outputs: Optional[List[str]],
|
|
329
|
+
feeds: Union[Dict[str, torch.Tensor], Dict[str, np.ndarray]],
|
|
330
|
+
) -> Union[List[Optional[torch.Tensor]], List[Optional[np.ndarray]]]:
|
|
331
|
+
"""
|
|
332
|
+
Runs the ONNX model.
|
|
333
|
+
|
|
334
|
+
:param outputs: outputs required
|
|
335
|
+
:param feeds: inputs
|
|
336
|
+
:return: output tensors.
|
|
337
|
+
"""
|
|
338
|
+
use_numpy = any(isinstance(t, np.ndarray) for t in feeds.values())
|
|
339
|
+
if use_numpy:
|
|
340
|
+
feeds = {k: torch.from_numpy(v) for k, v in feeds.items()}
|
|
341
|
+
if outputs is None:
|
|
342
|
+
outputs = self.output_names
|
|
343
|
+
|
|
344
|
+
# sets constants
|
|
345
|
+
for k, v in self.constants.items():
|
|
346
|
+
r = self.runtime_info[k]
|
|
347
|
+
if not r.has_value:
|
|
348
|
+
r.set_value(
|
|
349
|
+
torch_ops.OpRunTensor(
|
|
350
|
+
v.to(self.CUDA) if not r.is_shape and self.on_cuda else v,
|
|
351
|
+
is_constant=True,
|
|
352
|
+
may_cpu=len(v.shape) == 1 and v.numel() < 8 and v.dtype == torch.int64,
|
|
353
|
+
)
|
|
354
|
+
)
|
|
355
|
+
if self.verbose:
|
|
356
|
+
print(f"+C {r.name}: {r.string_type()}")
|
|
357
|
+
|
|
358
|
+
# inputs
|
|
359
|
+
for k, v in feeds.items():
|
|
360
|
+
r = self.runtime_info[k]
|
|
361
|
+
r.set_value(
|
|
362
|
+
torch_ops.OpRunTensor(
|
|
363
|
+
v.to(self.CUDA) if not r.is_shape and self.on_cuda else v,
|
|
364
|
+
is_constant=False,
|
|
365
|
+
may_cpu=len(v.shape) == 1 and v.numel() < 8 and v.dtype == torch.int64,
|
|
366
|
+
)
|
|
367
|
+
)
|
|
368
|
+
if self.verbose:
|
|
369
|
+
print(f"+I {r.name}: {r.string_type()}")
|
|
370
|
+
|
|
371
|
+
# node execution
|
|
372
|
+
for it, kernel in enumerate(self.kernels):
|
|
373
|
+
if kernel is not None:
|
|
374
|
+
if self.verbose:
|
|
375
|
+
print(
|
|
376
|
+
f"{kernel.__class__.__name__}"
|
|
377
|
+
f"({', '.join(kernel.input)}) -> "
|
|
378
|
+
f"{', '.join(kernel.output)}"
|
|
379
|
+
)
|
|
380
|
+
# kernel execution
|
|
381
|
+
inputs = [(self.runtime_info[i].value if i else None) for i in kernel.input]
|
|
382
|
+
if kernel.has_subgraphs():
|
|
383
|
+
res = kernel.run(*inputs, context=self.runtime_info) # type: ignore[call-arg]
|
|
384
|
+
else:
|
|
385
|
+
res = kernel.run(*inputs)
|
|
386
|
+
if isinstance(res, tuple):
|
|
387
|
+
# outputs
|
|
388
|
+
assert all(isinstance(o, torch_ops.OpRunValue) for o in res), (
|
|
389
|
+
f"Unexpected output type {[type(o) for o in res]} "
|
|
390
|
+
f"for kernel {type(kernel)}."
|
|
391
|
+
)
|
|
392
|
+
for name, t in zip(kernel.output, res):
|
|
393
|
+
self.runtime_info[name].set_value(t)
|
|
394
|
+
if self.verbose:
|
|
395
|
+
for name in kernel.output:
|
|
396
|
+
print(f"+R {name}: {self.runtime_info[name].string_type()}")
|
|
397
|
+
else:
|
|
398
|
+
assert isinstance(
|
|
399
|
+
res, torch_ops.OpRunValue
|
|
400
|
+
), f"Unexpected output type {type(res)} for kernel {type(kernel)}."
|
|
401
|
+
self.runtime_info[kernel.output[0]].set_value(res)
|
|
402
|
+
if self.verbose:
|
|
403
|
+
print(
|
|
404
|
+
f"+R {kernel.output[0]}: "
|
|
405
|
+
f"{self.runtime_info[kernel.output[0]].string_type()}"
|
|
406
|
+
)
|
|
407
|
+
|
|
408
|
+
# free intermediate results
|
|
409
|
+
for name in self.last_used[it]:
|
|
410
|
+
self.runtime_info[name].clean_value()
|
|
411
|
+
if self.verbose:
|
|
412
|
+
print(f"- clean {name}")
|
|
413
|
+
|
|
414
|
+
assert all(
|
|
415
|
+
self.runtime_info[o].value is not None for o in outputs
|
|
416
|
+
), "Not implemented yet when one output is None."
|
|
417
|
+
fres = [self.runtime_info[o].value.tensor for o in outputs] # type: ignore[union-attr]
|
|
418
|
+
if self.verbose:
|
|
419
|
+
print(f"++ outputs {', '.join(outputs)}")
|
|
420
|
+
|
|
421
|
+
# clean previous execution
|
|
422
|
+
for k in feeds:
|
|
423
|
+
self.runtime_info[k].clean_value()
|
|
424
|
+
if self.verbose:
|
|
425
|
+
print(f"- clean {k}")
|
|
426
|
+
for o in outputs:
|
|
427
|
+
self.runtime_info[o].clean_value()
|
|
428
|
+
if self.verbose:
|
|
429
|
+
print(f"- clean {o}")
|
|
430
|
+
|
|
431
|
+
if use_numpy:
|
|
432
|
+
return [None if a is None else a.detach().cpu().numpy() for a in fres]
|
|
433
|
+
return fres
|
|
434
|
+
|
|
435
|
+
def run_with_values(
|
|
436
|
+
self,
|
|
437
|
+
*args: Optional[torch_ops.OpRunTensor],
|
|
438
|
+
context: Optional[Dict[str, RuntimeValue]] = None,
|
|
439
|
+
) -> Union[torch_ops.OpRunValue, Tuple[torch_ops.OpRunValue, ...]]:
|
|
440
|
+
"""
|
|
441
|
+
Runs the ONNX model.
|
|
442
|
+
|
|
443
|
+
:param args: inputs
|
|
444
|
+
:param context: local context for the execution of subgraphs
|
|
445
|
+
:return: output OpRunTensor
|
|
446
|
+
"""
|
|
447
|
+
assert all(
|
|
448
|
+
isinstance(a, torch_ops.OpRunValue) for a in args
|
|
449
|
+
), f"Unexpected type in args: {[type(a) for a in args]}"
|
|
450
|
+
outputs = self.output_names
|
|
451
|
+
context = context or {}
|
|
452
|
+
|
|
453
|
+
# sets constants
|
|
454
|
+
for k, v in self.constants.items():
|
|
455
|
+
r = self.runtime_info[k]
|
|
456
|
+
if not r.has_value:
|
|
457
|
+
r.set_value(
|
|
458
|
+
torch_ops.OpRunTensor(
|
|
459
|
+
v.to(self.CUDA) if r.is_shape is False and self.on_cuda else v,
|
|
460
|
+
is_constant=True,
|
|
461
|
+
may_cpu=len(v.shape) == 1 and v.numel() < 8 and v.dtype == torch.int64,
|
|
462
|
+
)
|
|
463
|
+
)
|
|
464
|
+
|
|
465
|
+
# inputs
|
|
466
|
+
for k, v in zip(self.input_names, args):
|
|
467
|
+
r = self.runtime_info[k]
|
|
468
|
+
r.set_value(
|
|
469
|
+
torch_ops.OpRunTensor(None) if v is None else v.__class__(v.tensor_or_sequence)
|
|
470
|
+
)
|
|
471
|
+
|
|
472
|
+
# node execution
|
|
473
|
+
for it, kernel in enumerate(self.kernels):
|
|
474
|
+
if kernel is not None:
|
|
475
|
+
# kernel execution
|
|
476
|
+
inputs = [
|
|
477
|
+
(
|
|
478
|
+
(
|
|
479
|
+
self.runtime_info[i].value
|
|
480
|
+
if i in self.runtime_info
|
|
481
|
+
else context[i].value
|
|
482
|
+
)
|
|
483
|
+
if i
|
|
484
|
+
else None
|
|
485
|
+
)
|
|
486
|
+
for i in kernel.input
|
|
487
|
+
]
|
|
488
|
+
res = kernel.run(*inputs)
|
|
489
|
+
if isinstance(res, tuple):
|
|
490
|
+
# outputs
|
|
491
|
+
assert all(isinstance(o, torch_ops.OpRunTensor) for o in res), (
|
|
492
|
+
f"Unexpected output type {[type(o) for o in res]} "
|
|
493
|
+
f"for kernel {type(kernel)}."
|
|
494
|
+
)
|
|
495
|
+
for name, t in zip(kernel.output, res):
|
|
496
|
+
self.runtime_info[name].set_value(t)
|
|
497
|
+
else:
|
|
498
|
+
assert isinstance(
|
|
499
|
+
res, torch_ops.OpRunValue
|
|
500
|
+
), f"Unexpected output type {type(res)} for kernel {type(kernel)}."
|
|
501
|
+
self.runtime_info[kernel.output[0]].set_value(res)
|
|
502
|
+
|
|
503
|
+
# free intermediate results
|
|
504
|
+
for name in self.last_used[it]:
|
|
505
|
+
self.runtime_info[name].clean_value()
|
|
506
|
+
|
|
507
|
+
assert all(
|
|
508
|
+
self.runtime_info[o].value is not None for o in outputs
|
|
509
|
+
), "Not implemented yet when one output is None."
|
|
510
|
+
res2 = [self.runtime_info[o].value.copy() for o in outputs] # type: ignore[assignment, union-attr]
|
|
511
|
+
|
|
512
|
+
# clean previous execution
|
|
513
|
+
for k in self.input_names:
|
|
514
|
+
self.runtime_info[k].clean_value()
|
|
515
|
+
for o in self.output_names:
|
|
516
|
+
self.runtime_info[o].clean_value()
|
|
517
|
+
|
|
518
|
+
return res2[0] if len(res2) == 1 else tuple(res2) # type: ignore[index, return-value, arg-type]
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
from ._op_run import OpRun, OpRunFunction, OpRunSequence, OpRunTensor, OpRunValue
|
|
2
|
+
from .access_ops import Gather_1, ScatterND_16, Slice_13
|
|
3
|
+
from .binary_ops import (
|
|
4
|
+
And_1,
|
|
5
|
+
Add_1,
|
|
6
|
+
Div_1,
|
|
7
|
+
Equal_1,
|
|
8
|
+
Greater_1,
|
|
9
|
+
GreaterOrEqual_1,
|
|
10
|
+
Less_1,
|
|
11
|
+
LessOrEqual_1,
|
|
12
|
+
MatMul_1,
|
|
13
|
+
Mul_1,
|
|
14
|
+
Or_1,
|
|
15
|
+
Pow_12,
|
|
16
|
+
Sub_1,
|
|
17
|
+
)
|
|
18
|
+
from .controlflow_ops import If_1, Loop_16
|
|
19
|
+
from .generator_ops import Range_11
|
|
20
|
+
from .nn_ops import AveragePool_11, Conv_11, LayerNormalization_17, Softmax_13, Tanh_6
|
|
21
|
+
from .other_ops import (
|
|
22
|
+
Cast_6,
|
|
23
|
+
CastLike_15,
|
|
24
|
+
NonZero_13,
|
|
25
|
+
Concat_1,
|
|
26
|
+
Tile_6,
|
|
27
|
+
Transpose_1,
|
|
28
|
+
Trilu_14,
|
|
29
|
+
Where_9,
|
|
30
|
+
)
|
|
31
|
+
from .reduce_ops import ReduceMax_18, ReduceMean_18, ReduceMin_17, ReduceMin_18, ReduceSum_13
|
|
32
|
+
from .sequence_ops import ConcatFromSequence_11, SequenceEmpty_11, SequenceInsert_11
|
|
33
|
+
from .shape_ops import (
|
|
34
|
+
ConstantOfShape_9,
|
|
35
|
+
Expand_8,
|
|
36
|
+
Reshape_14,
|
|
37
|
+
Shape_15,
|
|
38
|
+
Squeeze_13,
|
|
39
|
+
Split_18,
|
|
40
|
+
Unsqueeze_13,
|
|
41
|
+
)
|
|
42
|
+
from .unary_ops import (
|
|
43
|
+
Abs_1,
|
|
44
|
+
Cos_1,
|
|
45
|
+
Erf_9,
|
|
46
|
+
Exp_1,
|
|
47
|
+
Identity_1,
|
|
48
|
+
Log_1,
|
|
49
|
+
Neg_1,
|
|
50
|
+
Not_1,
|
|
51
|
+
Reciprocal_1,
|
|
52
|
+
Sigmoid_6,
|
|
53
|
+
Sin_1,
|
|
54
|
+
Sqrt_1,
|
|
55
|
+
)
|