Skip to content
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

Update cancel_inverses to have better support for Adjoint #6752

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 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
3 changes: 3 additions & 0 deletions doc/releases/changelog-dev.md
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,9 @@ such as `shots`, `rng` and `prng_key`.

<h4>Other Improvements</h4>

* `qml.transforms.cancel_inverses` is now better at handling cancellation of `Adjoint` operators.
mudit2812 marked this conversation as resolved.
Show resolved Hide resolved
mudit2812 marked this conversation as resolved.
Show resolved Hide resolved
[(#6752)](https://github.com/PennyLaneAI/pennylane/pull/6752)

* `qml.math.grad` and `qml.math.jacobian` added to differentiate a function with inputs of any
interface in a jax-like manner.
[(#6741)](https://github.com/PennyLaneAI/pennylane/pull/6741)
Expand Down
96 changes: 45 additions & 51 deletions pennylane/transforms/optimization/cancel_inverses.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,11 @@


def _ops_equal(op1, op2):
"""Checks if two operators are equal up to class, data, hyperparameters, and wires"""
"""Checks if two operators are equal up to class, data, and hyperparameters"""
return (
op1.__class__ is op2.__class__
and (op1.data == op2.data)
and (op1.hyperparameters == op2.hyperparameters)
and (op1.wires == op2.wires)
)
Copy link
Contributor

Choose a reason for hiding this comment

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

Can we just use qml.equal now?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

qml.equal checks for wire equality as well, we want to compare all attributes except for wires.

Copy link
Contributor

Choose a reason for hiding this comment

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

Potentially rename this function to _non_wires_equality?

Copy link
Contributor

Choose a reason for hiding this comment

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

Should we instead update our definition of "equal" to take into consideration operations that are symmetric?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I changed the name of the function locally.

Should we instead update our definition of "equal" to take into consideration operations that are symmetric?

I feel like this is a tangential discussion to object vs numerical equality. It certainly shouldn't be hard to integrate wire symmetry into qml.equal since we already have Attributes containing a set of such ops. Maybe worth including more people in this discussion. Could be a potential "good first issue" if we decide it's worthwhile.



Expand Down Expand Up @@ -64,6 +63,45 @@ def _are_inverses(op1, op2):
return False


def _can_cancel_ops(op1, op2):
albi3ro marked this conversation as resolved.
Show resolved Hide resolved
"""Checks if two operators can be cancelled

Args:
op1 (~.Operator)
op2 (~.Operator)

Returns:
Bool
"""
if _are_inverses(op1, op2):
mudit2812 marked this conversation as resolved.
Show resolved Hide resolved
# Make sure that if one of the ops is Adjoint, it is always op2 by swapping
# the ops if op1 is Adjoint
if isinstance(op1, Adjoint):
op1, op2 = op2, op1

# If the wires are the same, then we can safely cancel both
if op1.wires == op2.wires:
return True
albi3ro marked this conversation as resolved.
Show resolved Hide resolved
# If wires are not equal, there are two things that can happen.
# 1. There is not full overlap in the wires; we cannot cancel
if len(Wires.shared_wires([op1.wires, op2.wires])) != len(op1.wires):
return False

# 2. There is full overlap, but the wires are in a different order.
# If the wires are in a different order, gates that are "symmetric"
# over all wires (e.g., CZ), can be cancelled.
if op1 in symmetric_over_all_wires:
return True
# For other gates, as long as the control wires are the same, we can still
# cancel (e.g., the Toffoli gate).
if op1 in symmetric_over_control_wires:
# TODO[David Wierichs]: This assumes single-qubit targets of controlled gates
if len(Wires.shared_wires([op1.wires[:-1], op2.wires[:-1]])) == len(op1.wires) - 1:
return True

return False


@lru_cache
def _get_plxpr_cancel_inverses(): # pylint: disable=missing-function-docstring,too-many-statements
try:
Expand Down Expand Up @@ -123,24 +161,7 @@ def interpret_operation(self, op: Operator):
self.previous_ops[w] = op
return []

cancel = False
if _are_inverses(op, prev_op):
# Same wires, cancel
if op.wires == prev_op.wires:
cancel = True
# Full overlap over wires
elif len(Wires.shared_wires([op.wires, prev_op.wires])) == len(op.wires):
# symmetric op + full wire overlap; cancel
if op in symmetric_over_all_wires:
cancel = True
# symmetric over control wires, full overlap over control wires; cancel
elif op in symmetric_over_control_wires and (
len(Wires.shared_wires([op.wires[:-1], prev_op.wires[:-1]]))
== len(op.wires) - 1
):
cancel = True
# No or partial overlap over wires; can't cancel

cancel = _can_cancel_ops(op, prev_op)
if cancel:
for w in op.wires:
self.previous_ops.pop(w)
Expand Down Expand Up @@ -353,42 +374,15 @@ def qfunc(x, y, z):
# Otherwise, get the next gate
next_gate = list_copy[next_gate_idx]

# If either of the two flags is true, we can potentially cancel the gates
if _are_inverses(current_gate, next_gate):
# If the wires are the same, then we can safely remove both
if current_gate.wires == next_gate.wires:
list_copy.pop(next_gate_idx)
continue
# If wires are not equal, there are two things that can happen.
# 1. There is not full overlap in the wires; we cannot cancel
if len(Wires.shared_wires([current_gate.wires, next_gate.wires])) != len(
current_gate.wires
):
operations.append(current_gate)
continue

# 2. There is full overlap, but the wires are in a different order.
# If the wires are in a different order, gates that are "symmetric"
# over all wires (e.g., CZ), can be cancelled.
if current_gate in symmetric_over_all_wires:
list_copy.pop(next_gate_idx)
continue
# For other gates, as long as the control wires are the same, we can still
# cancel (e.g., the Toffoli gate).
if current_gate in symmetric_over_control_wires:
# TODO[David Wierichs]: This assumes single-qubit targets of controlled gates
if (
len(Wires.shared_wires([current_gate.wires[:-1], next_gate.wires[:-1]]))
== len(current_gate.wires) - 1
):
list_copy.pop(next_gate_idx)
continue
# If operators are inverses, cancel
if _can_cancel_ops(current_gate, next_gate):
list_copy.pop(next_gate_idx)
continue
# Apply gate any cases where
# - there is no wire symmetry
# - the control wire symmetry does not apply because the control wires are not the same
# - neither of the flags are_self_inverses and are_inverses are true
operations.append(current_gate)
continue

new_tape = tape.copy(operations=operations)

Expand Down
18 changes: 12 additions & 6 deletions tests/capture/transforms/test_capture_cancel_inverses.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,15 +90,21 @@ def f():
jaxpr = jax.make_jaxpr(f)()
assert len(jaxpr.eqns) == 0

def test_cancel_inverses_symmetric_wires(self):
@pytest.mark.parametrize("adjoint_first", [True, False])
def test_cancel_inverses_symmetric_wires(self, adjoint_first):
"""Test that operations that are inverses regardless of wire order are cancelled."""

@CancelInversesInterpreter()
def f():
qml.CCZ([0, 1, 2])
qml.CCZ([2, 0, 1])

jaxpr = jax.make_jaxpr(f)()
def f(x):
if adjoint_first:
qml.adjoint(qml.MultiRZ(x, [2, 0, 1]))
qml.MultiRZ(x, [0, 1, 2])
else:
qml.MultiRZ(x, [2, 0, 1])
qml.adjoint(qml.MultiRZ(x, [0, 1, 2]))

args = (1.5,)
jaxpr = jax.make_jaxpr(f)(*args)
andrijapau marked this conversation as resolved.
Show resolved Hide resolved
assert len(jaxpr.eqns) == 0

def test_cancel_inverses_symmetric_control_wires(self):
Expand Down
20 changes: 20 additions & 0 deletions tests/transforms/test_optimization/test_cancel_inverses.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,26 @@ def qfunc():

assert len(ops) == 0

@pytest.mark.parametrize("adjoint_first", [True, False])
def test_symmetric_over_all_wires(self, adjoint_first):
"""Test that adjacent adjoint ops are cancelled due to wire symmetry."""

def qfunc(x):
if adjoint_first:
qml.adjoint(qml.MultiRZ(x, [2, 0, 1]))
qml.MultiRZ(x, [0, 1, 2])
else:
qml.MultiRZ(x, [2, 0, 1])
qml.adjoint(qml.MultiRZ(x, [0, 1, 2]))

transformed_qfunc = cancel_inverses(qfunc)

ops = qml.tape.make_qscript(transformed_qfunc)(1.5).operations

names_expected = []
wires_expected = []
compare_operation_lists(ops, names_expected, wires_expected)


# Example QNode and device for interface testing
dev = qml.device("default.qubit", wires=3)
Expand Down
Loading