Skip to content
Open
Show file tree
Hide file tree
Changes from 6 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
5 changes: 5 additions & 0 deletions doc/releases/changelog-dev.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ Release 0.46.0 (development release)
New features since last release
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

* Added a lattice-surgery decomposition for ``C(MultiX)`` with one control wire,
using three Pauli product measurements and one auxiliary qubit. It supports
dynamic bitstrings and controls on either ``0`` or ``1``.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggested change
using three Pauli product measurements and one auxiliary qubit. It supports
dynamic bitstrings and controls on either ``0`` or ``1``.
using three Pauli product measurements and one auxiliary qubit.

`(#10558) <https://github.com/PennyLaneAI/pennylane/pull/10558>`__

* A new decomposition for ``C(IsingZZ)`` in terms of ``CNOT``, ``C(RZ)``, and ``X`` gates has been added.
`(#10425) <https://github.com/PennyLaneAI/pennylane/pull/10425>`__

Expand Down
73 changes: 71 additions & 2 deletions pennylane/templates/subroutines/multix.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@
# limitations under the License.
"""Contains the MultiX template."""

from functools import partial
from math import pi

import numpy as np
from scipy import sparse

Expand All @@ -22,7 +25,9 @@
from pennylane.core.operator import Operator2
from pennylane.decomposition import add_decomps, register_condition, register_resources
from pennylane.decomposition.symbolic_decomposition import self_adjoint
from pennylane.ops import CNOT, Hadamard, PauliX, adjoint, cond
from pennylane.ops import CNOT, GlobalPhase, Hadamard, PauliX, PauliZ, adjoint, cond
from pennylane.ops.mid_measure.pauli_measure import PauliMeasure, pauli_measure
from pennylane.ops.op_math.controlled2 import _make_controlled_decomp
from pennylane.ops.op_math.controlled2 import flip_zero_control as flip_zero_control2
from pennylane.ops.op_math.pow2 import pow_involutory
from pennylane.ops.op_math.prod2 import _multi_temporary_and_all_ones
Expand Down Expand Up @@ -86,6 +91,10 @@ class MultiX(Operator2):
:image: /_static/decomposition_thumbnails/multix_conditional_x.svg

:class:`~.X` | :math:`\sum_i b_i \leq n` (one per :math:`b_i=1`) | 2

Single-control ``C(MultiX)`` supports a lattice-surgery decomposition using three

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Can you add a regular entry to the table instead? :)

:func:`~.pauli_measure` operations and one consumed auxiliary qubit. Both control
values are supported; traced bitstrings require numeric target wire labels.
"""

dynamic_argnames = ("bitstring",)
Expand Down Expand Up @@ -442,4 +451,64 @@ def _controlled_multix_ladder(base, control_wires, work_wires, work_wire_type, *
_multix_ladder_fanout(base, control_wires, work_wires=available + list(allocated))


add_decomps("C(MultiX)", flip_zero_control2(_controlled_multix_ladder))
# Keep the existing unitary fallback ahead of the PPM alternative.
_controlled_multix = _make_controlled_decomp(_multix_decomposition)
_controlled_multix.name = "_controlled_multix"
_controlled_multix.add_condition(lambda control_wires, **_: len(control_wires) == 1)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This may look strange but the reason of adding this is that if my C(MultiX) decomposition is the only decomposition added, it was always taking it and measurements always appears in not supported devices.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Ah this is interesting! Can you ask core if this is the preferred way of doing this? Might be good to let them know that we hit this scenario :)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

asked in #pennylane-core and they are fine with this provisional approach ✅

add_decomps("C(MultiX)", flip_zero_control2(_controlled_multix_ladder), _controlled_multix)


def _measure_z_multix(work_wire, bitstring, wires):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

We have this logic in the recently fixed QROM PPM rule, right? :) Maybe we can reuse it. But just an optional suggestion.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes, I used the same idea as QROM. I kept the helper separate for now because QROM already imports MultiX, but we could combine them later

"""Measure Z on a work wire jointly with X on the targets selected by the bitstring."""
if not math.is_tracer(bitstring):
targets = [wire for wire, bit in zip(wires, bitstring) if bit]
return pauli_measure("Z" + "X" * len(targets), [work_wire, *targets])

# Each branch has a fixed measurement width, with selected targets grouped first.
selected = math.array(wires, like="jax")[math.argsort(math.logical_not(bitstring))]
weight = math.sum(bitstring)
measurement = partial(pauli_measure, "Z", [work_wire])
for width in range(1, len(bitstring) + 1):
measurement = cond(
weight == width,
partial(pauli_measure, "Z" + "X" * width, [work_wire, *selected[:width]]),
measurement,
)
return measurement()


def _controlled_multix_lattice_surgery_ppm_resources(base, *_, **__):
resources = {
PauliMeasure("Z" + "X" * width, wires=Wire[width + 1]): 1
for width in range(len(base.wires) + 1)
}
resources[PauliMeasure("ZX", wires=Wire[2])] += 1
resources[PauliMeasure("X", wires=Wire[1])] = 1
resources[PauliX] = 2
resources[PauliZ] = 2
resources[base] = 1
resources[GlobalPhase] = 1
return resources


@register_condition(lambda control_wires, **_: len(control_wires) == 1)
@register_resources(
_controlled_multix_lattice_surgery_ppm_resources,
work_wires={"burnable": 1},
exact=False,
)
def _controlled_multix_lattice_surgery_ppm(base, control_wires, control_values, **_):
"""Implement a single-control MultiX with three PPMs and one consumed auxiliary qubit."""
cond(math.logical_not(control_values[0]), PauliX)(control_wires[0])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Could use the flip_zero_control2 wrapper here.

with allocate(1, state="zero", restored=False) as work_wires:
m0 = pauli_measure("ZX", [control_wires[0], work_wires[0]])
m1 = _measure_z_multix(work_wires[0], base.bitstring, base.wires)
m2 = pauli_measure("X", work_wires)
cond(m1, PauliZ)(control_wires[0])
cond(m0 != m2, MultiX)(base.bitstring, wires=base.wires)
cond(m1 & (m0 != m2), GlobalPhase)(pi)
cond(m2, PauliZ)(work_wires[0]) # Leave the auxiliary qubit in |+>.
cond(math.logical_not(control_values[0]), PauliX)(control_wires[0])


add_decomps("C(MultiX)", _controlled_multix_lattice_surgery_ppm)
109 changes: 109 additions & 0 deletions tests/templates/subroutines/test_multix.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,15 @@
# limitations under the License.
"""Tests for the MultiX template."""

from itertools import product

import numpy as np
import pytest
from scipy import sparse

import pennylane as qp
from pennylane.testing import assert_decomposable
from pennylane.transforms import _tape_decompose
from pennylane.typing import AbstractArray, AbstractWires, Bool, Float, Int, Wire
from pennylane.wires import Wires

Expand Down Expand Up @@ -421,6 +424,15 @@ def test_controlled_decomposition_capture_compatibility(self):

assert_decomposable(op)

@pytest.mark.usefixtures("enable_and_disable_graph_decomp")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

graph is enabled by default now, and I think it's okay to not test without :)

Suggested change
@pytest.mark.usefixtures("enable_and_disable_graph_decomp")

@pytest.mark.parametrize("control_value", [0, 1])
@pytest.mark.parametrize("bitstring", [[0, 0, 0], [1, 0, 1]])
def test_controlled_default_decomposition(self, bitstring, control_value):
"""The default decomposition remains unitary without auxiliary wires."""
op = qp.ctrl(qp.MultiX(bitstring, wires=[1, 2, 3]), 0, [control_value])
tape = qp.tape.QuantumScript(op.decomposition())
assert np.allclose(qp.matrix(tape, wire_order=op.wires), op.matrix())

@pytest.mark.usefixtures("enable_graph_decomposition")
@pytest.mark.parametrize(
("control_values", "gate_set", "expected"),
Expand Down Expand Up @@ -558,6 +570,103 @@ def test_multix_ladder_fanout_uses_for_loop_with_static_wires(self):
assert any(eqn.primitive == for_loop_prim for eqn in jaxpr.eqns)


class TestControlledMultiXLatticeSurgeryPPM:
"""Tests for the single-control MultiX decomposition using three Pauli measurements."""

@pytest.mark.usefixtures("enable_and_disable_capture")
@pytest.mark.parametrize("num_controls", [1, 2])
@pytest.mark.parametrize("control_value", [0, 1])
@pytest.mark.parametrize("bitstring", [[0], [1], [0, 0, 0], [1, 0, 1], [1, 1, 1]])
def test_resources(self, num_controls, control_value, bitstring):
"""The capture-compatible rule requires one control and one burnable wire."""
op = qp.ctrl(
qp.MultiX(bitstring, wires=range(2, 2 + len(bitstring))),
range(num_controls),
[control_value] * num_controls,
)
rule = qp.list_decomps(op)["_controlled_multix_lattice_surgery_ppm"]
assert rule.is_applicable(**op.arguments) == (num_controls == 1)
qp.testing.assert_valid_decomp_rule(op, rule)
work_wires = rule.get_work_wire_spec(**op.arguments)
assert work_wires.burnable == work_wires.total == 1

@pytest.mark.usefixtures("enable_graph_decomposition")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This is no longer needed as of very recently :)

Suggested change
@pytest.mark.usefixtures("enable_graph_decomposition")

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

the test fails without this fixture 🤔

@pytest.mark.parametrize("num_work_wires", [0, 1])
def test_graph_decomposition(self, num_work_wires):
"""The graph selects three PPMs with an auxiliary, or the CNOT fallback without one."""
op = qp.ctrl(qp.MultiX([1, 0, 1], wires=[1, 2, 3]), control=0)
gate_set = {qp.ops.PauliMeasure, qp.PauliZ, qp.PauliX, qp.GlobalPhase}
if num_work_wires == 0:
gate_set.add(qp.CNOT)
(decomposed,), _ = _tape_decompose(
qp.tape.QuantumScript([op]), gate_set=gate_set, num_work_wires=num_work_wires
)
names = [gate.name for gate in decomposed.operations]
assert names.count("PauliMeasure") == 3 * num_work_wires
assert names.count("CNOT") == 2 * (1 - num_work_wires)

@pytest.mark.parametrize("control_value", [0, 1])
@pytest.mark.parametrize("bitstring", [[0], [1], [0, 0, 0], [1, 0, 1], [1, 1, 1]])
@pytest.mark.parametrize("outcomes", list(product([0, 1], repeat=3)))
def test_all_measurement_branches(self, bitstring, control_value, outcomes, mocker):
"""Every branch has the correct map, phase, probability, and final auxiliary state."""
num_wires = len(bitstring) + 1
op = qp.ctrl(qp.MultiX(bitstring, wires=range(1, num_wires)), 0, [control_value])
rule = qp.list_decomps(op)["_controlled_multix_lattice_surgery_ppm"]
outcomes = iter(outcomes)

# Catalyst does not preserve pauli_measure's postselect argument under capture.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Is this a bug we should report? Are we using postselect? 🤔

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

We’re not using postselect here. The test uses projectors to check all possible measurement outcomes, so I’ve updated the comment to explain that

def measure_branch(word, wires):
outcome = next(outcomes)
with qp.QueuingManager.stop_recording():
observable = qp.matrix(qp.pauli.string_to_pauli_word(word))
projector = (qp.math.eye(len(observable)) + (-1) ** outcome * observable) / 2
qp.Hermitian(projector, wires=wires)
return outcome

mocker.patch(
"pennylane.templates.subroutines.multix.pauli_measure",
new=measure_branch,
)
tape = qp.tape.make_qscript(rule)(**op.arguments)
(tape,), _ = qp.transforms.resolve_dynamic_wires(tape, zeroed=[num_wires])

# Select every data input with the auxiliary initially in |0>.
actual = qp.matrix(tape, wire_order=range(num_wires + 1))[:, ::2]
# Each branch has probability 1/8 and leaves the auxiliary in |+>.
expected = qp.math.kron(op.matrix(), qp.math.array([[1], [1]]) / 4)
assert qp.math.allclose(actual, expected)

@pytest.mark.catalyst
def test_qjit_runtime_bitstring_and_control_value(self, seed):
"""One compiled circuit accepts different target masks and control values at runtime."""
pytest.importorskip("catalyst")
rule = qp.list_decomps("C(MultiX)")["_controlled_multix_lattice_surgery_ppm"]
rng = np.random.default_rng(seed)
initial_state = rng.random(16) + 1j * rng.random(16)
initial_state /= np.linalg.norm(initial_state)

@qp.qjit(capture=True)
@qp.qnode(qp.device("lightning.qubit", wires=5))
def circuit(bitstring, control_values):
qp.StatePrep(initial_state, wires=[0, 1, 2, 3])
# Construct the rule argument without applying another MultiX.
with qp.capture.pause():
base = qp.MultiX(bitstring, wires=[1, 2, 3])
rule(base=base, control_wires=[0], control_values=control_values)
return qp.state()

for bitstring, control_value in product(
[[0, 0, 0], [1, 0, 1], [0, 1, 0], [1, 1, 1]], [0, 1]
):
op = qp.ctrl(qp.MultiX(bitstring, wires=[1, 2, 3]), 0, [control_value])
# Catalyst resets the released auxiliary before returning the full state.
expected = np.kron(op.matrix() @ initial_state, np.array([1, 0]))
result = circuit(np.array(bitstring, dtype=bool), np.array([control_value], dtype=bool))

assert np.allclose(result, expected)


class TestExecution:
"""Tests execution on PennyLane devices and compilation interfaces."""

Expand Down
Loading