Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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.

`(#XXXX) <https://github.com/PennyLaneAI/pennylane/pull/XXXX>`__
Comment thread
KetpuntoG marked this conversation as resolved.
Resolved

* 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
77 changes: 76 additions & 1 deletion 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,8 @@
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 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 +90,15 @@ 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

With one control wire, ``C(MultiX)`` also has a lattice-surgery decomposition
using three :func:`~.pauli_measure` operations and one auxiliary qubit initialized
in :math:`|0\rangle` and consumed in :math:`|+\rangle`. The measurements are
:math:`Z_c X_a`, :math:`Z_a \bigotimes_i X_i^{b_i}`, and :math:`X_a`, followed
by conditional Pauli and global-phase corrections. Both control values and
dynamically supplied bitstrings are supported; traced bitstrings require
numeric target wire labels. Resource estimates include each possible width
of the second measurement, although only one is executed.
"""

dynamic_argnames = ("bitstring",)
Expand Down Expand Up @@ -443,3 +456,65 @@ def _controlled_multix_ladder(base, control_wires, work_wires, work_wire_type, *


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


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])

# PauliMeasure requires a static word and number of wires. Group selected targets
# first, then choose a measurement of fixed width, as in QROM's masked measurement.
selected = math.array(wires, like="jax")[math.argsort(math.logical_not(bitstring))]
weight = math.sum(bitstring)
num_targets = len(bitstring)

def measure_width(width):
return pauli_measure("Z" + "X" * width, [work_wire, *selected[:width]])

return cond(
weight == 0,
partial(measure_width, 0),
partial(measure_width, num_targets),
elifs=tuple(
(weight == width, partial(measure_width, width)) for width in range(1, num_targets)
),
)()


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)
168 changes: 168 additions & 0 deletions tests/templates/subroutines/test_multix.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,17 @@
# limitations under the License.
"""Tests for the MultiX template."""

from collections import Counter
from itertools import product

import numpy as np
import pytest
from scipy import sparse

import pennylane as qp
from pennylane.core.operator import abstractify
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 @@ -558,6 +563,169 @@ 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.parametrize("num_controls", [1, 2, 3])
def test_applicability(self, num_controls):
"""The PPM rule supports exactly one control wire."""
op = qp.ctrl(qp.MultiX([1, 0, 1], wires=[3, 4, 5]), control=range(num_controls))
rule = qp.list_decomps(op)["_controlled_multix_lattice_surgery_ppm"]

assert rule.is_applicable(**op.arguments) == (num_controls == 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 🤔

def test_graph_decomposition(self):
"""A PPM gate set selects the three-measurement rule when a work wire is available."""
op = qp.ctrl(qp.MultiX([1, 0, 1], wires=[1, 2, 3]), control=0)
tape = qp.tape.QuantumScript([op])

(decomposed,), _ = _tape_decompose(
tape,
gate_set={qp.ops.PauliMeasure, qp.PauliZ, qp.PauliX, qp.GlobalPhase},
num_work_wires=1,
)
measurements = [
gate for gate in decomposed.operations if isinstance(gate, qp.ops.PauliMeasure)
]

assert [measurement.pauli_word for measurement in measurements] == ["ZX", "ZXX", "X"]

@pytest.mark.usefixtures("enable_graph_decomposition")
def test_graph_decomposition_without_work_wire(self):
"""The CNOT fanout remains available when there is no auxiliary wire."""
op = qp.ctrl(qp.MultiX([1, 0, 1], wires=[1, 2, 3]), control=0)
tape = qp.tape.QuantumScript([op])

(decomposed,), _ = _tape_decompose(
tape,
gate_set={qp.CNOT, qp.ops.PauliMeasure, qp.PauliZ, qp.PauliX, qp.GlobalPhase},
num_work_wires=0,
)

assert decomposed.operations == [qp.CNOT([0, 1]), qp.CNOT([0, 3])]

@pytest.mark.usefixtures("enable_and_disable_capture")
@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, bitstring, control_value):
"""Resource bounds cover the captured rule and require one burnable work wire."""
op = qp.ctrl(
qp.MultiX(bitstring, wires=range(1, len(bitstring) + 1)),
control=0,
control_values=[control_value],
)
rule = qp.list_decomps(op)["_controlled_multix_lattice_surgery_ppm"]

qp.testing.assert_valid_decomp_rule(op, rule)
work_wires = rule.get_work_wire_spec(**op.arguments)
assert work_wires.burnable == 1
assert work_wires.total == 1

estimates = rule.compute_resources(**abstractify(op).arguments).gate_counts
tape = qp.testing.decomp_rule_to_tape(op, rule)
with qp.capture.pause():
(tape,), _ = qp.transforms.resolve_dynamic_wires(tape, zeroed=[len(op.wires)])
actual = Counter(
abstractify(gate.base if isinstance(gate, qp.ops.Conditional) else gate)
for gate in tape.operations
)
assert all(count <= estimates[gate] for gate, count in actual.items())

@pytest.mark.usefixtures("enable_and_disable_capture")
@pytest.mark.parametrize("control_value", [0, 1])
@pytest.mark.parametrize("bitstring", [[0], [1], [0, 0, 0], [1, 0, 1], [1, 1, 1]])
def test_all_measurement_branches(self, bitstring, control_value):
"""Every branch implements controlled MultiX, including its phase and final ancilla."""
op = qp.ctrl(
qp.MultiX(bitstring, wires=range(1, len(bitstring) + 1)),
control=0,
control_values=[control_value],
)
rule = qp.list_decomps(op)["_controlled_multix_lattice_surgery_ppm"]
tape = qp.testing.decomp_rule_to_tape(op, rule)

with qp.capture.pause():
auxiliary = len(op.wires)
(tape,), _ = qp.transforms.resolve_dynamic_wires(tape, zeroed=[auxiliary])
wire_order = [*op.wires, auxiliary]
measurements = [
gate for gate in tape.operations if isinstance(gate, qp.ops.PauliMeasure)
]
assert [measurement.pauli_word for measurement in measurements] == [
"ZX",
"Z" + "X" * sum(bitstring),
"X",
]

dimension = 2 ** len(op.wires)
identity = np.eye(2 * dimension)
# Columns span all inputs on the data wires, with the auxiliary prepared in |0>.
initial = np.kron(np.eye(dimension), np.array([[1], [0]]))
expected = np.kron(op.matrix(), np.array([[1], [1]]) / np.sqrt(2)) / np.sqrt(8)

for outcomes in product([0, 1], repeat=3):
results = dict(zip(measurements, outcomes))
branch = initial
for gate in tape.operations:
if isinstance(gate, qp.ops.PauliMeasure):
observable = qp.pauli.string_to_pauli_word(
gate.pauli_word,
wire_map={wire: index for index, wire in enumerate(gate.wires)},
)
projector = (
identity
+ (-1) ** results[gate] * qp.matrix(observable, wire_order=wire_order)
) / 2
branch = projector @ branch
elif isinstance(gate, qp.ops.Conditional):
if gate.meas_val.concretize(results):
branch = qp.matrix(gate.base, wire_order=wire_order) @ branch
else:
branch = qp.matrix(gate, wire_order=wire_order) @ branch

assert np.allclose(branch, expected), f"Incorrect measurement branch {outcomes}"

@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,
work_wires=[],
work_wire_type="borrowed",
)
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]),
control=0,
control_values=[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