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

Inconsistent result of CSwapGate.controlled(1) after converting to QASM #6474

Closed jiannanWang closed 7 months ago

jiannanWang commented 7 months ago

Description of the issue

For a circuit consisting of only a CSwapGate.controlled(1) gate, the result changed after converting to QASM and converting back.

How to reproduce the issue

import cirq
from cirq import *

qr = cirq.LineQubit.range(4)
qc = cirq.Circuit()

qc.append(CSwapGate().controlled(1).on(qr[0], qr[1], qr[2], qr[3]))

simulator = cirq.Simulator()
result = simulator.simulate(qc)
st = result.final_state_vector

qasm_str = qc.to_qasm()
from cirq.contrib.qasm_import import circuit_from_qasm
new_qc = circuit_from_qasm(qasm_str)

new_simulater = cirq.Simulator()
new_result = new_simulater.simulate(new_qc)
new_st = new_result.final_state_vector
print(cirq.equal_up_to_global_phase(st, new_st))
False

Executing the above code results in False, meaning the result state vector changed after QASM round trip conversion.

Cirq version

1.3.0

pavoljuhas commented 7 months ago

cirq csynque suggestion - print out the qasm_str is the original circuit decomposed to simpler gate, is that decomposition accurate?

The phase vectors seem similar on printout except of some round-off errors. are there tolerances in the cirq.equal_up_to_global_phase function?

NoureldinYosri commented 7 months ago

either specifiying more digits in precision for the simulator new_simulater = cirq.Simulator(dtype=np.complex128) or increasing the tolerance of cirq.equal_up_to_global_phase (print(cirq.equal_up_to_global_phase(st, new_st, atol=1e-7))) . The exact round of error between st and new_st is ~1.8e-8 which is slightlty above the default atol=1e-8 of equal_up_to_global_phase

pavoljuhas commented 7 months ago

works as intended, round-off issue. We should still check if qasm has a more accurate representation for CSwapGate.