Source code for pennylane.templates.subroutines.iqp

# 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.
"""
Contains the IQP template.
"""

from collections import defaultdict
from functools import reduce

from pennylane import math
from pennylane.core.operator import Operator2
from pennylane.decomposition import add_decomps, register_resources
from pennylane.math import expand_matrix
from pennylane.ops import PPR_4, Hadamard, MultiRZ, PauliX
from pennylane.typing import Float, TensorLike, Wire
from pennylane.wires import Wires, WiresLike


[docs] class IQP(Operator2): r""" A template that builds an Instantaneous Quantum Polynomial (IQP) circuit. The gates of these circuits correspond to multi-qubit X rotations, whose generators are given by tensor products of Pauli X operators. In this `IQPOpt <https://arxiv.org/pdf/2501.04776>`__ paper and this `train on classical, deploy on quantum <https://arxiv.org/pdf/2503.02934>`__ paper, the authors present methods for analytically approximating expectation values coming from measurements made on IQP circuits. This allows for the classical training of the parameters of these circuits prior to deploying them to a quantum computer for actual computation. Certain computational problems such as generative machine learning and combinatorial optimization can be cast as a minimization over functions of these expectation values. Since these circuits are also believed to be hard to sample from using classical algorithms, they can potentially lead to a quantum advantage. Args: weights (list): The parameters of the IQP gates. wires (WiresLike): The wires that the IQP circuit operates on. pattern (list[list[list[int]]]): Specification of the trainable gates. Each element of ``pattern`` corresponds to a unique trainable parameter. Each sublist specifies the generators to which that parameter applies. Generators are specified by listing the qubits on which an X operator acts. For example, the ``pattern`` ``[[[0]], [[1]], [[2]], [[3]]]`` specifies a circuit with single qubit rotations on the first four qubits, each with its own trainable parameter. The ``pattern`` ``[[[0],[1]], [[2],[3]]]`` correspond to a circuit with two trainable parameters with generators :math:`X_0+X_1` and :math:`X_2+X_3` respectively. A circuit with a single trainable gate with generator :math:`X_0\otimes X_1` corresponds to the ``pattern`` ``[[[0,1]]]``. spin_sym (bool, optional): If True, the circuit is equivalent to one where the initial state :math:`\frac{1}{\sqrt(2)}(|00\dots0> + |11\dots1>)` is used in place of :math:`|00\dots0>`. Raises: ValueError: when ``pattern`` and ``weights`` have a different number of elements. **Example:** Below is an example of a 2-qubit IQP circuit. At this small scale, a state vector simulation is tractable. .. code-block:: python dev = qp.device("default.qubit") @qp.qnode(dev) def iqp_circuit(weights, pattern, spin_sym): qp.IQP(weights=weights, wires=[0, 1], pattern=pattern, spin_sym=spin_sym) return [qp.expval(qp.PauliZ(0)), qp.expval(qp.PauliZ(1))] >>> iqp_circuit(weights=[0.89, 0.54], pattern=[[[0]], [[1]]], spin_sym=False) # doctest: +SKIP [np.float64(-0.20768100160878344), np.float64(0.47132836417373947)] >>> print(qp.draw(iqp_circuit, level="device")([0.89, 0.54], [[[0]], [[1]]], False)) # doctest: +SKIP 0: ─╭IQP─┤ <Z> 1: ─╰IQP─┤ <Z> .. seealso:: :func:`pennylane.math.iqp_expval`, :doc:`IQP tutorial <demo:demos/tutorial_iqp_circuit_optimization_jax>` .. details:: :title: Available decompositions .. decomposition-table:: qp.IQP :stacked: :symbols: :math:`n` wires and :math:`G` generators in total in ``pattern`` :example: :math:`n=2`, ``pattern=[[[0]], [[1]], [[0, 1]]]`` (meaning the number of generators :math:`G = 3`), ``spin_sym=True`` .. decomposition-rule:: to_h_multirz :image: /_static/decomposition_thumbnails/iqp_multirz.svg :where: the Pauli word ``"YX...X"`` acts on all :math:`n` wires: one Y, then :math:`n - 1` X's :class:`PPR_4(1, "YX...X") <.PPR_4>` | :math:`1` if ``spin_sym=True`` | 1 :class:`~.Hadamard` | :math:`2n` | 4 :class:`~.MultiRZ` on the wires of a generator | :math:`G` (one per generator) | 3 """ dynamic_argnames = ("weights",) compilable_argnames = ("pattern", "spin_sym") arg_specs = {"weights": Float[-1], "wires": Wire[-1]} def __init__( self, weights: TensorLike, wires: WiresLike, pattern: list[list[list[int]]], spin_sym: bool = False, ): if isinstance(weights, (list, tuple)): weights = math.asarray(weights) if len(weights) != len(pattern): raise ValueError( "Number of gates and number of parameters for an Instantaneous Quantum Polynomial " f"circuit must be the same, got {len(pattern)} gates and {len(weights)} weights." ) wires = Wires(wires) if len(wires) == 0: raise ValueError("At least one valid wire is required.") # ``pattern`` is a compilable argument, so it is stored as pytree metadata and must be # hashable. Canonicalize the nested lists into nested tuples. pattern = tuple(tuple(tuple(gen) for gen in gate) for gate in pattern) super().__init__(weights, wires=wires, pattern=pattern, spin_sym=spin_sym)
[docs] @staticmethod # pylint: disable-next=arguments-differ def compute_matrix(weights, wires, pattern, spin_sym) -> TensorLike: num_wires = len(Wires(wires)) layers = [] if spin_sym: pauli_mat = PPR_4.compute_matrix(1, "Y" + "X" * (num_wires - 1)) layers.append(pauli_mat) for par, gate in zip(weights, pattern, strict=True): for gen in gate: x_mat = reduce(math.kron, [PauliX.compute_matrix() for _ in gen]) rx_mat = math.expm(-1j * par * expand_matrix(x_mat, gen, list(range(num_wires)))) layers.append(rx_mat) return reduce(math.matmul, layers[::-1])
# pylint: disable-next=unused-argument def _instantaneous_quantum_polynomial_standard_resources(weights, wires, pattern, spin_sym): num_wires = len(wires) resources = defaultdict(int) if spin_sym: resources[PPR_4(1, pauli_word="Y" + "X" * (num_wires - 1), wires=Wire[num_wires])] = 1 resources[Hadamard] = 2 * num_wires for gate in pattern: for gen in gate: resources[MultiRZ(Float, Wire[len(gen)])] += 1 return resources @register_resources(_instantaneous_quantum_polynomial_standard_resources, name="to_h_multirz") def _instantaneous_quantum_polynomial_standard(weights, wires, pattern, spin_sym): num_wires = len(wires) if spin_sym: PPR_4(1, "Y" + "X" * (num_wires - 1), wires=wires) for i in range(num_wires): Hadamard(wires[i]) for par, gate in zip(weights, pattern, strict=True): for gen in gate: MultiRZ(2 * par, wires=[wires[g] for g in gen]) for i in range(num_wires): Hadamard(wires[i]) add_decomps(IQP, _instantaneous_quantum_polynomial_standard)