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
onnxscript/ir/_core.py ADDED
@@ -0,0 +1,3119 @@
1
+ # Copyright (c) Microsoft Corporation.
2
+ # Licensed under the MIT License.
3
+ """data structures for the intermediate representation."""
4
+
5
+ # NOTES for developers:
6
+ # NOTE: None of these classes will have a "to_onnx" or "from_protobuf" method because
7
+ # We cannot assume that the build tool chain has protoc installed and would like
8
+ # to keep this module protobuf free. This way we separate the concerns of the IR
9
+ # and the serialization/deserialization.
10
+ #
11
+ # NOTE: Do not import pathlib in the IR. It is slow. Use os.path methods instead.
12
+
13
+ from __future__ import annotations
14
+
15
+ import abc
16
+ import contextlib
17
+ import dataclasses
18
+ import heapq
19
+ import math
20
+ import mmap
21
+ import os
22
+ import sys
23
+ import textwrap
24
+ import typing
25
+ from collections.abc import Hashable
26
+ from typing import (
27
+ AbstractSet,
28
+ Any,
29
+ Collection,
30
+ Generic,
31
+ Iterable,
32
+ Iterator,
33
+ NamedTuple,
34
+ OrderedDict,
35
+ Sequence,
36
+ SupportsInt,
37
+ Union,
38
+ )
39
+
40
+ import ml_dtypes
41
+ import numpy as np
42
+ from typing_extensions import TypeIs
43
+
44
+ import onnxscript
45
+ from onnxscript.ir import (
46
+ _display,
47
+ _enums,
48
+ _linked_list,
49
+ _metadata,
50
+ _name_authority,
51
+ _protocols,
52
+ _type_casting,
53
+ )
54
+
55
+ if typing.TYPE_CHECKING:
56
+ import numpy.typing as npt
57
+ from typing_extensions import TypeGuard
58
+
59
+ TArrayCompatible = typing.TypeVar(
60
+ "TArrayCompatible",
61
+ bound=Union[_protocols.ArrayCompatible, _protocols.DLPackCompatible],
62
+ )
63
+
64
+ # System is little endian
65
+ _IS_LITTLE_ENDIAN = sys.byteorder == "little"
66
+ # Data types that are not supported by numpy
67
+ _NON_NUMPY_NATIVE_TYPES = frozenset(
68
+ (
69
+ _enums.DataType.BFLOAT16,
70
+ _enums.DataType.FLOAT8E4M3FN,
71
+ _enums.DataType.FLOAT8E4M3FNUZ,
72
+ _enums.DataType.FLOAT8E5M2,
73
+ _enums.DataType.FLOAT8E5M2FNUZ,
74
+ _enums.DataType.INT4,
75
+ _enums.DataType.UINT4,
76
+ _enums.DataType.FLOAT4E2M1,
77
+ )
78
+ )
79
+
80
+
81
+ def _compatible_with_numpy(obj: Any) -> TypeGuard[_protocols.ArrayCompatible]:
82
+ """Use this function to check if an object is compatible with numpy.
83
+
84
+ Avoid isinstance checks with the ArrayCompatible protocol for performance reasons.
85
+ """
86
+ return hasattr(obj, "__array__")
87
+
88
+
89
+ def _compatible_with_dlpack(obj: Any) -> TypeGuard[_protocols.DLPackCompatible]:
90
+ """Use this function to check if an object is compatible with DLPack.
91
+
92
+ Avoid isinstance checks with the DLPackCompatible protocol for performance reasons.
93
+ """
94
+ return hasattr(obj, "__dlpack__")
95
+
96
+
97
+ class TensorBase(abc.ABC, _protocols.TensorProtocol, _display.PrettyPrintable):
98
+ """Convenience Shared methods for classes implementing TensorProtocol."""
99
+
100
+ __slots__ = ()
101
+
102
+ def _printable_type_shape(self) -> str:
103
+ """Return a string representation of the shape and data type."""
104
+ return f"{self.dtype},{self.shape}"
105
+
106
+ def _repr_base(self) -> str:
107
+ """Base string for the repr method.
108
+
109
+ Example: Tensor<FLOAT,[5,42]>
110
+ """
111
+ return f"{self.__class__.__name__}<{self._printable_type_shape()}>"
112
+
113
+ @property
114
+ def size(self) -> int:
115
+ """The number of elements in the tensor."""
116
+ return np.prod(self.shape.numpy()) # type: ignore[return-value,attr-defined]
117
+
118
+ @property
119
+ def nbytes(self) -> int:
120
+ """The number of bytes in the tensor."""
121
+ # Use math.ceil because when dtype is INT4, the itemsize is 0.5
122
+ return math.ceil(self.dtype.itemsize * self.size)
123
+
124
+ def display(self, *, page: bool = False) -> None:
125
+ rich = _display.require_rich()
126
+
127
+ if rich is None:
128
+ status_manager = contextlib.nullcontext()
129
+ else:
130
+ import rich.status # type: ignore[import-not-found, no-redef] # pylint: disable=import-outside-toplevel
131
+
132
+ status_manager = rich.status.Status(f"Computing tensor stats for {self!r}")
133
+
134
+ from onnxscript._thirdparty import ( # pylint: disable=import-outside-toplevel
135
+ asciichartpy,
136
+ )
137
+
138
+ with status_manager:
139
+ # Construct the text to display
140
+ lines = []
141
+ array = self.numpy().flatten()
142
+ lines.append(repr(self))
143
+ lines.append("")
144
+ nan_values = np.isnan(array)
145
+ nan_count = np.count_nonzero(nan_values)
146
+ inf_count = np.count_nonzero(np.isinf(array))
147
+ numbers = array[~nan_values]
148
+ lines.append(
149
+ f"Min: {np.min(numbers)}, Max: {np.max(numbers)}, "
150
+ f"NaN count: {nan_count}, "
151
+ f"Inf count: {inf_count}"
152
+ )
153
+ # Compute sparsity
154
+ sparse_threathold = 1e-6
155
+ # NOTE: count_nonzero() is faster than sum() for boolean arrays
156
+ sparsity = np.count_nonzero(np.abs(array) < sparse_threathold) / array.size
157
+ lines.append(f"Sparsity (abs<{sparse_threathold}): {sparsity:.2f}")
158
+
159
+ # Compute histogram
160
+ finite_numbers = array[np.isfinite(array)]
161
+ lines.append("Histogram:")
162
+ hist, bin_edges = np.histogram(finite_numbers, bins=80, density=False)
163
+ lines.append(
164
+ asciichartpy.plot(
165
+ hist, bin_edges=bin_edges, cfg={"height": 8, "format": "{:8.0f}"}
166
+ )
167
+ )
168
+
169
+ text = "\n".join(lines)
170
+
171
+ if rich is None:
172
+ print(text)
173
+ elif page:
174
+ import rich.console # type: ignore[import-not-found, no-redef] # pylint: disable=import-outside-toplevel
175
+
176
+ console = rich.console.Console()
177
+ with console.pager():
178
+ console.print(text)
179
+ else:
180
+ rich.print(text)
181
+
182
+
183
+ def _check_numpy_representation_type(array: np.ndarray, dtype: _enums.DataType) -> None:
184
+ """Check if the numpy array dtype matches the IR data type.
185
+
186
+ When the dtype is not one of the numpy native dtypes, the value needs need to be:
187
+
188
+ - ``int8`` or ``uint8`` for int4, with the sign bit extended to 8 bits.
189
+ - ``uint8`` for uint4 or float4.
190
+ - ``uint8`` for 8-bit data types.
191
+ - ``uint16`` for bfloat16
192
+
193
+ or corresponding dtypes from the ``ml_dtype`` package.
194
+ """
195
+ if dtype in _NON_NUMPY_NATIVE_TYPES:
196
+ if dtype.itemsize == 2 and array.dtype not in (np.uint16, ml_dtypes.bfloat16):
197
+ raise TypeError(
198
+ f"The numpy array dtype must be uint16 or ml_dtypes.bfloat16 (not {array.dtype}) for IR data type {dtype}."
199
+ )
200
+ if dtype.itemsize == 1 and array.dtype not in (
201
+ np.uint8,
202
+ ml_dtypes.float8_e4m3b11fnuz,
203
+ ml_dtypes.float8_e4m3fn,
204
+ ml_dtypes.float8_e5m2fnuz,
205
+ ml_dtypes.float8_e5m2,
206
+ ):
207
+ raise TypeError(
208
+ f"The numpy array dtype must be uint8 or ml_dtypes.float8* (not {array.dtype}) for IR data type {dtype}."
209
+ )
210
+ if dtype == _enums.DataType.INT4:
211
+ if array.dtype not in (np.int8, np.uint8, ml_dtypes.int4):
212
+ raise TypeError(
213
+ f"The numpy array dtype must be int8 or uint8 or ml_dtypes.int4 (not {array.dtype}) for IR data type {dtype}."
214
+ )
215
+ if dtype == _enums.DataType.UINT4:
216
+ if array.dtype not in (np.uint8, ml_dtypes.uint4):
217
+ raise TypeError(
218
+ f"The numpy array dtype must be uint8 or or ml_dtypes.uint4 (not {array.dtype}) for IR data type {dtype}."
219
+ )
220
+ if dtype == _enums.DataType.FLOAT4E2M1:
221
+ if array.dtype not in (np.uint8, ml_dtypes.float4_e2m1fn):
222
+ raise TypeError(
223
+ f"The numpy array dtype must be uint8 or ml_dtypes.float4_e2m1fn (not {array.dtype}) for IR data type {dtype}."
224
+ )
225
+ return
226
+
227
+ try:
228
+ dtype_numpy = _enums.DataType.from_numpy(array.dtype)
229
+ except TypeError as e:
230
+ raise TypeError(
231
+ "Failed to convert the numpy dtype to an IR data type. "
232
+ "If you are using a non-native dtype, be sure to specify the corresponding IR dtype when "
233
+ "creating a Tensor."
234
+ ) from e
235
+
236
+ if dtype_numpy != dtype:
237
+ raise TypeError(
238
+ f"The numpy array dtype {array.dtype} does not match the IR data type {dtype}."
239
+ )
240
+
241
+
242
+ def _maybe_view_np_array_with_ml_dtypes(
243
+ array: np.ndarray, dtype: _enums.DataType
244
+ ) -> np.ndarray:
245
+ """Reinterpret the array when it is a bit representation of a dtype not supported by numpy.
246
+
247
+ Args:
248
+ array: The numpy array to reinterpret.
249
+ dtype: The data type to reinterpret the array as.
250
+
251
+ Returns:
252
+ The array reinterpreted as the dtype.
253
+ """
254
+ if dtype == _enums.DataType.BFLOAT16:
255
+ return array.view(ml_dtypes.bfloat16)
256
+ if dtype == _enums.DataType.FLOAT8E4M3FN:
257
+ return array.view(ml_dtypes.float8_e4m3fn)
258
+ if dtype == _enums.DataType.FLOAT8E4M3FNUZ:
259
+ return array.view(ml_dtypes.float8_e4m3fnuz)
260
+ if dtype == _enums.DataType.FLOAT8E5M2:
261
+ return array.view(ml_dtypes.float8_e5m2)
262
+ if dtype == _enums.DataType.FLOAT8E5M2FNUZ:
263
+ return array.view(ml_dtypes.float8_e5m2fnuz)
264
+ if dtype == _enums.DataType.INT4:
265
+ return array.view(ml_dtypes.int4)
266
+ if dtype == _enums.DataType.UINT4:
267
+ return array.view(ml_dtypes.uint4)
268
+ if dtype == _enums.DataType.FLOAT4E2M1:
269
+ return array.view(ml_dtypes.float4_e2m1fn)
270
+ return array
271
+
272
+
273
+ class Tensor(TensorBase, _protocols.TensorProtocol, Generic[TArrayCompatible]): # pylint: disable=too-many-ancestors
274
+ """An immutable concrete tensor.
275
+
276
+ This class is a wrapper around the raw tensor data. The raw tensor data can be a numpy array
277
+ compatible object (e.g. ``np.ndarray``, ``torch.Tensor``) or a ``DLPack`` compatible object.
278
+ The tensor is immutable and the data is not copied at initialization.
279
+
280
+ To create a tensor from a numpy array::
281
+
282
+ >>> import numpy as np
283
+ >>> array = np.array([1, 2, 3])
284
+ >>> tensor = Tensor(array)
285
+ >>> # The tensor itself can be treated as a numpy array because it implements the __array__ method
286
+ >>> np.allclose(tensor, array)
287
+ True
288
+
289
+ To get a numpy array from the tensor, call :meth:`numpy`. To convert the tensor
290
+ to a byte string for serialization, call :meth:`tobytes`.
291
+
292
+ It is recommended to check the size of the tensor first before accessing the
293
+ underlying data, because accessing the data may be expensive and incur IO
294
+ overhead.
295
+
296
+ Subclass this class to efficiently handle different types of tensors from different frameworks.
297
+
298
+ Attributes:
299
+ name: The name of the tensor.
300
+ shape: The shape of the tensor.
301
+ dtype: The data type of the elements of the tensor. It is an :class:`ir.DataType` enum.
302
+ doc_string: Documentation string.
303
+ raw: The raw data behind this tensor. It can be anything.
304
+ size: The number of elements in the tensor.
305
+ nbytes: The number of bytes in the tensor.
306
+ metadata_props: Metadata that will be serialized to the ONNX file.
307
+ meta: Metadata store for graph transform passes.
308
+ """
309
+
310
+ __slots__ = (
311
+ "_dtype",
312
+ "_metadata",
313
+ "_metadata_props",
314
+ "_raw",
315
+ "_shape",
316
+ "doc_string",
317
+ "name",
318
+ )
319
+
320
+ def __init__(
321
+ self,
322
+ value: TArrayCompatible,
323
+ dtype: _enums.DataType | None = None,
324
+ *,
325
+ shape: Shape | None = None,
326
+ name: str | None = None,
327
+ doc_string: str | None = None,
328
+ metadata_props: dict[str, str] | None = None,
329
+ ) -> None:
330
+ """Initialize a tensor.
331
+
332
+ Args:
333
+ value: The backing data of the tensor. It can be a numpy array compatible object or a DLPack compatible object.
334
+ When the dtype is not one of the numpy native dtypes, the value needs
335
+ to be ``uint8`` for 4-bit and 8-bit data types, and ``uint16`` for bfloat16
336
+ when the value is a numpy array; :param:`dtype` must be specified in this case.
337
+ dtype: The data type of the tensor. It can be None only when value is a numpy array.
338
+ Users are responsible for making sure the dtype matches the value when value is not a numpy array.
339
+ shape: The shape of the tensor. If None, the shape is obtained from the value.
340
+ name: The name of the tensor.
341
+ doc_string: The documentation string.
342
+ metadata_props: The metadata properties.
343
+
344
+ Raises:
345
+ TypeError: If the value is not a numpy array compatible or a DLPack compatible object.
346
+ TypeError: If the value is a numpy array and the dtype is specified but does not match the dtype of the array.
347
+ ValueError: If the shape is not specified and the value does not have a shape attribute.
348
+ ValueError: If the dtype is not specified and the value is not a numpy array.
349
+ """
350
+ # NOTE: We should not do any copying here for performance reasons
351
+ if not _compatible_with_numpy(value) and not _compatible_with_dlpack(value):
352
+ raise TypeError(f"Expected an array compatible object, got {type(value)}")
353
+ if shape is None:
354
+ # Obtain the shape from the value
355
+ if not hasattr(value, "shape"):
356
+ raise ValueError(
357
+ f"Expected an object with a shape attribute, but {type(value)} does not have shape. "
358
+ "Please specify the shape explicitly."
359
+ )
360
+ self._shape = Shape(getattr(value, "shape"), frozen=True) # noqa: B009
361
+ else:
362
+ self._shape = shape
363
+ self._shape._frozen = True
364
+ if dtype is None:
365
+ if isinstance(value, np.ndarray):
366
+ self._dtype = _enums.DataType.from_numpy(value.dtype)
367
+ else:
368
+ raise ValueError(
369
+ "The dtype must be specified when the value is not a numpy array."
370
+ )
371
+ else:
372
+ if isinstance(value, np.ndarray):
373
+ # Make sure the dtype matches the value
374
+ _check_numpy_representation_type(value, dtype)
375
+ # Users are responsible for making sure the dtype matches the value
376
+ # when value is not a numpy array
377
+ self._dtype = dtype
378
+
379
+ # View the bfloat16, float8 and int4 types using ml_dtypes
380
+ if isinstance(value, np.ndarray):
381
+ value = _maybe_view_np_array_with_ml_dtypes(value, self._dtype) # type: ignore[assignment]
382
+
383
+ self._raw = value
384
+ self.name = name
385
+ self.doc_string = doc_string
386
+ self._metadata: _metadata.MetadataStore | None = None
387
+ self._metadata_props = metadata_props
388
+
389
+ def __array__(self, dtype: Any = None) -> np.ndarray:
390
+ if isinstance(self._raw, np.ndarray) or _compatible_with_numpy(self._raw):
391
+ return self._raw.__array__(dtype)
392
+ assert _compatible_with_dlpack(self._raw), (
393
+ f"Bug: Expected DLPack or Numpy compatible objects, got {type(self._raw)}"
394
+ )
395
+ return np.from_dlpack(self._raw)
396
+
397
+ def __dlpack__(self, *, stream: Any = None) -> Any:
398
+ if _compatible_with_dlpack(self._raw):
399
+ return self._raw.__dlpack__(stream=stream)
400
+ return self.__array__().__dlpack__(stream=stream)
401
+
402
+ def __dlpack_device__(self) -> tuple[int, int]:
403
+ if _compatible_with_dlpack(self._raw):
404
+ return self._raw.__dlpack_device__()
405
+ return self.__array__().__dlpack_device__()
406
+
407
+ def __repr__(self) -> str:
408
+ return f"{self._repr_base()}({self._raw!r}, name={self.name!r})"
409
+
410
+ @property
411
+ def dtype(self) -> _enums.DataType:
412
+ """The data type of the tensor. Immutable."""
413
+ return self._dtype
414
+
415
+ @property
416
+ def shape(self) -> Shape:
417
+ """The shape of the tensor. Immutable."""
418
+ return self._shape
419
+
420
+ @property
421
+ def raw(self) -> TArrayCompatible:
422
+ """Backing data of the tensor. Immutable."""
423
+ return self._raw # type: ignore[return-value]
424
+
425
+ def numpy(self) -> np.ndarray:
426
+ """Return the tensor as a numpy array.
427
+
428
+ When the data type is not supported by numpy, the dtypes from the ``ml_dtype``
429
+ package are used. The values can be reinterpreted as bit representations
430
+ using the ``.view()`` method.
431
+ """
432
+ if isinstance(self._raw, np.ndarray):
433
+ return self._raw
434
+ # We do not cache the value to save memory
435
+ return self.__array__()
436
+
437
+ def tobytes(self) -> bytes:
438
+ """Returns the value as bytes encoded in little endian.
439
+
440
+ Override this method for more efficient serialization when the raw
441
+ value is not a numpy array.
442
+ """
443
+ # TODO(justinchuby): Support DLPack
444
+ array = self.numpy()
445
+ if self.dtype in {
446
+ _enums.DataType.INT4,
447
+ _enums.DataType.UINT4,
448
+ _enums.DataType.FLOAT4E2M1,
449
+ }:
450
+ # Pack the array into int4
451
+ array = _type_casting.pack_int4(array)
452
+ else:
453
+ assert self.dtype.itemsize == array.itemsize, "Bug: The itemsize should match"
454
+ if not _IS_LITTLE_ENDIAN:
455
+ array = array.view(array.dtype.newbyteorder("<"))
456
+ return array.tobytes()
457
+
458
+ @property
459
+ def metadata_props(self) -> dict[str, str]:
460
+ if self._metadata_props is None:
461
+ self._metadata_props = {}
462
+ return self._metadata_props
463
+
464
+ @property
465
+ def meta(self) -> _metadata.MetadataStore:
466
+ """The metadata store for intermediate analysis.
467
+
468
+ Write to the :attr:`metadata_props` if you would like the metadata to be serialized
469
+ to the ONNX proto.
470
+ """
471
+ if self._metadata is None:
472
+ self._metadata = _metadata.MetadataStore()
473
+ return self._metadata
474
+
475
+
476
+ class ExternalTensor(TensorBase, _protocols.TensorProtocol): # pylint: disable=too-many-ancestors
477
+ """An immutable concrete tensor with its data store on disk.
478
+
479
+ This class uses memory mapping to avoid loading the tensor into memory,
480
+ when the data type is supported by numpy. Otherwise, the tensor is loaded
481
+ into memory lazily when accessed.
482
+
483
+ Calling :attr:`shape` does not incur IO. Checking shape before loading
484
+ the tensor is recommended if IO overhead and memory usage is a concern.
485
+
486
+ To obtain an array, call :meth:`numpy`. To obtain the bytes,
487
+ call :meth:`tobytes`.
488
+
489
+ The :attr:`location` must be a relative path conforming to the ONNX
490
+ specification. Given the correct :attr:`base_dir`, the :attr:`path` is computed
491
+ to be the full path to the data file. Users should expect that the :attr:`path`
492
+ always leads to the correct file. At initialization, paths are not checked.
493
+ It is the user's responsibility to ensure the paths are valid and accessible.
494
+
495
+ Attributes:
496
+ location: The location of the data file. It is the path relative to the base directory.
497
+ base_dir: The base directory for the external data. It is used to resolve relative paths.
498
+ At serialization, only the :attr:`location` is serialized into the "location" field of the ``TensorProto``.
499
+ path: The path to the data file. This is computed by joining :attr:`base_dir` and :attr:`location`.
500
+ offset: The offset in bytes from the start of the file.
501
+ length: The length of the data in bytes.
502
+ dtype: The data type of the tensor.
503
+ shape: The shape of the tensor.
504
+ name: The name of the tensor. It must be specified.
505
+ doc_string: The documentation string.
506
+ metadata_props: The metadata properties.
507
+ """
508
+
509
+ __slots__ = (
510
+ "_array",
511
+ "_base_dir",
512
+ "_dtype",
513
+ "_length",
514
+ "_location",
515
+ "_metadata",
516
+ "_metadata_props",
517
+ "_offset",
518
+ "_shape",
519
+ "_valid",
520
+ "doc_string",
521
+ "name",
522
+ "raw",
523
+ )
524
+
525
+ def __init__(
526
+ self,
527
+ location: os.PathLike | str,
528
+ offset: int | None,
529
+ length: int | None,
530
+ dtype: _enums.DataType,
531
+ *,
532
+ shape: Shape,
533
+ name: str,
534
+ doc_string: str | None = None,
535
+ metadata_props: dict[str, str] | None = None,
536
+ base_dir: os.PathLike | str = "",
537
+ ) -> None:
538
+ """Initialize an external tensor.
539
+
540
+ Args:
541
+ location: The location of the data file. It is the path relative to the base directory.
542
+ offset: The offset in bytes from the start of the file.
543
+ length: The length of the data in bytes.
544
+ dtype: The data type of the tensor.
545
+ shape: The shape of the tensor.
546
+ name: The name of the tensor..
547
+ doc_string: The documentation string.
548
+ metadata_props: The metadata properties.
549
+ base_dir: The base directory for the external data. It is used to resolve relative paths.
550
+ """
551
+ # NOTE: Do not verify the location by default. This is because the location field
552
+ # in the tensor proto can be anything and we would like deserialization from
553
+ # proto to IR to not fail.
554
+ if onnxscript.DEBUG:
555
+ if os.path.isabs(location):
556
+ raise ValueError(
557
+ "The location must be a relative path. Please specify base_dir as well."
558
+ )
559
+ self._location = location
560
+ self._base_dir = base_dir
561
+ self._offset: int | None = offset
562
+ self._length: int | None = length
563
+ self._dtype: _enums.DataType = dtype
564
+ self.name: str = name # mutable
565
+ self._shape: Shape = shape
566
+ self._shape._frozen = True
567
+ self.doc_string: str | None = doc_string # mutable
568
+ self._array: np.ndarray | None = None
569
+ self.raw: mmap.mmap | None = None
570
+ self._metadata_props = metadata_props
571
+ self._metadata: _metadata.MetadataStore | None = None
572
+ self._valid = True
573
+
574
+ @property
575
+ def base_dir(self) -> str | os.PathLike:
576
+ # Mutable
577
+ return self._base_dir
578
+
579
+ @base_dir.setter
580
+ def base_dir(self, value: str | os.PathLike) -> None:
581
+ self._base_dir = value
582
+
583
+ @property
584
+ def location(self) -> str | os.PathLike:
585
+ # Immutable
586
+ return self._location
587
+
588
+ @property
589
+ def path(self) -> str:
590
+ # Immutable, computed
591
+ return os.path.join(self._base_dir, self._location)
592
+
593
+ @property
594
+ def offset(self) -> int | None:
595
+ # Immutable
596
+ return self._offset
597
+
598
+ @property
599
+ def length(self) -> int | None:
600
+ # Immutable
601
+ return self._length
602
+
603
+ @property
604
+ def dtype(self) -> _enums.DataType:
605
+ # Immutable
606
+ return self._dtype
607
+
608
+ @property
609
+ def shape(self) -> Shape:
610
+ # Immutable
611
+ return self._shape
612
+
613
+ def _load(self):
614
+ self._check_validity()
615
+ assert self._array is None, "Bug: The array should be loaded only once."
616
+ if self.size == 0:
617
+ # When the size is 0, mmap is impossible and meaningless
618
+ self._array = np.empty(self.shape.numpy(), dtype=self.dtype.numpy())
619
+ return
620
+ # Map the whole file into the memory
621
+ # TODO(justinchuby): Verify if this would exhaust the memory address space
622
+ with open(self.path, "rb") as f:
623
+ self.raw = mmap.mmap(
624
+ f.fileno(),
625
+ 0,
626
+ access=mmap.ACCESS_READ,
627
+ )
628
+ # Handle the byte order correctly by always using little endian
629
+ dt = np.dtype(self.dtype.numpy()).newbyteorder("<")
630
+ if self.dtype in {
631
+ _enums.DataType.INT4,
632
+ _enums.DataType.UINT4,
633
+ _enums.DataType.FLOAT4E2M1,
634
+ }:
635
+ # Use uint8 to read in the full byte. Otherwise ml_dtypes.int4 will clip the values
636
+ dt = np.dtype(np.uint8).newbyteorder("<")
637
+ count = self.size // 2 + self.size % 2
638
+ else:
639
+ count = self.size
640
+ self._array = np.frombuffer(self.raw, dtype=dt, offset=self.offset or 0, count=count)
641
+ shape = self.shape.numpy()
642
+ if self.dtype == _enums.DataType.INT4:
643
+ # Unpack the int4 arrays
644
+ self._array = _type_casting.unpack_int4(self._array, shape)
645
+ elif self.dtype == _enums.DataType.UINT4:
646
+ self._array = _type_casting.unpack_uint4(self._array, shape)
647
+ elif self.dtype == _enums.DataType.FLOAT4E2M1:
648
+ self._array = _type_casting.unpack_float4e2m1(self._array, shape)
649
+ else:
650
+ self._array = self._array.reshape(shape)
651
+
652
+ def __array__(self, dtype: Any = None) -> np.ndarray:
653
+ self._check_validity()
654
+ if self._array is None:
655
+ self._load()
656
+ assert self._array is not None
657
+ return self._array.__array__(dtype)
658
+
659
+ def __dlpack__(self, *, stream: Any = None) -> Any:
660
+ raise NotImplementedError(
661
+ "ExternalTensor does not support DLPack because it uses memory mapping. "
662
+ "Call numpy() to get a numpy array instead."
663
+ )
664
+
665
+ def __dlpack_device__(self) -> tuple[int, int]:
666
+ raise NotImplementedError(
667
+ "ExternalTensor does not support DLPack because it uses memory mapping. "
668
+ "Call numpy() to get a numpy array instead."
669
+ )
670
+
671
+ def __repr__(self) -> str:
672
+ return (
673
+ f"{self._repr_base()}(location='{self.location}', name={self.name!r}, "
674
+ f"offset={self.offset!r}, length={self.length!r}, base_dir={self.base_dir!r})"
675
+ )
676
+
677
+ def numpy(self) -> np.ndarray:
678
+ """Return the tensor as a numpy array.
679
+
680
+ The data will be memory mapped into memory and will not taken up physical memory space.
681
+ """
682
+ self._check_validity()
683
+ if self._array is None:
684
+ self._load()
685
+ assert self._array is not None
686
+ return self._array
687
+
688
+ def tobytes(self) -> bytes:
689
+ """Return the bytes of the tensor.
690
+
691
+ This will load the tensor into memory.
692
+ """
693
+ self._check_validity()
694
+ if self.raw is None:
695
+ self._load()
696
+ assert self.raw is not None
697
+ offset = self._offset or 0
698
+ length = self._length or self.nbytes
699
+ return self.raw[offset : offset + length]
700
+
701
+ def valid(self) -> bool:
702
+ """Check if the tensor is valid.
703
+
704
+ The external tensor is valid if it has not been invalidated.
705
+ """
706
+ return self._valid
707
+
708
+ def _check_validity(self) -> None:
709
+ if not self.valid():
710
+ raise ValueError(
711
+ f"The external tensor '{self!r}' is invalidated. The data may be corrupted or deleted."
712
+ )
713
+
714
+ def invalidate(self) -> None:
715
+ """Invalidate the tensor.
716
+
717
+ The external tensor is invalidated when the data is known to be corrupted or deleted.
718
+ """
719
+ self._valid = False
720
+
721
+ def release(self) -> None:
722
+ """Delete all references to the memory buffer and close the memory-mapped file."""
723
+ self._array = None
724
+ if self.raw is not None:
725
+ self.raw.close()
726
+ self.raw = None
727
+
728
+ @property
729
+ def metadata_props(self) -> dict[str, str]:
730
+ if self._metadata_props is None:
731
+ self._metadata_props = {}
732
+ return self._metadata_props
733
+
734
+ @property
735
+ def meta(self) -> _metadata.MetadataStore:
736
+ """The metadata store for intermediate analysis.
737
+
738
+ Write to the :attr:`metadata_props` if you would like the metadata to be serialized
739
+ to the ONNX proto.
740
+ """
741
+ if self._metadata is None:
742
+ self._metadata = _metadata.MetadataStore()
743
+ return self._metadata
744
+
745
+
746
+ class StringTensor(TensorBase, _protocols.TensorProtocol): # pylint: disable=too-many-ancestors
747
+ """Multidimensional array of strings (as binary data to match the string_data field in TensorProto)."""
748
+
749
+ __slots__ = (
750
+ "_metadata",
751
+ "_metadata_props",
752
+ "_raw",
753
+ "_shape",
754
+ "doc_string",
755
+ "name",
756
+ )
757
+
758
+ def __init__(
759
+ self,
760
+ value: Sequence[bytes] | npt.NDArray[np.bytes_],
761
+ *,
762
+ shape: Shape | None = None,
763
+ name: str | None = None,
764
+ doc_string: str | None = None,
765
+ metadata_props: dict[str, str] | None = None,
766
+ ) -> None:
767
+ """Initialize a tensor.
768
+
769
+ Args:
770
+ value: The backing data of the tensor. It can be a numpy array or a Sequence of bytes.
771
+ shape: The shape of the tensor. If None, the shape is obtained from the value.
772
+ name: The name of the tensor.
773
+ doc_string: The documentation string.
774
+ metadata_props: The metadata properties.
775
+ """
776
+ if shape is None:
777
+ if not hasattr(value, "shape"):
778
+ raise ValueError(
779
+ f"Expected an object with a shape attribute, but {type(value)} does not have shape. "
780
+ "Please specify the shape explicitly."
781
+ )
782
+ self._shape = Shape(getattr(value, "shape"), frozen=True) # noqa: B009
783
+ else:
784
+ self._shape = shape
785
+ self._shape._frozen = True
786
+ self._raw = value
787
+ self.name = name
788
+ self.doc_string = doc_string
789
+ self._metadata: _metadata.MetadataStore | None = None
790
+ self._metadata_props = metadata_props
791
+
792
+ def __array__(self, dtype: Any = None) -> np.ndarray:
793
+ if isinstance(self._raw, np.ndarray):
794
+ return self._raw
795
+ assert isinstance(self._raw, Sequence), (
796
+ f"Bug: Expected a sequence, got {type(self._raw)}"
797
+ )
798
+ return np.array(self._raw, dtype=dtype).reshape(self.shape.numpy())
799
+
800
+ def __dlpack__(self, *, stream: Any = None) -> Any:
801
+ del stream # unused
802
+ raise TypeError("StringTensor does not support DLPack")
803
+
804
+ def __dlpack_device__(self) -> tuple[int, int]:
805
+ raise TypeError("StringTensor does not support DLPack")
806
+
807
+ def __repr__(self) -> str:
808
+ return f"{self._repr_base()}({self._raw!r}, name={self.name!r})"
809
+
810
+ @property
811
+ def dtype(self) -> _enums.DataType:
812
+ """The data type of the tensor. Immutable."""
813
+ return _enums.DataType.STRING
814
+
815
+ @property
816
+ def shape(self) -> Shape:
817
+ """The shape of the tensor. Immutable."""
818
+ return self._shape
819
+
820
+ @property
821
+ def raw(self) -> Sequence[bytes] | npt.NDArray[np.bytes_]:
822
+ """Backing data of the tensor. Immutable."""
823
+ return self._raw # type: ignore[return-value]
824
+
825
+ def numpy(self) -> npt.NDArray[np.bytes_]:
826
+ """Return the tensor as a numpy array."""
827
+ return self.__array__()
828
+
829
+ def tobytes(self) -> bytes:
830
+ raise ValueError("StringTensor does not support tobytes. Use 'string_data' instead.")
831
+
832
+ def string_data(self) -> Sequence[bytes]:
833
+ """Return the string data of the tensor."""
834
+ if isinstance(self._raw, np.ndarray):
835
+ return self._raw.flatten().tolist()
836
+ return self._raw
837
+
838
+ @property
839
+ def metadata_props(self) -> dict[str, str]:
840
+ if self._metadata_props is None:
841
+ self._metadata_props = {}
842
+ return self._metadata_props
843
+
844
+ @property
845
+ def meta(self) -> _metadata.MetadataStore:
846
+ """The metadata store for intermediate analysis.
847
+
848
+ Write to the :attr:`metadata_props` if you would like the metadata to be serialized
849
+ to the ONNX proto.
850
+ """
851
+ if self._metadata is None:
852
+ self._metadata = _metadata.MetadataStore()
853
+ return self._metadata
854
+
855
+
856
+ class SymbolicDim(_protocols.SymbolicDimProtocol, _display.PrettyPrintable):
857
+ __slots__ = ("_value",)
858
+
859
+ def __init__(self, value: str | None) -> None:
860
+ """Initialize a symbolic dimension.
861
+
862
+ Args:
863
+ value: The value of the dimension. It should not be an int.
864
+ """
865
+ if isinstance(value, int):
866
+ raise TypeError(
867
+ "The value of a SymbolicDim cannot be an int. "
868
+ "If you are creating a Shape, use int directly instead of SymbolicDim."
869
+ )
870
+ self._value = value
871
+
872
+ def __eq__(self, other: object) -> bool:
873
+ if not isinstance(other, SymbolicDim):
874
+ return self.value == other
875
+ return self.value == other.value
876
+
877
+ def __hash__(self) -> int:
878
+ return hash(self.value)
879
+
880
+ @property
881
+ def value(self) -> str | None:
882
+ return self._value
883
+
884
+ def __str__(self) -> str:
885
+ return f"{self._value}"
886
+
887
+ def __repr__(self) -> str:
888
+ return f"{self.__class__.__name__}({self._value})"
889
+
890
+
891
+ def _is_int_compatible(value: object) -> TypeIs[SupportsInt]:
892
+ """Return True if the value is int compatible."""
893
+ if isinstance(value, int):
894
+ return True
895
+ if hasattr(value, "__int__"):
896
+ # For performance reasons, we do not use isinstance(value, SupportsInt)
897
+ return True
898
+ return False
899
+
900
+
901
+ def _maybe_convert_to_symbolic_dim(
902
+ dim: int | SupportsInt | SymbolicDim | str | None,
903
+ ) -> SymbolicDim | int:
904
+ """Convert the value to a SymbolicDim if it is not an int."""
905
+ if dim is None or isinstance(dim, str):
906
+ return SymbolicDim(dim)
907
+ if _is_int_compatible(dim):
908
+ return int(dim)
909
+ if isinstance(dim, SymbolicDim):
910
+ return dim
911
+ raise TypeError(
912
+ f"Expected int, str, None or SymbolicDim, but value {dim!r} has type '{type(dim)}'"
913
+ )
914
+
915
+
916
+ class Shape(_protocols.ShapeProtocol, _display.PrettyPrintable):
917
+ __slots__ = ("_dims", "_frozen")
918
+
919
+ def __init__(
920
+ self,
921
+ dims: Iterable[int | SupportsInt | SymbolicDim | str | None],
922
+ /,
923
+ denotations: Iterable[str | None] | None = None,
924
+ frozen: bool = False,
925
+ ) -> None:
926
+ """Initialize a shape.
927
+
928
+ Args:
929
+ dims: The dimensions of the shape. Each dimension can be an integer or a
930
+ SymbolicDim or any Python object. When a ``dim`` is not an integer or a
931
+ SymbolicDim, it is converted to a SymbolicDim.
932
+ denotations: The denotations of the dimensions. If None, the denotations are not set.
933
+ Standard denotation can optionally be used to denote tensor
934
+ dimensions with standard semantic descriptions to ensure
935
+ that operations are applied to the correct axis of a tensor.
936
+ Refer to https://github.com/onnx/onnx/blob/main/docs/DimensionDenotation.md#denotation-definition
937
+ for pre-defined dimension denotations.
938
+ frozen: If True, the shape is immutable and cannot be modified. This
939
+ is useful when the shape is initialized by a Tensor.
940
+ """
941
+ self._dims: list[int | SymbolicDim] = [
942
+ _maybe_convert_to_symbolic_dim(dim) for dim in dims
943
+ ]
944
+ self._denotations: list[str | None] = (
945
+ list(denotations) if denotations is not None else [None] * len(self._dims)
946
+ )
947
+ if len(self._denotations) != len(self._dims):
948
+ raise ValueError(
949
+ "The number of denotations, when provided, must be equal to the number of dimensions."
950
+ )
951
+ self._frozen: bool = frozen
952
+
953
+ def copy(self):
954
+ """Return a copy of the shape."""
955
+ return Shape(self._dims, self._denotations, self._frozen)
956
+
957
+ @property
958
+ def dims(self) -> tuple[int | SymbolicDim, ...]:
959
+ """All dimensions in the shape.
960
+
961
+ This property is read-only. Use __getitem__ and __setitem__ to modify the shape or create a new shape.
962
+ """
963
+ return tuple(self._dims)
964
+
965
+ def rank(self) -> int:
966
+ """The rank of the shape."""
967
+ return len(self._dims)
968
+
969
+ def numpy(self) -> tuple[int, ...]:
970
+ if any(not isinstance(dim, int) for dim in self._dims):
971
+ raise ValueError(f"Cannot convert the shape {self} to a tuple of ints")
972
+ return tuple(dim for dim in self._dims) # type: ignore
973
+
974
+ def __len__(self) -> int:
975
+ return len(self._dims)
976
+
977
+ def __iter__(self) -> Iterator[int | SymbolicDim]:
978
+ return iter(self._dims)
979
+
980
+ @typing.overload
981
+ def __getitem__(self, index: int) -> int | SymbolicDim: ...
982
+
983
+ @typing.overload
984
+ def __getitem__(self, index: slice) -> tuple[int | SymbolicDim, ...]: ...
985
+
986
+ def __getitem__(self, index):
987
+ return tuple(self._dims)[index]
988
+
989
+ def __setitem__(self, index: int, value: int | SymbolicDim | str | None) -> None:
990
+ """Set the dimension at the index.
991
+
992
+ Args:
993
+ index: The index of the dimension.
994
+ value: The value of the dimension.
995
+
996
+ Raises:
997
+ TypeError: If the shape is frozen and cannot be modified.
998
+ TypeError: If the value is not an int or SymbolicDim.
999
+ """
1000
+ if self._frozen:
1001
+ raise TypeError("The shape is frozen and cannot be modified.")
1002
+
1003
+ self._dims[index] = _maybe_convert_to_symbolic_dim(value)
1004
+
1005
+ def get_denotation(self, index: int) -> str | None:
1006
+ """Return the denotation of the dimension at the index.
1007
+
1008
+ Args:
1009
+ index: The index of the dimension.
1010
+
1011
+ Returns:
1012
+ The denotation of the dimension.
1013
+ """
1014
+ return self._denotations[index]
1015
+
1016
+ def set_denotation(self, index: int, denotation: str | None) -> None:
1017
+ """Set the denotation of the dimension at the index.
1018
+
1019
+ Args:
1020
+ index: The index of the dimension.
1021
+ denotation: The denotation of the dimension.
1022
+ """
1023
+ self._denotations[index] = denotation
1024
+
1025
+ def __repr__(self) -> str:
1026
+ return f"{self.__class__.__name__}({self._dims!r})"
1027
+
1028
+ def __str__(self) -> str:
1029
+ """Return a string representation of the shape.
1030
+
1031
+ E.g. [n,1,3]
1032
+ """
1033
+ return f"[{','.join([str(dim) for dim in self._dims])}]"
1034
+
1035
+ def __eq__(self, other: object) -> bool:
1036
+ """Return True if the shapes are equal.
1037
+
1038
+ Two shapes are equal if all their dimensions are equal.
1039
+ """
1040
+ if isinstance(other, Shape):
1041
+ return self._dims == other._dims
1042
+ if not isinstance(other, Iterable):
1043
+ return False
1044
+ return self._dims == list(other)
1045
+
1046
+ def __ne__(self, other: object) -> bool:
1047
+ return not self.__eq__(other)
1048
+
1049
+ @typing.overload
1050
+ def is_static(self, dim: int) -> bool: # noqa: D418
1051
+ """Return True if the dimension is static."""
1052
+
1053
+ @typing.overload
1054
+ def is_static(self) -> bool: # noqa: D418
1055
+ """Return True if all dimensions are static."""
1056
+
1057
+ def is_static(self, dim=None) -> bool:
1058
+ """Return True if the dimension is static. If dim is None, return True if all dimensions are static."""
1059
+ if dim is None:
1060
+ return all(isinstance(dim, int) for dim in self._dims)
1061
+ return isinstance(self[dim], int)
1062
+
1063
+ @typing.overload
1064
+ def is_dynamic(self, dim: int) -> bool: # noqa: D418
1065
+ """Return True if the dimension is dynamic."""
1066
+
1067
+ @typing.overload
1068
+ def is_dynamic(self) -> bool: # noqa: D418
1069
+ """Return True if any dimension is dynamic."""
1070
+
1071
+ def is_dynamic(self, dim=None) -> bool:
1072
+ if dim is None:
1073
+ return not self.is_static()
1074
+ return not self.is_static(dim)
1075
+
1076
+
1077
+ def _quoted(string: str) -> str:
1078
+ """Return a quoted string.
1079
+
1080
+ This function is used to quote value/node names in the IR for better readability.
1081
+ """
1082
+ return f'"{string}"'
1083
+
1084
+
1085
+ class Usage(NamedTuple):
1086
+ """A usage of a value in a node.
1087
+
1088
+ Attributes:
1089
+ node: The node that uses the value.
1090
+ idx: The input index of the value in the node.
1091
+ """
1092
+
1093
+ node: Node
1094
+ idx: int
1095
+
1096
+
1097
+ class Node(_protocols.NodeProtocol, _display.PrettyPrintable):
1098
+ """IR Node.
1099
+
1100
+ If the ``graph`` is provided, the node will be added to the graph. Otherwise,
1101
+ user is responsible to call ``graph.append(node)`` (or other mutation methods
1102
+ in :class:`Graph`) to add the node to the graph.
1103
+
1104
+ After the node is initialized, it will add itself as a user of the input values.
1105
+
1106
+ The output values of the node are created during node initialization and are immutable.
1107
+ To change the output values, create a new node and replace the each of the inputs of ``output.uses()`` with
1108
+ the new output values by calling :meth:`replace_input_with` on the using nodes
1109
+ of this node's outputs.
1110
+ """
1111
+
1112
+ __slots__ = (
1113
+ "_attributes",
1114
+ "_domain",
1115
+ "_graph",
1116
+ "_inputs",
1117
+ "_metadata",
1118
+ "_metadata_props",
1119
+ "_name",
1120
+ "_op_type",
1121
+ "_outputs",
1122
+ "_overload",
1123
+ "_version",
1124
+ "doc_string",
1125
+ )
1126
+
1127
+ def __init__(
1128
+ self,
1129
+ domain: str,
1130
+ op_type: str,
1131
+ inputs: Iterable[Value | None],
1132
+ attributes: Iterable[Attr | RefAttr] = (),
1133
+ *,
1134
+ overload: str = "",
1135
+ num_outputs: int | None = None,
1136
+ outputs: Sequence[Value] | None = None,
1137
+ version: int | None = None,
1138
+ graph: Graph | None = None,
1139
+ name: str | None = None,
1140
+ doc_string: str | None = None,
1141
+ metadata_props: dict[str, str] | None = None,
1142
+ ):
1143
+ """Initialize a node and add it as a user of the input values.
1144
+
1145
+ Args:
1146
+ domain: The domain of the operator. For onnx operators, this is an empty string.
1147
+ op_type: The name of the operator.
1148
+ inputs: The input values. When an input is None, it is an empty input.
1149
+ attributes: The attributes. RefAttr can be used only when the node is defined in a Function.
1150
+ overload: The overload name when the node is invoking a function.
1151
+ num_outputs: The number of outputs of the node. If not specified, the number is 1.
1152
+ outputs: The output values. If None, the outputs are created during initialization.
1153
+ version: The version of the operator. If None, the version is unspecified and will follow that of the graph.
1154
+ graph: The graph that the node belongs to. If None, the node is not added to any graph.
1155
+ A `Node` must belong to zero or one graph.
1156
+ name: The name of the node. If None, the node is anonymous.
1157
+ doc_string: The documentation string.
1158
+ metadata_props: The metadata properties.
1159
+
1160
+ Raises:
1161
+ TypeError: If the attributes are not Attr or RefAttr.
1162
+ ValueError: If `num_outputs`, when not None, is not the same as the length of the outputs.
1163
+ ValueError: If an output value is None, when outputs is specified.
1164
+ ValueError: If an output value has a producer set already, when outputs is specified.
1165
+ """
1166
+ self._name = name
1167
+ self._domain: str = domain
1168
+ self._op_type: str = op_type
1169
+ # NOTE: Make inputs immutable with the assumption that they are not mutated
1170
+ # very often. This way all mutations can be tracked.
1171
+ # If necessary, we can cache the inputs and outputs as tuples.
1172
+ self._inputs: tuple[Value | None, ...] = tuple(inputs)
1173
+ # Values belong to their defining nodes. The values list is immutable
1174
+ self._outputs: tuple[Value, ...] = self._create_outputs(num_outputs, outputs)
1175
+ attributes = tuple(attributes)
1176
+ if attributes and not isinstance(attributes[0], (Attr, RefAttr)):
1177
+ raise TypeError(
1178
+ f"Expected the attributes to be Attr or RefAttr, got {type(attributes[0])}. "
1179
+ "If you are copying the attributes from another node, make sure you call "
1180
+ "node.attributes.values() because it is a dictionary."
1181
+ )
1182
+ self._attributes: OrderedDict[str, Attr | RefAttr] = OrderedDict(
1183
+ (attr.name, attr) for attr in attributes
1184
+ )
1185
+ self._overload: str = overload
1186
+ # TODO(justinchuby): Potentially support a version range
1187
+ self._version: int | None = version
1188
+ self._metadata: _metadata.MetadataStore | None = None
1189
+ self._metadata_props: dict[str, str] | None = metadata_props
1190
+ self._graph: Graph | None = graph
1191
+ self.doc_string = doc_string
1192
+
1193
+ # Add the node as a use of the inputs
1194
+ for i, input_value in enumerate(self._inputs):
1195
+ if input_value is not None:
1196
+ input_value._add_usage(self, i) # pylint: disable=protected-access
1197
+
1198
+ # Add the node to the graph if graph is specified
1199
+ if self._graph is not None:
1200
+ self._graph.append(self)
1201
+
1202
+ def _create_outputs(
1203
+ self, num_outputs: int | None, outputs: Sequence[Value] | None
1204
+ ) -> tuple[Value, ...]:
1205
+ """Check the parameters and create outputs for the node.
1206
+
1207
+ Args:
1208
+ num_outputs: The number of outputs of the node.
1209
+ outputs: The output values of the node.
1210
+
1211
+ Returns:
1212
+ The output values of the node.
1213
+
1214
+ Raises:
1215
+ ValueError: If `num_outputs`, when not None, is not the same as the length of the outputs.
1216
+ ValueError: If an output value is None.
1217
+ ValueError: If an output value has a producer set already.
1218
+ """
1219
+ # Check num_outputs and outputs are consistent
1220
+ if num_outputs is not None and outputs is not None and num_outputs != len(outputs):
1221
+ raise ValueError(
1222
+ "num_outputs must be the same as len(outputs) when num_outputs is specified."
1223
+ f"num_outputs: {num_outputs}, outputs: {outputs}"
1224
+ )
1225
+ # 1. If outputs is specified (can be empty []), use the outputs
1226
+ if outputs is not None:
1227
+ # Check all output values are valid first
1228
+ for output in outputs:
1229
+ if output is None:
1230
+ raise ValueError(f"Output value cannot be None. All outputs: {outputs}")
1231
+ if output.producer() is not None:
1232
+ raise ValueError(
1233
+ f"Supplied output value cannot have a producer when used for initializing a Node. "
1234
+ f"Output: {output}. All outputs: {outputs}"
1235
+ )
1236
+ result = []
1237
+ for i, output in enumerate(outputs):
1238
+ output._producer = self # pylint: disable=protected-access
1239
+ output._index = i # pylint: disable=protected-access
1240
+ result.append(output)
1241
+ return tuple(result)
1242
+
1243
+ # 2. If num_outputs is specified, create num_outputs outputs
1244
+ if num_outputs is None:
1245
+ # Default to 1 output
1246
+ num_outputs = 1
1247
+ assert num_outputs is not None
1248
+ return tuple(Value(self, index=i) for i in range(num_outputs))
1249
+
1250
+ def __str__(self) -> str:
1251
+ node_type_text = f"{self._domain}::{self._op_type}" + f":{self._overload}" * (
1252
+ self._overload != ""
1253
+ )
1254
+ inputs_text = (
1255
+ "("
1256
+ + ", ".join(
1257
+ [
1258
+ (
1259
+ f"%{_quoted(x.name) if x.name else 'anonymous:' + str(id(x))}"
1260
+ if x is not None
1261
+ else "None"
1262
+ )
1263
+ for x in self._inputs
1264
+ ]
1265
+ )
1266
+ + ")"
1267
+ )
1268
+ attributes_text = (
1269
+ (" {" + ", ".join([f"{k}={v}" for k, v in self._attributes.items()]) + "}")
1270
+ if self._attributes
1271
+ else ""
1272
+ )
1273
+ outputs_text = ", ".join(str(x) for x in self._outputs)
1274
+
1275
+ return f"{outputs_text} ⬅️ {node_type_text}{inputs_text}{attributes_text}"
1276
+
1277
+ def __repr__(self) -> str:
1278
+ return (
1279
+ f"{self.__class__.__name__}(name={self._name!r}, domain={self._domain!r}, "
1280
+ f"op_type={self._op_type!r}, inputs={self._inputs!r}, attributes={self._attributes!r}, "
1281
+ f"overload={self._overload!r}, outputs={self._outputs!r}, "
1282
+ f"version={self._version!r}, doc_string={self.doc_string!r})"
1283
+ )
1284
+
1285
+ @property
1286
+ def name(self) -> str | None:
1287
+ return self._name
1288
+
1289
+ @name.setter
1290
+ def name(self, value: str | None) -> None:
1291
+ self._name = value
1292
+
1293
+ @property
1294
+ def domain(self) -> str:
1295
+ return self._domain
1296
+
1297
+ @domain.setter
1298
+ def domain(self, value: str) -> None:
1299
+ self._domain = value
1300
+
1301
+ @property
1302
+ def version(self) -> int | None:
1303
+ return self._version
1304
+
1305
+ @version.setter
1306
+ def version(self, value: int | None) -> None:
1307
+ self._version = value
1308
+
1309
+ @property
1310
+ def op_type(self) -> str:
1311
+ return self._op_type
1312
+
1313
+ @op_type.setter
1314
+ def op_type(self, value: str) -> None:
1315
+ self._op_type = value
1316
+
1317
+ @property
1318
+ def overload(self) -> str:
1319
+ return self._overload
1320
+
1321
+ @overload.setter
1322
+ def overload(self, value: str) -> None:
1323
+ self._overload = value
1324
+
1325
+ @property
1326
+ def inputs(self) -> Sequence[Value | None]:
1327
+ return self._inputs
1328
+
1329
+ @inputs.setter
1330
+ def inputs(self, _: Any) -> None:
1331
+ raise AttributeError(
1332
+ "Directly mutating the input sequence is unsupported. Please use Node.replace_input_with() instead."
1333
+ )
1334
+
1335
+ def predecessors(self) -> Sequence[Node]:
1336
+ """Return the predecessor nodes of the node, deduplicated, in a deterministic order."""
1337
+ # Use the ordered nature of a dictionary to deduplicate the nodes
1338
+ predecessors: dict[Node, None] = {}
1339
+ for value in self.inputs:
1340
+ if value is not None and (producer := value.producer()) is not None:
1341
+ predecessors[producer] = None
1342
+ return tuple(predecessors)
1343
+
1344
+ def successors(self) -> Sequence[Node]:
1345
+ """Return the successor nodes of the node, deduplicated, in a deterministic order."""
1346
+ # Use the ordered nature of a dictionary to deduplicate the nodes
1347
+ successors: dict[Node, None] = {}
1348
+ for value in self.outputs:
1349
+ assert value is not None, "Bug: Output values are not expected to be None"
1350
+ for usage in value.uses():
1351
+ successors[usage.node] = None
1352
+ return tuple(successors)
1353
+
1354
+ def replace_input_with(self, index: int, value: Value | None) -> None:
1355
+ """Replace an input with a new value."""
1356
+ if index < 0 or index >= len(self.inputs):
1357
+ raise ValueError(f"Index out of range: {index}")
1358
+ old_input = self.inputs[index]
1359
+ self._inputs = tuple(
1360
+ value if i == index else old_input for i, old_input in enumerate(self.inputs)
1361
+ )
1362
+ if old_input is not None:
1363
+ old_input._remove_usage(self, index) # pylint: disable=protected-access
1364
+ if value is not None:
1365
+ value._add_usage(self, index) # pylint: disable=protected-access
1366
+
1367
+ def prepend(self, /, nodes: Node | Iterable[Node]) -> None:
1368
+ """Insert a node before this node in the list of nodes in the graph.
1369
+
1370
+ It is the same as calling ``graph.insert_before(self, nodes)``.
1371
+
1372
+ Example::
1373
+
1374
+ Before: previous_node -> self
1375
+ previous_node' -> node -> next_node'
1376
+ After: previous_node -> node -> self
1377
+ previous_node' -> next_node'
1378
+
1379
+ Args:
1380
+ nodes: A node or a sequence of nodes to put before this node.
1381
+ """
1382
+ if self._graph is None:
1383
+ raise ValueError("The node to prepend to does not belong to any graph.")
1384
+ self._graph.insert_before(self, nodes)
1385
+
1386
+ def append(self, /, nodes: Node | Iterable[Node]) -> None:
1387
+ """Insert a node after this node in the list of nodes in the graph.
1388
+
1389
+ It is the same as calling ``graph.insert_after(self, nodes)``.
1390
+
1391
+ Example::
1392
+
1393
+ Before: previous_node -> self
1394
+ previous_node' -> node -> next_node'
1395
+ After: previous_node -> self -> node
1396
+ previous_node' -> next_node'
1397
+
1398
+ Args:
1399
+ nodes: A node or a sequence of nodes to put after this node.
1400
+ """
1401
+ if self._graph is None:
1402
+ raise ValueError("The node to append to does not belong to any graph.")
1403
+ self._graph.insert_after(self, nodes)
1404
+
1405
+ @property
1406
+ def outputs(self) -> Sequence[Value]:
1407
+ return self._outputs
1408
+
1409
+ @outputs.setter
1410
+ def outputs(self, _: Sequence[Value]) -> None:
1411
+ raise AttributeError("outputs is immutable. Please create a new node instead.")
1412
+
1413
+ @property
1414
+ def attributes(self) -> OrderedDict[str, Attr | RefAttr]:
1415
+ return self._attributes
1416
+
1417
+ @property
1418
+ def meta(self) -> _metadata.MetadataStore:
1419
+ """The metadata store for intermediate analysis.
1420
+
1421
+ Write to the :attr:`metadata_props` if you would like the metadata to be serialized
1422
+ to the ONNX proto.
1423
+ """
1424
+ if self._metadata is None:
1425
+ self._metadata = _metadata.MetadataStore()
1426
+ return self._metadata
1427
+
1428
+ @property
1429
+ def metadata_props(self) -> dict[str, str]:
1430
+ if self._metadata_props is None:
1431
+ self._metadata_props = {}
1432
+ return self._metadata_props
1433
+
1434
+ @property
1435
+ def graph(self) -> Graph | None:
1436
+ return self._graph
1437
+
1438
+ @graph.setter
1439
+ def graph(self, value: Graph | None) -> None:
1440
+ self._graph = value
1441
+
1442
+ def op_identifier(self) -> _protocols.OperatorIdentifier:
1443
+ return self.domain, self.op_type, self.overload
1444
+
1445
+ def display(self, *, page: bool = False) -> None:
1446
+ # Add the node's name to the displayed text
1447
+ print(f"Node: {self.name!r}")
1448
+ if self.doc_string:
1449
+ print(f"Doc: {self.doc_string}")
1450
+ super().display(page=page)
1451
+
1452
+
1453
+ class _TensorTypeBase(_protocols.TypeProtocol, _display.PrettyPrintable, Hashable):
1454
+ """Tensor types that are non recursive types."""
1455
+
1456
+ __slots__ = ("_dtype", "denotation")
1457
+
1458
+ def __init__(self, dtype: _enums.DataType, *, denotation: str | None = None) -> None:
1459
+ self._dtype = dtype
1460
+ self.denotation = denotation
1461
+
1462
+ @property
1463
+ def dtype(self) -> _enums.DataType:
1464
+ return self._dtype
1465
+
1466
+ @dtype.setter
1467
+ def dtype(self, value: _enums.DataType) -> None:
1468
+ self._dtype = value
1469
+
1470
+ @property
1471
+ def elem_type(self) -> _enums.DataType:
1472
+ """Return the element type of the tensor type"""
1473
+ return self.dtype
1474
+
1475
+ def __hash__(self) -> int:
1476
+ return hash(repr(self))
1477
+
1478
+ def __eq__(self, other: object) -> bool:
1479
+ if self.__class__ is not other.__class__:
1480
+ return False
1481
+ return self.dtype == other.dtype # type: ignore[attr-defined]
1482
+
1483
+ def __repr__(self) -> str:
1484
+ # Remove "Type" from name for display
1485
+ short_name = self.__class__.__name__[:-4]
1486
+ return f"{short_name}({self.dtype!r})"
1487
+
1488
+
1489
+ class TensorType(_TensorTypeBase):
1490
+ """A type that represents a tensor."""
1491
+
1492
+ def __str__(self) -> str:
1493
+ return f"{self.dtype}"
1494
+
1495
+
1496
+ class SparseTensorType(_TensorTypeBase):
1497
+ """A type that represents a sparse tensor."""
1498
+
1499
+
1500
+ class _RecursiveTypeBase(_protocols.TypeProtocol, _display.PrettyPrintable, Hashable):
1501
+ """Base for recursive types like Optional and Sequence."""
1502
+
1503
+ __slots__ = ("_elem_type", "denotation")
1504
+
1505
+ def __init__(
1506
+ self, elem_type: _protocols.TypeProtocol, *, denotation: str | None = None
1507
+ ) -> None:
1508
+ self._elem_type = elem_type
1509
+ self.denotation = denotation
1510
+
1511
+ @property
1512
+ def dtype(self) -> _enums.DataType:
1513
+ return self._elem_type.dtype
1514
+
1515
+ @dtype.setter
1516
+ def dtype(self, value: _enums.DataType) -> None:
1517
+ self._elem_type.dtype = value
1518
+
1519
+ @property
1520
+ def elem_type(self) -> _protocols.TypeProtocol:
1521
+ return self._elem_type
1522
+
1523
+ def __hash__(self) -> int:
1524
+ return hash(repr(self))
1525
+
1526
+ def __eq__(self, other: object) -> bool:
1527
+ if not isinstance(other, _RecursiveTypeBase):
1528
+ return False
1529
+ if self.__class__ != other.__class__:
1530
+ return False
1531
+ # Recursively compare the type of the elements
1532
+ return self.elem_type == other.elem_type
1533
+
1534
+ def __repr__(self) -> str:
1535
+ # Remove "Type" from name for display
1536
+ short_name = self.__class__.__name__[:-4]
1537
+ return f"{short_name}({self.elem_type!r})"
1538
+
1539
+
1540
+ class SequenceType(_RecursiveTypeBase):
1541
+ """A type that represents a sequence of elements."""
1542
+
1543
+
1544
+ class OptionalType(_RecursiveTypeBase):
1545
+ """A type that represents an optional element."""
1546
+
1547
+
1548
+ class Value(_protocols.ValueProtocol, _display.PrettyPrintable):
1549
+ """IR Value.
1550
+
1551
+ A value is a named entity that can be used to represent an input or output of a graph,
1552
+ a function, or a node. The information it stores generalizes over ``ValueInfoProto``
1553
+ in the ONNX specification.
1554
+
1555
+ A :class:`Value` is always not owned or owned by exactly one node. When the value is not
1556
+ owned, it must be an input of a graph or a function. ``producer`` and ``index``
1557
+ are ``None``.
1558
+
1559
+ When the value is owned by a node, it is an output of the node.
1560
+ The node that produces the value can be accessed with :meth:`producer`.
1561
+ The index of the output of the node that produces the value can be accessed with
1562
+ :meth:`index`.
1563
+
1564
+ To find all the nodes that use this value as an input, call :meth:`uses`.
1565
+
1566
+ To check if the value is an output of a graph, call :meth:`is_graph_output`.
1567
+
1568
+ Attributes:
1569
+ name: The name of the value. A value is always named when it is part of a graph.
1570
+ shape: The shape of the value.
1571
+ type: The type of the value.
1572
+ metadata_props: Metadata.
1573
+ """
1574
+
1575
+ __slots__ = (
1576
+ "_const_value",
1577
+ "_index",
1578
+ "_metadata",
1579
+ "_metadata_props",
1580
+ "_name",
1581
+ "_producer",
1582
+ "_shape",
1583
+ "_type",
1584
+ "_uses",
1585
+ "doc_string",
1586
+ )
1587
+
1588
+ def __init__(
1589
+ self,
1590
+ producer: Node | None = None,
1591
+ *,
1592
+ index: int | None = None,
1593
+ name: str | None = None,
1594
+ shape: Shape | None = None,
1595
+ type: _protocols.TypeProtocol | None = None,
1596
+ doc_string: str | None = None,
1597
+ const_value: _protocols.TensorProtocol | None = None,
1598
+ ) -> None:
1599
+ """Initialize a value.
1600
+
1601
+ Args:
1602
+ producer: The node that produces the value.
1603
+ It can be ``None`` when the value is initialized first than its producer.
1604
+ index: The index of the output of the defining node.
1605
+ name: The name of the value.
1606
+ shape: The shape of the value.
1607
+ type: The type of the value.
1608
+ doc_string: The documentation string.
1609
+ const_value: The constant tensor if the value is constant.
1610
+ """
1611
+ self._producer: Node | None = producer
1612
+ self._index: int | None = index
1613
+ self._metadata: _metadata.MetadataStore | None = None
1614
+ self._metadata_props: dict[str, str] | None = None
1615
+
1616
+ self._name: str | None = name
1617
+ self._shape: Shape | None = shape
1618
+ self._type: _protocols.TypeProtocol | None = type
1619
+ # TODO(justinchuby): Handle initialization when a const value is provided
1620
+ # We can get shape and type information from the const value
1621
+ self._const_value = const_value
1622
+ # Use a collection of (Node, int) to store uses. This is needed
1623
+ # because a single use can use the same value multiple times.
1624
+ # Use a dictionary to preserve insertion order so that the visiting order is deterministic
1625
+ self._uses: dict[Usage, None] = {}
1626
+ self.doc_string = doc_string
1627
+
1628
+ def __repr__(self) -> str:
1629
+ value_name = self.name if self.name else "anonymous:" + str(id(self))
1630
+ producer = self.producer()
1631
+ if producer is None:
1632
+ producer_text = "None"
1633
+ elif producer.name is not None:
1634
+ producer_text = producer.name
1635
+ else:
1636
+ producer_text = f"anonymous_node:{id(producer)}"
1637
+ return f"{self.__class__.__name__}({value_name!r}, type={self.type!r}, shape={self.shape}, producer={producer_text}, index={self.index()})"
1638
+
1639
+ def __str__(self) -> str:
1640
+ value_name = self.name if self.name is not None else "anonymous:" + str(id(self))
1641
+ shape_text = str(self.shape) if self.shape is not None else "?"
1642
+ type_text = str(self.type) if self.type is not None else "?"
1643
+
1644
+ # Quote the name because in reality the names can have invalid characters
1645
+ # that make them hard to read
1646
+ return f"%{_quoted(value_name)}<{type_text},{shape_text}>"
1647
+
1648
+ def producer(self) -> Node | None:
1649
+ """The node that produces this value.
1650
+
1651
+ When producer is ``None``, the value does not belong to a node, and is
1652
+ typically a graph input or an initializer.
1653
+ """
1654
+ return self._producer
1655
+
1656
+ def consumers(self) -> Sequence[Node]:
1657
+ """Return the nodes (deduplicated) that consume this value."""
1658
+ return tuple({usage.node: None for usage in self._uses})
1659
+
1660
+ def index(self) -> int | None:
1661
+ """The index of the output of the defining node."""
1662
+ return self._index
1663
+
1664
+ def uses(self) -> Collection[Usage]:
1665
+ """Return a set of uses of the value.
1666
+
1667
+ The set contains tuples of ``(Node, index)`` where the index is the index of the input
1668
+ of the node. For example, if ``node.inputs[1] == value``, then the use is ``(node, 1)``.
1669
+ """
1670
+ # Create a tuple for the collection so that iteration on will will not
1671
+ # be affected when the usage changes during graph mutation.
1672
+ # This adds a small overhead but is better a user experience than
1673
+ # having users call tuple().
1674
+ return tuple(self._uses)
1675
+
1676
+ def _add_usage(self, use: Node, index: int) -> None:
1677
+ """Add a usage of this value.
1678
+
1679
+ This is an internal method. It should only be called by the Node class.
1680
+ """
1681
+ self._uses[Usage(use, index)] = None
1682
+
1683
+ def _remove_usage(self, use: Node, index: int) -> None:
1684
+ """Remove a node from the uses of this value.
1685
+
1686
+ This is an internal method. It should only be called by the Node class.
1687
+ """
1688
+ self._uses.pop(Usage(use, index))
1689
+
1690
+ @property
1691
+ def name(self) -> str | None:
1692
+ return self._name
1693
+
1694
+ @name.setter
1695
+ def name(self, value: str | None) -> None:
1696
+ if self._const_value is not None:
1697
+ self._const_value.name = value
1698
+ self._name = value
1699
+
1700
+ @property
1701
+ def type(self) -> _protocols.TypeProtocol | None:
1702
+ """The type of the tensor.
1703
+
1704
+ Example types can be ``TensorType``, ``SparseTensorType``, ``SequenceType``, ``OptionalType``.
1705
+ To obtain the data type of the tensor, use ``type.dtype`` or conveniently
1706
+ :attr:`dtype`.
1707
+ """
1708
+ return self._type
1709
+
1710
+ @type.setter
1711
+ def type(self, value: _protocols.TypeProtocol | None) -> None:
1712
+ self._type = value
1713
+
1714
+ @property
1715
+ def dtype(self) -> _enums.DataType | None:
1716
+ """The data type of the tensor."""
1717
+ if self._type is None:
1718
+ return None
1719
+ return self._type.dtype
1720
+
1721
+ @dtype.setter
1722
+ def dtype(self, value: _enums.DataType) -> None:
1723
+ """Set the data type of the tensor.
1724
+
1725
+ If the type is not set, it will be initialized to a new TensorType. To
1726
+ set the type as other types like ``SequenceType``, initialize the type
1727
+ then set :attr:`type` instead.
1728
+ """
1729
+ if self._type is None:
1730
+ self._type = TensorType(value)
1731
+ else:
1732
+ self._type.dtype = value
1733
+
1734
+ @property
1735
+ def shape(self) -> Shape | None:
1736
+ return self._shape
1737
+
1738
+ @shape.setter
1739
+ def shape(self, value: Shape | None) -> None:
1740
+ if value is None:
1741
+ self._shape = None
1742
+ return
1743
+ if isinstance(value, Shape):
1744
+ self._shape = value
1745
+ return
1746
+ raise TypeError(f"Expected value to be a Shape or None, got '{type(value)}'")
1747
+
1748
+ @property
1749
+ def const_value(
1750
+ self,
1751
+ ) -> _protocols.TensorProtocol | None:
1752
+ """A concrete value.
1753
+
1754
+ The value can be backed by different raw data types, such as numpy arrays.
1755
+ The only guarantee is that it conforms TensorProtocol.
1756
+ """
1757
+ return self._const_value
1758
+
1759
+ @const_value.setter
1760
+ def const_value(
1761
+ self,
1762
+ value: _protocols.TensorProtocol | None,
1763
+ ) -> None:
1764
+ if onnxscript.DEBUG:
1765
+ if value is not None and not isinstance(value, _protocols.TensorProtocol):
1766
+ raise TypeError(
1767
+ f"Expected value to be a TensorProtocol or None, got '{type(value)}'"
1768
+ )
1769
+ self._const_value = value
1770
+
1771
+ @property
1772
+ def meta(self) -> _metadata.MetadataStore:
1773
+ """The metadata store for intermediate analysis.
1774
+
1775
+ Write to the :attr:`metadata_props` if you would like the metadata to be serialized
1776
+ to the ONNX proto.
1777
+ """
1778
+ if self._metadata is None:
1779
+ self._metadata = _metadata.MetadataStore()
1780
+ return self._metadata
1781
+
1782
+ @property
1783
+ def metadata_props(self) -> dict[str, str]:
1784
+ if self._metadata_props is None:
1785
+ self._metadata_props = {}
1786
+ return self._metadata_props
1787
+
1788
+ def is_graph_output(self) -> bool:
1789
+ """Whether the value is an output of a graph."""
1790
+ if (producer := self.producer()) is None:
1791
+ return False
1792
+ if (graph := producer.graph) is None:
1793
+ return False
1794
+ # Cannot use `in` because __eq__ may be defined by subclasses, even though
1795
+ # it is not recommended
1796
+ return any(output is self for output in graph.outputs)
1797
+
1798
+
1799
+ def Input(
1800
+ name: str | None = None,
1801
+ shape: Shape | None = None,
1802
+ type: _protocols.TypeProtocol | None = None,
1803
+ doc_string: str | None = None,
1804
+ ) -> Value:
1805
+ """Create an input of a Graph or a Function.
1806
+
1807
+ This is equivalent to calling ``Value(name=name, shape=shape, type=type, doc_string=doc_string)``.
1808
+ """
1809
+
1810
+ # NOTE: The function name is capitalized to maintain API backward compatibility.
1811
+
1812
+ return Value(name=name, shape=shape, type=type, doc_string=doc_string)
1813
+
1814
+
1815
+ def _check_node_safe_to_remove(
1816
+ node: Node, to_remove: AbstractSet[Node], graph_outputs: AbstractSet[Value]
1817
+ ) -> None:
1818
+ """Check if a node is safe to remove.
1819
+
1820
+ 1. It checks to make sure there are no users of the node that are not
1821
+ to be removed before removing it.
1822
+ 2. It checks the node does not contribute to any graph outputs.
1823
+
1824
+ This check is typically O(1) assuming the number of uses of the node is small
1825
+
1826
+ Args:
1827
+ node: The node to check.
1828
+ to_remove: A set of nodes that are to be removed.
1829
+ This set is used to check if the node is still being used by other
1830
+ nodes that are not to be removed.
1831
+ graph_outputs: A set of values that are outputs of the graph.
1832
+
1833
+ Raises:
1834
+ ValueError: If the node does not belong to this graph or if there are users of the node.
1835
+ ValueError: If the node is still being used by other nodes not to be removed.
1836
+ """
1837
+ for output in node.outputs:
1838
+ if output in graph_outputs:
1839
+ raise ValueError(
1840
+ f"Node '{node!r}' is still an output of the graph and cannot be removed when safe=True."
1841
+ )
1842
+ uses_not_to_remove = [user for user, _ in output.uses() if user not in to_remove]
1843
+ if uses_not_to_remove:
1844
+ raise ValueError(
1845
+ f"Output value '{output!r}' is still being used by other nodes that are not to be "
1846
+ f"removed. All of its users that is not being removed: {uses_not_to_remove!r}. "
1847
+ "Please make sure these nodes are no longer using the output value."
1848
+ )
1849
+
1850
+
1851
+ class Graph(_protocols.GraphProtocol, Sequence[Node], _display.PrettyPrintable):
1852
+ """IR Graph.
1853
+
1854
+ Graph represents a computation graph. In addition to the ONNX specification
1855
+ specified fields, it also contains a mapping of :attr:`opset_imports`. This
1856
+ allows different subgraphs to import different opsets. It is the responsibility
1857
+ of the deserializer to reconcile the different opsets.
1858
+
1859
+ The `nodes` are not guaranteed to be topologically sorted. But the
1860
+ iteration order should be deterministic across different runs. It is the
1861
+ responsibility of the user to maintain a topological order of the nodes.
1862
+
1863
+ Note that there is not a ``node`` attribute in the Graph. The Graph can be
1864
+ seen as a Sequence of nodes and should be used as such. For example, to obtain
1865
+ all nodes as a list, call ``list(graph)``.
1866
+
1867
+ Attributes:
1868
+ name: The name of the graph.
1869
+ inputs: The input values of the graph.
1870
+ outputs: The output values of the graph.
1871
+ initializers: The initializers in the graph.
1872
+ doc_string: Documentation string.
1873
+ opset_imports: Opsets imported by the graph.
1874
+ metadata_props: Metadata that will be serialized to the ONNX file.
1875
+ meta: Metadata store for graph transform passes.
1876
+ """
1877
+
1878
+ __slots__ = (
1879
+ "_doc_string",
1880
+ "_initializers",
1881
+ "_inputs",
1882
+ "_metadata",
1883
+ "_metadata_props",
1884
+ "_name_authority",
1885
+ "_nodes",
1886
+ "_opset_imports",
1887
+ "_outputs",
1888
+ "name",
1889
+ )
1890
+
1891
+ def __init__(
1892
+ self,
1893
+ inputs: Sequence[Value],
1894
+ outputs: Sequence[Value],
1895
+ *,
1896
+ nodes: Iterable[Node],
1897
+ initializers: Sequence[Value] = (),
1898
+ doc_string: str | None = None,
1899
+ opset_imports: dict[str, int] | None = None,
1900
+ name: str | None = None,
1901
+ metadata_props: dict[str, str] | None = None,
1902
+ ):
1903
+ self.name = name
1904
+
1905
+ # Private fields that are not to be accessed by any other classes
1906
+ self._inputs = list(inputs)
1907
+ self._outputs = list(outputs)
1908
+ self._initializers = {}
1909
+ for initializer in initializers:
1910
+ if isinstance(initializer, str):
1911
+ raise TypeError(
1912
+ "Initializer must be a Value, not a string. "
1913
+ "If you are copying the initializers from another graph, "
1914
+ "make sure you call graph.initializers.values() because it is a dictionary."
1915
+ )
1916
+ if initializer.name is None:
1917
+ raise ValueError(f"Initializer must have a name: {initializer}")
1918
+ self._initializers[initializer.name] = initializer
1919
+ self._doc_string = doc_string
1920
+ self._opset_imports = opset_imports or {}
1921
+ self._metadata: _metadata.MetadataStore | None = None
1922
+ self._metadata_props: dict[str, str] | None = metadata_props
1923
+ self._nodes: _linked_list.DoublyLinkedSet[Node] = _linked_list.DoublyLinkedSet()
1924
+ # Be sure the initialize the name authority before extending the nodes
1925
+ # because it is used to name the nodes and their outputs
1926
+ self._name_authority = _name_authority.NameAuthority()
1927
+ # Call self.extend not self._nodes.extend so the graph reference is added to the nodes
1928
+ self.extend(nodes)
1929
+
1930
+ @property
1931
+ def inputs(self) -> list[Value]:
1932
+ return self._inputs
1933
+
1934
+ @property
1935
+ def outputs(self) -> list[Value]:
1936
+ return self._outputs
1937
+
1938
+ @property
1939
+ def initializers(self) -> dict[str, Value]:
1940
+ return self._initializers
1941
+
1942
+ def register_initializer(self, value: Value) -> None:
1943
+ """Register an initializer to the graph.
1944
+
1945
+ This is a convenience method to register an initializer to the graph with
1946
+ checks.
1947
+
1948
+ Args:
1949
+ value: The :class:`Value` to register as an initializer of the graph.
1950
+ It must have its ``.const_value`` set.
1951
+
1952
+ Raises:
1953
+ ValueError: If a value of the same name that is not this value
1954
+ is already registered.
1955
+ ValueError: If the value does not have a name.
1956
+ ValueError: If the initializer is produced by a node.
1957
+ ValueError: If the value does not have its ``.const_value`` set.
1958
+ """
1959
+ if value.name in self._initializers:
1960
+ if self._initializers[value.name] is not value:
1961
+ raise ValueError(
1962
+ f"Initializer '{value.name}' is already registered, but"
1963
+ " it is not the same object: existing={self._initializers[value.name]!r},"
1964
+ f" new={value!r}"
1965
+ )
1966
+ if not value.name:
1967
+ raise ValueError(f"Initializer must have a name: {value!r}")
1968
+ if value.producer() is not None:
1969
+ raise ValueError(
1970
+ f"Value '{value!r}' is produced by a node and cannot be an initializer."
1971
+ )
1972
+ if value.const_value is None:
1973
+ raise ValueError(
1974
+ f"Value '{value!r}' must have its const_value set to be an initializer."
1975
+ )
1976
+ self._initializers[value.name] = value
1977
+
1978
+ @property
1979
+ def doc_string(self) -> str | None:
1980
+ return self._doc_string
1981
+
1982
+ @doc_string.setter
1983
+ def doc_string(self, value: str | None) -> None:
1984
+ self._doc_string = value
1985
+
1986
+ @property
1987
+ def opset_imports(self) -> dict[str, int]:
1988
+ return self._opset_imports
1989
+
1990
+ def __getitem__(self, index: int) -> Node:
1991
+ return self._nodes[index]
1992
+
1993
+ def __len__(self) -> int:
1994
+ return len(self._nodes)
1995
+
1996
+ def __iter__(self) -> Iterator[Node]:
1997
+ return iter(self._nodes)
1998
+
1999
+ def __reversed__(self) -> Iterator[Node]:
2000
+ return reversed(self._nodes)
2001
+
2002
+ def _set_node_graph_to_self_and_assign_names(self, node: Node) -> Node:
2003
+ """Set the graph reference for the node and assign names to it and its outputs if they don't have one."""
2004
+ if node.graph is not None and node.graph is not self:
2005
+ raise ValueError(
2006
+ f"The node '{node!r}' belongs to another graph. Please remove it first with Graph.remove()."
2007
+ )
2008
+ # Give the node and its output values names if they don't not have one
2009
+ self._name_authority.register_or_name_node(node)
2010
+ for value in node._outputs: # pylint: disable=protected-access
2011
+ self._name_authority.register_or_name_value(value)
2012
+ node.graph = self
2013
+ return node
2014
+
2015
+ def node(self, index_or_name: int | str, /) -> Node:
2016
+ """Get a node by index or name.
2017
+
2018
+ This is an O(n) operation. Getting nodes on the ends of the graph (0 or -1) is O(1).
2019
+
2020
+ .. note::
2021
+ If you need repeated random access, consider turning it into a list with ``list(graph)`` .
2022
+ Or a dictionary for repeated access by name: ``{node.name for node in graph}`` .
2023
+
2024
+ When a name is provided and if there are multiple nodes with the same name,
2025
+ the first node with the name is returned.
2026
+
2027
+ Args:
2028
+ index_or_name: The index or name of the node.
2029
+
2030
+ Returns:
2031
+ The node if found.
2032
+
2033
+ Raises:
2034
+ IndexError: If the index is out of range.
2035
+ ValueError: If the node with the given name is not found.
2036
+ """
2037
+ # NOTE: This is a method specific to Graph, not required by the protocol unless proven
2038
+ if isinstance(index_or_name, int):
2039
+ return self[index_or_name]
2040
+ for node in self:
2041
+ if node.name == index_or_name:
2042
+ return node
2043
+ raise ValueError(f"Node with name '{index_or_name}' not found.")
2044
+
2045
+ def num_nodes(self) -> int:
2046
+ """Get the number of nodes in the graph in O(1) time.
2047
+
2048
+ Note that this method returns the number of nodes this graph directly contains.
2049
+ It does not count nodes in subgraphs.
2050
+
2051
+ This is an alias for ``len(graph)``. Use this if you prefer a more descriptive
2052
+ name for readability.
2053
+ """
2054
+ # NOTE: This is a method specific to Graph, not required by the protocol unless proven
2055
+ return len(self)
2056
+
2057
+ # Mutation methods
2058
+ def append(self, node: Node, /) -> None:
2059
+ """Append a node to the graph in O(1) time.
2060
+
2061
+ Unique names will be assigned to the node and its values if any name is ``None``.
2062
+
2063
+ Args:
2064
+ node: The node to append.
2065
+
2066
+ Raises:
2067
+ ValueError: If the node belongs to another graph.
2068
+ """
2069
+ self._set_node_graph_to_self_and_assign_names(node)
2070
+ self._nodes.append(node)
2071
+
2072
+ def extend(self, nodes: Iterable[Node], /) -> None:
2073
+ """Extend the graph with the given nodes in O(#new_nodes) time.
2074
+
2075
+ Unique names will be assigned to the node and its values if any name is ``None``.
2076
+
2077
+ Args:
2078
+ nodes: The nodes to extend the graph with.
2079
+
2080
+ Raises:
2081
+ ValueError: If any node belongs to another graph.
2082
+ """
2083
+ nodes = [self._set_node_graph_to_self_and_assign_names(node) for node in nodes]
2084
+ self._nodes.extend(nodes)
2085
+
2086
+ def remove(self, nodes: Node | Iterable[Node], /, safe: bool = False) -> None:
2087
+ """Remove nodes from the graph in O(#num of nodes to remove) time.
2088
+
2089
+ If any errors are raise, to ensure the graph is not left in an inconsistent state,
2090
+ the graph is not modified.
2091
+
2092
+ Args:
2093
+ nodes: The node to remove.
2094
+ safe: If True, performs the following actions before removal:
2095
+
2096
+ 1. It checks to make sure there are no users of the node that are not
2097
+ to be removed before removing it.
2098
+ 2. It checks the node does not contribute to any graph outputs.
2099
+ 3. It removes references to all inputs so it is no longer a user of other nodes.
2100
+
2101
+ Raises:
2102
+ ValueError: If any node to remove does not belong to this graph.
2103
+ ValueError: (When ``safe=True``) If the node does not belong to this graph or if there are users of the node.
2104
+ ValueError: (When ``safe=True``) If the node is still being used by other nodes not to be removed.
2105
+ """
2106
+ if not isinstance(nodes, Iterable):
2107
+ nodes_set: AbstractSet[Node] = {nodes}
2108
+ else:
2109
+ nodes_set = frozenset(nodes)
2110
+ graph_outputs = frozenset(self.outputs)
2111
+ for node in nodes_set:
2112
+ if node.graph is not self:
2113
+ raise ValueError(f"The node '{node!r}' does not belong to this graph.")
2114
+ if safe:
2115
+ # Check 1, 2
2116
+ _check_node_safe_to_remove(node, nodes_set, graph_outputs)
2117
+ for node in nodes_set:
2118
+ if safe:
2119
+ # 3. Detach from all inputs so that it is no longer a user of other nodes
2120
+ for i in range(len(node.inputs)):
2121
+ node.replace_input_with(i, None)
2122
+ # Set attributes to remove the node from this graph
2123
+ node.graph = None
2124
+ self._nodes.remove(node)
2125
+
2126
+ def insert_after(self, node: Node, new_nodes: Iterable[Node] | Node, /) -> None:
2127
+ """Insert new nodes after the given node in O(#new_nodes) time.
2128
+
2129
+ Unique names will be assigned to the node and its values if any name is ``None``.
2130
+
2131
+ Args:
2132
+ node: The node to insert after.
2133
+ new_nodes: The new nodes to insert.
2134
+
2135
+ Raises:
2136
+ ValueError: If any node belongs to another graph.
2137
+ """
2138
+ if isinstance(new_nodes, Node):
2139
+ new_nodes = (new_nodes,)
2140
+ new_nodes = [self._set_node_graph_to_self_and_assign_names(node) for node in new_nodes]
2141
+ self._nodes.insert_after(node, new_nodes)
2142
+
2143
+ def insert_before(self, node: Node, new_nodes: Iterable[Node] | Node, /) -> None:
2144
+ """Insert new nodes before the given node in O(#new_nodes) time.
2145
+
2146
+ Unique names will be assigned to the node and its values if any name is ``None``.
2147
+
2148
+ Args:
2149
+ node: The node to insert before.
2150
+ new_nodes: The new nodes to insert.
2151
+
2152
+ Raises:
2153
+ ValueError: If any node belongs to another graph.
2154
+ """
2155
+ if isinstance(new_nodes, Node):
2156
+ new_nodes = (new_nodes,)
2157
+ new_nodes = [self._set_node_graph_to_self_and_assign_names(node) for node in new_nodes]
2158
+ self._nodes.insert_before(node, new_nodes)
2159
+
2160
+ def sort(self) -> None:
2161
+ """Perform a topological sort of this graph and all subgraphs in O(#nodes + #values) time.
2162
+
2163
+ This sort is stable. It preserves the original order as much as possible.
2164
+
2165
+ Referece: https://github.com/madelson/MedallionTopologicalSort#stable-sort
2166
+
2167
+ Raises:
2168
+ ValueError: If the graph contains a cycle, making topological sorting impossible.
2169
+ """
2170
+ # Obtain all nodes from the graph and its subgraphs for sorting
2171
+ nodes = list(onnxscript.ir.traversal.RecursiveGraphIterator(self))
2172
+ # Store the sorted nodes of each subgraph
2173
+ sorted_nodes_by_graph: dict[Graph, list[Node]] = {
2174
+ graph: [] for graph in {node.graph for node in nodes if node.graph is not None}
2175
+ }
2176
+ # TODO: Explain why we need to store direct predecessors and children and why
2177
+ # we only need to store the direct ones
2178
+
2179
+ # The depth of a node is defined as the number of direct children it has
2180
+ node_depth: dict[Node, int] = dict.fromkeys(nodes, 0)
2181
+ # Direct predecessors of a node
2182
+ node_predecessors: dict[Node, list[Node]] = {node: [] for node in nodes}
2183
+ # Store the negative index of the nodes because heapq is a min heap and we
2184
+ # want to pop the node with largest index value first, effectively turning
2185
+ # it to a max heap
2186
+ neg_node_index: dict[Node, int] = {node: -i for i, node in enumerate(nodes)}
2187
+
2188
+ def add_predecessor(child: Node, predecessor: Node | None) -> None:
2189
+ """Add a predecessor of a node, and increment the depth of the predecessor."""
2190
+ if predecessor is None:
2191
+ return
2192
+ node_predecessors[child].append(predecessor)
2193
+ node_depth[predecessor] += 1
2194
+
2195
+ # 1. Build the direct predecessors of each node and the depth of each node
2196
+ # for sorting topolocally using Kahn's algorithm.
2197
+ # Note that when a node contains graph attributes (aka. has subgraphs),
2198
+ # we consider all nodes in the subgraphs *predecessors* of this node. This
2199
+ # way we ensure the implicit dependencies of the subgraphs are captured
2200
+ # as predecessors of the node.
2201
+ for node in nodes:
2202
+ # All producers of input values are considered as direct predecessors.
2203
+ for input_value in node.inputs:
2204
+ if input_value is None:
2205
+ continue
2206
+ predecessor_node = input_value.producer()
2207
+ add_predecessor(node, predecessor_node)
2208
+ # All nodes in attribute graphs are considered as direct predecessors.
2209
+ for attr in node.attributes.values():
2210
+ if not isinstance(attr, Attr):
2211
+ continue
2212
+ # A nice thing about this algorithm is that we only need to record
2213
+ # direct predecessors. This continues to be true even with subgraphs.
2214
+ # When a node in a subgraph (a) contains its own subgraphs (b), the
2215
+ # node in subgraphs (b) are guranteed to appear before the node
2216
+ # in (a).
2217
+ if attr.type == _enums.AttributeType.GRAPH:
2218
+ for predecessor_node in attr.value:
2219
+ add_predecessor(node, predecessor_node)
2220
+ elif attr.type == _enums.AttributeType.GRAPHS:
2221
+ for attribute_graph in attr.value:
2222
+ for predecessor_node in attribute_graph:
2223
+ add_predecessor(node, predecessor_node)
2224
+
2225
+ # 2. Priority Queue: Track nodes with zero direct children in a priority queue,
2226
+ # using NEGATIVE original index for ordering.
2227
+ # This ensures nodes appearing LATER in the original order are processed EARLIER.
2228
+ # We get REVERSED topological order of each subgraph.
2229
+ priority_queue: list[tuple[int, Node]] = [
2230
+ (neg_node_index[node], node) for node in nodes if node_depth[node] == 0
2231
+ ]
2232
+ heapq.heapify(priority_queue)
2233
+
2234
+ # 3. Topological Sort:
2235
+ num_of_sorted_nodes = 0
2236
+ while priority_queue:
2237
+ # Pop the node with the most negative index and add it to the sorted nodes by subgraph.
2238
+ _, current_node = heapq.heappop(priority_queue)
2239
+ assert current_node.graph is not None
2240
+ sorted_nodes_by_graph[current_node.graph].append(current_node)
2241
+ num_of_sorted_nodes += 1
2242
+ # Decrement the depth of its predecessors. If any predecessor node has zero direct children, push it into the queue.
2243
+ for predecessor_node in node_predecessors[current_node]:
2244
+ node_depth[predecessor_node] -= 1
2245
+ if node_depth[predecessor_node] == 0:
2246
+ heapq.heappush(
2247
+ priority_queue, (neg_node_index[predecessor_node], predecessor_node)
2248
+ )
2249
+
2250
+ # 4. Cycle Check: Ensure all nodes are processed. If not, raise a ValueError indicating a cycle.
2251
+ if num_of_sorted_nodes != len(nodes):
2252
+ raise ValueError("Graph contains a cycle, topological sort is not possible.")
2253
+
2254
+ # 5. Reverse: Reverse the sorted nodes of each subgraph to get the topological order.
2255
+ for graph, sorted_nodes in sorted_nodes_by_graph.items():
2256
+ # The graph container ensures all the nodes are unique so we can safely extend
2257
+ graph.extend(reversed(sorted_nodes))
2258
+
2259
+ # End of mutation methods
2260
+
2261
+ @property
2262
+ def meta(self) -> _metadata.MetadataStore:
2263
+ """The metadata store for intermediate analysis.
2264
+
2265
+ Write to the :attr:`metadata_props` if you would like the metadata to be serialized
2266
+ to the ONNX proto.
2267
+ """
2268
+ if self._metadata is None:
2269
+ self._metadata = _metadata.MetadataStore()
2270
+ return self._metadata
2271
+
2272
+ @property
2273
+ def metadata_props(self) -> dict[str, str]:
2274
+ if self._metadata_props is None:
2275
+ self._metadata_props = {}
2276
+ return self._metadata_props
2277
+
2278
+ def __str__(self) -> str:
2279
+ return _graph_str(self)
2280
+
2281
+ def __repr__(self) -> str:
2282
+ return _graph_repr(self)
2283
+
2284
+
2285
+ def _graph_str(graph: Graph | GraphView) -> str:
2286
+ """Return a string representation of the graph."""
2287
+ # TODO(justinchuby): Show docstrings and metadata
2288
+ inputs_text = "\n" + ",\n".join(str(x) for x in graph.inputs)
2289
+ outputs_text = "\n" + ",\n".join(str(x) for x in graph.outputs)
2290
+ initializers_text = ",\n".join(str(x) for x in graph.initializers.values())
2291
+ if initializers_text:
2292
+ initializers_text = (
2293
+ "\ninitializers=(\n" + textwrap.indent(initializers_text, " " * 4) + "\n),"
2294
+ )
2295
+ signature = f"""\
2296
+ graph(
2297
+ name={graph.name or "anonymous_graph:" + str(id(graph))},
2298
+ inputs=({textwrap.indent(inputs_text, " " * 8)}
2299
+ ),
2300
+ outputs=({textwrap.indent(outputs_text, " " * 8)}
2301
+ ),{textwrap.indent(initializers_text, " " * 4)}
2302
+ )"""
2303
+ node_count = len(graph)
2304
+ number_width = len(str(node_count))
2305
+ node_lines = []
2306
+ for i, node in enumerate(graph):
2307
+ node_name = node.name if node.name else f":anonymous_node:{id(node)}"
2308
+ node_text = f"# {node_name}\n{node}"
2309
+ indented_node_text = textwrap.indent(node_text, " " * (number_width + 4))
2310
+ # Remove the leading spaces
2311
+ indented_node_text = indented_node_text.strip()
2312
+ node_lines.append(f"{i:>{number_width}} | {indented_node_text}")
2313
+ returns = ", ".join(str(x) for x in graph.outputs)
2314
+ body = (
2315
+ "{\n"
2316
+ + textwrap.indent("\n".join(node_lines), " " * 4)
2317
+ + textwrap.indent(f"\nreturn {returns}", " " * 4)
2318
+ + "\n}"
2319
+ )
2320
+
2321
+ return f"{signature} {body}"
2322
+
2323
+
2324
+ def _graph_repr(graph: Graph | GraphView) -> str:
2325
+ """Return an repr string of the graph."""
2326
+ inputs_text = "\n" + ",\n".join(str(x) for x in graph.inputs)
2327
+ outputs_text = "\n" + ",\n".join(str(x) for x in graph.outputs)
2328
+ initializers_text = ",\n".join(str(x) for x in graph.initializers.values())
2329
+ if initializers_text:
2330
+ initializers_text = (
2331
+ "\ninitializers=(\n" + textwrap.indent(initializers_text, " " * 4) + "\n),"
2332
+ )
2333
+ return f"""\
2334
+ {graph.__class__.__name__}(
2335
+ name={graph.name or "anonymous_graph:" + str(id(graph))!r},
2336
+ inputs=({textwrap.indent(inputs_text, " " * 8)}
2337
+ ),
2338
+ outputs=({textwrap.indent(outputs_text, " " * 8)}
2339
+ ),{textwrap.indent(initializers_text, " " * 4)}
2340
+ len()={len(graph)}
2341
+ )"""
2342
+
2343
+
2344
+ class GraphView(Sequence[Node], _display.PrettyPrintable):
2345
+ """A read-only view on a graph.
2346
+
2347
+ The GraphView is useful for analysis of a subgraph. It can be initialized
2348
+ with a subset of nodes from a :class:`Graph`. Creating GraphView does not
2349
+ change the ownership of the nodes, and so it is possible to create multiple
2350
+ GraphViews that contain the same nodes. If the underlying nodes / connections
2351
+ are mutated, the mutation will be reflected in all views as well.
2352
+
2353
+ The graph view can be serialized to ONNX::
2354
+
2355
+ graph_proto = ir.serde.serialize_graph(graph_view)
2356
+
2357
+ It can also be used to create a model::
2358
+
2359
+ model = ir.Model(graph_view, ir_version=8)
2360
+ model_proto = ir.serde.serialize_model(model)
2361
+
2362
+ The model created with a GraphView will have a fixed topology, and its graph
2363
+ will remain read-only as a GraphView. No copying will be done during the
2364
+ initialization process.
2365
+
2366
+ Attributes:
2367
+ name: The name of the graph.
2368
+ inputs: The input values of the graph.
2369
+ outputs: The output values of the graph.
2370
+ initializers: The initializers in the graph.
2371
+ doc_string: Documentation string.
2372
+ opset_imports: Opsets imported by the graph.
2373
+ metadata_props: Metadata that will be serialized to the ONNX file.
2374
+ meta: Metadata store for graph transform passes.
2375
+ """
2376
+
2377
+ __slots__ = (
2378
+ "_metadata",
2379
+ "_metadata_props",
2380
+ "doc_string",
2381
+ "initializers",
2382
+ "inputs",
2383
+ "name",
2384
+ "nodes",
2385
+ "opset_imports",
2386
+ "outputs",
2387
+ )
2388
+
2389
+ def __init__(
2390
+ self,
2391
+ inputs: Sequence[Value],
2392
+ outputs: Sequence[Value],
2393
+ *,
2394
+ nodes: Iterable[Node],
2395
+ initializers: Sequence[_protocols.ValueProtocol] = (),
2396
+ doc_string: str | None = None,
2397
+ opset_imports: dict[str, int] | None = None,
2398
+ name: str | None = None,
2399
+ metadata_props: dict[str, str] | None = None,
2400
+ ):
2401
+ self.name = name
2402
+ self.inputs = tuple(inputs)
2403
+ self.outputs = tuple(outputs)
2404
+ for initializer in initializers:
2405
+ if initializer.name is None:
2406
+ raise ValueError(f"Initializer must have a name: {initializer}")
2407
+ self.initializers = {tensor.name: tensor for tensor in initializers}
2408
+ self.doc_string = doc_string
2409
+ self.opset_imports = opset_imports or {}
2410
+ self._metadata: _metadata.MetadataStore | None = None
2411
+ self._metadata_props: dict[str, str] | None = metadata_props
2412
+ self._nodes: tuple[Node, ...] = tuple(nodes)
2413
+
2414
+ def __getitem__(self, index: int) -> Node:
2415
+ return self._nodes[index]
2416
+
2417
+ def __len__(self) -> int:
2418
+ return len(self._nodes)
2419
+
2420
+ def __iter__(self) -> Iterator[Node]:
2421
+ return iter(self._nodes)
2422
+
2423
+ def __reversed__(self) -> Iterator[Node]:
2424
+ return reversed(self._nodes)
2425
+
2426
+ @property
2427
+ def meta(self) -> _metadata.MetadataStore:
2428
+ """The metadata store for intermediate analysis.
2429
+
2430
+ Write to the :attr:`metadata_props` if you would like the metadata to be serialized
2431
+ to the ONNX proto.
2432
+ """
2433
+ if self._metadata is None:
2434
+ self._metadata = _metadata.MetadataStore()
2435
+ return self._metadata
2436
+
2437
+ @property
2438
+ def metadata_props(self) -> dict[str, str]:
2439
+ if self._metadata_props is None:
2440
+ self._metadata_props = {}
2441
+ return self._metadata_props
2442
+
2443
+ def __str__(self) -> str:
2444
+ return _graph_str(self)
2445
+
2446
+ def __repr__(self) -> str:
2447
+ return _graph_repr(self)
2448
+
2449
+
2450
+ class Model(_protocols.ModelProtocol, _display.PrettyPrintable):
2451
+ __slots__ = (
2452
+ "_functions",
2453
+ "_metadata",
2454
+ "_metadata_props",
2455
+ "doc_string",
2456
+ "domain",
2457
+ "graph",
2458
+ "ir_version",
2459
+ "model_version",
2460
+ "producer_name",
2461
+ "producer_version",
2462
+ )
2463
+ """IR Model.
2464
+
2465
+ A model is a container for a graph and metadata.
2466
+
2467
+ Attributes:
2468
+ graph: The graph of the model.
2469
+ ir_version: The version of the IR.
2470
+ producer_name: The name of the producer.
2471
+ producer_version: The version of the producer.
2472
+ domain: The domain of the model.
2473
+ model_version: The version of the model.
2474
+ doc_string: Documentation string.
2475
+ functions: The functions defined in the model.
2476
+ metadata_props: Metadata.
2477
+ """
2478
+
2479
+ def __init__(
2480
+ self,
2481
+ graph: Graph,
2482
+ *,
2483
+ ir_version: int,
2484
+ producer_name: str | None = None,
2485
+ producer_version: str | None = None,
2486
+ domain: str | None = None,
2487
+ model_version: int | None = None,
2488
+ doc_string: str | None = None,
2489
+ functions: Sequence[Function] = (),
2490
+ meta_data_props: dict[str, str] | None = None,
2491
+ ) -> None:
2492
+ self.graph: Graph = graph
2493
+ self.ir_version = ir_version
2494
+ self.producer_name = producer_name
2495
+ self.producer_version = producer_version
2496
+ self.domain = domain
2497
+ self.model_version = model_version
2498
+ self.doc_string = doc_string
2499
+ self._functions = {func.identifier(): func for func in functions}
2500
+ self._metadata: _metadata.MetadataStore | None = None
2501
+ self._metadata_props: dict[str, str] | None = meta_data_props
2502
+
2503
+ @property
2504
+ def functions(self) -> dict[_protocols.OperatorIdentifier, Function]:
2505
+ return self._functions
2506
+
2507
+ @property
2508
+ def opset_imports(self) -> dict[str, int]:
2509
+ return self.graph.opset_imports
2510
+
2511
+ @property
2512
+ def meta(self) -> _metadata.MetadataStore:
2513
+ """The metadata store for intermediate analysis.
2514
+
2515
+ Write to the :attr:`metadata_props` if you would like the metadata to be serialized
2516
+ to the ONNX proto.
2517
+ """
2518
+ if self._metadata is None:
2519
+ self._metadata = _metadata.MetadataStore()
2520
+ return self._metadata
2521
+
2522
+ @property
2523
+ def metadata_props(self) -> dict[str, str]:
2524
+ if self._metadata_props is None:
2525
+ self._metadata_props = {}
2526
+ return self._metadata_props
2527
+
2528
+ def __str__(self) -> str:
2529
+ # TODO(justinchuby): Show docstrings and metadata
2530
+ signature = f"""\
2531
+ <
2532
+ ir_version={self.ir_version!r},
2533
+ opset_imports={self.opset_imports!r},
2534
+ producer_name={self.producer_name!r},
2535
+ producer_version={self.producer_version!r},
2536
+ domain={self.domain!r},
2537
+ model_version={self.model_version!r},
2538
+ >"""
2539
+ graph_text = str(self.graph)
2540
+ functions_text = "\n\n".join(str(func) for func in self.functions.values())
2541
+ return f"{signature}\n{graph_text}" + f"\n\n{functions_text}"
2542
+
2543
+ def __repr__(self) -> str:
2544
+ return f"""\
2545
+ Model(
2546
+ ir_version={self.ir_version!r},
2547
+ opset_imports={self.opset_imports!r},
2548
+ producer_name={self.producer_name!r},
2549
+ producer_version={self.producer_version!r},
2550
+ domain={self.domain!r},
2551
+ model_version={self.model_version!r},
2552
+ functions={self.functions!r},
2553
+ graph={textwrap.indent(repr(self.graph), " " * 4).strip()}
2554
+ )"""
2555
+
2556
+
2557
+ class Function(_protocols.FunctionProtocol, Sequence[Node], _display.PrettyPrintable):
2558
+ """IR functions.
2559
+
2560
+ Like a graph, a function can have nodes that are not topologically sorted. It is
2561
+ the responsibility of the user to maintain a topological order of the nodes.
2562
+
2563
+ Note that there is not a ``node`` attribute in the Function. The Function can be
2564
+ seen as a Sequence of nodes and should be used as such. For example, to obtain
2565
+ all nodes as a list, call ``list(function)``.
2566
+
2567
+ Attributes:
2568
+ name: The function name.
2569
+ domain: The domain this function is defined in.
2570
+ overload: The overload name when the function is overloaded.
2571
+ inputs: The input values of the function.
2572
+ attributes: The attributes this function defines.
2573
+ outputs: The output values of the function.
2574
+ opset_imports: Opsets imported by the function.
2575
+ doc_string: Documentation string.
2576
+ metadata_props: Metadata that will be serialized to the ONNX file.
2577
+ meta: Metadata store for graph transform passes.
2578
+ """
2579
+
2580
+ __slots__ = (
2581
+ "_attributes",
2582
+ "_domain",
2583
+ "_graph",
2584
+ "_metadata",
2585
+ "_metadata_props",
2586
+ "_name",
2587
+ "_overload",
2588
+ )
2589
+
2590
+ def __init__(
2591
+ self,
2592
+ domain: str,
2593
+ name: str,
2594
+ overload: str = "",
2595
+ *,
2596
+ # Ensure the inputs and outputs of the function belong to a graph
2597
+ # and not from an outer scope
2598
+ graph: Graph,
2599
+ attributes: Sequence[Attr],
2600
+ metadata_props: dict[str, str] | None = None,
2601
+ ) -> None:
2602
+ self._domain = domain
2603
+ self._name = name
2604
+ self._overload = overload
2605
+ self._graph = graph
2606
+ self._attributes = OrderedDict((attr.name, attr) for attr in attributes)
2607
+ self._metadata: _metadata.MetadataStore | None = None
2608
+ self._metadata_props: dict[str, str] | None = metadata_props
2609
+
2610
+ def identifier(self) -> _protocols.OperatorIdentifier:
2611
+ return self.domain, self.name, self.overload
2612
+
2613
+ @property
2614
+ def name(self) -> str:
2615
+ return self._name
2616
+
2617
+ @name.setter
2618
+ def name(self, value: str) -> None:
2619
+ self._name = value
2620
+
2621
+ @property
2622
+ def domain(self) -> str:
2623
+ return self._domain
2624
+
2625
+ @domain.setter
2626
+ def domain(self, value: str) -> None:
2627
+ self._domain = value
2628
+
2629
+ @property
2630
+ def overload(self) -> str:
2631
+ return self._overload
2632
+
2633
+ @overload.setter
2634
+ def overload(self, value: str) -> None:
2635
+ self._overload = value
2636
+
2637
+ @property
2638
+ def inputs(self) -> list[Value]:
2639
+ return self._graph.inputs
2640
+
2641
+ @property
2642
+ def outputs(self) -> list[Value]:
2643
+ return self._graph.outputs
2644
+
2645
+ @property
2646
+ def attributes(self) -> OrderedDict[str, Attr]:
2647
+ return self._attributes
2648
+
2649
+ def __getitem__(self, index: int) -> Node:
2650
+ return self._graph.__getitem__(index)
2651
+
2652
+ def __len__(self) -> int:
2653
+ return self._graph.__len__()
2654
+
2655
+ def __iter__(self) -> Iterator[Node]:
2656
+ return self._graph.__iter__()
2657
+
2658
+ def __reversed__(self) -> Iterator[Node]:
2659
+ return self._graph.__reversed__()
2660
+
2661
+ @property
2662
+ def doc_string(self) -> str | None:
2663
+ return self._graph.doc_string
2664
+
2665
+ @doc_string.setter
2666
+ def doc_string(self, value: str | None) -> None:
2667
+ self._graph.doc_string = value
2668
+
2669
+ @property
2670
+ def opset_imports(self) -> dict[str, int]:
2671
+ return self._graph.opset_imports
2672
+
2673
+ @property
2674
+ def meta(self) -> _metadata.MetadataStore:
2675
+ """The metadata store for intermediate analysis.
2676
+
2677
+ Write to the :attr:`metadata_props` if you would like the metadata to be serialized
2678
+ to the ONNX proto.
2679
+ """
2680
+ if self._metadata is None:
2681
+ self._metadata = _metadata.MetadataStore()
2682
+ return self._metadata
2683
+
2684
+ @property
2685
+ def metadata_props(self) -> dict[str, str]:
2686
+ if self._metadata_props is None:
2687
+ self._metadata_props = {}
2688
+ return self._metadata_props
2689
+
2690
+ # Mutation methods
2691
+ def append(self, node: Node, /) -> None:
2692
+ """Append a node to the function in O(1) time."""
2693
+ self._graph.append(node)
2694
+
2695
+ def extend(self, nodes: Iterable[Node], /) -> None:
2696
+ """Extend the function with the given nodes in O(#new_nodes) time."""
2697
+ self._graph.extend(nodes)
2698
+
2699
+ def remove(self, nodes: Node | Iterable[Node], /, safe: bool = False) -> None:
2700
+ """Remove nodes from the graph in O(#num of nodes) time.
2701
+
2702
+ If any errors are raise, to ensure the graph is not left in an inconsistent state,
2703
+ the graph is not modified.
2704
+
2705
+ Args:
2706
+ nodes: The node to remove.
2707
+ safe: If True, performs the following actions before removal:
2708
+
2709
+ 1. It checks to make sure there are no users of the node that are not
2710
+ to be removed before removing it.
2711
+ 2. It checks the node does not contribute to any graph outputs.
2712
+ 3. It removes references to all inputs so it is no longer a user of other nodes.
2713
+
2714
+ Raises:
2715
+ ValueError: If any node to remove does not belong to this graph.
2716
+ ValueError: (When ``safe=True``) If the node does not belong to this graph or if there are users of the node.
2717
+ ValueError: (When ``safe=True``) If the node is still being used by other nodes not to be removed.
2718
+ """
2719
+ self._graph.remove(nodes, safe=safe)
2720
+
2721
+ def insert_after(self, node: Node, new_nodes: Iterable[Node], /) -> None:
2722
+ """Insert new nodes after the given node in O(#new_nodes) time."""
2723
+ self._graph.insert_after(node, new_nodes)
2724
+
2725
+ def insert_before(self, node: Node, new_nodes: Iterable[Node], /) -> None:
2726
+ """Insert new nodes before the given node in O(#new_nodes) time."""
2727
+ self._graph.insert_before(node, new_nodes)
2728
+
2729
+ def sort(self) -> None:
2730
+ """Perform a topological sort of this graph and all subgraphs in O(#nodes + #values) time."""
2731
+ self._graph.sort()
2732
+
2733
+ # End of mutation methods
2734
+
2735
+ def __str__(self) -> str:
2736
+ full_name = f"{self.domain}::{self.name}" + f":{self.overload}" * (self.overload != "")
2737
+ inputs_text = ",\n".join(str(x) for x in self.inputs)
2738
+ outputs_text = ",\n".join(str(x) for x in self.outputs)
2739
+ attributes_text = ",\n".join(
2740
+ f"{attr.name}: {attr.type}" + f" = {attr.value}" * (attr.value is not None)
2741
+ for attr in self.attributes.values()
2742
+ )
2743
+ if attributes_text:
2744
+ attributes_text = (
2745
+ "\nattributes={\n" + textwrap.indent(attributes_text, " " * 4) + "\n}"
2746
+ )
2747
+ signature = f"""\
2748
+ <
2749
+ opset_imports={self.opset_imports!r},
2750
+ >
2751
+ def {full_name}(
2752
+ inputs=(
2753
+ {textwrap.indent(inputs_text, " " * 8)}
2754
+ ),{textwrap.indent(attributes_text, " " * 4)}
2755
+ outputs=(
2756
+ {textwrap.indent(outputs_text, " " * 8)}
2757
+ ),
2758
+ )"""
2759
+ node_count = len(self)
2760
+ number_width = len(str(node_count))
2761
+ node_lines = []
2762
+ for i, node in enumerate(self):
2763
+ node_name = node.name if node.name else f":anonymous_node:{id(node)}"
2764
+ node_text = f"# {node_name}\n{node}"
2765
+ indented_node_text = textwrap.indent(node_text, " " * (number_width + 4))
2766
+ # Remove the leading spaces
2767
+ indented_node_text = indented_node_text.strip()
2768
+ node_lines.append(f"{i:>{number_width}} | {indented_node_text}")
2769
+ returns = ", ".join(str(x) for x in self.outputs)
2770
+ body = (
2771
+ "{\n"
2772
+ + textwrap.indent("\n".join(node_lines), " " * 4)
2773
+ + textwrap.indent(f"\nreturn {returns}", " " * 4)
2774
+ + "\n}"
2775
+ )
2776
+
2777
+ return f"{signature} {body}"
2778
+
2779
+ def __repr__(self) -> str:
2780
+ return f"{self.__class__.__name__}({self.domain!r}, {self.name!r}, {self.overload!r}, inputs={self.inputs!r}, attributes={self.attributes!r}), outputs={self.outputs!r})"
2781
+
2782
+
2783
+ class RefAttr(_protocols.ReferenceAttributeProtocol, _display.PrettyPrintable):
2784
+ """Reference attribute."""
2785
+
2786
+ __slots__ = ("_name", "_ref_attr_name", "_type", "doc_string")
2787
+
2788
+ def __init__(
2789
+ self,
2790
+ name: str,
2791
+ ref_attr_name: str,
2792
+ type: _enums.AttributeType,
2793
+ *,
2794
+ doc_string: str | None = None,
2795
+ ) -> None:
2796
+ self._name = name
2797
+ self._ref_attr_name = ref_attr_name
2798
+ self._type = type
2799
+ self.doc_string = doc_string
2800
+
2801
+ @property
2802
+ def name(self) -> str:
2803
+ return self._name
2804
+
2805
+ @name.setter
2806
+ def name(self, value: str) -> None:
2807
+ self._name = value
2808
+
2809
+ @property
2810
+ def ref_attr_name(self) -> str:
2811
+ return self._ref_attr_name
2812
+
2813
+ @ref_attr_name.setter
2814
+ def ref_attr_name(self, value: str) -> None:
2815
+ self._ref_attr_name = value
2816
+
2817
+ @property
2818
+ def type(self) -> _enums.AttributeType:
2819
+ return self._type
2820
+
2821
+ @type.setter
2822
+ def type(self, value: _enums.AttributeType) -> None:
2823
+ self._type = value
2824
+
2825
+ def __repr__(self) -> str:
2826
+ return f"{self.__class__.__name__}({self._name!r}, {self._type!r}, ref_attr_name={self.ref_attr_name!r})"
2827
+
2828
+
2829
+ class Attr(_protocols.AttributeProtocol, _display.PrettyPrintable):
2830
+ """Base class for ONNX attributes."""
2831
+
2832
+ __slots__ = ("doc_string", "name", "type", "value")
2833
+
2834
+ def __init__(
2835
+ self,
2836
+ name: str,
2837
+ type: _enums.AttributeType,
2838
+ value: Any,
2839
+ *,
2840
+ doc_string: str | None = None,
2841
+ ):
2842
+ self.name = name
2843
+ self.type = type
2844
+ self.value = value
2845
+ self.doc_string = doc_string
2846
+
2847
+ def __eq__(self, other: object) -> bool:
2848
+ if not isinstance(other, _protocols.AttributeProtocol):
2849
+ return False
2850
+
2851
+ if self.name != other.name:
2852
+ return False
2853
+ if self.type != other.type:
2854
+ return False
2855
+ if self.value != other.value:
2856
+ return False
2857
+ if self.doc_string != other.doc_string:
2858
+ return False
2859
+ return True
2860
+
2861
+ def __str__(self) -> str:
2862
+ if self.type == _enums.AttributeType.GRAPH:
2863
+ return textwrap.indent("\n" + str(self.value), " " * 4)
2864
+ return str(self.value)
2865
+
2866
+ def __repr__(self) -> str:
2867
+ return f"{self.__class__.__name__}({self.name!r}, {self.type!r}, {self.value!r})"
2868
+
2869
+ # Well typed getters
2870
+ def as_float(self) -> float:
2871
+ """Get the attribute value as a float."""
2872
+ # Do not use isinstance check because it may prevent np.float32 etc. from being used
2873
+ return float(self.value)
2874
+
2875
+ def as_int(self) -> int:
2876
+ """Get the attribute value as an int."""
2877
+ # Do not use isinstance check because it may prevent np.int32 etc. from being used
2878
+ return int(self.value)
2879
+
2880
+ def as_string(self) -> str:
2881
+ """Get the attribute value as a string."""
2882
+ if not isinstance(self.value, str):
2883
+ raise TypeError(f"Value of attribute '{self!r}' is not a string.")
2884
+ return self.value
2885
+
2886
+ def as_tensor(self) -> _protocols.TensorProtocol:
2887
+ """Get the attribute value as a tensor."""
2888
+ if not isinstance(self.value, _protocols.TensorProtocol):
2889
+ raise TypeError(f"Value of attribute '{self!r}' is not a tensor.")
2890
+ return self.value
2891
+
2892
+ def as_graph(self) -> Graph:
2893
+ """Get the attribute value as a graph."""
2894
+ if not isinstance(self.value, Graph):
2895
+ raise TypeError(f"Value of attribute '{self!r}' is not a graph.")
2896
+ return self.value
2897
+
2898
+ def as_floats(self) -> Sequence[float]:
2899
+ """Get the attribute value as a sequence of floats."""
2900
+ if not isinstance(self.value, Sequence):
2901
+ raise TypeError(f"Value of attribute '{self!r}' is not a Sequence.")
2902
+ # Do not use isinstance check on elements because it may prevent np.int32 etc. from being used
2903
+ # Create a copy of the list to prevent mutation
2904
+ return [float(v) for v in self.value]
2905
+
2906
+ def as_ints(self) -> Sequence[int]:
2907
+ """Get the attribute value as a sequence of ints."""
2908
+ if not isinstance(self.value, Sequence):
2909
+ raise TypeError(f"Value of attribute '{self!r}' is not a Sequence.")
2910
+ # Do not use isinstance check on elements because it may prevent np.int32 etc. from being used
2911
+ # Create a copy of the list to prevent mutation
2912
+ return list(self.value)
2913
+
2914
+ def as_strings(self) -> Sequence[str]:
2915
+ """Get the attribute value as a sequence of strings."""
2916
+ if not isinstance(self.value, Sequence):
2917
+ raise TypeError(f"Value of attribute '{self!r}' is not a Sequence.")
2918
+ if onnxscript.DEBUG:
2919
+ if not all(isinstance(x, str) for x in self.value):
2920
+ raise TypeError(f"Value of attribute '{self!r}' is not a Sequence of strings.")
2921
+ # Create a copy of the list to prevent mutation
2922
+ return list(self.value)
2923
+
2924
+ def as_tensors(self) -> Sequence[_protocols.TensorProtocol]:
2925
+ """Get the attribute value as a sequence of tensors."""
2926
+ if not isinstance(self.value, Sequence):
2927
+ raise TypeError(f"Value of attribute '{self!r}' is not a Sequence.")
2928
+ if onnxscript.DEBUG:
2929
+ if not all(isinstance(x, _protocols.TensorProtocol) for x in self.value):
2930
+ raise TypeError(f"Value of attribute '{self!r}' is not a Sequence of tensors.")
2931
+ # Create a copy of the list to prevent mutation
2932
+ return list(self.value)
2933
+
2934
+ def as_graphs(self) -> Sequence[Graph]:
2935
+ """Get the attribute value as a sequence of graphs."""
2936
+ if not isinstance(self.value, Sequence):
2937
+ raise TypeError(f"Value of attribute '{self!r}' is not a Sequence.")
2938
+ if onnxscript.DEBUG:
2939
+ if not all(isinstance(x, Graph) for x in self.value):
2940
+ raise TypeError(f"Value of attribute '{self!r}' is not a Sequence of graphs.")
2941
+ # Create a copy of the list to prevent mutation
2942
+ return list(self.value)
2943
+
2944
+
2945
+ # NOTE: The following functions are just for convenience
2946
+ def AttrFloat32(name: str, value: float, doc_string: str | None = None) -> Attr:
2947
+ """Create a float attribute."""
2948
+ # NOTE: The function name is capitalized to maintain API backward compatibility.
2949
+ return Attr(
2950
+ name,
2951
+ _enums.AttributeType.FLOAT,
2952
+ value,
2953
+ doc_string=doc_string,
2954
+ )
2955
+
2956
+
2957
+ def AttrInt64(name: str, value: int, doc_string: str | None = None) -> Attr:
2958
+ """Create an int attribute."""
2959
+ # NOTE: The function name is capitalized to maintain API backward compatibility.
2960
+ return Attr(
2961
+ name,
2962
+ _enums.AttributeType.INT,
2963
+ value,
2964
+ doc_string=doc_string,
2965
+ )
2966
+
2967
+
2968
+ def AttrString(name: str, value: str, doc_string: str | None = None) -> Attr:
2969
+ """Create a str attribute."""
2970
+ # NOTE: The function name is capitalized to maintain API backward compatibility.
2971
+ return Attr(
2972
+ name,
2973
+ _enums.AttributeType.STRING,
2974
+ value,
2975
+ doc_string=doc_string,
2976
+ )
2977
+
2978
+
2979
+ def AttrTensor(
2980
+ name: str, value: _protocols.TensorProtocol, doc_string: str | None = None
2981
+ ) -> Attr:
2982
+ """Create a tensor attribute."""
2983
+ # NOTE: The function name is capitalized to maintain API backward compatibility.
2984
+ return Attr(
2985
+ name,
2986
+ _enums.AttributeType.TENSOR,
2987
+ value,
2988
+ doc_string=doc_string,
2989
+ )
2990
+
2991
+
2992
+ def AttrGraph(name: str, value: Graph, doc_string: str | None = None) -> Attr:
2993
+ """Create a graph attribute."""
2994
+ # NOTE: The function name is capitalized to maintain API backward compatibility.
2995
+ return Attr(
2996
+ name,
2997
+ _enums.AttributeType.GRAPH,
2998
+ value,
2999
+ doc_string=doc_string,
3000
+ )
3001
+
3002
+
3003
+ def AttrFloat32s(name: str, value: Sequence[float], doc_string: str | None = None) -> Attr:
3004
+ """Create a float sequence attribute."""
3005
+ # NOTE: The function name is capitalized to maintain API backward compatibility.
3006
+ return Attr(
3007
+ name,
3008
+ _enums.AttributeType.FLOATS,
3009
+ value,
3010
+ doc_string=doc_string,
3011
+ )
3012
+
3013
+
3014
+ def AttrInt64s(name: str, value: Sequence[int], doc_string: str | None = None) -> Attr:
3015
+ """Create an int sequence attribute."""
3016
+ # NOTE: The function name is capitalized to maintain API backward compatibility.
3017
+ return Attr(
3018
+ name,
3019
+ _enums.AttributeType.INTS,
3020
+ value,
3021
+ doc_string=doc_string,
3022
+ )
3023
+
3024
+
3025
+ def AttrStrings(name: str, value: Sequence[str], doc_string: str | None = None) -> Attr:
3026
+ """Create a string sequence attribute."""
3027
+ # NOTE: The function name is capitalized to maintain API backward compatibility.
3028
+ return Attr(
3029
+ name,
3030
+ _enums.AttributeType.STRINGS,
3031
+ value,
3032
+ doc_string=doc_string,
3033
+ )
3034
+
3035
+
3036
+ def AttrTensors(
3037
+ name: str, value: Sequence[_protocols.TensorProtocol], doc_string: str | None = None
3038
+ ) -> Attr:
3039
+ """Create a tensor sequence attribute."""
3040
+ # NOTE: The function name is capitalized to maintain API backward compatibility.
3041
+ return Attr(
3042
+ name,
3043
+ _enums.AttributeType.TENSORS,
3044
+ value,
3045
+ doc_string=doc_string,
3046
+ )
3047
+
3048
+
3049
+ def AttrGraphs(name: str, value: Sequence[Graph], doc_string: str | None = None) -> Attr:
3050
+ """Create a graph sequence attribute."""
3051
+ # NOTE: The function name is capitalized to maintain API backward compatibility.
3052
+ return Attr(
3053
+ name,
3054
+ _enums.AttributeType.GRAPHS,
3055
+ value,
3056
+ doc_string=doc_string,
3057
+ )
3058
+
3059
+
3060
+ # NOTE: SparseTensor should be a sparse tensor proto
3061
+ def AttrSparseTensor(
3062
+ name: str, value: _protocols.SparseTensorProtocol, doc_string: str | None = None
3063
+ ) -> Attr:
3064
+ """Create a sparse tensor attribute."""
3065
+ # NOTE: The function name is capitalized to maintain API backward compatibility.
3066
+ return Attr(
3067
+ name,
3068
+ _enums.AttributeType.SPARSE_TENSOR,
3069
+ value,
3070
+ doc_string=doc_string,
3071
+ )
3072
+
3073
+
3074
+ def AttrSparseTensors(
3075
+ name: str, value: Sequence[_protocols.SparseTensorProtocol], doc_string: str | None = None
3076
+ ) -> Attr:
3077
+ """Create a sparse tensor sequence attribute."""
3078
+ # NOTE: The function name is capitalized to maintain API backward compatibility.
3079
+ return Attr(
3080
+ name,
3081
+ _enums.AttributeType.SPARSE_TENSORS,
3082
+ value,
3083
+ doc_string=doc_string,
3084
+ )
3085
+
3086
+
3087
+ @dataclasses.dataclass
3088
+ class TypeAndShape:
3089
+ """Type and shape.
3090
+
3091
+ Useful for constructing a type proto.
3092
+ """
3093
+
3094
+ type: _protocols.TypeProtocol | None
3095
+ shape: Shape | None
3096
+
3097
+
3098
+ def AttrTypeProto(name: str, value: TypeAndShape, doc_string: str | None = None) -> Attr:
3099
+ """Create a type attribute."""
3100
+ # NOTE: The function name is capitalized to maintain API backward compatibility.
3101
+ return Attr(
3102
+ name,
3103
+ _enums.AttributeType.TYPE_PROTO,
3104
+ value,
3105
+ doc_string=doc_string,
3106
+ )
3107
+
3108
+
3109
+ def AttrTypeProtos(
3110
+ name: str, value: Sequence[TypeAndShape], doc_string: str | None = None
3111
+ ) -> Attr:
3112
+ """Create a type sequence attribute."""
3113
+ # NOTE: The function name is capitalized to maintain API backward compatibility.
3114
+ return Attr(
3115
+ name,
3116
+ _enums.AttributeType.TYPE_PROTOS,
3117
+ value,
3118
+ doc_string=doc_string,
3119
+ )