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.
- onnxscript/__init__.py +131 -0
- onnxscript/_framework_apis/__init__.py +3 -0
- onnxscript/_framework_apis/torch_2_5.py +117 -0
- onnxscript/_framework_apis/torch_2_6.py +45 -0
- onnxscript/_internal/__init__.py +0 -0
- onnxscript/_internal/analysis.py +229 -0
- onnxscript/_internal/ast_utils.py +64 -0
- onnxscript/_internal/autocast.py +250 -0
- onnxscript/_internal/deprecation.py +78 -0
- onnxscript/_internal/param_manipulation.py +148 -0
- onnxscript/_internal/runtime_typing.py +43 -0
- onnxscript/_internal/utils.py +99 -0
- onnxscript/_internal/version_utils.py +118 -0
- onnxscript/_legacy_ir/__init__.py +341 -0
- onnxscript/_legacy_ir/visitor.py +937 -0
- onnxscript/_thirdparty/asciichartpy.py +313 -0
- onnxscript/backend/__init__.py +2 -0
- onnxscript/backend/onnx_backend.py +303 -0
- onnxscript/backend/onnx_export.py +885 -0
- onnxscript/converter.py +1470 -0
- onnxscript/evaluator.py +619 -0
- onnxscript/function_libs/tools/torch_lib/deduce_type_constraints.py +403 -0
- onnxscript/function_libs/tools/torch_lib/generate_aten_signatures.py +333 -0
- onnxscript/function_libs/tools/torch_lib/generate_prims_signatures.py +331 -0
- onnxscript/function_libs/torch_lib/__init__.py +12 -0
- onnxscript/function_libs/torch_lib/_constants.py +5 -0
- onnxscript/function_libs/torch_lib/_flags.py +58 -0
- onnxscript/function_libs/torch_lib/graph_building/__init__.py +56 -0
- onnxscript/function_libs/torch_lib/graph_building/_graph_building_ir.py +723 -0
- onnxscript/function_libs/torch_lib/graph_building/_graph_building_torch.py +1125 -0
- onnxscript/function_libs/torch_lib/ops/__init__.py +27 -0
- onnxscript/function_libs/torch_lib/ops/common.py +80 -0
- onnxscript/function_libs/torch_lib/ops/core.py +8935 -0
- onnxscript/function_libs/torch_lib/ops/fft.py +385 -0
- onnxscript/function_libs/torch_lib/ops/linalg.py +399 -0
- onnxscript/function_libs/torch_lib/ops/nested.py +25 -0
- onnxscript/function_libs/torch_lib/ops/nn.py +2713 -0
- onnxscript/function_libs/torch_lib/ops/prims.py +850 -0
- onnxscript/function_libs/torch_lib/ops/quantized_decomposed.py +63 -0
- onnxscript/function_libs/torch_lib/ops/sparse.py +23 -0
- onnxscript/function_libs/torch_lib/ops/special.py +387 -0
- onnxscript/function_libs/torch_lib/ops/vision.py +25 -0
- onnxscript/function_libs/torch_lib/registration.py +151 -0
- onnxscript/function_libs/torch_lib/tensor_typing.py +74 -0
- onnxscript/ir/__init__.py +153 -0
- onnxscript/ir/_convenience.py +447 -0
- onnxscript/ir/_core.py +3119 -0
- onnxscript/ir/_display.py +49 -0
- onnxscript/ir/_enums.py +163 -0
- onnxscript/ir/_graph_comparison.py +23 -0
- onnxscript/ir/_io.py +97 -0
- onnxscript/ir/_linked_list.py +276 -0
- onnxscript/ir/_metadata.py +44 -0
- onnxscript/ir/_name_authority.py +72 -0
- onnxscript/ir/_polyfill.py +25 -0
- onnxscript/ir/_protocols.py +598 -0
- onnxscript/ir/_schemas.py +548 -0
- onnxscript/ir/_tape.py +120 -0
- onnxscript/ir/_type_casting.py +106 -0
- onnxscript/ir/convenience.py +32 -0
- onnxscript/ir/external_data.py +396 -0
- onnxscript/ir/passes/__init__.py +33 -0
- onnxscript/ir/passes/_pass_infra.py +172 -0
- onnxscript/ir/serde.py +1620 -0
- onnxscript/ir/tensor_adapters.py +122 -0
- onnxscript/ir/traversal.py +82 -0
- onnxscript/irbuilder.py +542 -0
- onnxscript/main.py +167 -0
- onnxscript/onnx_opset/__init__.py +232 -0
- onnxscript/onnx_opset/_impl/opset1.py +4100 -0
- onnxscript/onnx_opset/_impl/opset10.py +1227 -0
- onnxscript/onnx_opset/_impl/opset11.py +4013 -0
- onnxscript/onnx_opset/_impl/opset12.py +1078 -0
- onnxscript/onnx_opset/_impl/opset13.py +3924 -0
- onnxscript/onnx_opset/_impl/opset14.py +999 -0
- onnxscript/onnx_opset/_impl/opset15.py +604 -0
- onnxscript/onnx_opset/_impl/opset16.py +1255 -0
- onnxscript/onnx_opset/_impl/opset17.py +561 -0
- onnxscript/onnx_opset/_impl/opset18.py +1803 -0
- onnxscript/onnx_opset/_impl/opset19.py +1942 -0
- onnxscript/onnx_opset/_impl/opset2.py +218 -0
- onnxscript/onnx_opset/_impl/opset20.py +675 -0
- onnxscript/onnx_opset/_impl/opset21.py +1976 -0
- onnxscript/onnx_opset/_impl/opset22.py +2588 -0
- onnxscript/onnx_opset/_impl/opset3.py +199 -0
- onnxscript/onnx_opset/_impl/opset4.py +77 -0
- onnxscript/onnx_opset/_impl/opset5.py +84 -0
- onnxscript/onnx_opset/_impl/opset6.py +944 -0
- onnxscript/onnx_opset/_impl/opset7.py +1243 -0
- onnxscript/onnx_opset/_impl/opset8.py +444 -0
- onnxscript/onnx_opset/_impl/opset9.py +1485 -0
- onnxscript/onnx_opset/_impl/opset_ai_onnx_ml1.py +974 -0
- onnxscript/onnx_opset/_impl/opset_ai_onnx_ml2.py +112 -0
- onnxscript/onnx_opset/_impl/opset_ai_onnx_ml3.py +308 -0
- onnxscript/onnx_opset/_impl/opset_ai_onnx_ml4.py +129 -0
- onnxscript/onnx_opset/_impl/opset_ai_onnx_ml5.py +158 -0
- onnxscript/onnx_opset/_impl/opset_ai_onnx_preview_training1.py +577 -0
- onnxscript/onnx_types.py +229 -0
- onnxscript/optimizer/__init__.py +39 -0
- onnxscript/optimizer/_constant_folding.py +1083 -0
- onnxscript/optimizer/_inliner.py +312 -0
- onnxscript/optimizer/_legacy/_optimizer.py +98 -0
- onnxscript/optimizer/_legacy/_remove_unused_proto.py +144 -0
- onnxscript/optimizer/_legacy/_simple_function_folding.py +243 -0
- onnxscript/optimizer/_legacy/constant_folding.py +293 -0
- onnxscript/optimizer/_legacy/evaluator.py +439 -0
- onnxscript/optimizer/_optimizer.py +61 -0
- onnxscript/optimizer/_remove_unused.py +106 -0
- onnxscript/optimizer/_remove_unused_function.py +72 -0
- onnxscript/py.typed +1 -0
- onnxscript/rewriter/__init__.py +56 -0
- onnxscript/rewriter/_ir_utils.py +111 -0
- onnxscript/rewriter/broadcast_to_matmul.py +180 -0
- onnxscript/rewriter/cast_constant_of_shape.py +50 -0
- onnxscript/rewriter/collapse_slices.py +141 -0
- onnxscript/rewriter/erfgelu.py +27 -0
- onnxscript/rewriter/function_rule.py +232 -0
- onnxscript/rewriter/gemm_to_matmul_add.py +21 -0
- onnxscript/rewriter/generic_pattern.py +700 -0
- onnxscript/rewriter/llama_rule_sets.py +287 -0
- onnxscript/rewriter/no_op.py +56 -0
- onnxscript/rewriter/onnxruntime/__init__.py +50 -0
- onnxscript/rewriter/onnxruntime/bfloat16_utils/bfloat16_converter.py +99 -0
- onnxscript/rewriter/onnxruntime/fused_matmul_rule_sets.py +177 -0
- onnxscript/rewriter/onnxruntime/group_normalization_merge_silu.py +64 -0
- onnxscript/rewriter/onnxruntime/instance_to_group_normalization.py +155 -0
- onnxscript/rewriter/onnxruntime/softmax.py +63 -0
- onnxscript/rewriter/onnxruntime/transformers/__init__.py +21 -0
- onnxscript/rewriter/onnxruntime/transformers/biassplitgelu.py +31 -0
- onnxscript/rewriter/onnxruntime/transformers/fastgelu.py +29 -0
- onnxscript/rewriter/onnxruntime/transformers/layernorm.py +47 -0
- onnxscript/rewriter/onnxruntime/transformers/multihead_attention.py +715 -0
- onnxscript/rewriter/ort_fusions/__init__.py +9 -0
- onnxscript/rewriter/ort_fusions/_core.py +28 -0
- onnxscript/rewriter/ort_fusions/_smollm_1.py +253 -0
- onnxscript/rewriter/ort_fusions/_smollm_2.py +467 -0
- onnxscript/rewriter/ort_fusions/_test_models.py +122 -0
- onnxscript/rewriter/ort_fusions/_test_utils.py +42 -0
- onnxscript/rewriter/ort_fusions/cos_sin_cache.py +154 -0
- onnxscript/rewriter/ort_fusions/gqa.py +156 -0
- onnxscript/rewriter/ort_fusions/mha.py +198 -0
- onnxscript/rewriter/ort_fusions/rms_normalization.py +95 -0
- onnxscript/rewriter/ort_fusions/rotary_embedding.py +64 -0
- onnxscript/rewriter/ort_fusions/sdpa.py +75 -0
- onnxscript/rewriter/ort_fusions/skip_normalization.py +46 -0
- onnxscript/rewriter/pattern.py +1714 -0
- onnxscript/rewriter/testing.py +77 -0
- onnxscript/sourceinfo.py +59 -0
- onnxscript/tensor.py +227 -0
- onnxscript/testing/__init__.py +482 -0
- onnxscript/tools/__init__.py +4 -0
- onnxscript/tools/benchmark/__init__.py +23 -0
- onnxscript/tools/benchmark/benchmark_helpers.py +783 -0
- onnxscript/tools/benchmark/benchmark_run.py +140 -0
- onnxscript/tools/benchmark/export_model.py +207 -0
- onnxscript/tools/benchmark/export_model_batch.py +146 -0
- onnxscript/tools/memory_peak.py +244 -0
- onnxscript/tools/training_helper.py +50 -0
- onnxscript/tools/transformers_models/__init__.py +190 -0
- onnxscript/tools/transformers_models/llama.py +168 -0
- onnxscript/tools/transformers_models/mistral.py +238 -0
- onnxscript/tools/transformers_models/phi.py +248 -0
- onnxscript/tools/transformers_models/phi3.py +259 -0
- onnxscript/type_annotation.py +281 -0
- onnxscript/utils/__init__.py +0 -0
- onnxscript/utils/evaluation_utils.py +56 -0
- onnxscript/utils/timing_utils.py +33 -0
- onnxscript/utils/utils.py +84 -0
- onnxscript/values.py +790 -0
- onnxscript/version_converter/__init__.py +21 -0
- onnxscript/version_converter/_version_converter.py +314 -0
- onnxscript-0.1.0.dist-info/LICENSE +21 -0
- onnxscript-0.1.0.dist-info/METADATA +370 -0
- onnxscript-0.1.0.dist-info/RECORD +176 -0
- onnxscript-0.1.0.dist-info/WHEEL +5 -0
- onnxscript-0.1.0.dist-info/top_level.txt +1 -0
onnxscript/values.py
ADDED
|
@@ -0,0 +1,790 @@
|
|
|
1
|
+
# Copyright (c) Microsoft Corporation.
|
|
2
|
+
# Licensed under the MIT License.
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import dataclasses
|
|
6
|
+
import functools
|
|
7
|
+
import inspect
|
|
8
|
+
import logging
|
|
9
|
+
import types
|
|
10
|
+
import typing
|
|
11
|
+
from enum import IntFlag
|
|
12
|
+
from typing import ( # type: ignore[attr-defined]
|
|
13
|
+
Any,
|
|
14
|
+
Callable,
|
|
15
|
+
ClassVar,
|
|
16
|
+
Optional,
|
|
17
|
+
Protocol,
|
|
18
|
+
Sequence,
|
|
19
|
+
_GenericAlias,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
import onnx
|
|
23
|
+
import onnx.defs
|
|
24
|
+
|
|
25
|
+
from onnxscript import converter as converter_module
|
|
26
|
+
from onnxscript import irbuilder, sourceinfo, type_annotation
|
|
27
|
+
from onnxscript._internal import ast_utils, deprecation
|
|
28
|
+
from onnxscript.ir import _schemas
|
|
29
|
+
|
|
30
|
+
_ATTRIBUTE_TYPE_TO_PYTHON_TYPE = {
|
|
31
|
+
onnx.defs.OpSchema.AttrType.FLOAT: float,
|
|
32
|
+
onnx.defs.OpSchema.AttrType.INT: int,
|
|
33
|
+
onnx.defs.OpSchema.AttrType.STRING: str,
|
|
34
|
+
onnx.defs.OpSchema.AttrType.TENSOR: None,
|
|
35
|
+
onnx.defs.OpSchema.AttrType.GRAPH: None,
|
|
36
|
+
onnx.defs.OpSchema.AttrType.SPARSE_TENSOR: None,
|
|
37
|
+
onnx.defs.OpSchema.AttrType.TYPE_PROTO: None,
|
|
38
|
+
onnx.defs.OpSchema.AttrType.FLOATS: Sequence[float],
|
|
39
|
+
onnx.defs.OpSchema.AttrType.INTS: Sequence[int],
|
|
40
|
+
onnx.defs.OpSchema.AttrType.STRINGS: Sequence[str],
|
|
41
|
+
onnx.defs.OpSchema.AttrType.TENSORS: None,
|
|
42
|
+
onnx.defs.OpSchema.AttrType.GRAPHS: None,
|
|
43
|
+
onnx.defs.OpSchema.AttrType.SPARSE_TENSORS: None,
|
|
44
|
+
onnx.defs.OpSchema.AttrType.TYPE_PROTOS: None,
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
# A special value to indicate that the default value is not specified
|
|
48
|
+
_EmptyDefault = object()
|
|
49
|
+
|
|
50
|
+
logger = logging.getLogger(__name__)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class Opset:
|
|
54
|
+
"""Represents an ONNX Opset, which consists of a domain name, a version.
|
|
55
|
+
|
|
56
|
+
It also contains a set of operations. This represents an Opset defined
|
|
57
|
+
in the ONNX schema registry and the operations are retrieved from the
|
|
58
|
+
ONNX schema registry. It also stores function definitions created for
|
|
59
|
+
ops in the corresponding Opset.
|
|
60
|
+
|
|
61
|
+
Only a single instance of Opset is created for a given (domain, version) pair.
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
domain: str
|
|
65
|
+
version: int
|
|
66
|
+
cache: ClassVar[dict[tuple[type, str, int], Opset]] = {}
|
|
67
|
+
|
|
68
|
+
def __new__(cls, domain: str, version: int):
|
|
69
|
+
key = (cls, domain, version)
|
|
70
|
+
existing = cls.cache.get(key)
|
|
71
|
+
if existing:
|
|
72
|
+
return existing
|
|
73
|
+
instance = super().__new__(cls)
|
|
74
|
+
instance.domain = domain # type: ignore[attr-defined]
|
|
75
|
+
instance.version = version # type: ignore[attr-defined]
|
|
76
|
+
instance.function_defs = {} # type: ignore[attr-defined]
|
|
77
|
+
cls.cache[key] = instance
|
|
78
|
+
return instance
|
|
79
|
+
|
|
80
|
+
def __init__(self, domain: Optional[str] = None, version: Optional[int] = None):
|
|
81
|
+
# Nothing to do. Object is initialized by __new__
|
|
82
|
+
pass
|
|
83
|
+
|
|
84
|
+
def __repr__(self):
|
|
85
|
+
return f"{self.__class__.__name__}({self.domain!r}, {self.version!r})"
|
|
86
|
+
|
|
87
|
+
def __getitem__(self, opname):
|
|
88
|
+
try:
|
|
89
|
+
return onnx.defs.get_schema(opname, self.version, self.domain)
|
|
90
|
+
except Exception: # pylint: disable=broad-except # TODO: more specific exception
|
|
91
|
+
return None
|
|
92
|
+
|
|
93
|
+
def __contains__(self, opname):
|
|
94
|
+
try:
|
|
95
|
+
onnx.defs.get_schema(opname, self.version, self.domain)
|
|
96
|
+
except Exception: # pylint: disable=broad-except # TODO: more specific exception
|
|
97
|
+
return False
|
|
98
|
+
else:
|
|
99
|
+
return True
|
|
100
|
+
|
|
101
|
+
def __str__(self) -> str:
|
|
102
|
+
return self.domain
|
|
103
|
+
|
|
104
|
+
def __getattr__(self, attr: str):
|
|
105
|
+
try:
|
|
106
|
+
schema = onnx.defs.get_schema(attr, self.version, self.domain)
|
|
107
|
+
return Op(self, attr, schema)
|
|
108
|
+
except Exception as exc:
|
|
109
|
+
raise AttributeError(f"Attribute {attr} not found.") from exc
|
|
110
|
+
|
|
111
|
+
def add_function_def(self, fun):
|
|
112
|
+
if fun.name in self.function_defs:
|
|
113
|
+
logger.warning("%s: Already defined.", fun.name)
|
|
114
|
+
self.function_defs[fun.name] = fun
|
|
115
|
+
|
|
116
|
+
def _prepare_inputs(self, _: onnx.defs.OpSchema, *inputs):
|
|
117
|
+
"""Trims 'None' values from the end of the inputs list. This is used to support
|
|
118
|
+
omitting optional inputs when no more required inputs follow to prepare a valid call
|
|
119
|
+
against the Op. Used by the static opset code generator.
|
|
120
|
+
"""
|
|
121
|
+
# TODO: validate the op schema as 'None' values are removed?
|
|
122
|
+
input_list = list(inputs)
|
|
123
|
+
while input_list and input_list[-1] is None:
|
|
124
|
+
input_list.pop()
|
|
125
|
+
return input_list
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
# ONNX ops
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
@dataclasses.dataclass(frozen=True)
|
|
132
|
+
class ParamSchema:
|
|
133
|
+
"""A schema for a parameter of an Op or a OnnxFunction.
|
|
134
|
+
|
|
135
|
+
Attributes:
|
|
136
|
+
name: The name of the parameter.
|
|
137
|
+
type: The type of the parameter.
|
|
138
|
+
default: The default value of the parameter.
|
|
139
|
+
required: Whether the input or attribute is required.
|
|
140
|
+
For example, `Slice` has two optional inputs `axes` and `steps`.
|
|
141
|
+
`SoftmaxCrossEntropyLoss` has an optional attribute `ignore_index`.
|
|
142
|
+
is_input: Whether the parameter is an ONNX input.
|
|
143
|
+
is_variadic_input: Whether the parameter, which has to be an INPUT, is variadic.
|
|
144
|
+
"""
|
|
145
|
+
|
|
146
|
+
name: str
|
|
147
|
+
type: Any = None # Op input does not have a type, for now
|
|
148
|
+
default: Any = _EmptyDefault
|
|
149
|
+
required: bool = True
|
|
150
|
+
is_input: bool = True
|
|
151
|
+
is_variadic_input: bool = False
|
|
152
|
+
|
|
153
|
+
def __str__(self) -> str:
|
|
154
|
+
"""Return a string representation of the parameter.
|
|
155
|
+
|
|
156
|
+
E.g. "x: Input[INT64]" or "axis: Attribute[int] = 0"
|
|
157
|
+
"""
|
|
158
|
+
param_kind = "Input" if self.is_input else "Attribute"
|
|
159
|
+
text = f"{self.name}: {param_kind}[{self.type}]"
|
|
160
|
+
if self.default is not _EmptyDefault:
|
|
161
|
+
text += f" = {self.default}"
|
|
162
|
+
return text
|
|
163
|
+
|
|
164
|
+
@property
|
|
165
|
+
def is_attribute(self) -> bool:
|
|
166
|
+
"""Returns True if the parameter is an ONNX attribute."""
|
|
167
|
+
return not self.is_input
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _get_attribute_value(attr_proto: onnx.AttributeProto) -> Any:
|
|
171
|
+
"""Get the default value of an ONNX attribute."""
|
|
172
|
+
if attr_proto.type == onnx.AttributeProto.UNDEFINED:
|
|
173
|
+
return _EmptyDefault
|
|
174
|
+
return onnx.helper.get_attribute_value(attr_proto)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _param_schemas_from_op_schema(
|
|
178
|
+
op_schema: onnx.defs.OpSchema,
|
|
179
|
+
) -> tuple[ParamSchema, ...]:
|
|
180
|
+
"""Get the parameter schemas from an ONNX OpSchema."""
|
|
181
|
+
schemas = []
|
|
182
|
+
for input_ in op_schema.inputs:
|
|
183
|
+
param_schema = ParamSchema(
|
|
184
|
+
name=input_.name,
|
|
185
|
+
is_input=True,
|
|
186
|
+
required=(input_.option != onnx.defs.OpSchema.FormalParameterOption.Optional),
|
|
187
|
+
is_variadic_input=(
|
|
188
|
+
input_.option == onnx.defs.OpSchema.FormalParameterOption.Variadic
|
|
189
|
+
),
|
|
190
|
+
)
|
|
191
|
+
schemas.append(param_schema)
|
|
192
|
+
for attr_name, attribute in op_schema.attributes.items():
|
|
193
|
+
default_attr_proto = attribute.default_value
|
|
194
|
+
param_schema = ParamSchema(
|
|
195
|
+
name=attr_name,
|
|
196
|
+
type=_ATTRIBUTE_TYPE_TO_PYTHON_TYPE[attribute.type],
|
|
197
|
+
default=_get_attribute_value(default_attr_proto),
|
|
198
|
+
is_input=False,
|
|
199
|
+
required=attribute.required,
|
|
200
|
+
)
|
|
201
|
+
schemas.append(param_schema)
|
|
202
|
+
|
|
203
|
+
return tuple(schemas)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _param_schema_from_function_ir_input(input: irbuilder.IRVar):
|
|
207
|
+
if type_annotation.is_optional(input.typeinfo):
|
|
208
|
+
required = False
|
|
209
|
+
else:
|
|
210
|
+
required = True
|
|
211
|
+
return ParamSchema(name=input.name, type=input.typeinfo, is_input=True, required=required)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _param_schema_from_function_ir_attr(attr: irbuilder.IRAttributeParameter):
|
|
215
|
+
return ParamSchema(
|
|
216
|
+
name=attr.name,
|
|
217
|
+
type=_ATTRIBUTE_TYPE_TO_PYTHON_TYPE.get(
|
|
218
|
+
onnx.defs.OpSchema.AttrType(attr.type) # type: ignore[call-arg]
|
|
219
|
+
),
|
|
220
|
+
default=_EmptyDefault if attr.default_value is None else attr.default_value,
|
|
221
|
+
is_input=False,
|
|
222
|
+
required=not attr.has_default,
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _param_schemas_from_function_ir(
|
|
227
|
+
function_ir: irbuilder.IRFunction,
|
|
228
|
+
) -> tuple[ParamSchema, ...]:
|
|
229
|
+
"""Get the parameter schemas from a FunctionIR."""
|
|
230
|
+
schemas = []
|
|
231
|
+
|
|
232
|
+
# OnnxFunction supports interleaving inputs and attributes as arguments.
|
|
233
|
+
# Preserve the original order for param_schemas.
|
|
234
|
+
# NOTE the interleave ordering is only preserved at OnnxFunction/FunctionIR level.
|
|
235
|
+
# ONNX OpSchema and FunctionProto does not support interleaving inputs and attributes.
|
|
236
|
+
# This is by design. See more at https://github.com/microsoft/onnxscript/issues/771.
|
|
237
|
+
for arg in function_ir.ordered_inputs_and_attrs:
|
|
238
|
+
if isinstance(arg, irbuilder.IRVar):
|
|
239
|
+
# input
|
|
240
|
+
schemas.append(_param_schema_from_function_ir_input(arg))
|
|
241
|
+
elif isinstance(arg, irbuilder.IRAttributeParameter):
|
|
242
|
+
# attr
|
|
243
|
+
schemas.append(_param_schema_from_function_ir_attr(arg))
|
|
244
|
+
else:
|
|
245
|
+
raise TypeError(f"Unknown input/attr type {type(arg)} from FunctionIR.")
|
|
246
|
+
|
|
247
|
+
return tuple(schemas)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
@typing.runtime_checkable
|
|
251
|
+
class OpLike(Protocol):
|
|
252
|
+
"""A protocol for objects that have an ONNX OpSchema."""
|
|
253
|
+
|
|
254
|
+
@property
|
|
255
|
+
def name(self) -> str: ...
|
|
256
|
+
|
|
257
|
+
@property
|
|
258
|
+
def opset(self) -> Opset: ...
|
|
259
|
+
|
|
260
|
+
@property
|
|
261
|
+
def op_schema(self) -> Optional[onnx.defs.OpSchema]: ...
|
|
262
|
+
|
|
263
|
+
@property
|
|
264
|
+
def op_signature(self) -> Optional[_schemas.OpSignature]: ...
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
class Op(OpLike):
|
|
268
|
+
"""Represents an ONNX op instance (for example, the MatMul op from ONNX opset version 13).
|
|
269
|
+
|
|
270
|
+
It belongs to a particular Opset and has a name.
|
|
271
|
+
|
|
272
|
+
Attributes:
|
|
273
|
+
opset: The Opset that this op belongs to.
|
|
274
|
+
name: The name of the op.
|
|
275
|
+
op_schema: The ONNX OpSchema for the op.
|
|
276
|
+
"""
|
|
277
|
+
|
|
278
|
+
def __init__(
|
|
279
|
+
self, opset: Opset, name: str, op_schema: Optional[onnx.defs.OpSchema] = None
|
|
280
|
+
) -> None:
|
|
281
|
+
self._opset = opset
|
|
282
|
+
self._name = name
|
|
283
|
+
self._op_schema = op_schema or opset[name]
|
|
284
|
+
self._signature: Optional[_schemas.OpSignature] = None
|
|
285
|
+
self._param_schemas: Optional[tuple[ParamSchema, ...]] = None
|
|
286
|
+
|
|
287
|
+
if self._op_schema is None:
|
|
288
|
+
logger.debug(
|
|
289
|
+
"An OpSchema was not provided for Op '%s' and "
|
|
290
|
+
"there is not one found in opset '%s'.",
|
|
291
|
+
name,
|
|
292
|
+
opset,
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
def __call__(self, *args, **kwargs):
|
|
296
|
+
# FIXME(after #225): Move import to the top of the file.
|
|
297
|
+
from onnxscript import evaluator # pylint: disable=import-outside-toplevel
|
|
298
|
+
|
|
299
|
+
schema = self.op_schema
|
|
300
|
+
if schema is None:
|
|
301
|
+
raise RuntimeError(
|
|
302
|
+
f"Op '{self.name}' does not have an OpSchema and cannot be evaluated."
|
|
303
|
+
)
|
|
304
|
+
return evaluator.default().eval(schema, args, kwargs)
|
|
305
|
+
|
|
306
|
+
@property
|
|
307
|
+
def name(self) -> str:
|
|
308
|
+
return self._name
|
|
309
|
+
|
|
310
|
+
@property
|
|
311
|
+
def opset(self) -> Opset:
|
|
312
|
+
return self._opset
|
|
313
|
+
|
|
314
|
+
@property
|
|
315
|
+
def op_schema(self) -> Optional[onnx.defs.OpSchema]:
|
|
316
|
+
return self._op_schema
|
|
317
|
+
|
|
318
|
+
@deprecation.deprecated(
|
|
319
|
+
since="0.1",
|
|
320
|
+
removed_in="the future",
|
|
321
|
+
instructions="check if '.op_schema' is not None instead",
|
|
322
|
+
)
|
|
323
|
+
def has_schema(self) -> bool:
|
|
324
|
+
"""Returns True if this op has an OpSchema."""
|
|
325
|
+
return self.op_schema is not None
|
|
326
|
+
|
|
327
|
+
@property
|
|
328
|
+
def op_signature(self) -> Optional[_schemas.OpSignature]:
|
|
329
|
+
"""Returns the signature of this op."""
|
|
330
|
+
if self._signature is not None:
|
|
331
|
+
return self._signature
|
|
332
|
+
|
|
333
|
+
if self.op_schema is None:
|
|
334
|
+
return None
|
|
335
|
+
|
|
336
|
+
self._signature = _schemas.OpSignature.from_op_schema(self.op_schema)
|
|
337
|
+
return self._signature
|
|
338
|
+
|
|
339
|
+
@op_signature.setter
|
|
340
|
+
def op_signature(self, value: _schemas.OpSignature):
|
|
341
|
+
self._signature = value
|
|
342
|
+
|
|
343
|
+
@deprecation.deprecated(
|
|
344
|
+
since="0.1",
|
|
345
|
+
removed_in="the future",
|
|
346
|
+
instructions="use '.op_signature' instead",
|
|
347
|
+
)
|
|
348
|
+
def param_schemas(self) -> Optional[tuple[ParamSchema, ...]]:
|
|
349
|
+
"""Returns the parameter schemas for this op, if it has one."""
|
|
350
|
+
if self._param_schemas is not None:
|
|
351
|
+
return self._param_schemas
|
|
352
|
+
|
|
353
|
+
op_schema = self.op_schema
|
|
354
|
+
if op_schema is None:
|
|
355
|
+
return None
|
|
356
|
+
|
|
357
|
+
self._param_schemas = _param_schemas_from_op_schema(op_schema)
|
|
358
|
+
return self._param_schemas
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
@dataclasses.dataclass(repr=False, eq=False)
|
|
362
|
+
class OnnxClosure:
|
|
363
|
+
"""Represents a nested function used as a graph-valued attribute for an ONNX op call."""
|
|
364
|
+
|
|
365
|
+
function_ir: irbuilder.IRFunction
|
|
366
|
+
|
|
367
|
+
# frame is python's stack-frame for the execution of top-level
|
|
368
|
+
# script function (in eager-mode). It is used to get the current
|
|
369
|
+
# value of outer-scope variables referred to inside this nested
|
|
370
|
+
# function/GraphProto.
|
|
371
|
+
frame: types.FrameType
|
|
372
|
+
|
|
373
|
+
function: Any
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
@dataclasses.dataclass
|
|
377
|
+
class TypeConstraint:
|
|
378
|
+
"""Represents a type constraint for an ONNX op.
|
|
379
|
+
|
|
380
|
+
Attributes:
|
|
381
|
+
name: The name of the type constraint.
|
|
382
|
+
allowed_types: The allowed types for the type constraint.
|
|
383
|
+
"""
|
|
384
|
+
|
|
385
|
+
name: str
|
|
386
|
+
allowed_types: list[str]
|
|
387
|
+
description: str = ""
|
|
388
|
+
|
|
389
|
+
def as_tuple(self) -> tuple[str, list[str], str]:
|
|
390
|
+
"""Returns the type constraint as a tuple."""
|
|
391
|
+
return (self.name, self.allowed_types, self.description)
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def _op_schema_from_function_ir(
|
|
395
|
+
function_ir: irbuilder.IRFunction, opset: Opset
|
|
396
|
+
) -> onnx.defs.OpSchema:
|
|
397
|
+
"""Construct an ONNX OpSchema from an IRFunction."""
|
|
398
|
+
|
|
399
|
+
# Find all distinct types in the inputs and outputs
|
|
400
|
+
distinct_types = {arg.typeinfo for arg in function_ir.inputs}.union(
|
|
401
|
+
{arg.typeinfo for arg in function_ir.outputs}
|
|
402
|
+
)
|
|
403
|
+
# Create a mapping from type to a unique name
|
|
404
|
+
type_to_constraint = {}
|
|
405
|
+
for i, type_ in enumerate(distinct_types):
|
|
406
|
+
name = f"T{i}"
|
|
407
|
+
type_to_constraint[type_] = TypeConstraint(
|
|
408
|
+
name=type_annotation.get_type_constraint_name(type_) or name,
|
|
409
|
+
allowed_types=type_annotation.pytype_to_type_strings(type_),
|
|
410
|
+
)
|
|
411
|
+
|
|
412
|
+
formal_inputs = [
|
|
413
|
+
onnx.defs.OpSchema.FormalParameter(
|
|
414
|
+
arg.name,
|
|
415
|
+
type_to_constraint[arg.typeinfo].name,
|
|
416
|
+
param_option=(
|
|
417
|
+
onnx.defs.OpSchema.FormalParameterOption.Optional
|
|
418
|
+
if type_annotation.is_optional(arg.typeinfo)
|
|
419
|
+
else onnx.defs.OpSchema.FormalParameterOption.Single
|
|
420
|
+
),
|
|
421
|
+
# TODO(justinchu): Check this is_homogeneous thing
|
|
422
|
+
is_homogeneous=True,
|
|
423
|
+
)
|
|
424
|
+
for arg in function_ir.inputs
|
|
425
|
+
]
|
|
426
|
+
formal_outputs = [
|
|
427
|
+
onnx.defs.OpSchema.FormalParameter(
|
|
428
|
+
arg.name,
|
|
429
|
+
type_to_constraint[arg.typeinfo].name,
|
|
430
|
+
param_option=(
|
|
431
|
+
onnx.defs.OpSchema.FormalParameterOption.Optional
|
|
432
|
+
if type_annotation.is_optional(arg.typeinfo)
|
|
433
|
+
else onnx.defs.OpSchema.FormalParameterOption.Single
|
|
434
|
+
),
|
|
435
|
+
# TODO(justinchu): Check this is_homogeneous thing
|
|
436
|
+
is_homogeneous=True,
|
|
437
|
+
)
|
|
438
|
+
for arg in function_ir.outputs
|
|
439
|
+
]
|
|
440
|
+
return onnx.defs.OpSchema(
|
|
441
|
+
function_ir.name,
|
|
442
|
+
opset.domain,
|
|
443
|
+
since_version=opset.version,
|
|
444
|
+
doc=function_ir.docstring,
|
|
445
|
+
inputs=formal_inputs,
|
|
446
|
+
outputs=formal_outputs,
|
|
447
|
+
type_constraints=[constraint.as_tuple() for constraint in type_to_constraint.values()],
|
|
448
|
+
attributes=[
|
|
449
|
+
*[
|
|
450
|
+
onnx.defs.OpSchema.Attribute(
|
|
451
|
+
attr.name,
|
|
452
|
+
type=onnx.defs.OpSchema.AttrType(attr.type), # type: ignore[call-arg]
|
|
453
|
+
)
|
|
454
|
+
for attr in function_ir.attrs
|
|
455
|
+
if not attr.has_default
|
|
456
|
+
],
|
|
457
|
+
*[
|
|
458
|
+
onnx.defs.OpSchema.Attribute(
|
|
459
|
+
attr.name,
|
|
460
|
+
default_value=attr.attr_proto,
|
|
461
|
+
)
|
|
462
|
+
for attr in function_ir.attrs
|
|
463
|
+
if attr.has_default
|
|
464
|
+
],
|
|
465
|
+
],
|
|
466
|
+
)
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
class OnnxFunction(Op):
|
|
470
|
+
"""Represents an ONNX op for which a function-body has been defined in onnxscript.
|
|
471
|
+
|
|
472
|
+
Attributes:
|
|
473
|
+
opset: Opset the function belongs to.
|
|
474
|
+
name: Name of the function.
|
|
475
|
+
function: Python function.
|
|
476
|
+
function_ir: Python code parsed as an :class:`irbuilder.IRFunction`.
|
|
477
|
+
source: Source code used to generate the function.
|
|
478
|
+
kwargs: Additional properties used to construct a ModelProto.
|
|
479
|
+
op_schema: Generated ONNX OpSchema for this op.
|
|
480
|
+
"""
|
|
481
|
+
|
|
482
|
+
def __init__(
|
|
483
|
+
self,
|
|
484
|
+
opset: Optional[Opset],
|
|
485
|
+
pyfun: Callable,
|
|
486
|
+
irfun: irbuilder.IRFunction,
|
|
487
|
+
source: str,
|
|
488
|
+
kwargs: dict[str, Any],
|
|
489
|
+
):
|
|
490
|
+
"""Constructs an OnnxFunction.
|
|
491
|
+
|
|
492
|
+
Args:
|
|
493
|
+
opset: opset the function belongs to
|
|
494
|
+
pyfun: python function
|
|
495
|
+
irfun: python code parsed by class
|
|
496
|
+
:class:`onnxscript.converter.Converter`
|
|
497
|
+
source: source code used to generate the function
|
|
498
|
+
kwargs: additional properties used to construct a ModelProto
|
|
499
|
+
"""
|
|
500
|
+
opset = opset or Opset(irfun.domain, 1)
|
|
501
|
+
super().__init__(opset, irfun.name)
|
|
502
|
+
self.function = pyfun
|
|
503
|
+
self.function_ir = irfun
|
|
504
|
+
self.source = source
|
|
505
|
+
self.kwargs = kwargs
|
|
506
|
+
self._param_schemas: Optional[tuple[ParamSchema, ...]] = None
|
|
507
|
+
self._op_schema: Optional[onnx.defs.OpSchema] = None
|
|
508
|
+
|
|
509
|
+
# Allow the object to be inspected as a function
|
|
510
|
+
functools.update_wrapper(self, pyfun)
|
|
511
|
+
|
|
512
|
+
# Experimental fields
|
|
513
|
+
self.traceable = False
|
|
514
|
+
|
|
515
|
+
@property
|
|
516
|
+
@deprecation.deprecated(
|
|
517
|
+
since="0.1",
|
|
518
|
+
removed_in="the future",
|
|
519
|
+
instructions="use '.name' instead",
|
|
520
|
+
)
|
|
521
|
+
def opname(self) -> str:
|
|
522
|
+
# NOTE: This is a temporary alias for backward compatibility with PyTorch 2.0.
|
|
523
|
+
# TODO: Remove this in onnxscript 0.3.
|
|
524
|
+
return self.name
|
|
525
|
+
|
|
526
|
+
@property
|
|
527
|
+
def op_schema(self) -> Optional[onnx.defs.OpSchema]:
|
|
528
|
+
"""Construct an OpSchema from function_ir."""
|
|
529
|
+
if self._op_schema is not None:
|
|
530
|
+
return self._op_schema
|
|
531
|
+
|
|
532
|
+
self._op_schema = _op_schema_from_function_ir(self.function_ir, self.opset)
|
|
533
|
+
|
|
534
|
+
return self._op_schema
|
|
535
|
+
|
|
536
|
+
@property
|
|
537
|
+
def op_signature(self) -> Optional[_schemas.OpSignature]:
|
|
538
|
+
"""Returns the signature of this op."""
|
|
539
|
+
if self._signature is not None:
|
|
540
|
+
return self._signature
|
|
541
|
+
|
|
542
|
+
if self.op_schema is None:
|
|
543
|
+
return None
|
|
544
|
+
|
|
545
|
+
self._signature = _schemas.OpSignature.from_function(
|
|
546
|
+
self.function, domain=self.function_ir.domain, name=self.name
|
|
547
|
+
)
|
|
548
|
+
return self._signature
|
|
549
|
+
|
|
550
|
+
@op_signature.setter
|
|
551
|
+
def op_signature(self, value: _schemas.OpSignature):
|
|
552
|
+
self._signature = value
|
|
553
|
+
|
|
554
|
+
def __getitem__(self, instance):
|
|
555
|
+
"""Returns a lambda to evaluate function using given evaluator instance.
|
|
556
|
+
|
|
557
|
+
Usage:
|
|
558
|
+
script_fun(X) executes the function using the default evaluator instance.
|
|
559
|
+
script_fun[instance](X) executes the function using the given evaluator instance.
|
|
560
|
+
"""
|
|
561
|
+
|
|
562
|
+
def fun(*args, **kwargs):
|
|
563
|
+
# FIXME(after #225): Move import to the top of the file.
|
|
564
|
+
from onnxscript import evaluator # pylint: disable=import-outside-toplevel
|
|
565
|
+
|
|
566
|
+
with evaluator.default_as(instance):
|
|
567
|
+
return self.__call__(*args, **kwargs)
|
|
568
|
+
|
|
569
|
+
return fun
|
|
570
|
+
|
|
571
|
+
def __call__(self, *args, **kwargs):
|
|
572
|
+
"""Implements an eager-mode execution of an onnxscript function."""
|
|
573
|
+
# FIXME(after #225): Move import to the top of the file.
|
|
574
|
+
from onnxscript import evaluator # pylint: disable=import-outside-toplevel
|
|
575
|
+
|
|
576
|
+
return evaluator.default().eval_function(self, args, kwargs)
|
|
577
|
+
|
|
578
|
+
def __repr__(self) -> str:
|
|
579
|
+
return f"{self.__class__.__name__}({self.function!r})"
|
|
580
|
+
|
|
581
|
+
@deprecation.deprecated(
|
|
582
|
+
since="0.1",
|
|
583
|
+
removed_in="the future",
|
|
584
|
+
instructions="use '.op_signature' instead",
|
|
585
|
+
)
|
|
586
|
+
def param_schemas(self) -> tuple[ParamSchema, ...]:
|
|
587
|
+
"""Returns the parameter schemas of this function."""
|
|
588
|
+
if self._param_schemas is not None:
|
|
589
|
+
return self._param_schemas
|
|
590
|
+
|
|
591
|
+
# NOTE: We generate the parameter schemas from the function_ir instead
|
|
592
|
+
# of relying on the auto generated OpSchema because we need to preserve the keyword
|
|
593
|
+
# argument order from the Python function definition, which is lost in OpSchema.
|
|
594
|
+
self._param_schemas = _param_schemas_from_function_ir(self.function_ir)
|
|
595
|
+
return self._param_schemas
|
|
596
|
+
|
|
597
|
+
def to_function_proto(self) -> onnx.FunctionProto:
|
|
598
|
+
"""Converts the function into :class:`onnx.FunctionProto`."""
|
|
599
|
+
return self.function_ir.to_function_proto()
|
|
600
|
+
|
|
601
|
+
def to_model_proto(self, **kwargs):
|
|
602
|
+
"""Converts the function into :class:`onnx.ModelProto`."""
|
|
603
|
+
if self.function_ir.attrs and any(
|
|
604
|
+
not attr.has_default for attr in self.function_ir.attrs
|
|
605
|
+
):
|
|
606
|
+
raise ValueError(
|
|
607
|
+
"A function with required attributes cannot be exported as a model."
|
|
608
|
+
)
|
|
609
|
+
# Note: The function must also have monomorphic type annotation for inputs/outputs
|
|
610
|
+
# to be converted into a valid model. Otherwise, we can still produce an ONNX
|
|
611
|
+
# model, but it will not pass the ONNX model checker. We do not report an error
|
|
612
|
+
# at this stage.
|
|
613
|
+
|
|
614
|
+
# Merge kwargs specified in script-decorator with those specified in this call.
|
|
615
|
+
merged_kw_args = {**self.kwargs, **kwargs}
|
|
616
|
+
return self.function_ir.to_model_proto(**merged_kw_args)
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
class TracedOnnxFunction(Op):
|
|
620
|
+
"""TracedOnnxFunction.
|
|
621
|
+
|
|
622
|
+
Attributes:
|
|
623
|
+
name: Name of the op. E.g. "aten::add".
|
|
624
|
+
func: Function.
|
|
625
|
+
"""
|
|
626
|
+
|
|
627
|
+
def __init__(self, opset: Opset, func: Callable):
|
|
628
|
+
super().__init__(opset, func.__name__)
|
|
629
|
+
self.func = func
|
|
630
|
+
|
|
631
|
+
# Allow the object to be inspected as a function
|
|
632
|
+
functools.update_wrapper(self, func)
|
|
633
|
+
|
|
634
|
+
def __call__(self, *args, **kwargs):
|
|
635
|
+
return self.func(*args, **kwargs)
|
|
636
|
+
|
|
637
|
+
def __repr__(self):
|
|
638
|
+
return f"{self.__class__.__name__}({self.func!r})"
|
|
639
|
+
|
|
640
|
+
@property
|
|
641
|
+
def function_ir(self) -> irbuilder.IRFunction:
|
|
642
|
+
"""Return the function_ir.
|
|
643
|
+
|
|
644
|
+
This function IR contains only the signature of the function.
|
|
645
|
+
"""
|
|
646
|
+
src, func_ast = ast_utils.get_src_and_ast(self.func)
|
|
647
|
+
module = inspect.getmodule(self.func)
|
|
648
|
+
closure = inspect.getclosurevars(self.func)
|
|
649
|
+
global_names = module.__dict__.copy()
|
|
650
|
+
global_names.update(closure.nonlocals)
|
|
651
|
+
converter = converter_module.Converter(
|
|
652
|
+
opset=self._opset,
|
|
653
|
+
global_names=global_names,
|
|
654
|
+
source=src,
|
|
655
|
+
)
|
|
656
|
+
|
|
657
|
+
return converter.translate_function_signature(func_ast)
|
|
658
|
+
|
|
659
|
+
@property
|
|
660
|
+
def op_schema(self) -> Optional[onnx.defs.OpSchema]:
|
|
661
|
+
"""Return the OpSchema."""
|
|
662
|
+
|
|
663
|
+
if self._op_schema is not None:
|
|
664
|
+
return self._op_schema
|
|
665
|
+
|
|
666
|
+
# FIXME(justinchuby): outputs are empty. Need to fix.
|
|
667
|
+
self._op_schema = _op_schema_from_function_ir(self.function_ir, self._opset)
|
|
668
|
+
|
|
669
|
+
return self._op_schema
|
|
670
|
+
|
|
671
|
+
@property
|
|
672
|
+
def op_signature(self) -> Optional[_schemas.OpSignature]:
|
|
673
|
+
"""Returns the signature of this op."""
|
|
674
|
+
if self._signature is not None:
|
|
675
|
+
return self._signature
|
|
676
|
+
|
|
677
|
+
if self.op_schema is None:
|
|
678
|
+
return None
|
|
679
|
+
|
|
680
|
+
self._signature = _schemas.OpSignature.from_function(
|
|
681
|
+
self.func, domain="_traced", name=self.name
|
|
682
|
+
)
|
|
683
|
+
return self._signature
|
|
684
|
+
|
|
685
|
+
@op_signature.setter
|
|
686
|
+
def op_signature(self, value: _schemas.OpSignature):
|
|
687
|
+
self._signature = value
|
|
688
|
+
|
|
689
|
+
@deprecation.deprecated(
|
|
690
|
+
since="0.1",
|
|
691
|
+
removed_in="the future",
|
|
692
|
+
instructions="use '.op_signature' instead",
|
|
693
|
+
)
|
|
694
|
+
def param_schemas(self) -> tuple[ParamSchema, ...]:
|
|
695
|
+
"""Returns the parameter schemas of this function."""
|
|
696
|
+
if self._param_schemas is not None:
|
|
697
|
+
return self._param_schemas
|
|
698
|
+
|
|
699
|
+
# NOTE: We generate the parameter schemas from the function_ir instead
|
|
700
|
+
# of relying on the auto generated OpSchema because we need to preserve the keyword
|
|
701
|
+
# argument order from the Python function definition, which is lost in OpSchema.
|
|
702
|
+
self._param_schemas = _param_schemas_from_function_ir(self.function_ir)
|
|
703
|
+
return self._param_schemas
|
|
704
|
+
|
|
705
|
+
|
|
706
|
+
class SymbolValue:
|
|
707
|
+
"""Represents script-time value information about named variables used in a script.
|
|
708
|
+
|
|
709
|
+
At translation-time, the (local) variables of a script, including its parameters,
|
|
710
|
+
are bound to a SymbolValue.
|
|
711
|
+
|
|
712
|
+
SymbolValues fall into the following categories:
|
|
713
|
+
|
|
714
|
+
AttrRef: Function parameters of attribute-kind, also mapped to ONNX attributes
|
|
715
|
+
|
|
716
|
+
Dynamic: values computed at runtime (of tensor type, for now) mapped to NodeArgs.
|
|
717
|
+
Dynamic values include input-parameters of the script, as well intermediate
|
|
718
|
+
values computed in the script.
|
|
719
|
+
|
|
720
|
+
For example, consider the following script definition:
|
|
721
|
+
::
|
|
722
|
+
|
|
723
|
+
@script()
|
|
724
|
+
def ThresholdedRelu(X, alpha: float):
|
|
725
|
+
zero = op.CastLike(0, X)
|
|
726
|
+
return op.Where(X > alpha, X, zero)
|
|
727
|
+
|
|
728
|
+
Here, `X` has a Dynamic value, `alpha` has an AttrRef value, and `zero`
|
|
729
|
+
has a Dynamic value.
|
|
730
|
+
|
|
731
|
+
Scripts may also contain references to global variables, but the translator
|
|
732
|
+
does not associate a SymbolValue with them. The python value of global variables
|
|
733
|
+
is used directly in the translation, and such global variables are intended
|
|
734
|
+
to be used for limited purposes, namely:
|
|
735
|
+
* To identify an opset
|
|
736
|
+
* To represent constant-values, translated into ONNX constants.
|
|
737
|
+
"""
|
|
738
|
+
|
|
739
|
+
def __init__(self, info: sourceinfo.SourceInfo) -> None:
|
|
740
|
+
if not isinstance(info, sourceinfo.SourceInfo):
|
|
741
|
+
raise TypeError(f"info must be of type sourceinfo.SourceInfo not {type(info)!r}.")
|
|
742
|
+
self.info = info
|
|
743
|
+
|
|
744
|
+
|
|
745
|
+
class AttrRef(SymbolValue):
|
|
746
|
+
def __init__(
|
|
747
|
+
self, attr_name: str, typeinfo: _GenericAlias, info: sourceinfo.SourceInfo
|
|
748
|
+
) -> None:
|
|
749
|
+
"""Initializes AttrRef.
|
|
750
|
+
|
|
751
|
+
Arguments:
|
|
752
|
+
attr_name: name of the attribute-parameter
|
|
753
|
+
typeinfo: type annotation of the attribute.
|
|
754
|
+
op's attributes in ONNX are usually single type or list of single type.
|
|
755
|
+
info: for debugging use.
|
|
756
|
+
"""
|
|
757
|
+
super().__init__(info)
|
|
758
|
+
self.value = attr_name
|
|
759
|
+
self.typeinfo = typeinfo
|
|
760
|
+
if not isinstance(typeinfo, (type, _GenericAlias)):
|
|
761
|
+
# typing._GenericAlias for List[int] and List[str], etc.
|
|
762
|
+
raise TypeError(f"Expecting a type not f{type(typeinfo)} for typeinfo.")
|
|
763
|
+
self.typeinfo = typeinfo
|
|
764
|
+
|
|
765
|
+
|
|
766
|
+
class DynamicKind(IntFlag):
|
|
767
|
+
Unknown = 0
|
|
768
|
+
Input = 1
|
|
769
|
+
Output = 2
|
|
770
|
+
Intermediate = 4
|
|
771
|
+
Loop = 8
|
|
772
|
+
|
|
773
|
+
|
|
774
|
+
class Dynamic(SymbolValue):
|
|
775
|
+
def __init__(
|
|
776
|
+
self, onnx_var: str, kind: DynamicKind, info: sourceinfo.SourceInfo, typeinfo=None
|
|
777
|
+
) -> None:
|
|
778
|
+
"""Initializes Dynamic.
|
|
779
|
+
|
|
780
|
+
Arguments:
|
|
781
|
+
onnx_var: the name of the ONNX variable used to represent this value
|
|
782
|
+
kind: the DynamicKind of this variable
|
|
783
|
+
info: source-location information for error-messages/debugging
|
|
784
|
+
typeinfo: type-information for the value
|
|
785
|
+
"""
|
|
786
|
+
super().__init__(info)
|
|
787
|
+
assert isinstance(kind, DynamicKind)
|
|
788
|
+
self.value = onnx_var
|
|
789
|
+
self.kind = kind
|
|
790
|
+
self.typeinfo = typeinfo
|