onnx-ir 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of onnx-ir might be problematic. Click here for more details.

@@ -0,0 +1,313 @@
1
+ # Copyright (c) Microsoft Corporation.
2
+ # Licensed under the MIT License.
3
+ #
4
+ # Copyright © 2016 Igor Kroitor
5
+ #
6
+ # MIT License
7
+ #
8
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ # of this software and associated documentation files (the "Software"), to deal
10
+ # in the Software without restriction, including without limitation the rights
11
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ # copies of the Software, and to permit persons to whom the Software is
13
+ # furnished to do so, subject to the following conditions:
14
+ #
15
+ # The above copyright notice and this permission notice shall be included in all
16
+ # copies or substantial portions of the Software.
17
+ #
18
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
+ # SOFTWARE.
25
+
26
+ """Module to generate ascii charts.
27
+
28
+ This module provides a single function `plot` that can be used to generate an
29
+ ascii chart from a series of numbers. The chart can be configured via several
30
+ options to tune the output.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ from math import ceil, floor, isnan
36
+ from typing import Mapping
37
+
38
+ black = "\033[30m"
39
+ red = "\033[31m"
40
+ green = "\033[32m"
41
+ yellow = "\033[33m"
42
+ blue = "\033[34m"
43
+ magenta = "\033[35m"
44
+ cyan = "\033[36m"
45
+ lightgray = "\033[37m"
46
+ default = "\033[39m"
47
+ darkgray = "\033[90m"
48
+ lightred = "\033[91m"
49
+ lightgreen = "\033[92m"
50
+ lightyellow = "\033[93m"
51
+ lightblue = "\033[94m"
52
+ lightmagenta = "\033[95m"
53
+ lightcyan = "\033[96m"
54
+ white = "\033[97m"
55
+ reset = "\033[0m"
56
+
57
+
58
+ __all__ = [
59
+ "plot",
60
+ "black",
61
+ "red",
62
+ "green",
63
+ "yellow",
64
+ "blue",
65
+ "magenta",
66
+ "cyan",
67
+ "lightgray",
68
+ "default",
69
+ "darkgray",
70
+ "lightred",
71
+ "lightgreen",
72
+ "lightyellow",
73
+ "lightblue",
74
+ "lightmagenta",
75
+ "lightcyan",
76
+ "white",
77
+ "reset",
78
+ ]
79
+
80
+
81
+ # Python 3.2 has math.isfinite, which could have been used, but to support older
82
+ # versions, this little helper is shorter than having to keep doing not isnan(),
83
+ # plus the double-negative of "not is not a number" is confusing, so this should
84
+ # help with readability.
85
+ def _isnum(n):
86
+ return not isnan(n)
87
+
88
+
89
+ def colored(char, color):
90
+ if not color:
91
+ return char
92
+ else:
93
+ return color + char + reset
94
+
95
+
96
+ _DEFAULT_SYMBOLS = ("┼", "┤", "╶", "╴", "─", "╰", "╭", "╮", "╯", "│")
97
+
98
+
99
+ def plot(series, *, bin_edges=None, cfg=None):
100
+ """Generate an ascii chart for a series of numbers.
101
+
102
+ `series` should be a list of ints or floats. Missing data values in the
103
+ series can be specified as a NaN. In Python versions less than 3.5, use
104
+ float("nan") to specify an NaN. With 3.5 onwards, use math.nan to specify a
105
+ NaN.
106
+
107
+ >>> series = [1,2,3,4,float("nan"),4,3,2,1]
108
+ >>> print(plot(series))
109
+ 4.00 ┤ ╭╴╶╮
110
+ 3.00 ┤ ╭╯ ╰╮
111
+ 2.00 ┤╭╯ ╰╮
112
+ 1.00 ┼╯ ╰
113
+
114
+ `series` can also be a list of lists to support multiple data series.
115
+
116
+ >>> series = [[10,20,30,40,30,20,10], [40,30,20,10,20,30,40]]
117
+ >>> print(plot(series, cfg={'height': 3}))
118
+ 40.00 ┤╮ ╭╮ ╭
119
+ 30.00 ┤╰╮╯╰╭╯
120
+ 20.00 ┤╭╰╮╭╯╮
121
+ 10.00 ┼╯ ╰╯ ╰
122
+
123
+ `bin_edges` is an optional list of bin edges to display on the x-axis. If
124
+ provided, the x-axis will be labeled with the bin edges. If there are too
125
+ many bin edges to fit on the x-axis, some labels will be dropped and they
126
+ will be spaced out evenly to fit the width of the chart.
127
+ The labels will be formatted using the `x_format` option in `cfg`.
128
+
129
+ `cfg` is an optional dictionary of various parameters to tune the appearance
130
+ of the chart. `min` and `max` will clamp the y-axis and all values:
131
+
132
+ >>> series = [1,2,3,4,float("nan"),4,3,2,1]
133
+ >>> print(plot(series, cfg={'min': 0}))
134
+ 4.00 ┼ ╭╴╶╮
135
+ 3.00 ┤ ╭╯ ╰╮
136
+ 2.00 ┤╭╯ ╰╮
137
+ 1.00 ┼╯ ╰
138
+ 0.00 ┤
139
+
140
+ >>> print(plot(series, cfg={'min': 2}))
141
+ 4.00 ┤ ╭╴╶╮
142
+ 3.00 ┤ ╭╯ ╰╮
143
+ 2.00 ┼─╯ ╰─
144
+
145
+ >>> print(plot(series, cfg={'min': 2, 'max': 3}))
146
+ 3.00 ┤ ╭─╴╶─╮
147
+ 2.00 ┼─╯ ╰─
148
+
149
+ `height` specifies the number of rows the graph should occupy. It can be
150
+ used to scale down a graph with large data values:
151
+
152
+ >>> series = [10,20,30,40,50,40,30,20,10]
153
+ >>> print(plot(series, cfg={'height': 4}))
154
+ 50.00 ┤ ╭╮
155
+ 40.00 ┤ ╭╯╰╮
156
+ 30.00 ┤ ╭╯ ╰╮
157
+ 20.00 ┤╭╯ ╰╮
158
+ 10.00 ┼╯ ╰
159
+
160
+ `format` specifies a Python format string used to format the labels on the
161
+ y-axis. The default value is "{:8.2f} ". This can be used to remove the
162
+ decimal point:
163
+
164
+ >>> series = [10,20,30,40,50,40,30,20,10]
165
+ >>> print(plot(series, cfg={'height': 4, 'format':'{:8.0f}'}))
166
+ 50 ┤ ╭╮
167
+ 40 ┤ ╭╯╰╮
168
+ 30 ┤ ╭╯ ╰╮
169
+ 20 ┤╭╯ ╰╮
170
+ 10 ┼╯ ╰
171
+ """
172
+ if len(series) == 0:
173
+ return ""
174
+
175
+ if not isinstance(series[0], list):
176
+ if all(isnan(n) for n in series):
177
+ return ""
178
+ else:
179
+ series = [series]
180
+
181
+ if cfg is not None and not isinstance(cfg, Mapping):
182
+ raise TypeError("cfg must be a dictionary or None")
183
+
184
+ cfg = cfg or {}
185
+
186
+ colors = cfg.get("colors", [None])
187
+
188
+ minimum = cfg.get("min", min(filter(_isnum, [j for i in series for j in i])))
189
+ maximum = cfg.get("max", max(filter(_isnum, [j for i in series for j in i])))
190
+
191
+ symbols = cfg.get("symbols", _DEFAULT_SYMBOLS)
192
+
193
+ if minimum > maximum:
194
+ raise ValueError("The min value cannot exceed the max value.")
195
+
196
+ interval = maximum - minimum
197
+ offset = cfg.get("offset", 3)
198
+ height = cfg.get("height", interval)
199
+ ratio = height / interval if interval > 0 else 1
200
+
201
+ min2 = floor(minimum * ratio)
202
+ max2 = ceil(maximum * ratio)
203
+
204
+ def clamp(n):
205
+ return min(max(n, minimum), maximum)
206
+
207
+ def scaled(y):
208
+ return int(round(clamp(y) * ratio) - min2)
209
+
210
+ rows = max2 - min2
211
+
212
+ width = 0
213
+ for series_i in series:
214
+ width = max(width, len(series_i))
215
+ width += offset
216
+
217
+ placeholder = cfg.get("format", "{:8.2f} ")
218
+ x_placeholder = cfg.get("x_format", "{:4.4f}")
219
+
220
+ result = [[" "] * width for i in range(rows + 1)]
221
+
222
+ # axis and labels
223
+ for y in range(min2, max2 + 1):
224
+ label = placeholder.format(maximum - ((y - min2) * interval / (rows if rows else 1)))
225
+ result[y - min2][max(offset - len(label), 0)] = label
226
+ result[y - min2][offset - 1] = symbols[0] if y == 0 else symbols[1] # zero tick mark
227
+
228
+ # first value is a tick mark across the y-axis
229
+ d0 = series[0][0]
230
+ if _isnum(d0):
231
+ result[rows - scaled(d0)][offset - 1] = symbols[0]
232
+
233
+ for i, series_i in enumerate(series):
234
+ color = colors[i % len(colors)]
235
+
236
+ # plot the line
237
+ for x in range(len(series_i) - 1):
238
+ d0 = series_i[x + 0]
239
+ d1 = series_i[x + 1]
240
+
241
+ if isnan(d0) and isnan(d1):
242
+ continue
243
+
244
+ if isnan(d0) and _isnum(d1):
245
+ result[rows - scaled(d1)][x + offset] = colored(symbols[2], color)
246
+ continue
247
+
248
+ if _isnum(d0) and isnan(d1):
249
+ result[rows - scaled(d0)][x + offset] = colored(symbols[3], color)
250
+ continue
251
+
252
+ y0 = scaled(d0)
253
+ y1 = scaled(d1)
254
+ if y0 == y1:
255
+ result[rows - y0][x + offset] = colored(symbols[4], color)
256
+ continue
257
+
258
+ result[rows - y1][x + offset] = (
259
+ colored(symbols[5], color) if y0 > y1 else colored(symbols[6], color)
260
+ )
261
+ result[rows - y0][x + offset] = (
262
+ colored(symbols[7], color) if y0 > y1 else colored(symbols[8], color)
263
+ )
264
+
265
+ start = min(y0, y1) + 1
266
+ end = max(y0, y1)
267
+ for y in range(start, end):
268
+ result[rows - y][x + offset] = colored(symbols[9], color)
269
+
270
+ the_plot = "\n".join(["".join(row).rstrip() for row in result])
271
+
272
+ if bin_edges is None or len(bin_edges) == 0:
273
+ return the_plot
274
+
275
+ # Plot x axis labels
276
+ current_location = 0
277
+ # Compute the amount of leading space for the first x-label using the old label size
278
+ leading_space = offset + len(label)
279
+ # Obtain the first x-label to compute its size
280
+ x_label = x_placeholder.format(bin_edges[0])
281
+ # Initialize the x-label text with the leading space. We allow the first label to
282
+ # recess so that the center of it is aligned with the first tick mark.
283
+ x_label_size = len(x_label)
284
+ x_leading_space = max(0, leading_space - x_label_size)
285
+
286
+ x_labels = []
287
+ # This is the amount of space we have to fit the x-labels. It can overflow the width
288
+ # by half of the x-label size
289
+ workable_width = width + x_label_size // 2
290
+ # Compute the spacing between x-labels
291
+ # If we fit labels and space them by 2 characters, we can fit this many labels:
292
+ min_spacing = 2
293
+ num_labels_can_fit = width // (x_label_size + min_spacing)
294
+ labels_count = len(bin_edges)
295
+ # Find out the actual number of labels we need to display
296
+ num_labels_to_display = min(labels_count, num_labels_can_fit)
297
+ num_spaces = num_labels_to_display - 1
298
+ spacing = max(
299
+ min_spacing,
300
+ (workable_width - num_labels_to_display * x_label_size) // num_spaces,
301
+ )
302
+ # Now start placing labels
303
+ while current_location < workable_width:
304
+ # Find the current label that would be suitable for the current location
305
+ bin_index = int((current_location / workable_width) * labels_count)
306
+ x_label = x_placeholder.format(bin_edges[bin_index])
307
+ x_labels.append(x_label)
308
+ # Move to the next location
309
+ current_location += len(x_label) + spacing
310
+ # Create the x-label row
311
+ x_labels_text = " " * x_leading_space + (" " * spacing).join(x_labels)
312
+
313
+ return the_plot + "\n" + x_labels_text
@@ -0,0 +1,91 @@
1
+ # Copyright (c) Microsoft Corporation.
2
+ # Licensed under the MIT License.
3
+ """Numpy utilities for non-native type operation."""
4
+ # TODO(justinchuby): Upstream the logic to onnx
5
+
6
+ from __future__ import annotations
7
+
8
+ import typing
9
+ from typing import Sequence
10
+
11
+ import ml_dtypes
12
+ import numpy as np
13
+
14
+ if typing.TYPE_CHECKING:
15
+ import numpy.typing as npt
16
+
17
+
18
+ def pack_int4(array: np.ndarray) -> npt.NDArray[np.uint8]:
19
+ """Convert a numpy array to flatten, packed int4/uint4. Elements must be in the correct range."""
20
+ # Create a 1D copy
21
+ array_flat = array.ravel().view(np.uint8).copy()
22
+ size = array.size
23
+ odd_sized = size % 2 == 1
24
+ if odd_sized:
25
+ array_flat.resize([size + 1], refcheck=False)
26
+ array_flat &= 0x0F
27
+ array_flat[1::2] <<= 4
28
+ return array_flat[0::2] | array_flat[1::2] # type: ignore[return-type]
29
+
30
+
31
+ def _unpack_uint4_as_uint8(
32
+ data: npt.NDArray[np.uint8], dims: Sequence[int]
33
+ ) -> npt.NDArray[np.uint8]:
34
+ """Convert a packed uint4 array to unpacked uint4 array represented as uint8.
35
+
36
+ Args:
37
+ data: A numpy array.
38
+ dims: The dimensions are used to reshape the unpacked buffer.
39
+
40
+ Returns:
41
+ A numpy array of int8/uint8 reshaped to dims.
42
+ """
43
+ result = np.empty([data.size * 2], dtype=data.dtype)
44
+ array_low = data & np.uint8(0x0F)
45
+ array_high = data & np.uint8(0xF0)
46
+ array_high >>= np.uint8(4)
47
+ result[0::2] = array_low
48
+ result[1::2] = array_high
49
+ if result.size == np.prod(dims) + 1:
50
+ # handle single-element padding due to odd number of elements
51
+ result = result[:-1]
52
+ result.resize(dims, refcheck=False)
53
+ return result
54
+
55
+
56
+ def unpack_uint4(
57
+ data: npt.NDArray[np.uint8], dims: Sequence[int]
58
+ ) -> npt.NDArray[ml_dtypes.uint4]:
59
+ """Convert a packed uint4 array to unpacked uint4 array represented as uint8.
60
+
61
+ Args:
62
+ data: A numpy array.
63
+ dims: The dimensions are used to reshape the unpacked buffer.
64
+
65
+ Returns:
66
+ A numpy array of int8/uint8 reshaped to dims.
67
+ """
68
+ return _unpack_uint4_as_uint8(data, dims).view(ml_dtypes.uint4)
69
+
70
+
71
+ def _extend_int4_sign_bits(x: npt.NDArray[np.uint8]) -> npt.NDArray[np.int8]:
72
+ """Extend 4-bit signed integer to 8-bit signed integer."""
73
+ return np.where((x >> 3) == 0, x, x | 0xF0).astype(np.int8)
74
+
75
+
76
+ def unpack_int4(
77
+ data: npt.NDArray[np.uint8], dims: Sequence[int]
78
+ ) -> npt.NDArray[ml_dtypes.int4]:
79
+ """Convert a packed (signed) int4 array to unpacked int4 array represented as int8.
80
+
81
+ The sign bit is extended to the most significant bit of the int8.
82
+
83
+ Args:
84
+ data: A numpy array.
85
+ dims: The dimensions are used to reshape the unpacked buffer.
86
+
87
+ Returns:
88
+ A numpy array of int8 reshaped to dims.
89
+ """
90
+ unpacked = _unpack_uint4_as_uint8(data, dims)
91
+ return _extend_int4_sign_bits(unpacked).view(ml_dtypes.int4)
onnx_ir/convenience.py ADDED
@@ -0,0 +1,32 @@
1
+ # Copyright (c) Microsoft Corporation.
2
+ # Licensed under the MIT License.
3
+ """Convenience methods for constructing and manipulating the IR."""
4
+
5
+ from __future__ import annotations
6
+
7
+ __all__ = [
8
+ "convert_attribute",
9
+ "convert_attributes",
10
+ "replace_all_uses_with",
11
+ "replace_nodes_and_values",
12
+ ]
13
+
14
+ from onnx_ir._convenience import (
15
+ convert_attribute,
16
+ convert_attributes,
17
+ replace_all_uses_with,
18
+ replace_nodes_and_values,
19
+ )
20
+
21
+ # NOTE: Do not implement any other functions in this module.
22
+ # implement them in the _convenience module and import them here instead.
23
+
24
+
25
+ def __set_module() -> None:
26
+ """Set the module of all functions in this module to this public module."""
27
+ global_dict = globals()
28
+ for name in __all__:
29
+ global_dict[name].__module__ = __name__
30
+
31
+
32
+ __set_module()
@@ -0,0 +1,33 @@
1
+ # Copyright (c) Microsoft Corporation.
2
+ # Licensed under the MIT License.
3
+
4
+ __all__ = [
5
+ "PassBase",
6
+ "PassResult",
7
+ "PassManager",
8
+ # Errors
9
+ "InvariantError",
10
+ "PreconditionError",
11
+ "PostconditionError",
12
+ "PassError",
13
+ ]
14
+
15
+ from onnx_ir.passes._pass_infra import (
16
+ InvariantError,
17
+ PassBase,
18
+ PassError,
19
+ PassManager,
20
+ PassResult,
21
+ PostconditionError,
22
+ PreconditionError,
23
+ )
24
+
25
+
26
+ def __set_module() -> None:
27
+ """Set the module of all functions in this module to this public module."""
28
+ global_dict = globals()
29
+ for name in __all__:
30
+ global_dict[name].__module__ = __name__
31
+
32
+
33
+ __set_module()
@@ -0,0 +1,172 @@
1
+ # Copyright (c) Microsoft Corporation.
2
+ # Licensed under the MIT License.
3
+ #
4
+ # This module implements some APIs described in
5
+ # https://pytorch.org/executorch/stable/compiler-custom-compiler-passes.html
6
+ # for the ONNX IR.
7
+ # The classes {PassResult and PassManager} are derived from
8
+ # https://github.com/pytorch/pytorch/blob/1e47c7b11b312b47a621efd547f5c90081f0d9cb/torch/fx/passes/infra/pass_base.py#L12
9
+ # and
10
+ # https://github.com/pytorch/pytorch/blob/1e47c7b11b312b47a621efd547f5c90081f0d9cb/torch/fx/passes/infra/pass_manager.py#L147
11
+ # The original code is licensed under the PyTorch License https://github.com/pytorch/pytorch/blob/main/LICENSE
12
+
13
+ """Passes infrastructure for the IR."""
14
+
15
+ from __future__ import annotations
16
+
17
+ import dataclasses
18
+ import logging
19
+ from typing import Sequence
20
+
21
+ __all__ = [
22
+ "PassBase",
23
+ "PassManager",
24
+ "PassResult",
25
+ # Errors
26
+ "InvariantError",
27
+ "PreconditionError",
28
+ "PostconditionError",
29
+ "PassError",
30
+ ]
31
+
32
+ import abc
33
+
34
+ import onnx_ir as ir
35
+
36
+ logger = logging.getLogger(__name__)
37
+
38
+
39
+ class InvariantError(Exception):
40
+ """Raised when an invariant is violated."""
41
+
42
+
43
+ class PreconditionError(InvariantError):
44
+ """Raised when a precondition is violated."""
45
+
46
+
47
+ class PostconditionError(InvariantError):
48
+ """Raised when a postcondition is violated."""
49
+
50
+
51
+ class PassError(RuntimeError):
52
+ """Raised when an error occurs during a pass."""
53
+
54
+
55
+ @dataclasses.dataclass
56
+ class PassResult:
57
+ """Result of a pass.
58
+
59
+ Attributes:
60
+ model: The transformed model.
61
+ modified: Whether the model was modified.
62
+ """
63
+
64
+ model: ir.Model
65
+ modified: bool
66
+
67
+
68
+ class PassBase(abc.ABC):
69
+ """Base class for all passes.
70
+
71
+ Class attributes:
72
+ in_place: Whether the pass modifies the model in place.
73
+ """
74
+
75
+ in_place: bool = True
76
+
77
+ def __call__(self, model: ir.Model) -> PassResult:
78
+ return self.call(model)
79
+
80
+ @abc.abstractmethod
81
+ def call(self, model: ir.Model) -> PassResult:
82
+ """The main entry point for the pass."""
83
+ ...
84
+
85
+ def requires(self, model: ir.Model) -> None:
86
+ """Pre-conditions for the pass.
87
+
88
+ This is optional to implement, will be called before call() if run by a pass manager.
89
+ """
90
+ del model # Unused
91
+
92
+ def ensures(self, model: ir.Model) -> None:
93
+ """Post-conditions for the pass.
94
+
95
+ This is optional to implement, will be called after call() if run by a pass manager.
96
+ """
97
+ del model # Unused
98
+
99
+
100
+ class PassManager:
101
+ """Pass manager for the IR.
102
+
103
+ The PassManager is a callable that runs a sequence of passes on a model.
104
+
105
+ Attributes:
106
+ passes: The passes to run.
107
+ check_invariants: Whether to check invariants before and after each pass.
108
+ steps: The number of times to run the passes.
109
+ """
110
+
111
+ def __init__(
112
+ self,
113
+ passes: Sequence[PassBase],
114
+ check_invariants: bool = False,
115
+ steps: int = 1,
116
+ ):
117
+ # TODO(justinchuby): Implement constraints
118
+ self.passes = list(passes)
119
+ self.check_invariants = check_invariants
120
+ self.steps = steps
121
+
122
+ def __call__(self, model: ir.Model) -> PassResult:
123
+ """Run the set of passes `steps` number of times or until the graph stops changing."""
124
+ overall_modified = False
125
+ for step in range(self.steps):
126
+ step_result = self._run_one_step(model, step)
127
+ model = step_result.model
128
+ modified = step_result.modified
129
+ overall_modified = overall_modified or modified
130
+ # If the graph no longer changes, then we can stop running these passes
131
+ if not modified:
132
+ logger.info("PassManager: No more graph changes detected after step %s", step)
133
+ break
134
+ return PassResult(model, overall_modified)
135
+
136
+ def _run_one_step(self, model: ir.Model, step: int) -> PassResult:
137
+ modified = False
138
+ for i, pass_ in enumerate(self.passes):
139
+ logger.debug("Running the %s-th pass '%s', (step %s)", i, pass_, step)
140
+
141
+ # 1. Check preconditions
142
+ if self.check_invariants:
143
+ try:
144
+ pass_.requires(model)
145
+ except Exception as e:
146
+ raise PreconditionError(f"Pre-condition failed for {pass_}") from e
147
+
148
+ # 2. Run the pass
149
+ try:
150
+ pass_result = pass_(model)
151
+ except Exception as e:
152
+ prev_pass_names = [str(p) for p in self.passes[:i]]
153
+ raise PassError(
154
+ f"An error occurred when running the '{pass_}' pass after the "
155
+ f"following passes: {prev_pass_names} during step {step}"
156
+ ) from e
157
+ if not isinstance(pass_result, PassResult):
158
+ raise TypeError(
159
+ f"The result of the pass {pass_} should be type PassResult."
160
+ "Please create one with ir.passes.PassResult()."
161
+ )
162
+
163
+ model = pass_result.model
164
+ modified = modified or pass_result.modified
165
+
166
+ # 3. Check postconditions
167
+ if self.check_invariants:
168
+ try:
169
+ pass_.ensures(model)
170
+ except Exception as e:
171
+ raise PostconditionError(f"Post-condition failed for {pass_}") from e
172
+ return PassResult(model, modified)