Source code for pennylane.decomposition.decomposition_rule

# Copyright 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.

"""Defines the ``DecompositionRule`` class to represent a decomposition rule."""

from __future__ import annotations

import inspect
import re
from collections import Counter, defaultdict
from collections.abc import Callable, Sequence
from contextlib import contextmanager
from contextvars import ContextVar
from dataclasses import dataclass
from functools import singledispatch, update_wrapper
from textwrap import dedent
from typing import overload

import pennylane as qp
from pennylane.core import QueuingManager, queuing
from pennylane.core.operator import Operator, Operator2, abstractify
from pennylane.pytrees import flatten
from pennylane.typing import AbstractArray, AbstractWires
from pennylane.wires import Wires

from .resources import (
    AbstractOperatorLike,
    CompressedResourceOp,
    Resources,
    _gate_count_dict_to_str,
)
from .utils import _get_decomp_args, to_name


@dataclass(frozen=True)
class WorkWireSpec:
    """The number of each type of work wires that a decomposition rule requires."""

    zeroed: int = 0
    r"""Zeroed wires are guaranteed to be in the :math:`|0\rangle` state initially, and they
    must be restored to the :math:`|0\rangle>` state before deallocation."""

    borrowed: int = 0
    """Borrowed wires could be allocated in any state, and they must be restored to their
    initial state before deallocation."""

    burnable: int = 0
    r"""Burnable wires are guaranteed to be in the :math:`|0\rangle` state initially, and they
    could be deallocated in any arbitrary state."""

    garbage: int = 0
    """Garbage wires could be allocated in any state, and can be deallocated in any state."""

    @property
    def total(self) -> int:
        """The total number of work wires."""
        return self.zeroed + self.borrowed + self.burnable + self.garbage


@overload
def register_condition(condition: Callable) -> Callable[[Callable], DecompositionRule]: ...
@overload
def register_condition(condition: Callable, qfunc: Callable) -> DecompositionRule: ...
[docs] def register_condition( condition: Callable[..., bool], qfunc: Callable | None = None ) -> Callable[[Callable], DecompositionRule] | DecompositionRule: """Binds a condition to a decomposition rule for when it is applicable. Args: condition (Callable): a function which takes the resource parameters of an operator as arguments and returns ``True`` or ``False`` based on whether the decomposition rule is applicable to an operator with the given resource parameters. qfunc (Callable): the quantum function that implements the decomposition. If ``None``, returns a decorator for acting on a function. Returns: DecompositionRule: a data structure that represents a decomposition rule, which contains a PennyLane quantum function representing the decomposition, and its resource function. **Example** This function can be used as a decorator to bind a condition function to a quantum function that implements a decomposition rule. .. code-block:: python import pennylane as qp from pennylane.math.decomposition import zyz_rotation_angles # The parameters must be consistent with ``qp.QubitUnitary.resource_keys`` def _zyz_condition(num_wires): return num_wires == 1 @qp.register_condition(_zyz_condition) @qp.register_resources({qp.RZ: 2, qp.RY: 1, qp.GlobalPhase: 1}, name="zyz_decomposition") def zyz_decomposition(U, wires, **__): # Assumes that U is a 2x2 unitary matrix phi, theta, omega, phase = zyz_rotation_angles(U) qp.RZ(phi, wires=wires[0]) qp.RY(theta, wires=wires[0]) qp.RZ(omega, wires=wires[0]) qp.GlobalPhase(-phase) # This decomposition will be ignored for `QubitUnitary` on more than one wire. qp.add_decomps(qp.QubitUnitary, zyz_decomposition) """ def _decorator(_qfunc) -> DecompositionRule: if not isinstance(_qfunc, DecompositionRule): _qfunc = DecompositionRule(_qfunc) _qfunc.add_condition(condition) return _qfunc return _decorator(qfunc) if qfunc else _decorator
@overload def register_resources( ops: Callable | dict, *, name: str | None = None, work_wires: Callable | dict | None = None, exact: bool = True, ) -> Callable[[Callable], DecompositionRule]: ... @overload def register_resources( ops: Callable | dict, qfunc: Callable, *, name: str | None = None, work_wires: Callable | dict | None = None, exact: bool = True, ) -> DecompositionRule: ...
[docs] def register_resources( ops: Callable | dict, qfunc: Callable | None = None, *, name: str | None = None, work_wires: Callable | dict | None = None, exact: bool = True, ) -> Callable[[Callable], DecompositionRule] | DecompositionRule: r"""Binds a quantum function to its required resources. Args: ops (dict or Callable): a dictionary mapping unique operators within the given ``qfunc`` to their number of occurrences therein. If a function is provided instead of a static dictionary, a dictionary must be returned from the function. For more information, consult the "Quantum Functions as Decomposition Rules" section below. qfunc (Callable): the quantum function that implements the decomposition. If ``None``, returns a decorator for acting on a function. Keyword Args: name (Optional(str)): Optional public rule name, if ``None``, use the function name with leading underscores removed. Names must be non-blank and must not start with an underscore. work_wires (dict or Callable): a dictionary declaring the number of work wires of each type required to perform this decomposition. Accepted work wire types include ``"zeroed"``, ``"borrowed"``, ``"burnable"``, and ``"garbage"``. For more information, consult the "Dynamic Allocation of Work Wires" section below. exact (bool): whether the resources are computed exactly (``True``, default) or estimated heuristically (``False``). This information is only relevant for testing and validation purposes. Returns: DecompositionRule: a data structure that represents a decomposition rule, which contains a PennyLane quantum function representing the decomposition, and its resource function. Raises: TypeError: If an explicit name is not a string. ValueError: If the name is blank or starts with an underscore, or a registered rule is renamed. **Example** This function can be used as a decorator to bind a quantum function to its required resources so that it can be used as a decomposition rule within the new graph-based decomposition system. .. code-block:: python import pennylane as qp @qp.register_resources({qp.H: 2, qp.CZ: 1}, name="my_cnot") def my_cnot(wires, **_): qp.H(wires=wires[1]) qp.CZ(wires=wires) qp.H(wires=wires[1]) @qp.transforms._tape_decompose(gate_set={qp.CZ, qp.H}, fixed_decomps={qp.CNOT: my_cnot}) @qp.qnode(qp.device("default.qubit")) def circuit(): qp.CNOT(wires=[0, 1]) return qp.state() >>> print(qp.draw(circuit, level="device")()) 0: ────╭●────┤ ╭State 1: ──H─╰Z──H─┤ ╰State Alternatively, the decomposition rule can be created in-line: >>> my_cnot = qp.register_resources({qp.H: 2, qp.CZ: 1}, my_cnot, name="my_cnot") The public name is set by :func:`~pennylane.register_resources`, independently of the function name. >>> my_cnot.name 'my_cnot' For example, use a short strategy name: .. code-block:: python @qp.register_resources({qp.H: 2, qp.CZ: 1}, name="to_cz") def my_cnot(wires, **_): qp.H(wires=wires[1]) qp.CZ(wires=wires) qp.H(wires=wires[1]) >>> my_cnot.name 'to_cz' .. details:: :title: Quantum Functions as Decomposition Rules Quantum functions representing decomposition rules within the new decomposition system are expected to take ``(*op.parameters, op.wires, **op.hyperparameters)`` as arguments, where ``op`` is an instance of the operator type that the decomposition is for. .. details:: :title: Operators with Dynamic Resource Requirements In many cases, the resource requirement of an operator's decomposition is not static; some operators have properties that directly affect the resource estimate of its decompositions, i.e., the types of gates that exist in the decomposition and their number of occurrences. For each operator class, the set of parameters that affects the type of gates and their number of occurrences in its decompositions is given by the ``resource_keys`` attribute. .. seealso:: :func:`~pennylane.resource_rep` .. details:: :title: Dynamically Allocated Wires as a Resource Some decomposition rules make use of work wires, which can be dynamically requested within the quantum function using :func:`~pennylane.allocation.allocate`. Such decomposition rules should register the number of work wires they require so that the decomposition algorithm is able to budget the use of work wires across decomposition rules. There are four types of work wires: - "zeroed" wires are guaranteed to be in the :math:`|0\rangle` state initially, and they must be restored to the :math:`|0\rangle` state before deallocation. - "borrowed" wires are allocated in an arbitrary state, but they must be restored to the same initial state before deallocation. - "burnable" wires are guaranteed to be in the :math:`|0\rangle` state initially, but they can be deallocated in any arbitrary state. - "garbage" wires can be allocated in any state, and can be deallocated in any state. Here's a decomposition for a multi-controlled ``Rot`` that uses a zeroed work wire: .. code-block:: python import pennylane as qp from pennylane.allocation import allocate from pennylane.typing import Wire def _condition_fn(control_wires, **_): return len(control_wires) > 1 def _ops_fn(control_wires, **_): return { qp.MultiControlledX(Wire[len(control_wires) + 1]): 2, qp.CRot: 1 } @qp.register_condition(_condition_fn) @qp.register_resources(ops=_ops_fn, work_wires={"zeroed": 1}, name="ancilla_controlled_rot") def _controlled_rot_standard(base, control_wires, **_): wires = control_wires + base.wires with allocate(1, state="zero", restored=True) as work_wires: qp.MultiControlledX([*wires[:-1], work_wires[0]]) qp.CRot(**base.dynamic_args, wires=[work_wires[0], wires[-1]]) qp.MultiControlledX([*wires[:-1], work_wires[0]]) decomps = {"C(Rot)": _controlled_rot_standard} @qp.transforms._tape_decompose( gate_set={qp.MultiControlledX, qp.CRot}, fixed_decomps=decomps, num_work_wires=1, ) @qp.qnode(qp.device("default.qubit")) def circuit(): qp.ctrl(qp.Rot(0.1, 0.2, 0.3, wires=3), control=[0, 1, 2]) return qp.probs(wires=[0, 1, 2, 3]) >>> print(qp.draw(circuit)()) 0: ───────╭●──────────────────────╭●────┤ ╭Probs 1: ───────├●──────────────────────├●────┤ ├Probs 2: ───────├●──────────────────────├●────┤ ├Probs 3: ───────│──╭Rot(0.10,0.20,0.30)─│─────┤ ╰Probs |0>├─╰X─╰●───────────────────╰X──┤ """ if name is not None: if not isinstance(name, str): raise TypeError("Decomposition rule names must be strings.") if not name.strip(): raise ValueError("Decomposition rule names must not be blank.") if name.startswith("_"): raise ValueError("Decomposition rule names must not start with an underscore.") def _decorator(_qfunc) -> DecompositionRule: if isinstance(_qfunc, DecompositionRule): if name is not None: if any(_qfunc in decomps for decomps in _decompositions_var.get().values()): raise ValueError( "Cannot rename a decomposition rule already registered with an operator." ) _qfunc.name = name _qfunc.set_resources(ops, exact_resources=exact) if work_wires: _qfunc.set_work_wire_spec(work_wires) return _qfunc return DecompositionRule( _qfunc, resources=ops, work_wires=work_wires, exact_resources=exact, name=name, ) return _decorator(qfunc) if qfunc else _decorator
[docs] class DecompositionRule: # pylint: disable=too-many-instance-attributes """Represents a decomposition rule for an operator.""" def __init__( self, func: Callable, resources: Callable | dict | None = None, work_wires: Callable | dict | None = None, exact_resources: bool = True, name: str | None = None, ): update_wrapper(self, func) self._impl = func try: self._source = inspect.getsource(func) except OSError: # pragma: no cover # OSError is raised if the source code cannot be retrieved self._source = "Unable to retrieve source code." # pragma: no cover self.name = func.__name__.lstrip("_") if name is None else name if isinstance(resources, dict): def resource_fn(*_, **__): return resources self._compute_resources = resource_fn else: self._compute_resources = resources self._conditions = [] self._work_wire_spec = work_wires or {} self.exact_resources = exact_resources def __call__(self, *args, **kwargs): return self._impl(*args, **kwargs) def __str__(self): return dedent(self._source).strip() def __repr__(self): return f"DecompositionRule(name={self.name})" @property def name(self) -> str: """The public name used to select this decomposition rule.""" return self._name @name.setter def name(self, name: str): if name.startswith("_"): raise ValueError("Decomposition rule names must not start with an underscore.") self._name = name
[docs] @QueuingManager.stop_recording() def compute_resources(self, *args, **kwargs) -> Resources: """Computes the resources required to implement this decomposition rule.""" if self._compute_resources is None: raise NotImplementedError("No resource estimation found for this decomposition rule.") raw_gate_counts = self._compute_resources(*args, **kwargs) assert isinstance(raw_gate_counts, dict), "Resource function must return a dictionary." gate_counter = Counter() for op, count in raw_gate_counts.items(): if not ( isinstance(op, (CompressedResourceOp, Operator2)) or (isinstance(op, type) and issubclass(op, Operator)) ): raise TypeError( "The keys of the dictionary returned by the resource function must be a " "subclass of Operator or a CompressedResourceOp constructed with " "qp.resource_rep, or an Operator2 constructed with abstract inputs." ) op = abstractify(op) _verify_is_abstract_and_fixed(op) if count > 0: gate_counter.update({op: count}) return Resources(dict(gate_counter))
[docs] def is_applicable(self, *args, **kwargs) -> bool: """Checks whether this decomposition rule is applicable.""" return all(condition(*args, **kwargs) for condition in self._conditions)
[docs] def get_work_wire_spec(self, *args, **kwargs) -> WorkWireSpec: """Gets the work wire requirements of this decomposition rule""" if isinstance(self._work_wire_spec, dict): return WorkWireSpec(**self._work_wire_spec) return WorkWireSpec(**self._work_wire_spec(*args, **kwargs))
[docs] def add_condition(self, condition: Callable[..., bool]) -> None: """Adds a condition for this decomposition rule.""" self._conditions.append(condition)
[docs] def set_resources(self, resources: Callable | dict, exact_resources: bool = True) -> None: """Sets the resources for this decomposition rule.""" if isinstance(resources, dict): def resource_fn(*_, **__): return resources self._compute_resources = resource_fn else: self._compute_resources = resources self.exact_resources = exact_resources
[docs] def set_work_wire_spec(self, work_wires: Callable | dict) -> None: """Sets the work wire usage of this decomposition rule.""" self._work_wire_spec = work_wires
[docs] class DecompCollection: """An ordered, name-addressable collection of :class:`~.DecompositionRule` objects. A ``DecompCollection`` is exclusively returned by :func:`~pennylane.list_decomps`, which retrieves all registered decomposition rules for a given operator. Each rule in the collection has a unique name, optionally set using the ``name`` argument of :func:`~pennylane.register_resources`. Individual rules can be accessed by integer index or by string name. The collection supports :func:`len`, iteration, membership checks (by name or by :class:`~.DecompositionRule` instance), :meth:`copy`, :meth:`append`, :meth:`extend`, ``+``, and ``+=``. Duplicate names within a collection are rejected with a ``ValueError``. .. important:: A ``DecompCollection`` returned by :func:`~pennylane.list_decomps` is a **copy** of the internally registered rules. Mutating it (e.g. with :meth:`append` or :meth:`extend`) does **not** update the global decomposition registry. Use :func:`~pennylane.add_decomps` to register new decomposition rules globally. .. seealso:: :class:`~.DecompositionRule`, :func:`~pennylane.register_resources`, :func:`~pennylane.list_decomps`, :func:`~pennylane.add_decomps`, :func:`~pennylane.inspect_decomps` **Examples** Retrieve and explore decomposition rules for an operator: >>> decomps = qp.list_decomps(qp.CRX) >>> len(decomps) 4 >>> print(decomps) Available Decomposition Rules: 0: to_rx_cz 1: to_rz_ry 2: to_h_crz 3: to_paulirot Access rules by index or by name: >>> decomps[0] DecompositionRule(name=to_rx_cz) >>> decomps["to_paulirot"] DecompositionRule(name=to_paulirot) Check membership: >>> "to_paulirot" in decomps True Iterate through rule names: >>> [rule.name for rule in decomps] ['to_rx_cz', 'to_rz_ry', 'to_h_crz', 'to_paulirot'] """ _decomps: dict[str, DecompositionRule] def __init__( self, decomps: dict[str, DecompositionRule] | Sequence[DecompositionRule] | None = None ) -> None: decomps = decomps or {} if not isinstance(decomps, dict): names = [rule.name for rule in decomps] if dup := next((r for i, r in enumerate(names) if r in names[i + 1 :]), None): raise ValueError( "Decomposition rules in the same collection must have unique names. " f"Found multiple decompositions with the same name: '{dup}'." ) decomps = {rule.name: rule for rule in decomps} self._decomps = decomps.copy() def __getitem__(self, arg: int | str) -> DecompositionRule: if isinstance(arg, int): return list(self._decomps.values())[arg] if arg not in self._decomps: raise KeyError( f"Cannot find a decomposition with the given name: {arg}. " f"Available names: {list(self._decomps)}." ) return self._decomps[arg] def __repr__(self) -> str: rules = [" " + repr(rule) for rule in self] inner_str = "" if not rules else "\n" + ",\n".join(rules) + "\n" return f"DecompCollection([{inner_str}])" def __str__(self) -> str: rules = [f"{i}: {rule.name}" for i, rule in enumerate(self)] return "Available Decomposition Rules:\n" + "\n".join(rules) def __iter__(self): return iter(self._decomps.values()) def __len__(self) -> int: return len(self._decomps)
[docs] def copy(self) -> DecompCollection: """Return a copy of the DecompCollection.""" return DecompCollection(self._decomps)
def __contains__(self, other) -> bool: if isinstance(other, str): return other in self._decomps if isinstance(other, DecompositionRule): return other in self._decomps.values() return False
[docs] def append(self, rule: DecompositionRule): """Add a decomposition rule to the collection.""" if rule.name in self._decomps and rule is not self._decomps[rule.name]: raise ValueError(f"A decomposition of the name: {rule.name} already exists!") self._decomps[rule.name] = rule
[docs] def extend(self, rules: DecompCollection | Sequence[DecompositionRule]): """Add a sequence of decomposition rules to the collection.""" if dup := next((r.name for r in rules if r.name in self and r is not self[r.name]), None): raise ValueError(f"A decomposition of the name: {dup} already exists!") decomps = rules if isinstance(rules, DecompCollection) else DecompCollection(rules) self._decomps |= decomps._decomps # pylint: disable=protected-access
def __add__(self, other: DecompCollection | Sequence[DecompositionRule]) -> DecompCollection: return DecompCollection(list(self) + list(other)) def __radd__(self, other: DecompCollection | Sequence[DecompositionRule]) -> DecompCollection: return DecompCollection(list(other) + list(self)) def __iadd__(self, other) -> DecompCollection: self.extend(other) return self
_decompositions_private = defaultdict(DecompCollection) """dict[str, DecompCollection]: A dictionary mapping operator names to decomposition rules.""" _decompositions_var = ContextVar("_decompositions", default=_decompositions_private) _fixed_decomps_private = {} """dict[str, DecompositionRule]: A dictionary mapping operators a unique decomposition rule.""" _fixed_decomps_var = ContextVar("_fixed_decomps", default=_fixed_decomps_private) _excluded_decomps_private = {} """dict[str, frozenset[str]]: A dictionary mapping operator names to excluded rule names.""" _excluded_decomps_var = ContextVar("_excluded_decomps", default=_excluded_decomps_private)
[docs] def add_decomps(op_type: type[Operator | Operator2] | str, *decomps: DecompositionRule) -> None: """Globally registers new decomposition rules with an operator class. Multiple decomposition rules can be registered for the same operator class. The specified decomposition rules in ``add_decomps`` serve as alternative decomposition rules that may be chosen if they lead to a more resource-efficient decomposition. Args: op_type (type or str): the operator type for which new decomposition rules are specified. For symbolic operators, use strings such as ``"Adjoint(RY)"``, ``"Pow(H)"``, ``"C(RX)"``, etc. decomps (DecompositionRule): new decomposition rules to add to the given ``op_type``. A decomposition is a quantum function registered with a resource estimate using ``qp.register_resources``. .. seealso:: :func:`~pennylane.register_resources` and :class:`~pennylane.list_decomps` **Example** This example demonstrates adding two new decomposition rules to the ``qp.Hadamard`` operator. .. code-block:: python import pennylane as qp import numpy as np @qp.register_resources({qp.RZ: 2, qp.RX: 1, qp.GlobalPhase: 1}, name="my_hadamard1") def my_hadamard1(wires): qp.RZ(np.pi / 2, wires=wires) qp.RX(np.pi / 2, wires=wires) qp.RZ(np.pi / 2, wires=wires) qp.GlobalPhase(-np.pi / 2) @qp.register_resources({qp.RZ: 1, qp.RY: 1, qp.GlobalPhase: 1}, name="my_hadamard2") def my_hadamard2(wires): qp.RZ(np.pi, wires=wires) qp.RY(np.pi / 2, wires=wires) qp.GlobalPhase(-np.pi / 2) qp.add_decomps(qp.Hadamard, my_hadamard1, my_hadamard2) These two new decomposition rules for ``qp.Hadamard`` will be subsequently stored within the scope of this program, and they will be taken into account for all circuit decompositions for the duration of the session. To keep alternative decompositions local to a workflow, register the rules and compile the circuit within a :func:`~.local_decomps` context. Use ``fixed_decomps`` or ``exclude_decomps`` with :func:`~pennylane.transforms.decompose` to select or exclude rules for an individual compilation pass. Custom decomposition rules can also be specified for symbolic operators. In this case, the operator type can be specified as a string. For example, .. code-block:: python @register_resources({qp.RY: 1}, name="adjoint_ry") def adjoint_ry(phi, wires, **_): qp.RY(-phi, wires=wires) qp.add_decomps("Adjoint(RY)", adjoint_ry) .. seealso:: :func:`~pennylane.transforms.decompose` """ if not all(isinstance(d, DecompositionRule) for d in decomps): raise TypeError( "A decomposition rule must be a qfunc with a resource estimate " "registered using qp.register_resources" ) _decompositions_var.get()[to_name(op_type)].extend(decomps)
def _get_registered_decomps(op_name: str) -> DecompCollection: """Retrieves a copy of the decomposition rules directly registered for an operator name. Args: op_name (str): operator name, including symbolic names such as ``"C(RX)"`` """ return _decompositions_var.get()[op_name].copy() @singledispatch def _list_decomps(op: type[Operator] | Operator | str) -> DecompCollection: """Retrieves decomposition rules before exclusion filtering.""" if fixed_rule := get_fixed_decomp(op): return DecompCollection([fixed_rule]) op_name = to_name(op) if isinstance(op, str) and re.fullmatch(r"C\(.*\)", op_name): return _list_control_decomps(op_name) return _get_registered_decomps(op_name) def _list_control_decomps(op_name: str) -> DecompCollection: """Lists custom rules and generic fallback candidates for a controlled operator name. All three generic fallbacks are included. Their applicability conditions are checked using operator arguments rather than the name alone. Args: op_name (str): operator name, including symbolic names such as ``"C(RX)"`` """ # TODO: the circular dependency can be eliminated when we move the decomposition # rule library to a separate module [sc-136709] from pennylane.ops.op_math.controlled2 import ( # pylint: disable=import-outside-toplevel _controlled_to_unitary, ctrl_many_zeroed_work_wires, ctrl_single_work_wire, ) registered_rules = _get_registered_decomps(op_name) generic_decomps = [_controlled_to_unitary, ctrl_many_zeroed_work_wires, ctrl_single_work_wire] generic_rules = DecompCollection(generic_decomps) return registered_rules + generic_rules
[docs] def list_decomps(op: type[Operator] | Operator | str) -> DecompCollection: """Lists decomposition rules for an operator. Args: op (type or Operator or str): the operator or operator type to retrieve decomposition rules for. For symbolic operators, use strings like ``"Adjoint(RY)"``, ``"Pow(H)"``, ``"C(RX)"``, etc. Returns: DecompCollection: a collection of decomposition rules for the given operator. .. important:: The returned :class:`~.DecompCollection` is a **copy** of the registered rules. Mutating it does not update the global decomposition registry; use :func:`~pennylane.add_decomps` to register rules globally. **Example** >>> import pennylane as qp >>> qp.list_decomps(qp.CRX) DecompCollection([ DecompositionRule(name=to_rx_cz), DecompositionRule(name=to_rz_ry), DecompositionRule(name=to_h_crz), DecompositionRule(name=to_paulirot) ]) >>> print(qp.list_decomps(qp.CRX)) Available Decomposition Rules: 0: to_rx_cz 1: to_rz_ry 2: to_h_crz 3: to_paulirot Each decomposition rule can be accessed by name or by index. >>> qp.list_decomps(qp.CRX)['to_paulirot'] DecompositionRule(name=to_paulirot) >>> print(qp.list_decomps(qp.CRX)[0]) @register_resources(_crx_to_rx_cz_resources, name="to_rx_cz") def _crx_to_rx_cz(phi: TensorLike, wires: WiresLike): qp.RX(phi / 2, wires=wires[1]) qp.CZ(wires=wires) qp.RX(-phi / 2, wires=wires[1]) qp.CZ(wires=wires) >>> print(qp.draw(qp.list_decomps(qp.CRX)[0])(0.5, wires=[0, 1])) 0: ───────────╭●────────────╭●─┤ 1: ──RX(0.25)─╰Z──RX(-0.25)─╰Z─┤ """ decomps = _list_decomps(op) excluded_rules = _excluded_decomps_var.get() if excluded := excluded_rules.get(to_name(op)): return DecompCollection([rule for rule in decomps if rule.name not in excluded]) return decomps
class _DecompExclusion: """The exclusion of decomposition rules, which is undone when used as a context manager.""" def __init__(self, op_name: str, names: frozenset[str]) -> None: self._op_name = op_name self._names = names def __enter__(self) -> None: pass def __exit__(self, *_) -> None: all_excluded = _excluded_decomps_var.get() remaining = all_excluded.get(self._op_name, frozenset()) - self._names _excluded_decomps_var.set(all_excluded | {self._op_name: remaining})
[docs] def exclude_decomps(op: type[Operator] | Operator | str, *names: str) -> _DecompExclusion: """Excludes decomposition rules of an operator by name. Excluded rules are not removed from the registry. They are hidden from :func:`~pennylane.list_decomps`, and are therefore not considered by the graph-based decomposition system. When used as a context manager, the rules are excluded only within the context. This function is thread-safe. Args: op (type or Operator or str): the operator type to exclude decomposition rules for. For symbolic operators, use strings like ``"Adjoint(RY)"``, ``"C(RX)"``, etc. *names (str): the names of the decomposition rules to exclude. Each name must be one of the rules listed by :func:`~pennylane.list_decomps` for ``op``. To exclude rules that are generated for specific operator instances, pass an instance as ``op``. Raises: TypeError: if a name is not a string, e.g., a ``DecompositionRule`` instance. ValueError: if no decomposition rule with a given name exists for ``op``. .. seealso:: :func:`~pennylane.list_decomps` and :func:`~pennylane.decomposition.local_decomps` **Example** When used as a context manager, the rules are excluded only within the context: >>> with qp.exclude_decomps(qp.CRX, "to_paulirot", "to_h_crz"): ... print(qp.list_decomps(qp.CRX)) Available Decomposition Rules: 0: to_rx_cz 1: to_rz_ry >>> print(qp.list_decomps(qp.CRX)) Available Decomposition Rules: 0: to_rx_cz 1: to_rz_ry 2: to_h_crz 3: to_paulirot Otherwise, the rules remain excluded for the rest of the session, or until the enclosing :func:`~pennylane.decomposition.local_decomps` context exits: .. code-block:: python with qp.decomposition.local_decomps(): qp.exclude_decomps(qp.CRX, "to_paulirot") assert "to_paulirot" not in qp.list_decomps(qp.CRX) assert "to_paulirot" in qp.list_decomps(qp.CRX) """ op_name = to_name(op) if invalid := [name for name in names if not isinstance(name, str)]: raise TypeError( "Decomposition rules must be excluded by name, e.g. rule.name for a " f"DecompositionRule, got {invalid[0]!r}." ) available = [rule.name for rule in _list_decomps(op)] if missing := [name for name in names if name not in available]: raise ValueError( f"Cannot find a decomposition rule named '{missing[0]}' for {op_name}. " f"Available decomposition rules: {available}." ) all_excluded = _excluded_decomps_var.get() already_excluded = all_excluded.get(op_name, frozenset()) _excluded_decomps_var.set(all_excluded | {op_name: already_excluded | frozenset(names)}) return _DecompExclusion(op_name, frozenset(names) - already_excluded)
[docs] def has_decomp(op: type[Operator] | Operator | str) -> bool: """Checks whether an operator has decomposition rules defined. Args: op (type or Operator or str): the operator or operator type to check for decomposition rules. For symbolic operators, use strings like ``"Adjoint(RY)"``, ``"Pow(H)"``, ``"C(RX)"``, etc. Returns: bool: whether decomposition rules are defined for the given operator. """ return len(list_decomps(op)) > 0
[docs] @contextmanager def local_decomps(): """Start a new context in which additions to decomposition rules are localized. This context manager is thread-safe because it uses ``ContextVar`` under the hood. """ # Handle the global decomposition library. current_decomps = {k: v.copy() for k, v in _decompositions_var.get().items()} _new_decomps = defaultdict(DecompCollection, current_decomps) token_all_decomps = _decompositions_var.set(_new_decomps) # Handle the registry of fixed decomposition rules. _new_fixed_decomps = _fixed_decomps_var.get().copy() token_fixed_decomps = _fixed_decomps_var.set(_new_fixed_decomps) # Handle the registry of excluded decomposition rules. token_excluded_decomps = _excluded_decomps_var.set(_excluded_decomps_var.get().copy()) try: yield finally: _decompositions_var.reset(token_all_decomps) _fixed_decomps_var.reset(token_fixed_decomps) _excluded_decomps_var.reset(token_excluded_decomps)
def _fix_decomp(op: type[Operator] | Operator | str, rule: DecompositionRule): """Fix a unique decomposition rule for an operator. This is a developer-facing function meant to be used within a local decomps context. """ _fixed_decomps_var.get()[to_name(op)] = rule def get_fixed_decomp(op: type[Operator] | Operator | str) -> DecompositionRule | None: """Get the decomposition rule fixed to an operator if there is one. This is a developer-facing function meant to be used within a local decomps context. """ return _fixed_decomps_var.get().get(to_name(op), None) class _DecompInfo: # pylint: disable=too-few-public-methods """A data structure that stores a decomposition rule and an operator for inspectability.""" def __init__(self, op: Operator, rule: DecompositionRule, num_work_wires: int | None) -> None: self._op = op self._rule = rule self._decomp_args = _get_decomp_args(op) self._conditions_met = rule.is_applicable(**self._decomp_args[0]) self._work_wire_spec = rule.get_work_wire_spec(**self._decomp_args[0]) n_work_wires = self._work_wire_spec.total self._enough_work_wires = num_work_wires is None or n_work_wires <= num_work_wires self._num_work_wires = num_work_wires def __str__(self) -> str: if not self._conditions_met: return "Not applicable (provided operator instance does not meet all conditions for this rule)." if not self._enough_work_wires: req = self._work_wire_spec.total avail = self._num_work_wires return f"Insufficient work wires: requires {req} but only {avail} available." return self._circuit_drawing + "\n" + self._gate_counts_and_allocations def _repr_markdown_(self) -> str: """The string representation of this rule in Markdown format.""" if not self._conditions_met: return "_Not applicable (provided operator instance does not meet all conditions for this rule)._" if not self._enough_work_wires: req = self._work_wire_spec.total avail = self._num_work_wires return f"_Insufficient work wires: requires {req} but only {avail} available._" circuit_drawing = "```\n" + self._circuit_drawing + "\n```" gate_counts_title = "Gate Counts and Wire Allocations" return ( circuit_drawing + "\n" + f"<details><summary>{gate_counts_title}</summary>\n\n" + f"{self._gate_counts_and_allocations_md}\n</details>" ) @property def _circuit_drawing(self) -> str: """The circuit drawing of this decomposition rule.""" _, args, kwargs = _get_decomp_args(self._op) assert self._conditions_met and self._enough_work_wires return qp.draw(self._rule)(*args, **kwargs) @property def _name(self) -> str: """The name of the decomposition rule.""" return self._rule.name @property def _gate_counts_and_allocations(self) -> str: """The actual and estimated gate counts of this rule.""" assert self._conditions_met and self._enough_work_wires estimated_count = self._rule.compute_resources(**self._decomp_args[0]).gate_counts actual_count, allocations = _count_gates(self._op, self._rule) gate_count_str = self._get_gate_count_str(estimated_count, actual_count) if allocations: gate_count_str += f"\nWire Allocations: {allocations}" return gate_count_str @property def _gate_counts_and_allocations_md(self) -> str: """The actual and estimated gate counts of this rule in the Markdown format.""" assert self._conditions_met and self._enough_work_wires estimated_count = self._rule.compute_resources(**self._decomp_args[0]).gate_counts actual_count, allocations = _count_gates(self._op, self._rule) gate_count_str = self._get_gate_count_markdown(estimated_count, actual_count) if allocations: entries = list(allocations.items()) gate_count_str += "\n\n" + self._make_table(entries, ("Wire Type", "Num Allocated")) return gate_count_str def _get_gate_count_str(self, estimated_count, actual_count) -> str: """Get the section of the string that specifies the gate count.""" estimated_count = {k: v for k, v in estimated_count.items() if v > 0} estimated_str = _gate_count_dict_to_str(estimated_count) if estimated_count == actual_count: return f"Gate Count: {estimated_str}" actual_str = _gate_count_dict_to_str(actual_count) return f"Estimated Gate Count: {estimated_str}\nActual Gate Count: {actual_str}" def _get_gate_count_markdown(self, estimated_count, actual_count) -> str: """Get the section of the string that specifies the gate count.""" estimated_count = {k: v for k, v in estimated_count.items() if v > 0} if estimated_count == actual_count: entries = list(estimated_count.items()) return self._make_table(entries, ("Gate", "Count")) all_ops = set(estimated_count.keys()) | set(actual_count.keys()) entries = [(op, estimated_count.get(op, 0), actual_count.get(op, 0)) for op in all_ops] return self._make_table(entries, ("Gate", "Estimated", "Actual")) def _make_table(self, entries: Sequence[tuple], columns: Sequence[str]) -> str: column_str = " | ".join(columns) header_line = " | ".join((":---",) * len(columns)) header = f"| {column_str} |\n| {header_line} |\n" lines = [] entries = sorted(tuple(str(x) for x in entry) for entry in entries) for entry in entries: line_str = " | ".join(str(s) for s in entry) lines.append(f"| {line_str} |") return header + "\n".join(lines) @property def _is_applicable(self) -> bool: """Whether the decomposition rule is applicable.""" return self._conditions_met and self._enough_work_wires class _DecompInfoCollection: """A collection of _DecompInfo.""" def __init__( self, rule_infos: Sequence[_DecompInfo], show_not_applicable: bool = True, ) -> None: self._n_rules_original = len(rule_infos) indexed_rule_infos = enumerate(rule_infos) self._show_not_applicable = show_not_applicable if not show_not_applicable: # pylint: disable-next=protected-access indexed_rule_infos = filter(lambda p: p[1]._is_applicable, indexed_rule_infos) self._rules = list(indexed_rule_infos) def _title(self, index, rule) -> str: return f"Decomposition {index} (name: {rule._name})" # pylint: disable=protected-access def _title_md(self, index, rule) -> str: # pylint: disable-next=protected-access return f"#### Decomposition {index} (name: {rule._name})" def __str__(self) -> str: if not self._n_rules_original: return "No available decomposition rules." if not self._rules: return "No applicable decomposition rules (non-applicable rules are excluded)." return "\n\n".join(f"{self._title(i, rule)}\n{rule}" for i, rule in self._rules) def _repr_markdown_(self) -> str: if not self._n_rules_original: return "No available decomposition rules." if not self._rules: return "No applicable decomposition rules (non-applicable rules are excluded)." # pylint: disable-next=protected-access lines = (f"{self._title_md(i, d)}\n\n{d._repr_markdown_()}" for i, d in self._rules) return "\n\n---\n\n".join(lines).rstrip("\n") def __repr__(self) -> str: return self.__str__()
[docs] def inspect_decomps( op: Operator, *rules: str | DecompositionRule, show_not_applicable: bool = True, num_work_wires: int | None = None, ) -> _DecompInfoCollection: """Inspect the decomposition rules of an operator. Takes an operator instance and displays how the operator is decomposed using different decomposition rules. Args: op (Operator): the operator instance whose decomposition rules will be inspected. *rules (str or DecompositionRule): the decomposition rules to inspect. Accepts instances of the ``DecompositionRule`` class or rule names (str) that represent the decomposition rules registered with the type of ``op``. If none are provided, all available rules will be displayed. show_not_applicable (bool): if True (the default), all decomposition rules, including those that are not applicable to the specific operator instance (e.g., due to constraints on the number of wires), are displayed. num_work_wires (int or None): the maximum number of available work wires for dynamic allocation. Decomposition rules that allocate more wires than are available will be marked as "Not applicable" (and excluded if ``show_not_applicable=False``). Defaults to ``None``, which puts no constraint on the maximum number of work wires. Returns: a displayable object with information about decomposition rules. **Example** By default, this function displays all available decomposition rules for an operator. >>> qp.inspect_decomps(qp.CRX(0.5, wires=[0, 1])) Decomposition 0 (name: to_rx_cz) 0: ───────────╭●────────────╭●─┤ 1: ──RX(0.25)─╰Z──RX(-0.25)─╰Z─┤ Gate Count: {CZ: 2, RX: 2} <BLANKLINE> Decomposition 1 (name: to_rz_ry) 0: ─────────────────────╭●────────────╭●────────────┤ 1: ──RZ(1.57)──RY(0.25)─╰X──RY(-0.25)─╰X──RZ(-1.57)─┤ Gate Count: {CNOT: 2, RY: 2, RZ: 2} <BLANKLINE> Decomposition 2 (name: to_h_crz) 0: ────╭●───────────┤ 1: ──H─╰RZ(0.50)──H─┤ Gate Count: {CRZ: 1, Hadamard: 2} <BLANKLINE> Decomposition 3 (name: to_paulirot) 0: ───────────╭RZX(-0.25)─┤ 1: ──RX(0.25)─╰RZX(-0.25)─┤ Gate Count: {PauliRot(theta=AbstractArray((), float64, weak_type=True), pauli_word=X, wires=AbstractWires(1)): 1, PauliRot(theta=AbstractArray((), float64, weak_type=True), pauli_word=ZX, wires=AbstractWires(2)): 1} For each decomposition rule, the output includes its name, circuit diagram, gate count, and wire allocation (if any). Alternatively, you can inspect a single decomposition rule by passing its name. >>> qp.inspect_decomps(qp.CRX(0.5, wires=[0, 1]), "to_h_crz") Decomposition 0 (name: to_h_crz) 0: ────╭●───────────┤ 1: ──H─╰RZ(0.50)──H─┤ Gate Count: {CRZ: 1, Hadamard: 2} Or use this tool to inspect a custom decomposition rule: .. code-block:: python @qp.register_resources({qp.CNOT: 1, qp.H: 2}, name="my_cz") def my_cz(wires, **_): qp.H(wires[1]) qp.CNOT(wires) qp.H(wires[1]) >>> qp.inspect_decomps(qp.CZ([0, 1]), my_cz) Decomposition 0 (name: my_cz) 0: ────╭●────┤ 1: ──H─╰X──H─┤ Gate Count: {CNOT: 1, Hadamard: 2} """ if isinstance(op, type) and issubclass(op, Operator): raise TypeError( "The inspect_decomps function takes a concrete operator instance as its " "first argument, not an operator type." ) display_rules = list_decomps(op) if rules: display_rules = [display_rules[rule] if isinstance(rule, str) else rule for rule in rules] rule_infos = [_DecompInfo(op, rule, num_work_wires) for rule in display_rules] return _DecompInfoCollection(rule_infos, show_not_applicable)
def _count_gates(op: Operator, rule: DecompositionRule) -> tuple[dict, dict]: """Count the gates that a decomposition rule produced.""" _, args, kwargs = _get_decomp_args(op) with queuing.AnnotatedQueue() as q: rule(*args, **kwargs) actual_gate_counts = defaultdict(int) allocations = defaultdict(int) for _op in q.queue: if isinstance(_op, qp.ops.Conditional): _op = _op.base if isinstance(_op, qp.allocation.Allocate): allocations[str(_op.state)] += len(_op.wires) continue if isinstance(_op, qp.allocation.Deallocate): continue op_rep = abstractify(_op) actual_gate_counts[op_rep] += 1 return dict(actual_gate_counts), dict(allocations)
[docs] @register_resources({}, name="null_decomp") def null_decomp(*_, **__): """A decomposition rule that can be assigned to an operator so that the operator decomposes to nothing. **Example** .. code-block:: python import pennylane as qp from pennylane.decomposition import null_decomp @qp.transforms._tape_decompose( gate_set={qp.RZ}, fixed_decomps={qp.GlobalPhase: null_decomp} ) @qp.qnode(qp.device("default.qubit")) def circuit(): qp.Z(0) >>> print(qp.draw(circuit)()) 0: ──RZ(3.14)─┤ """ return
def _is_abstract_and_fixed(val, is_leaf=False): """Checks whether `val` is (or only contains) abstract data of fixed shapes.""" if isinstance(val, (AbstractArray, AbstractWires)): return val.shape_fixed if isinstance(val, CompressedResourceOp): # Legacy resource representations are valid, fully-abstract resource leaves. return True if is_leaf: # This branch is added as a precaution to avoid infinite recursion, but this should # never actually happen, because we always call `abstractify` first to fully abstractify # an operator, which should ensure that all pytree leaves are abstract. return False # return False if val is a non-abstract pytree leaf leaves, _ = flatten(val, is_leaf=lambda l: isinstance(l, Wires)) return all(_is_abstract_and_fixed(leaf, is_leaf=True) for leaf in leaves) def _verify_is_abstract_and_fixed(op: AbstractOperatorLike): """Checks if an operator is fully abstract and contains only abstract data of fixed shapes.""" if isinstance(op, CompressedResourceOp): return target_argnames = op.dynamic_argnames + op.wire_argnames + op.hybrid_argnames target_args = [val for name, val in op.arguments.items() if name in target_argnames] if any(not _is_abstract_and_fixed(val) for val in target_args): raise TypeError( "The resources of a decomposition rule cannot contain operators with " f"abstract data of undetermined dimensions, got {op}." ) def _is_measurement(resource_op) -> bool: """Whether a resource key represents a mid-circuit or Pauli-product measurement.""" op_type = ( resource_op.op_type if isinstance(resource_op, CompressedResourceOp) else type(resource_op) ) return issubclass(op_type, (qp.ops.MidMeasure, qp.ops.PauliMeasure)) def _decomp_contains_mcm(rule, params): if not rule.is_applicable(**params): return False resources = rule.compute_resources(**params).gate_counts return any(_is_measurement(resource_op) for resource_op in resources)