NVIDIA / cuda-quantum

C++ and Python support for the CUDA Quantum programming model for heterogeneous quantum-classical workflows
https://nvidia.github.io/cuda-quantum/
Other
458 stars 161 forks source link

Endian is inconsistent between State and SpinOperator.to_matrix #1895

Open ikkoham opened 1 month ago

ikkoham commented 1 month ago

Required prerequisites

Describe the bug

Endian is inconsistent between State and SpinOperator.to_matrix.

Steps to reproduce the bug

@cudaq.kernel
def bell():
    qubits = cudaq.qvector(2)
    h(qubits[0])
observable = cudaq.SpinOperator.from_word("XZ")
res = cudaq.observe(bell, observable)
print(res.expectation())

0.9999999403953552

state = np.array(cudaq.get_state(bell))
print(state @ observable.to_matrix() @ state)

0j

Expected behavior

These two examples should return the same result. In my understanding, CUDA-Q is big-endian, so observe's behavior is correct.

Is this a regression? If it is, put the last known working version (or commit) here.

Not a regression

Environment

Suggestions

No response

ikkoham commented 1 month ago

Workaround:

def reverse_endian(spin: cudaq.SpinOperator) -> cudaq.SpinOperator:
    return sum(
        term.get_coefficient() * SpinOperator.from_word(term.to_string(False)[::-1])
        for term in spin
    )

print(state @ reverse_endian(observable).to_matrix() @ state)
ikkoham commented 1 month ago

I think the endian of observable.to_matrix() is wrong. [should be confirmed]