onnxscript 0.1.0__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.
Files changed (176) hide show
  1. onnxscript/__init__.py +131 -0
  2. onnxscript/_framework_apis/__init__.py +3 -0
  3. onnxscript/_framework_apis/torch_2_5.py +117 -0
  4. onnxscript/_framework_apis/torch_2_6.py +45 -0
  5. onnxscript/_internal/__init__.py +0 -0
  6. onnxscript/_internal/analysis.py +229 -0
  7. onnxscript/_internal/ast_utils.py +64 -0
  8. onnxscript/_internal/autocast.py +250 -0
  9. onnxscript/_internal/deprecation.py +78 -0
  10. onnxscript/_internal/param_manipulation.py +148 -0
  11. onnxscript/_internal/runtime_typing.py +43 -0
  12. onnxscript/_internal/utils.py +99 -0
  13. onnxscript/_internal/version_utils.py +118 -0
  14. onnxscript/_legacy_ir/__init__.py +341 -0
  15. onnxscript/_legacy_ir/visitor.py +937 -0
  16. onnxscript/_thirdparty/asciichartpy.py +313 -0
  17. onnxscript/backend/__init__.py +2 -0
  18. onnxscript/backend/onnx_backend.py +303 -0
  19. onnxscript/backend/onnx_export.py +885 -0
  20. onnxscript/converter.py +1470 -0
  21. onnxscript/evaluator.py +619 -0
  22. onnxscript/function_libs/tools/torch_lib/deduce_type_constraints.py +403 -0
  23. onnxscript/function_libs/tools/torch_lib/generate_aten_signatures.py +333 -0
  24. onnxscript/function_libs/tools/torch_lib/generate_prims_signatures.py +331 -0
  25. onnxscript/function_libs/torch_lib/__init__.py +12 -0
  26. onnxscript/function_libs/torch_lib/_constants.py +5 -0
  27. onnxscript/function_libs/torch_lib/_flags.py +58 -0
  28. onnxscript/function_libs/torch_lib/graph_building/__init__.py +56 -0
  29. onnxscript/function_libs/torch_lib/graph_building/_graph_building_ir.py +723 -0
  30. onnxscript/function_libs/torch_lib/graph_building/_graph_building_torch.py +1125 -0
  31. onnxscript/function_libs/torch_lib/ops/__init__.py +27 -0
  32. onnxscript/function_libs/torch_lib/ops/common.py +80 -0
  33. onnxscript/function_libs/torch_lib/ops/core.py +8935 -0
  34. onnxscript/function_libs/torch_lib/ops/fft.py +385 -0
  35. onnxscript/function_libs/torch_lib/ops/linalg.py +399 -0
  36. onnxscript/function_libs/torch_lib/ops/nested.py +25 -0
  37. onnxscript/function_libs/torch_lib/ops/nn.py +2713 -0
  38. onnxscript/function_libs/torch_lib/ops/prims.py +850 -0
  39. onnxscript/function_libs/torch_lib/ops/quantized_decomposed.py +63 -0
  40. onnxscript/function_libs/torch_lib/ops/sparse.py +23 -0
  41. onnxscript/function_libs/torch_lib/ops/special.py +387 -0
  42. onnxscript/function_libs/torch_lib/ops/vision.py +25 -0
  43. onnxscript/function_libs/torch_lib/registration.py +151 -0
  44. onnxscript/function_libs/torch_lib/tensor_typing.py +74 -0
  45. onnxscript/ir/__init__.py +153 -0
  46. onnxscript/ir/_convenience.py +447 -0
  47. onnxscript/ir/_core.py +3119 -0
  48. onnxscript/ir/_display.py +49 -0
  49. onnxscript/ir/_enums.py +163 -0
  50. onnxscript/ir/_graph_comparison.py +23 -0
  51. onnxscript/ir/_io.py +97 -0
  52. onnxscript/ir/_linked_list.py +276 -0
  53. onnxscript/ir/_metadata.py +44 -0
  54. onnxscript/ir/_name_authority.py +72 -0
  55. onnxscript/ir/_polyfill.py +25 -0
  56. onnxscript/ir/_protocols.py +598 -0
  57. onnxscript/ir/_schemas.py +548 -0
  58. onnxscript/ir/_tape.py +120 -0
  59. onnxscript/ir/_type_casting.py +106 -0
  60. onnxscript/ir/convenience.py +32 -0
  61. onnxscript/ir/external_data.py +396 -0
  62. onnxscript/ir/passes/__init__.py +33 -0
  63. onnxscript/ir/passes/_pass_infra.py +172 -0
  64. onnxscript/ir/serde.py +1620 -0
  65. onnxscript/ir/tensor_adapters.py +122 -0
  66. onnxscript/ir/traversal.py +82 -0
  67. onnxscript/irbuilder.py +542 -0
  68. onnxscript/main.py +167 -0
  69. onnxscript/onnx_opset/__init__.py +232 -0
  70. onnxscript/onnx_opset/_impl/opset1.py +4100 -0
  71. onnxscript/onnx_opset/_impl/opset10.py +1227 -0
  72. onnxscript/onnx_opset/_impl/opset11.py +4013 -0
  73. onnxscript/onnx_opset/_impl/opset12.py +1078 -0
  74. onnxscript/onnx_opset/_impl/opset13.py +3924 -0
  75. onnxscript/onnx_opset/_impl/opset14.py +999 -0
  76. onnxscript/onnx_opset/_impl/opset15.py +604 -0
  77. onnxscript/onnx_opset/_impl/opset16.py +1255 -0
  78. onnxscript/onnx_opset/_impl/opset17.py +561 -0
  79. onnxscript/onnx_opset/_impl/opset18.py +1803 -0
  80. onnxscript/onnx_opset/_impl/opset19.py +1942 -0
  81. onnxscript/onnx_opset/_impl/opset2.py +218 -0
  82. onnxscript/onnx_opset/_impl/opset20.py +675 -0
  83. onnxscript/onnx_opset/_impl/opset21.py +1976 -0
  84. onnxscript/onnx_opset/_impl/opset22.py +2588 -0
  85. onnxscript/onnx_opset/_impl/opset3.py +199 -0
  86. onnxscript/onnx_opset/_impl/opset4.py +77 -0
  87. onnxscript/onnx_opset/_impl/opset5.py +84 -0
  88. onnxscript/onnx_opset/_impl/opset6.py +944 -0
  89. onnxscript/onnx_opset/_impl/opset7.py +1243 -0
  90. onnxscript/onnx_opset/_impl/opset8.py +444 -0
  91. onnxscript/onnx_opset/_impl/opset9.py +1485 -0
  92. onnxscript/onnx_opset/_impl/opset_ai_onnx_ml1.py +974 -0
  93. onnxscript/onnx_opset/_impl/opset_ai_onnx_ml2.py +112 -0
  94. onnxscript/onnx_opset/_impl/opset_ai_onnx_ml3.py +308 -0
  95. onnxscript/onnx_opset/_impl/opset_ai_onnx_ml4.py +129 -0
  96. onnxscript/onnx_opset/_impl/opset_ai_onnx_ml5.py +158 -0
  97. onnxscript/onnx_opset/_impl/opset_ai_onnx_preview_training1.py +577 -0
  98. onnxscript/onnx_types.py +229 -0
  99. onnxscript/optimizer/__init__.py +39 -0
  100. onnxscript/optimizer/_constant_folding.py +1083 -0
  101. onnxscript/optimizer/_inliner.py +312 -0
  102. onnxscript/optimizer/_legacy/_optimizer.py +98 -0
  103. onnxscript/optimizer/_legacy/_remove_unused_proto.py +144 -0
  104. onnxscript/optimizer/_legacy/_simple_function_folding.py +243 -0
  105. onnxscript/optimizer/_legacy/constant_folding.py +293 -0
  106. onnxscript/optimizer/_legacy/evaluator.py +439 -0
  107. onnxscript/optimizer/_optimizer.py +61 -0
  108. onnxscript/optimizer/_remove_unused.py +106 -0
  109. onnxscript/optimizer/_remove_unused_function.py +72 -0
  110. onnxscript/py.typed +1 -0
  111. onnxscript/rewriter/__init__.py +56 -0
  112. onnxscript/rewriter/_ir_utils.py +111 -0
  113. onnxscript/rewriter/broadcast_to_matmul.py +180 -0
  114. onnxscript/rewriter/cast_constant_of_shape.py +50 -0
  115. onnxscript/rewriter/collapse_slices.py +141 -0
  116. onnxscript/rewriter/erfgelu.py +27 -0
  117. onnxscript/rewriter/function_rule.py +232 -0
  118. onnxscript/rewriter/gemm_to_matmul_add.py +21 -0
  119. onnxscript/rewriter/generic_pattern.py +700 -0
  120. onnxscript/rewriter/llama_rule_sets.py +287 -0
  121. onnxscript/rewriter/no_op.py +56 -0
  122. onnxscript/rewriter/onnxruntime/__init__.py +50 -0
  123. onnxscript/rewriter/onnxruntime/bfloat16_utils/bfloat16_converter.py +99 -0
  124. onnxscript/rewriter/onnxruntime/fused_matmul_rule_sets.py +177 -0
  125. onnxscript/rewriter/onnxruntime/group_normalization_merge_silu.py +64 -0
  126. onnxscript/rewriter/onnxruntime/instance_to_group_normalization.py +155 -0
  127. onnxscript/rewriter/onnxruntime/softmax.py +63 -0
  128. onnxscript/rewriter/onnxruntime/transformers/__init__.py +21 -0
  129. onnxscript/rewriter/onnxruntime/transformers/biassplitgelu.py +31 -0
  130. onnxscript/rewriter/onnxruntime/transformers/fastgelu.py +29 -0
  131. onnxscript/rewriter/onnxruntime/transformers/layernorm.py +47 -0
  132. onnxscript/rewriter/onnxruntime/transformers/multihead_attention.py +715 -0
  133. onnxscript/rewriter/ort_fusions/__init__.py +9 -0
  134. onnxscript/rewriter/ort_fusions/_core.py +28 -0
  135. onnxscript/rewriter/ort_fusions/_smollm_1.py +253 -0
  136. onnxscript/rewriter/ort_fusions/_smollm_2.py +467 -0
  137. onnxscript/rewriter/ort_fusions/_test_models.py +122 -0
  138. onnxscript/rewriter/ort_fusions/_test_utils.py +42 -0
  139. onnxscript/rewriter/ort_fusions/cos_sin_cache.py +154 -0
  140. onnxscript/rewriter/ort_fusions/gqa.py +156 -0
  141. onnxscript/rewriter/ort_fusions/mha.py +198 -0
  142. onnxscript/rewriter/ort_fusions/rms_normalization.py +95 -0
  143. onnxscript/rewriter/ort_fusions/rotary_embedding.py +64 -0
  144. onnxscript/rewriter/ort_fusions/sdpa.py +75 -0
  145. onnxscript/rewriter/ort_fusions/skip_normalization.py +46 -0
  146. onnxscript/rewriter/pattern.py +1714 -0
  147. onnxscript/rewriter/testing.py +77 -0
  148. onnxscript/sourceinfo.py +59 -0
  149. onnxscript/tensor.py +227 -0
  150. onnxscript/testing/__init__.py +482 -0
  151. onnxscript/tools/__init__.py +4 -0
  152. onnxscript/tools/benchmark/__init__.py +23 -0
  153. onnxscript/tools/benchmark/benchmark_helpers.py +783 -0
  154. onnxscript/tools/benchmark/benchmark_run.py +140 -0
  155. onnxscript/tools/benchmark/export_model.py +207 -0
  156. onnxscript/tools/benchmark/export_model_batch.py +146 -0
  157. onnxscript/tools/memory_peak.py +244 -0
  158. onnxscript/tools/training_helper.py +50 -0
  159. onnxscript/tools/transformers_models/__init__.py +190 -0
  160. onnxscript/tools/transformers_models/llama.py +168 -0
  161. onnxscript/tools/transformers_models/mistral.py +238 -0
  162. onnxscript/tools/transformers_models/phi.py +248 -0
  163. onnxscript/tools/transformers_models/phi3.py +259 -0
  164. onnxscript/type_annotation.py +281 -0
  165. onnxscript/utils/__init__.py +0 -0
  166. onnxscript/utils/evaluation_utils.py +56 -0
  167. onnxscript/utils/timing_utils.py +33 -0
  168. onnxscript/utils/utils.py +84 -0
  169. onnxscript/values.py +790 -0
  170. onnxscript/version_converter/__init__.py +21 -0
  171. onnxscript/version_converter/_version_converter.py +314 -0
  172. onnxscript-0.1.0.dist-info/LICENSE +21 -0
  173. onnxscript-0.1.0.dist-info/METADATA +370 -0
  174. onnxscript-0.1.0.dist-info/RECORD +176 -0
  175. onnxscript-0.1.0.dist-info/WHEEL +5 -0
  176. onnxscript-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,619 @@
1
+ # Copyright (c) Microsoft Corporation.
2
+ # Licensed under the MIT License.
3
+ from __future__ import annotations
4
+
5
+ import abc
6
+ import contextlib
7
+ import pprint
8
+ from typing import (
9
+ Any,
10
+ Callable,
11
+ Mapping,
12
+ Optional,
13
+ Protocol,
14
+ Sequence,
15
+ TypeVar,
16
+ Union,
17
+ runtime_checkable,
18
+ )
19
+
20
+ import numpy as np
21
+ import onnx
22
+ import onnx.defs
23
+ import onnx.helper
24
+ import onnx.reference
25
+ from typing_extensions import TypeAlias
26
+
27
+ from onnxscript import irbuilder, onnx_opset, tensor, values
28
+ from onnxscript._internal import autocast, param_manipulation, utils
29
+
30
+ UserModeValue: TypeAlias = Union[Optional[np.ndarray], Sequence["UserModeValue"]]
31
+
32
+ EagerModeValue: TypeAlias = Union[Optional["tensor.Tensor"], Sequence["EagerModeValue"]]
33
+
34
+ ExtendedModeValue: TypeAlias = Union[
35
+ Optional["tensor.Tensor"],
36
+ Sequence["ExtendedModeValue"],
37
+ np.ndarray,
38
+ int,
39
+ float,
40
+ bool,
41
+ str,
42
+ ]
43
+
44
+ _T = TypeVar("_T")
45
+
46
+
47
+ def _adapt_to_eager_mode(inputs: ExtendedModeValue) -> tuple[EagerModeValue, bool]:
48
+ """Adapts inputs into representation used by onnxscript eager mode.
49
+
50
+ This does the following transformations:
51
+ * It adds an onnxscript Tensor wrapper around numpy arrays, which
52
+ allows the use of overloaded operators like + to be controlled by onnxscript.
53
+ * It also provides a promotion of scalars into tensors as a convenience.
54
+ This is needed to complement the similar promotion supported by the
55
+ onnxscript converter (for example, when an attribute is promoted and used
56
+ as an input argument).
57
+
58
+ Args:
59
+ inputs: a list/tuple of inputs to an ONNX function
60
+
61
+ Returns:
62
+ a pair (wrapped_inputs, flag) where flag indicates whether any numpy array
63
+ was wrapped into a Tensor.
64
+ """
65
+ has_array = False
66
+
67
+ def adapt(input: ExtendedModeValue) -> EagerModeValue:
68
+ if isinstance(input, np.ndarray):
69
+ nonlocal has_array
70
+ has_array = True
71
+ return tensor.Tensor(input)
72
+ if isinstance(input, tensor.Tensor):
73
+ return input
74
+ if isinstance(input, (bool, float)):
75
+ return tensor.Tensor(np.array(input))
76
+ if isinstance(input, int):
77
+ return tensor.Tensor(np.array(input, dtype=np.int64))
78
+ if input is None:
79
+ return None
80
+ if isinstance(input, list):
81
+ return [adapt(elt) for elt in input]
82
+ if isinstance(input, tuple):
83
+ return tuple(adapt(elt) for elt in input)
84
+ raise TypeError(f"Unexpected input type {type(input)}.")
85
+
86
+ result = adapt(inputs)
87
+ return result, has_array
88
+
89
+
90
+ def _adapt_to_user_mode(output: ExtendedModeValue) -> UserModeValue:
91
+ """Unwraps Tensor wrapper around numpy arrays.
92
+
93
+ Args:
94
+ output: output of an ONNX function, which can be either a single
95
+ onnx value or a list/tuple of onnx values.
96
+
97
+ Returns:
98
+ unwrapped output
99
+ """
100
+ if isinstance(output, tensor.Tensor):
101
+ return output.value
102
+ if output is None:
103
+ return None
104
+ if isinstance(output, list):
105
+ return [_adapt_to_user_mode(elt) for elt in output]
106
+ if isinstance(output, tuple):
107
+ return tuple(_adapt_to_user_mode(elt) for elt in output)
108
+ if isinstance(output, np.ndarray):
109
+ return output
110
+ raise TypeError(f"Unexpected type {type(output)}.")
111
+
112
+
113
+ def _unwrap_tensors_in_kwargs(kwargs: Mapping[str, Any]) -> dict[str, Any]:
114
+ """Unwrap tensors in a mapping to numpy arrays."""
115
+ new_kwargs = {}
116
+ for k, v in kwargs.items():
117
+ new_kwargs[k] = v
118
+ if isinstance(v, tensor.Tensor):
119
+ new_kwargs[k] = v.value
120
+
121
+ return new_kwargs
122
+
123
+
124
+ @runtime_checkable
125
+ class Evaluator(Protocol):
126
+ """Protocol for evaluating ONNX ops."""
127
+
128
+ def eval(
129
+ self,
130
+ schema: onnx.defs.OpSchema,
131
+ inputs: Sequence[ExtendedModeValue],
132
+ attributes: Mapping[str, Any],
133
+ ):
134
+ """Evaluates an ONNX op.
135
+
136
+ Args:
137
+ schema: The OpSchema of the operator to evaluate.
138
+ inputs: The ONNX inputs to the op.
139
+ attributes: The ONNX attributes to the op.
140
+ """
141
+
142
+ def eval_function(
143
+ self,
144
+ function: values.OnnxFunction,
145
+ args: Sequence[ExtendedModeValue],
146
+ kwargs: Mapping[str, ExtendedModeValue],
147
+ ):
148
+ """Evaluates an OnnxFunction.
149
+
150
+ Args:
151
+ function: The OnnxFunction to evaluate.
152
+ args: The positional arguments to the function.
153
+ kwargs: The keyword arguments to the function.
154
+ """
155
+
156
+
157
+ class BaseEvaluator(Evaluator, abc.ABC):
158
+ """Base class for evaluation of ONNX ops.
159
+
160
+ The execution of onnxscript functions in eager-mode is dispatched to an Evaluator
161
+ instance (or, more precisely, to the eval method of the Evaluator instance).
162
+ The evaluator is expected to transform the input/output/attribute representation
163
+ supported by onnxscript to those expected by a particular backend.
164
+ """
165
+
166
+ def __init__(self, ignore_unknown_function_kwargs: bool = False):
167
+ """Initializes a BaseEvaluator.
168
+
169
+ Args:
170
+ ignore_unknown_function_kwargs: Whether to ignore unknown keyword arguments
171
+ when evaluating an OnnxFunction. This is useful when using the
172
+ evaluator to validate operators programmatically, where
173
+ additional keyword arguments that is not part of the signature
174
+ may be provided to the function.
175
+ """
176
+ self._ignore_unknown_function_kwargs = ignore_unknown_function_kwargs
177
+
178
+ def eval(
179
+ self,
180
+ schema: onnx.defs.OpSchema,
181
+ inputs: Sequence[ExtendedModeValue],
182
+ attributes: Mapping[str, Any],
183
+ ):
184
+ """Evaluates an ONNX op.
185
+
186
+ Args:
187
+ schema: The OpSchema of the operator to evaluate.
188
+ inputs: The ONNX inputs to the op.
189
+ attributes: The ONNX attributes to the op.
190
+ """
191
+ attributes = _unwrap_tensors_in_kwargs(attributes)
192
+ attributes, closure = self.adapt_attributes(schema, attributes)
193
+ inputs = self.adapt_inputs(schema, inputs)
194
+ outputs = self._eval(schema, inputs, attributes, closure)
195
+ return self.adapt_outputs(schema, outputs)
196
+
197
+ def adapt_inputs(self, schema: onnx.defs.OpSchema, inputs: Sequence[ExtendedModeValue]):
198
+ """Transform inputs to the expected format for the evaluator.
199
+
200
+ Enables some syntactic sugar, such as the use of Python scalars,
201
+ in a manner consistent with the translator. See autocast.py for details.
202
+ """
203
+ return autocast.dynamic_cast_inputs(schema, inputs)
204
+
205
+ def adapt_attributes(
206
+ self, schema: onnx.defs.OpSchema, attributes: Mapping[str, ExtendedModeValue]
207
+ ) -> tuple[dict[str, ExtendedModeValue], dict[str, ExtendedModeValue]]:
208
+ """Transform attributes to the expected format for the evaluator.
209
+
210
+ Returns:
211
+ A closure that can be used to evaluate graph-valued attributes.
212
+ """
213
+ use_graph_attribute = self.use_graph_attribute(schema)
214
+ closure: dict[Any, Any] = {}
215
+ adapted_attributes = {}
216
+ for k, v in attributes.items():
217
+ if isinstance(v, values.OnnxClosure):
218
+ if use_graph_attribute:
219
+ adapted_attributes[k] = v.function_ir.to_graph_proto()
220
+ for pyvar, onnxvar in v.function_ir.outer_scope_variables:
221
+ closure[onnxvar.value] = v.frame.f_locals[pyvar]
222
+ else:
223
+ adapted_attributes[k] = v.function
224
+ elif callable(v):
225
+ raise TypeError(
226
+ f"Error: function-valued attribute {v.__name__} has no graph_proto"
227
+ "attribute. Did you forget to decorate it with @graph?"
228
+ )
229
+ else:
230
+ adapted_attributes[k] = v
231
+ return adapted_attributes, closure
232
+
233
+ def adapt_outputs(self, schema: onnx.defs.OpSchema, outputs: Sequence[EagerModeValue]):
234
+ """Adapt evaluator's output to convention used in onnxscript.
235
+
236
+ Onnxscript uses a tuple/sequence only when number of outputs > 1.
237
+ """
238
+ del schema # unused
239
+ return outputs[0] if len(outputs) == 1 else outputs
240
+
241
+ def use_graph_attribute(self, schema: onnx.defs.OpSchema):
242
+ del schema # unused
243
+ return True
244
+
245
+ @abc.abstractmethod
246
+ def _eval(
247
+ self,
248
+ schema: onnx.defs.OpSchema,
249
+ inputs: Sequence[ExtendedModeValue],
250
+ attributes: Mapping[str, ExtendedModeValue],
251
+ closure: Mapping[str, ExtendedModeValue],
252
+ ) -> EagerModeValue:
253
+ """Evaluates an ONNX op given its schema and inputs/attributes.
254
+
255
+ Args:
256
+ schema: The schema of the op to evaluate.
257
+ inputs: The ONNX inputs to the op.
258
+ attributes: The ONNX attributes to the op.
259
+ closure: The closure to use when evaluating graph-valued attributes.
260
+ """
261
+
262
+ def eval_function(
263
+ self,
264
+ function: values.OnnxFunction,
265
+ args: Sequence[ExtendedModeValue],
266
+ kwargs: Mapping[str, ExtendedModeValue],
267
+ ):
268
+ """Evaluates a function in eager mode.
269
+
270
+ Override this function to change the evaluator's behavior for functions.
271
+
272
+ Args:
273
+ function: The OnnxFunction to evaluate.
274
+ args: The positional arguments to the function.
275
+ kwargs: The keyword arguments to the function.
276
+ """
277
+ param_schemas = function.param_schemas()
278
+ # Split happens in the evaluator instead of the OnnxFunction __call__ method
279
+ # so that evaluators can control behaviors like whether to fill in default values for attributes.
280
+ tagged_args, tagged_kwargs = param_manipulation.tag_arguments_with_param_schemas(
281
+ param_schemas,
282
+ args,
283
+ kwargs,
284
+ fill_defaults=False,
285
+ allow_extra_kwargs=self._ignore_unknown_function_kwargs,
286
+ )
287
+
288
+ adapted_args: list[ExtendedModeValue] = []
289
+ adapted_kwargs: dict[str, ExtendedModeValue] = {}
290
+ has_array = False
291
+ for arg, param_schema in tagged_args:
292
+ if param_schema.is_input:
293
+ adapted_arg, has_array_ = _adapt_to_eager_mode(arg)
294
+ has_array = has_array or has_array_
295
+ adapted_args.append(adapted_arg)
296
+ else:
297
+ adapted_args.append(arg)
298
+
299
+ for key, (arg, param_schema) in tagged_kwargs.items():
300
+ if param_schema.is_input:
301
+ adapted_arg, has_array_ = _adapt_to_eager_mode(arg)
302
+ has_array = has_array or has_array_
303
+ adapted_kwargs[key] = adapted_arg
304
+ else:
305
+ adapted_kwargs[key] = arg
306
+
307
+ result = function.function(*adapted_args, **adapted_kwargs)
308
+
309
+ # We use a heuristic to decide whether to return output values as
310
+ # numpy arrays or tensor.Tensors. If the function has at least one
311
+ # numpy array as input, we return numpy arrays. Otherwise, we return
312
+ # tensor.Tensors. We could use a user-specified flag to control this
313
+ # or explicitly track whether this is a top-level function-call or
314
+ # a nested function-call.
315
+
316
+ return _adapt_to_user_mode(result) if has_array else result
317
+
318
+
319
+ # Utilities for evaluation using ORT:
320
+
321
+
322
+ class EagerModeError(RuntimeError):
323
+ pass
324
+
325
+
326
+ def _rename_io(prefix, i, arg):
327
+ if arg is None:
328
+ return ""
329
+ return f"{prefix}{i}"
330
+
331
+
332
+ def compute_num_outputs(
333
+ schema: onnx.defs.OpSchema, args: Sequence[Any], kwargs: Mapping[str, Any]
334
+ ) -> int:
335
+ """Returns the number of outputs expected."""
336
+
337
+ # TODO: Use ONNX type inference to replace the special-case handling below.
338
+ if schema.domain == "":
339
+ if schema.name == "BatchNormalization":
340
+ if not kwargs.get("training_mode", 0):
341
+ return 1
342
+ if schema.name == "LSTM":
343
+ return 3
344
+ if schema.name == "Split":
345
+ if len(args) == 1 and "num_outputs" not in kwargs:
346
+ raise EagerModeError(
347
+ "Operator Split: the number of expected outputs defines the split. "
348
+ "This information is unknown here."
349
+ )
350
+ if len(args) == 2: # has argument(split)
351
+ return len(args[1])
352
+ else: # no argument(split), check attribute(num_outputs)
353
+ return kwargs["num_outputs"]
354
+ if schema.name == "Scan":
355
+ scan_body = kwargs["body"]
356
+ return len(scan_body.output)
357
+ if schema.name == "Loop":
358
+ loop_body = kwargs["body"]
359
+ return len(loop_body.output) - 1
360
+ return len(schema.outputs)
361
+
362
+
363
+ def _onnxscript_to_numpy_value(v):
364
+ """Converts an onnxscript encoding of an ONNX value into the numpy encoding used by runtimes."""
365
+ if isinstance(v, tensor.Tensor):
366
+ return v.value
367
+ if isinstance(v, list):
368
+ return [_onnxscript_to_numpy_value(x) for x in v]
369
+ if isinstance(v, tuple):
370
+ if len(v) > 0 and type(v[0]) is int: # pylint: disable=unidiomatic-typecheck
371
+ return np.array(v, dtype=np.int64)
372
+ return np.array(v)
373
+ if v is None:
374
+ # Treated as a static-optional value.
375
+ # Dynamic optional None not yet supported.
376
+ return v
377
+ if isinstance(v, np.ndarray):
378
+ return v
379
+ raise TypeError(
380
+ f"Unexpected onnxscript value type '{type(v)}'."
381
+ "Valid value types are 'Tensor | list[Tensor] | None | np.ndarray | list[np.ndarray]'"
382
+ )
383
+
384
+
385
+ def _numpy_to_onnxscript_value(
386
+ v: np.ndarray | np.generic | list[np.ndarray] | list[np.generic],
387
+ ):
388
+ """Converts an ORT encoding of an ONNX value into the encoding used by onnxscript."""
389
+ if isinstance(v, np.ndarray):
390
+ # ORT may reuse buffers when the output numpy array is provided back as input.
391
+ # We need to make a copy to ensure that the tensor is not modified in-place.
392
+ return tensor.Tensor(v.copy())
393
+ if issubclass(type(v), np.generic):
394
+ # Numpy scalar types that are not ndarray
395
+ # https://numpy.org/doc/stable/reference/arrays.scalars.html
396
+ return tensor.Tensor(np.array(v))
397
+ if isinstance(v, list):
398
+ return [_numpy_to_onnxscript_value(x) for x in v]
399
+ if v is None:
400
+ raise TypeError("Dynamic optional values not yet supported.")
401
+ raise TypeError(
402
+ f"Unexpected runtime value type '{type(v)}'."
403
+ "Valid types are: 'np.ndarray | np.generic | list[np.ndarray] | list[np.generic]'"
404
+ )
405
+
406
+
407
+ def _prepare_model_and_inputs_for_eager(
408
+ schema: onnx.defs.OpSchema,
409
+ args: Sequence[Any],
410
+ kwargs: Mapping[str, Any],
411
+ implicit_args: Optional[Mapping[str, Any]],
412
+ ):
413
+ implicit_args = implicit_args or {}
414
+ # Convert input values to ORT representation-type:
415
+ args = [_onnxscript_to_numpy_value(x) for x in args]
416
+ implicit_args = {k: _onnxscript_to_numpy_value(v) for k, v in implicit_args.items()}
417
+
418
+ # Utility to convert kwarg to ONNX AttributeProto:
419
+ def make_attr(key: str, value: Any) -> onnx.AttributeProto:
420
+ def make_tensor_name() -> str:
421
+ return f"attr_{key}"
422
+
423
+ return autocast.pyvalue_to_onnx_attribute(
424
+ key, value, make_tensor_name, schema.attributes[key].type
425
+ )
426
+
427
+ # Construct ONNX model with a single op call:
428
+ inputs = [_rename_io("input", i, arg) for i, arg in enumerate(args)]
429
+
430
+ num_outputs = compute_num_outputs(schema, args, kwargs)
431
+ outputs = [f"output{i}" for i in range(num_outputs)]
432
+
433
+ node = onnx.helper.make_node(schema.name, inputs, outputs, domain=schema.domain)
434
+ node.attribute.extend(
435
+ make_attr(key, value) for key, value in kwargs.items() if value is not None
436
+ )
437
+ input_value_infos = utils.values_to_value_infos(zip(inputs, args))
438
+ implicit_value_infos = utils.values_to_value_infos(implicit_args.items())
439
+ output_value_infos = [
440
+ onnx.helper.make_value_info(name, onnx.TypeProto()) for name in outputs
441
+ ]
442
+
443
+ graph = onnx.helper.make_graph(
444
+ [node], "node_graph", input_value_infos + implicit_value_infos, output_value_infos
445
+ )
446
+ opset_id = onnx.helper.make_opsetid(schema.domain, schema.since_version)
447
+ model = onnx.helper.make_model(
448
+ graph,
449
+ opset_imports=[opset_id],
450
+ ir_version=irbuilder.select_ir_version(schema.since_version, domain=schema.domain),
451
+ )
452
+ model = onnx.shape_inference.infer_shapes(model)
453
+
454
+ session_run_input = {name: arg for name, arg in zip(inputs, args) if name != ""}
455
+ session_run_input.update(implicit_args)
456
+
457
+ return model, session_run_input, inputs
458
+
459
+
460
+ def _call_ort(
461
+ schema: onnx.defs.OpSchema,
462
+ args: Sequence[Any],
463
+ kwargs: Mapping[str, Any],
464
+ implicit_args: Optional[Mapping[str, Any]],
465
+ ):
466
+ # Delay import onnxruntime so that onnxscript can be used without
467
+ # installing onnxruntime.
468
+ import onnxruntime as ort # pylint: disable=import-outside-toplevel
469
+ from onnxruntime.capi.onnxruntime_pybind11_state import ( # pylint: disable=import-outside-toplevel
470
+ Fail,
471
+ InvalidArgument,
472
+ InvalidGraph,
473
+ )
474
+
475
+ model, session_run_input, inputs = _prepare_model_and_inputs_for_eager(
476
+ schema, args, kwargs, implicit_args
477
+ )
478
+
479
+ try:
480
+ session = ort.InferenceSession(
481
+ model.SerializeToString(), providers=("CPUExecutionProvider",)
482
+ )
483
+ except (Fail, InvalidGraph, InvalidArgument) as e:
484
+ raise EagerModeError(
485
+ f"Unable to create onnxruntime InferenceSession "
486
+ f"for executing {schema.domain}.{schema.name} op "
487
+ f"with onnx model\n{onnx.printer.to_text(model)}"
488
+ ) from e
489
+
490
+ try:
491
+ result = session.run(None, session_run_input)
492
+ except (RuntimeError, Fail) as e:
493
+ raise EagerModeError(
494
+ f"Unable to execute model operator {schema.name!r} due to {e!r}"
495
+ f"\ninput types:\n"
496
+ f"{pprint.pformat({k: type(v) for k, v in zip(inputs, args)})}"
497
+ f"\nmodified input types:\n"
498
+ f"{pprint.pformat({k: type(v) for k, v in session_run_input.items()})}"
499
+ f"\ninputs:\n{pprint.pformat(session_run_input)}\n{model}"
500
+ ) from e
501
+
502
+ # Map ORT output values to the onnxscript representation-type.
503
+ return [_numpy_to_onnxscript_value(x) for x in result]
504
+
505
+
506
+ def _schema_id(schema: onnx.defs.OpSchema) -> tuple[str, str, int]:
507
+ return schema.name, schema.domain, schema.since_version
508
+
509
+
510
+ class ORTEvaluator(BaseEvaluator):
511
+ """Evaluates ONNX ops using ONNX Runtime."""
512
+
513
+ def _eval(self, schema, inputs, attributes, closure):
514
+ return _call_ort(schema, inputs, attributes, closure)
515
+
516
+
517
+ class OnnxReferenceRuntimeEvaluator(BaseEvaluator):
518
+ """Evaluates ONNX ops using ONNX Runtime."""
519
+
520
+ def _eval(self, schema, inputs, attributes, closure):
521
+ model, session_run_input, adapted_inputs = _prepare_model_and_inputs_for_eager(
522
+ schema, inputs, attributes, closure
523
+ )
524
+ session = onnx.reference.ReferenceEvaluator(model)
525
+ try:
526
+ result = session.run(None, session_run_input)
527
+ except RuntimeError as e:
528
+ raise EagerModeError(
529
+ f"Unable to execute model operator {schema.name!r} due to {e!r}"
530
+ f"\ninput types:\n"
531
+ f"{pprint.pformat({k: type(v) for k, v in zip(adapted_inputs, inputs)})}"
532
+ f"\nmodified input types:\n"
533
+ f"{pprint.pformat({k: type(v) for k, v in session_run_input.items()})}"
534
+ f"\ninputs:\n{pprint.pformat(session_run_input)}\n{model}"
535
+ ) from e
536
+
537
+ return [_numpy_to_onnxscript_value(x) for x in result]
538
+
539
+
540
+ ort_evaluator = ORTEvaluator()
541
+
542
+
543
+ class ORTMixedEvaluator(ORTEvaluator):
544
+ """Evaluates ONNX ops using ONNX Runtime, unless an overriding python implementation is registered.
545
+
546
+ This is useful for higher-order ops such as Scan and SequenceMap, allowing for
547
+ python-based debugging.
548
+ """
549
+
550
+ def __init__(self) -> None:
551
+ super().__init__()
552
+ self._python_ops: dict[tuple[str, str, int], Any] = {}
553
+
554
+ def use_graph_attribute(self, schema: onnx.defs.OpSchema) -> bool:
555
+ return _schema_id(schema) not in self._python_ops
556
+
557
+ def _eval(self, schema, inputs, attributes, closure):
558
+ schemaid = _schema_id(schema)
559
+ if schemaid in self._python_ops:
560
+ return self._python_ops[schemaid](inputs, attributes)
561
+ else:
562
+ return super()._eval(schema, inputs, attributes, closure)
563
+
564
+ def register(self, opset: values.Opset) -> Callable[[_T], _T]:
565
+ assert opset is not None
566
+
567
+ def decorator(function: _T) -> _T:
568
+ schema = opset[function.__name__]
569
+ self._python_ops[_schema_id(schema)] = function
570
+ return function
571
+
572
+ return decorator
573
+
574
+
575
+ ort_mixed_evaluator = ORTMixedEvaluator()
576
+
577
+
578
+ @ort_mixed_evaluator.register(opset=onnx_opset.opset18)
579
+ def SequenceMap(inputs: Sequence[Any], attributes: Mapping[str, Any]):
580
+ """Evaluates a SequenceMap op."""
581
+ fun = attributes["body"]
582
+
583
+ def get_input_of(input_index, iter_num):
584
+ input = inputs[input_index]
585
+ if isinstance(input, list):
586
+ return input[iter_num]
587
+ return input
588
+
589
+ def get_input(iter_num):
590
+ return [get_input_of(input_index, iter_num) for input_index in range(len(inputs))]
591
+
592
+ return [fun(*(get_input(i))) for i in range(len(inputs[0]))]
593
+
594
+
595
+ # Used to control the default evaluator instance. A simple approach for now.
596
+
597
+ _default_evaluator: Evaluator = ort_evaluator
598
+
599
+
600
+ def default() -> Evaluator:
601
+ """Returns the default Evaluator default."""
602
+ return _default_evaluator
603
+
604
+
605
+ def set_default(new_default: Evaluator) -> None:
606
+ """Sets the current Evaluator default."""
607
+ global _default_evaluator # pylint: disable=global-statement
608
+ _default_evaluator = new_default
609
+
610
+
611
+ @contextlib.contextmanager
612
+ def default_as(temp_default: Evaluator):
613
+ """Context manager that temporarily switches the default evaluator."""
614
+ old_default = _default_evaluator
615
+ set_default(temp_default)
616
+ try:
617
+ yield
618
+ finally:
619
+ set_default(old_default)