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

Return more info about circuit separation during partitioning #304

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
3 changes: 3 additions & 0 deletions circuit_knitting/cutting/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
:template: autosummary/class_no_inherited_members.rst

PartitionedCuttingProblem
CutInfo
CuttingExperimentResults

Quasi-Probability Decomposition (QPD)
Expand Down Expand Up @@ -80,6 +81,7 @@
cut_gates,
decompose_gates,
PartitionedCuttingProblem,
CutInfo,
)
from .cutting_evaluation import execute_experiments, CuttingExperimentResults
from .cutting_reconstruction import reconstruct_expectation_values
Expand All @@ -92,5 +94,6 @@
"execute_experiments",
"reconstruct_expectation_values",
"PartitionedCuttingProblem",
"CutInfo",
"CuttingExperimentResults",
]
52 changes: 43 additions & 9 deletions circuit_knitting/cutting/cutting_decomposition.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,34 @@
from ..utils.observable_grouping import observables_restricted_to_subsystem
from ..utils.transforms import separate_circuit
from .qpd.qpd_basis import QPDBasis
from .qpd.instructions import TwoQubitQPDGate
from .qpd.instructions import BaseQPDGate, SingleQubitQPDGate, TwoQubitQPDGate


class PartitionedCuttingProblem(NamedTuple):
"""The result of decomposing and separating a circuit and observable(s)."""

subcircuits: dict[str | int, QuantumCircuit]
bases: list[QPDBasis]
subobservables: dict[str | int, QuantumCircuit] | None = None
subcircuits: dict[Hashable, QuantumCircuit]
cuts: list[CutInfo]
subobservables: dict[Hashable, QuantumCircuit] | None = None


class CutInfo(NamedTuple):
"""
The decomposition and circuit index information associated with one cut.

If the cut is associated with more than one subcircuit, the ``gates`` field should
be represented as a list of length-2 tuples containing the partition labels and
subcircuit instruction indices to the associated gates.

If the cut is associated with more than one :class:`~circuit_knitting.cutting.qpd.SingleQubitQPDGate` in an unseparated
circuit, the ``gates`` may be specified as a list of circuit indices to those gates.

If the cut is associated with a single :class:`~circuit_knitting.cutting.qpd.BaseQPDGate` instance in an unseparated circuit, the ``gates``
may be specified by a single index to the gate.
"""

basis: QPDBasis
gates: list[tuple[Hashable, int]] | list[int] | int


def partition_circuit_qubits(
Expand Down Expand Up @@ -195,6 +214,7 @@ def partition_problem(
ValueError: An input observable acts on a different number of qubits than the input circuit.
ValueError: An input observable has a phase not equal to 1.
ValueError: The input circuit should contain no classical bits or registers.
ValueError: The input circuit should contain no :class:`~circuit_knitting.cutting.qpd.SingleQubitQPDGate` instances.
"""
if len(partition_labels) != circuit.num_qubits:
raise ValueError(
Expand All @@ -221,14 +241,28 @@ def partition_problem(
bases = []
i = 0
for inst in qpd_circuit.data:
if isinstance(inst.operation, SingleQubitQPDGate):
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

We probably want to support these for wire cutting, but they are not well-handled as of this PR, so this ValueError is appropriate. We can remove it for the wire cutting PR, if necessary

raise ValueError(
"Input circuit may not contain SingleQubitQPDGate instances."
)
if isinstance(inst.operation, TwoQubitQPDGate):
bases.append(inst.operation.basis)
inst.operation.label = inst.operation.label + f"_{i}"
i += 1

# Separate the decomposed circuit into its subcircuits
qpd_circuit_dx = qpd_circuit.decompose(TwoQubitQPDGate)
separated_circs = separate_circuit(qpd_circuit_dx, partition_labels)
subcircuits = separate_circuit(qpd_circuit_dx, partition_labels).subcircuits

# Gather the basis and location information for the cuts
cuts_dict = defaultdict(list)
for label in subcircuits.keys():
circuit = subcircuits[label]
for i, inst in enumerate(circuit.data):
if isinstance(inst.operation, BaseQPDGate):
cut_num = int(inst.operation.label.split("_")[-1])
cuts_dict[cut_num].append((label, i))
cuts = [CutInfo(basis, cuts_dict[cut_num]) for cut_num, basis in enumerate(bases)]

# Decompose the observables, if provided
subobservables_by_subsystem = None
Expand All @@ -238,15 +272,15 @@ def partition_problem(
)

return PartitionedCuttingProblem(
separated_circs.subcircuits, # type: ignore
bases,
subcircuits,
cuts,
subobservables=subobservables_by_subsystem,
)


def decompose_observables(
observables: PauliList, partition_labels: Sequence[str | int]
) -> dict[str | int, PauliList]:
observables: PauliList, partition_labels: Sequence[Hashable]
) -> dict[Hashable, PauliList]:
"""
Decompose a list of observables with respect to some qubit partition labels.

Expand Down
2 changes: 1 addition & 1 deletion circuit_knitting/cutting/cutting_reconstruction.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def reconstruct_expectation_values(
for label, subobservable in observables.items():
if any(obs.phase != 0 for obs in subobservable):
raise ValueError("An input observable has a phase not equal to 1.")
subobservables_by_subsystem = observables
subobservables_by_subsystem = observables # type: ignore
Copy link
Collaborator Author

@caleb-johnson caleb-johnson Jul 4, 2023

Choose a reason for hiding this comment

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

I believe this is a false positive from mypy. The variable is a dict[Hashable, Any], and the expression is a dict[str | int, Any]. I believe the expression type lies in a subset of the variable type, which should be fine.

Copy link
Member

@garrison garrison Jul 5, 2023

Choose a reason for hiding this comment

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

https://mypy.readthedocs.io/en/stable/generics.html#variance-of-generic-types explains why dict is considered an invariant type rather than a covariant type. But yes, I think ignoring this type check makes the most sense for now.

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Cool, since this is technically correct, this means we have "correct" type hints with respect to Hashable and str | int. All the functions correctly indicate what functionality they expect

expvals = np.zeros(len(list(observables.values())[0]))

subsystem_observables = {
Expand Down

Large diffs are not rendered by default.

6 changes: 6 additions & 0 deletions releasenotes/notes/cut-info-49e59b465b64d48f.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
upgrade:
- |
Introduction of `~circuit_knitting.cutting.CutInfo` class, which contains the decomposition and gate index information for a single cut.

Removed the ``bases`` field from the :class:`~circuit_knitting.cutting.PartitionedCuttingProblem` class in favor of a ``cuts`` field. Users may now extract the :class:`~circuit_knitting.cutting.qpd.QPDBasis` instances from the ``basis`` field of each `~circuit_knitting.cutting.CutInfo` instance in ``cuts``.
3 changes: 2 additions & 1 deletion test/cutting/test_backwards_compatibility.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,10 @@ def test_v0_2_cutting_width_workflow():
circuit = EfficientSU2(4, entanglement="linear", reps=2).decompose()
circuit.assign_parameters([0.8] * len(circuit.parameters), inplace=True)
observables = PauliList(["ZZII", "IZZI", "IIZZ", "XIXI", "ZIZZ", "IXIX"])
subcircuits, bases, subobservables = partition_problem(
subcircuits, cuts, subobservables = partition_problem(
circuit=circuit, partition_labels="AABB", observables=observables
)
bases = [cut_info.basis for cut_info in cuts]
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

This PR is a breaking change, users now need to get each basis from the CutInfo object

assert np.prod([basis.overhead for basis in bases]) == pytest.approx(81)

samplers = {
Expand Down
18 changes: 17 additions & 1 deletion test/cutting/test_cutting_decomposition.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
)
from circuit_knitting.cutting.qpd import (
QPDBasis,
SingleQubitQPDGate,
TwoQubitQPDGate,
BaseQPDGate,
)
Expand Down Expand Up @@ -170,7 +171,22 @@ def test_partition_problem(self):
compare_obs = {"A": PauliList(["XX"]), "B": PauliList(["ZZ"])}

self.assertEqual(subobservables, compare_obs)

with self.subTest("test single qubit qpd gate input"):
# Split 4q HWEA in middle of qubits
partition_labels = "AABB"
circuit = self.circuit.copy()
circuit.data.append(
CircuitInstruction(
SingleQubitQPDGate(QPDBasis.from_gate(CXGate()), qubit_id=0),
qubits=[0],
)
)
with pytest.raises(ValueError) as e_info:
partition_problem(circuit, partition_labels)
assert (
e_info.value.args[0]
== "Input circuit may not contain SingleQubitQPDGate instances."
)
with self.subTest("test mismatching inputs"):
# Split 4q HWEA in middle of qubits
partition_labels = "AB"
Expand Down