Skip to content

[IR] Improve pass infra #2120

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 21 commits into from
Mar 26, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions onnxscript/ir/passes/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
"PassBase",
"PassResult",
"PassManager",
"Sequential",
"InPlacePass",
"FunctionalPass",
# Errors
"InvariantError",
"PreconditionError",
Expand All @@ -13,13 +16,16 @@
]

from onnxscript.ir.passes._pass_infra import (
FunctionalPass,
InPlacePass,
InvariantError,
PassBase,
PassError,
PassManager,
PassResult,
PostconditionError,
PreconditionError,
Sequential,
)


Expand Down
192 changes: 141 additions & 51 deletions onnxscript/ir/passes/_pass_infra.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@

__all__ = [
"PassBase",
"Sequential",
"InPlacePass",
"FunctionalPass",
"PassManager",
"PassResult",
# Errors
Expand Down Expand Up @@ -68,14 +71,72 @@
class PassBase(abc.ABC):
"""Base class for all passes.

Class attributes:
in_place: Whether the pass modifies the model in place.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is it possible to add a paragraph in the documentation of the exporter (torch.onnx.export) to mention the list of passes applied to the fx graph?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure!

``in_place`` and ``changes_input`` properties and what they mean:

+------------+------------------+----------------------------+
| | changes_inputs | not changes_inputs |
+------------+------------------+----------------------------+
| in_place | in place | Side-effect-only pass |
+------------+------------------+----------------------------+
| not | destructive | functional |
| in_place | | |
+------------+------------------+----------------------------+
"""

in_place: bool = True
@property
@abc.abstractmethod
def in_place(self) -> bool:
"""Whether the pass modifies the model in place and returns it.

If True, the pass will return the same model object that was passed in.
If False, the pass will return a new model object.
"""
raise NotImplementedError

Check warning on line 95 in onnxscript/ir/passes/_pass_infra.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/passes/_pass_infra.py#L95

Added line #L95 was not covered by tests

@property
@abc.abstractmethod
def changes_input(self) -> bool:
"""Whether the pass modifies input model."""
raise NotImplementedError

Check warning on line 101 in onnxscript/ir/passes/_pass_infra.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/passes/_pass_infra.py#L101

Added line #L101 was not covered by tests

@property
def destructive(self) -> bool:
"""Whether the pass will destroy the input model when ``in_place=False``.

A pass is destructive if it is not in place and it modifies the input model.
"""
return not self.in_place and self.changes_input

Check warning on line 109 in onnxscript/ir/passes/_pass_infra.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/passes/_pass_infra.py#L109

Added line #L109 was not covered by tests

def __call__(self, model: ir.Model) -> PassResult:
return self.call(model)
# Check preconditions
try:
self.requires(model)
except PreconditionError:
raise
except Exception as e:
raise PreconditionError(

Check warning on line 118 in onnxscript/ir/passes/_pass_infra.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/passes/_pass_infra.py#L115-L118

Added lines #L115 - L118 were not covered by tests
f"Pre-condition for pass '{self.__class__.__name__}' failed"
) from e

result = self.call(model)

# Check postconditions
try:
self.ensures(model)
except PostconditionError:
raise
except Exception as e:
raise PostconditionError(

Check warning on line 130 in onnxscript/ir/passes/_pass_infra.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/passes/_pass_infra.py#L127-L130

Added lines #L127 - L130 were not covered by tests
f"Post-condition for pass '{self.__class__.__name__}' failed"
) from e

if not isinstance(result, PassResult):
raise TypeError(

Check warning on line 135 in onnxscript/ir/passes/_pass_infra.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/passes/_pass_infra.py#L135

Added line #L135 was not covered by tests
f"The result of the pass '{self.__class__.__name__}' should be type PassResult. "
"Please create one with ir.passes.PassResult()."
)
return result

@abc.abstractmethod
def call(self, model: ir.Model) -> PassResult:
Expand All @@ -97,76 +158,105 @@
del model # Unused


class PassManager:
class InPlacePass(PassBase):
"""A pass that modifies the input model in place and returns it."""

@property
def in_place(self) -> bool:
return True

Check warning on line 166 in onnxscript/ir/passes/_pass_infra.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/passes/_pass_infra.py#L166

Added line #L166 was not covered by tests

@property
def changes_input(self) -> bool:
return True

Check warning on line 170 in onnxscript/ir/passes/_pass_infra.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/passes/_pass_infra.py#L170

Added line #L170 was not covered by tests


class FunctionalPass(PassBase):
"""A pass that returns a new model but does not modify the input model."""

@property
def in_place(self) -> bool:
return False

Check warning on line 178 in onnxscript/ir/passes/_pass_infra.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/passes/_pass_infra.py#L178

Added line #L178 was not covered by tests

@property
def changes_input(self) -> bool:
return False

Check warning on line 182 in onnxscript/ir/passes/_pass_infra.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/passes/_pass_infra.py#L182

Added line #L182 was not covered by tests


class Sequential(PassBase):
"""Run a sequence of passes in order."""

def __init__(self, *passes: PassBase):
if not passes:
raise ValueError("Sequential must take at least one pass")
self.passes = passes
self._in_place = all(pass_.in_place for pass_ in passes)

Check warning on line 192 in onnxscript/ir/passes/_pass_infra.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/passes/_pass_infra.py#L190-L192

Added lines #L190 - L192 were not covered by tests
# The reason changes_inputs is decided by the first pass is that if the first pass is either in-place,
# or if it is not designed to be in-place but somehow changes the input (destructive),
# this pass sequence will change inputs.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I mean would second or other passes that changes inputs after the first pass?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the first pass is functional, the second pass will take the new model that the first pass returns, which means the second pass has no chance to affect the input model.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But if the first pass is side-effect only pass. Shouldn't we check the following passes?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point. In that case we just assume it changes the model for now. I think that's ok?

self._changes_input = self.passes[0].changes_input or self.passes[0].in_place

Check warning on line 196 in onnxscript/ir/passes/_pass_infra.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/passes/_pass_infra.py#L196

Added line #L196 was not covered by tests

@property
def in_place(self) -> bool:
return self._in_place

Check warning on line 200 in onnxscript/ir/passes/_pass_infra.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/passes/_pass_infra.py#L200

Added line #L200 was not covered by tests

@property
def changes_input(self) -> bool:
return self._changes_input

Check warning on line 204 in onnxscript/ir/passes/_pass_infra.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/passes/_pass_infra.py#L204

Added line #L204 was not covered by tests

def call(self, model: ir.Model) -> PassResult:
modified = False

Check warning on line 207 in onnxscript/ir/passes/_pass_infra.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/passes/_pass_infra.py#L207

Added line #L207 was not covered by tests
for i, pass_ in enumerate(self.passes):
logger.debug("Running the %s-th pass '%s'", i, pass_)
try:
pass_result = pass_(model)
except Exception as e:
prev_pass_names = [str(p) for p in self.passes[:i]]
raise PassError(

Check warning on line 214 in onnxscript/ir/passes/_pass_infra.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/passes/_pass_infra.py#L209-L214

Added lines #L209 - L214 were not covered by tests
f"An error occurred when running the '{pass_}' pass after the "
f"following passes: {prev_pass_names}"
) from e

model = pass_result.model
modified = modified or pass_result.modified

Check warning on line 220 in onnxscript/ir/passes/_pass_infra.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/passes/_pass_infra.py#L219-L220

Added lines #L219 - L220 were not covered by tests

return PassResult(model, modified)

Check warning on line 222 in onnxscript/ir/passes/_pass_infra.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/passes/_pass_infra.py#L222

Added line #L222 was not covered by tests


class PassManager(Sequential):
"""Pass manager for the IR.

The PassManager is a callable that runs a sequence of passes on a model.
The PassManager is a Pass that runs a sequence of passes on a model.

Attributes:
passes: The passes to run.
check_invariants: Whether to check invariants before and after each pass.
steps: The number of times to run the passes.
early_stop: Whether to stop running the passes if the graph stops changing.
"""

def __init__(
self,
passes: Sequence[PassBase],
check_invariants: bool = False,
steps: int = 1,
early_stop: bool = True,
):
# TODO(justinchuby): Implement constraints
self.passes = list(passes)
self.check_invariants = check_invariants
super().__init__(*passes)

Check warning on line 243 in onnxscript/ir/passes/_pass_infra.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/passes/_pass_infra.py#L243

Added line #L243 was not covered by tests
self.steps = steps
self.early_stop = early_stop

Check warning on line 245 in onnxscript/ir/passes/_pass_infra.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/passes/_pass_infra.py#L245

Added line #L245 was not covered by tests

def __call__(self, model: ir.Model) -> PassResult:
def call(self, model: ir.Model) -> PassResult:
"""Run the set of passes `steps` number of times or until the graph stops changing."""
overall_modified = False
for step in range(self.steps):
step_result = self._run_one_step(model, step)
try:
step_result = super().__call__(model)
except Exception as e:
raise PassError(f"An error occurred at step {step}") from e

Check warning on line 254 in onnxscript/ir/passes/_pass_infra.py

View check run for this annotation

Codecov / codecov/patch

onnxscript/ir/passes/_pass_infra.py#L251-L254

Added lines #L251 - L254 were not covered by tests
model = step_result.model
modified = step_result.modified
overall_modified = overall_modified or modified
# If the graph no longer changes, then we can stop running these passes
if not modified:
if not modified and self.early_stop:
logger.info("PassManager: No more graph changes detected after step %s", step)
break
return PassResult(model, overall_modified)

def _run_one_step(self, model: ir.Model, step: int) -> PassResult:
modified = False
for i, pass_ in enumerate(self.passes):
logger.debug("Running the %s-th pass '%s', (step %s)", i, pass_, step)

# 1. Check preconditions
if self.check_invariants:
try:
pass_.requires(model)
except Exception as e:
raise PreconditionError(f"Pre-condition failed for {pass_}") from e

# 2. Run the pass
try:
pass_result = pass_(model)
except Exception as e:
prev_pass_names = [str(p) for p in self.passes[:i]]
raise PassError(
f"An error occurred when running the '{pass_}' pass after the "
f"following passes: {prev_pass_names} during step {step}"
) from e
if not isinstance(pass_result, PassResult):
raise TypeError(
f"The result of the pass {pass_} should be type PassResult."
"Please create one with ir.passes.PassResult()."
)

model = pass_result.model
modified = modified or pass_result.modified

# 3. Check postconditions
if self.check_invariants:
try:
pass_.ensures(model)
except Exception as e:
raise PostconditionError(f"Post-condition failed for {pass_}") from e
return PassResult(model, modified)
5 changes: 1 addition & 4 deletions onnxscript/ir/passes/common/shape_inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,9 @@
_BIG_TENSOR_SIZE_LIMIT = 1000 # 1KB


class ShapeInferencePass(ir.passes.PassBase):
class ShapeInferencePass(ir.passes.FunctionalPass):
"""This pass performs shape inference on the graph."""

# This pass does not modify the model in place.
in_place = False

def __init__(
self, check_type: bool = True, strict_mode: bool = True, data_prop: bool = True
) -> None:
Expand Down
2 changes: 1 addition & 1 deletion onnxscript/optimizer/_constant_folding.py
Original file line number Diff line number Diff line change
Expand Up @@ -797,7 +797,7 @@ def merge_dims(dim1, dim2):
return ir.Shape([merge_dims(dim1, dim2) for dim1, dim2 in zip(shape1, shape2)])


class FoldConstantsPass(ir.passes.PassBase):
class FoldConstantsPass(ir.passes.InPlacePass):
def __init__(
self,
*,
Expand Down
2 changes: 1 addition & 1 deletion onnxscript/optimizer/_remove_unused.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def _process_function_or_graph(function_or_graph: ir.Function | ir.Graph) -> int
return count


class RemoveUnusedNodesPass(ir.passes.PassBase):
class RemoveUnusedNodesPass(ir.passes.InPlacePass):
def call(self, model: ir.Model) -> ir.passes.PassResult:
count = _process_function_or_graph(model.graph)
graph_outputs = frozenset(model.graph.outputs)
Expand Down
2 changes: 1 addition & 1 deletion onnxscript/optimizer/_remove_unused_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def _clean_up_unused_functions(model: ir.Model, unused: set[ir.OperatorIdentifie
logger.debug("Functions removed: %s", unused)


class RemoveUnusedFunctionPass(ir.passes.PassBase):
class RemoveUnusedFunctionPass(ir.passes.InPlacePass):
def __init__(self):
super().__init__()
self.used: set[ir.OperatorIdentifier] | None = None
Expand Down
Loading