quantumlib / Cirq

A Python framework for creating, editing, and invoking Noisy Intermediate Scale Quantum (NISQ) circuits.
Apache License 2.0
4.24k stars 1.01k forks source link

Incorrect behaviour when inserting classical control circuit element, causing `ValueError` #6727

Open Bennybenassius opened 2 weeks ago

Bennybenassius commented 2 weeks ago

Description of the issue Under specific circumstances, it seems that classical controls are inserted wrongly and causing errors when getting measurement keys.

How to reproduce the issue

Run the following code:

from cirq import *
from cirq.transformers import *
import numpy as np

all_passes = { "align_left": align_left, "align_right": align_right}

def individual_pass(circ : Circuit, circ_num : int, pass_to_do : str):
    simulator = Simulator()
    shots = 1024

    # Takes the modified copy of circ
    if pass_to_do == "merge_k_qubit_unitaries":
        circ_new = all_passes[pass_to_do](circ, k=np.random.randint(1, 5))
    else :
        circ_new = all_passes[pass_to_do](circ)
    c_orig = simulator.run(circ, repetitions=shots).histogram(key="results")
    c_new = simulator.run(circ_new, repetitions=shots).histogram(key='results')

# Adding qubits 
qubits = NamedQubit.range(6, prefix="q")

main_circ = Circuit()

main_circ.append(measure(qubits[4], key="cbit0"))
main_circ.append(ry(0.645000).on(qubits[1]).with_classical_controls('cbit0'), strategy=InsertStrategy.INLINE) #Comment me out
# main_circ.append(ry(0.645000).on(qubits[1]).with_classical_controls('cbit0'), strategy=InsertStrategy.EARLIEST) #Uncomment me for working circuit

main_circ.append(measure(qubits, key="results"))
print(main_circ)
individual_pass(main_circ, 26, "align_right")
#individual_pass(main_circ, 26, "align_left") #Or uncomment me

The code above will run into an issue where the ry gate with classical controls will return an error where it cannot find the key cbit0, even though it was inserted before it.

Changing the circuit such that the passes use an insert strategy of EARLIEST or NEW_THEN_INLINE would make it work. Changing the pass to apply on the circuit to align_left instead would also make the circuit not throw an exception, however the resulting circuit would look the same as the wrong one. The commented lines of code above can be uncommented to demonstrate this.

Circuit that doesn't work looks like this: ```sh ┌───────────┐ q0: ──────────────────────M('results')─── │ q1: ────────Ry(0.205π)────M────────────── ║ │ q2: ────────╫─────────────M────────────── ║ │ q3: ────────╫─────────────M────────────── ║ │ q4: ───────M╫─────────────M────────────── ║║ │ q5: ───────╫╫─────────────M────────────── ║║ cbit0: ════@^════════════════════════════ └───────────┘ ``` This also throws an error: ```sh ValueError: Measurement key cbit0 missing when testing classical control ``` Circuit that works looks like this: ```sh q0: ───────────────────────M('results')─── │ q1: ──────────Ry(0.205π)───M────────────── ║ │ q2: ──────────╫────────────M────────────── ║ │ q3: ──────────╫────────────M────────────── ║ │ q4: ──────M───╫────────────M────────────── ║ ║ │ q5: ──────╫───╫────────────M────────────── ║ ║ cbit0: ═══@═══^═══════════════════════════ ``` Using `align right` would give the same looking circuit without any exceptions thrown: ```sh ┌───────────┐ q0: ──────────────────────M('results')─── │ q1: ────────Ry(0.205π)────M────────────── ║ │ q2: ────────╫─────────────M────────────── ║ │ q3: ────────╫─────────────M────────────── ║ │ q4: ───────M╫─────────────M────────────── ║║ │ q5: ───────╫╫─────────────M────────────── ║║ cbit0: ════@^════════════════════════════ └───────────┘ ```

Cirq version

1.4.1

daxfohl commented 1 week ago

Looks like the INLINE strategy here https://github.com/quantumlib/Cirq/blob/d74e0dce73adf45f15b873bf28236ef355d960ce/cirq-core/cirq/circuits/circuit.py#L2095-L2098, the _can_add_op_at it calls doesn't take measurement keys into account. This seems like it would also allow for creating multiple measurement ops measuring to the same key in the same moment.