Skip to content

insertion_sort_transformerreorders measures that write to the same clbit #7619

@p51lee

Description

@p51lee

Describe the issue

insertion_sort_transformer can reorder measures that write to the same classical bit (same measurement key).
When two or more measurements write to the same clbit, their relative order matters because later writes overwrite earlier values. The transformer currently shuffles these writes, changing circuit semantics.

Example

In this circuit, q_1 is put in superposition and then measured into m_c1_0. There's also a fixed measurement of q_2 that always writes 0 into the same clbit m_c1_0. In the original circuit, the last write to m_c1_0 is the measure of q_1, so it should be 0 or 1 with ~50/50 frequency. After transformation, the q_2 measurement is moved to be the last writer into m_c1_0, forcing it to 0 and changing behavior.

Original:
                         ┌──────────────────────────────┐   ┌────────────┐
q_0: ──────M('m_c0_0')─────X(conditions=[Eq(m_c1_0, 1)])─────────────────────
                           ║
q_1: ──────H───────────────╫─────────────────────────────────M───────────────
                           ║                                 ║
q_2: ──────M──────────────X╫─────────────────────────────────╫M('m_c0_0')────
           ║               ║                                 ║
m_c1_0: ═══@═══════════════^═════════════════════════════════@═══════════════
                         └──────────────────────────────┘   └────────────┘
Transformed (after insertion_sort_transformer)
q_0: ──────M('m_c0_0')───X(conditions=[Eq(m_c1_0, 1)])─────────────────────────────
                         ║
q_1: ──────H─────────────╫───────────────────────────────M─────────────────────────
                         ║                               ║
q_2: ────────────────────╫───────────────────────────────╫───M───X───M('m_c0_0')───
                         ║                               ║   ║
m_c1_0: ═════════════════^═══════════════════════════════@═══@═════════════════════

Explain how to reproduce the bug or problem

from cirq.contrib.qasm_import import circuit_from_qasm
from cirq.transformers import insertion_sort_transformer

qasm = """OPENQASM 2.0;
include "qelib1.inc";

qreg q[3];
creg m_c0[1];
creg m_c1[1];

measure q[2] -> m_c1[0];
x q[2];
h q[1];
measure q[0] -> m_c0[0];
if(m_c1==1) x q[0];
measure q[1] -> m_c1[0];
measure q[2] -> m_c0[0];
"""

circuit = circuit_from_qasm(qasm)
print(circuit)

circuit = insertion_sort_transformer(circuit)
print(circuit)

Tell us the version of Cirq where this happens

Cirq version: 1.6.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    kind/bug-reportSomething doesn't seem to work.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions