Investigate why some Python expectation value tests failed with NumPy 2
Describe the issue
When running the Python test cases (in /qsimcirq_tests) with NumPy 2, there are 2 cases that fail unless we loosen the numerical comparison tolerance by 1 order of magnitude. (Specifically, a tolerance of 1e-6 succeeds with NumPy 1, but fails in NP 2 unless I loosen the tolerance to 1e-5.) Those cases are not the only place where a tolerance of 1e-5 shows up in qsimcirq_tests; there's one other in that file. The exact cause is not clear. The failures occur only for the "noisy" versions of the two tests in question, which suggests the cause has something to do with that.
We should investigate this after the next qsim release.
What version of qsim are you using?
0.22.0.dev0
How can the issue be reproduced?
No response
Hey @mhucka , I came across this issue and would love to help investigate the root cause! I'm fairly new to open source contributions but I'm comfortable with Python and NumPy. Would it be okay if I take a look at this?
PR #755 addressed the symptom by loosening the tolerances, but the root cause still reamins open (why the noisy qtrajectory path loses an order of magnitude of precision under NumPy 2)
@suryanshsrivastava Thank you for your interest! I've assigned the issue to you.
Hey @mhucka, apologies for the delay. Missed this assignment here.
As mentioned earlier in #755, the test failures are because qsim_result is compared to cirq_result in:
- test_expectation_values (qsimcirq_tests/qsimcirq_test.py#L515) and
- test_cirq_qsim_circuit_memoization_simulate_expectation_values_sweep (qsimcirq_tests/qsimcirq_test.py#L2096),
The root cause is NumPy 2's new type promotion rules (NEP 50). Previously, operations between a complex64 array and a Python scalar silently upcast cirq's reference simulation to double precision. Under NumPy 2, it remains in single-precision (complex64).
Since both qsim and cirq now run in single-precision, their independent rounding errors can combine to an order of 10^-6 in tests like test_expectation_values, exceeding the old atol=1e-6 check.
Let me know what you think since a fix for this could be
- either keeping the atol=1e-5 tolerance as-is #755, or
- forcing the reference cirq simulator to use dtype=np.complex128 if we want to restore
atol=1e-6threshold.
@suryanshsrivastava Thank you! I'm leaning towards option 1, using 1e-5, as the better of the two options.
Thanks again.