Skip to content

[Python Compiler] Prototype for the merge_rotations transform implemented with xDSL #7364

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 41 commits into from
May 29, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
d732767
Porting files from Catalyst PR
PietropaoloFrisoni Apr 30, 2025
6b5fbe8
Triggering CI
PietropaoloFrisoni Apr 30, 2025
744d40c
Moving `xdsl` package from requirements to requirements CI
PietropaoloFrisoni Apr 30, 2025
abb7182
isort
PietropaoloFrisoni Apr 30, 2025
faf0c06
Add deep_cancel_inverses xDSL transform
mudit2812 Apr 30, 2025
4029d83
Merge branch 'master' into xdsl-cancel-inverses
mudit2812 May 9, 2025
c0f57e1
Temporary upadte to tach.toml
mudit2812 May 9, 2025
97cebc3
Update cancel_inverses to work with multi-wire gates
mudit2812 May 9, 2025
bfedbd8
Remove xdsl from requirements-ci.txt
mudit2812 May 9, 2025
7058372
Revert tach.toml
mudit2812 May 9, 2025
20a8fba
Update license
mudit2812 May 9, 2025
fd06601
Accommodate for control values
mudit2812 May 16, 2025
b37766e
Merge branch 'master' into xdsl-cancel-inverses
mudit2812 May 20, 2025
9b96c43
Add constructors for `CustomOp` and `ExtractOp`
mudit2812 May 21, 2025
83338fc
Address code review; Add constructor for `AdjointOp`
mudit2812 May 21, 2025
5ce4f2b
Add constructors for more key operations
mudit2812 May 22, 2025
66c11d6
Add `MeasureOp.verify_`
mudit2812 May 22, 2025
3e86562
Add verification for `AllocOp`
mudit2812 May 22, 2025
1c031a8
Fix verify_ methods
mudit2812 May 23, 2025
7a34fba
Fix type hints
mudit2812 May 23, 2025
127e43c
Add changelog
mudit2812 May 23, 2025
57527a7
Merge branch 'master' into xdsl-quantum-init
mudit2812 May 23, 2025
93e0fdf
Pylint
mudit2812 May 22, 2025
359851a
[skip ci] Skip CI
mudit2812 May 22, 2025
955d133
Move cancel_inverses to transforms submodule
mudit2812 May 23, 2025
c1d0e66
E.C.
PietropaoloFrisoni May 1, 2025
6818101
Skeleton of implementation
PietropaoloFrisoni May 1, 2025
802c9b4
E.C.
PietropaoloFrisoni May 1, 2025
5afa328
Add implementation for merge rotations
mudit2812 May 9, 2025
f499cc5
Move transform
mudit2812 May 23, 2025
dd20dde
Add support for checking control values
mudit2812 May 23, 2025
0c63388
Remove dep on qml.ops
mudit2812 May 23, 2025
eb43808
Add changelog
mudit2812 May 23, 2025
0c3b39c
Update changelog
mudit2812 May 23, 2025
8f9af15
Use new CustomOp constructor
mudit2812 May 23, 2025
02389e3
Merge branch 'master' into merge_rotations_prototype
mudit2812 May 28, 2025
3c94a1f
Remove usage of deprecated code
mudit2812 May 28, 2025
ba68a21
Merge branch 'master' into merge_rotations_prototype
mudit2812 May 28, 2025
ada6141
Merge branch 'master' into merge_rotations_prototype
mudit2812 May 28, 2025
c2a5781
Merge branch 'master' into merge_rotations_prototype
mudit2812 May 29, 2025
775537b
Merge branch 'master' into merge_rotations_prototype
mudit2812 May 29, 2025
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
12 changes: 8 additions & 4 deletions doc/releases/changelog-dev.md
Original file line number Diff line number Diff line change
Expand Up @@ -311,10 +311,14 @@
that contains fewer gates than the previous decomposition.
[(#7370)](https://github.com/PennyLaneAI/pennylane/pull/7370)

* A transform for applying `cancel_inverses` has been added that can be used with the experimental
xDSL Python compiler integration. This transform is optimized to cancel self-inverse operations
iteratively to cancel nested self-inverse operations.
[(#7363)](https://github.com/PennyLaneAI/pennylane/pull/7363)
* An xDSL `qml.compiler.python_compiler.transforms.MergeRotationsPass` pass for applying `merge_rotations` to an
xDSL module has been added for the experimental xDSL Python compiler integration.
[(#7364)](https://github.com/PennyLaneAI/pennylane/pull/7364)

* An xDSL `qml.compiler.python_compiler.transforms.IterativeCancelInversesPass` pass for applying `cancel_inverses`
iteratively to an xDSL module has been added for the experimental xDSL Python compiler integration. This pass is
optimized to cancel self-inverse operations iteratively to cancel nested self-inverse operations.
[(#7364)](https://github.com/PennyLaneAI/pennylane/pull/7364)

* An experimental integration for a Python compiler using [xDSL](https://xdsl.dev/index) has been introduced.
This is similar to [Catalyst's MLIR dialects](https://docs.pennylane.ai/projects/catalyst/en/stable/dev/dialects.html#mlir-dialects-in-catalyst),
Expand Down
2 changes: 2 additions & 0 deletions pennylane/compiler/python_compiler/transforms/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,13 @@
from xdsl.transforms.transform_interpreter import TransformInterpreterPass
from .apply_transform_sequence import ApplyTransformSequence, register_pass
from .cancel_inverses import IterativeCancelInversesPass
from .merge_rotations import MergeRotationsPass


__all__ = [
"ApplyTransformSequence",
"IterativeCancelInversesPass",
"MergeRotationsPass",
"TransformInterpreterPass",
"register_pass",
]
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ class IterativeCancelInversesPass(passes.ModulePass):
name = "iterative-cancel-inverses"

# pylint: disable=arguments-renamed,no-self-use
def apply(self, _ctx: context.MLContext, module: builtin.ModuleOp) -> None:
def apply(self, _ctx: context.Context, module: builtin.ModuleOp) -> None:
"""Apply the iterative cancel inverses pass."""
pattern_rewriter.PatternRewriteWalker(
pattern_rewriter.GreedyRewritePatternApplier([IterativeCancelInversesPattern()])
Expand Down
120 changes: 120 additions & 0 deletions pennylane/compiler/python_compiler/transforms/merge_rotations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
# Copyright 2018-2025 Xanadu Quantum Technologies Inc.

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

# http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""This file contains the implementation of the merge_rotations transform,
written using xDSL."""

from dataclasses import dataclass

from xdsl import context, passes, pattern_rewriter
from xdsl.dialects import arith, builtin, func
from xdsl.ir import Operation
from xdsl.rewriter import InsertPoint

from ..quantum_dialect import CustomOp

# Can handle all composible rotations except Rot... for now
composable_rotations = [
"RX",
"RY",
"RZ",
"PhaseShift",
"CRX",
"CRY",
"CRZ",
"ControlledPhaseShift",
"IsingXX",
"IsingYY",
"IsingZZ",
]


def _can_merge(op: CustomOp, next_op: Operation) -> bool:
if isinstance(next_op, CustomOp):
if op.gate_name.data == next_op.gate_name.data:
if op.out_qubits == next_op.in_qubits and op.out_ctrl_qubits == next_op.in_ctrl_qubits:
for v1, v2 in zip(op.in_ctrl_values, next_op.in_ctrl_values, strict=True):
if v1.data != v2.data:
return False
return True

return False


class MergeRotationsPattern(
pattern_rewriter.RewritePattern
): # pylint: disable=too-few-public-methods
"""RewritePattern for merging consecutive composable rotations."""

# pylint: disable=no-self-use
@pattern_rewriter.op_type_rewrite_pattern
def match_and_rewrite(
self, funcOp: func.FuncOp, rewriter: pattern_rewriter.PatternRewriter
): # pylint: disable=arguments-differ
"""Implementation of rewriting FuncOps that may contain operations corresponding to
consecutive composable rotations."""
for op in funcOp.body.walk():
if not isinstance(op, CustomOp):
continue

gate_name = op.gate_name.data
if gate_name not in composable_rotations:
continue

param = op.operands[0]
while True:
next_user = None
for use in op.results[0].uses:
user = use.operation
if _can_merge(op, user):
next_user = user
break

if next_user is None:
break

for q1, q2 in zip(op.in_qubits, op.out_qubits, strict=True):
rewriter.replace_all_uses_with(q2, q1)
for cq1, cq2 in zip(op.in_ctrl_qubits, op.out_ctrl_qubits, strict=True):
rewriter.replace_all_uses_with(cq2, cq1)

rewriter.erase_op(op)
next_param = next_user.operands[0]
addOp = arith.AddfOp(param, next_param)
rewriter.insert_op(addOp, InsertPoint.before(next_user))
param = addOp.result
new_op = CustomOp(
in_qubits=next_user.in_qubits,
gate_name=next_user.gate_name,
params=(param,),
in_ctrl_qubits=next_user.in_ctrl_qubits,
in_ctrl_values=next_user.in_ctrl_values,
adjoint=getattr(next_user, "adjoint", False),
)
rewriter.replace_op(next_user, new_op)
op = new_op


@dataclass(frozen=True)
class MergeRotationsPass(passes.ModulePass):
"""Pass for merging consecutive composable rotation gates."""

name = "merge-rotations"

# pylint: disable=arguments-renamed,no-self-use
def apply(self, _ctx: context.Context, module: builtin.ModuleOp) -> None:
"""Apply the merge rotations pass."""
pattern_rewriter.PatternRewriteWalker(
pattern_rewriter.GreedyRewritePatternApplier([MergeRotationsPattern()])
).rewrite_module(module)