Skip to content

Commit

Permalink
Fix process-based non-determinism in SparsePauliOp.to_matrix (#13439)
Browse files Browse the repository at this point in the history
* Fix process-based non-determinism in `SparsePauliOp.to_matrix`

The simplification step of the summed Pauli terms in
`SparsePauliOp.to_matrix` had introduced a non-determinism via hash-map
iteration.  In practice, the base hash seed was set per initialisation
of the extension module, then stayed the same.  This is hard to detect
from within tests, but caused unexpected numerical behaviour on
different invocations of the same script.

* Use ahash::RandomState

---------

Co-authored-by: Kevin Hartman <[email protected]>
  • Loading branch information
jakelishman and kevinhartman authored Nov 14, 2024
1 parent b258efc commit 74b32c9
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
8 changes: 7 additions & 1 deletion crates/accelerate/src/sparse_pauli_op.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
// copyright notice, and modified files need to carry a notice indicating
// that they have been altered from the originals.

use ahash::RandomState;
use pyo3::exceptions::{PyRuntimeError, PyValueError};
use pyo3::prelude::*;
use pyo3::types::PyTuple;
Expand All @@ -20,6 +21,7 @@ use numpy::prelude::*;
use numpy::{PyArray1, PyArray2, PyReadonlyArray1, PyReadonlyArray2, PyUntypedArrayMethods};

use hashbrown::HashMap;
use indexmap::IndexMap;
use ndarray::{s, ArrayView1, ArrayView2, Axis};
use num_complex::Complex64;
use num_traits::Zero;
Expand Down Expand Up @@ -298,7 +300,11 @@ impl MatrixCompressedPaulis {
/// explicitly stored operations, if there are duplicates. After the summation, any terms that
/// have become zero are dropped.
pub fn combine(&mut self) {
let mut hash_table = HashMap::<(u64, u64), Complex64>::with_capacity(self.coeffs.len());
let mut hash_table =
IndexMap::<(u64, u64), Complex64, RandomState>::with_capacity_and_hasher(
self.coeffs.len(),
RandomState::new(),
);
for (key, coeff) in self
.x_like
.drain(..)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
fixes:
- |
Fixed a per-process based non-determinism in `SparsePauliOp.to_matrix`. The exact order of the
floating-point operations in the summation would previously vary per process, but will now be
identical between different invocations of the same script. See `#13413 <https://github.com/Qiskit/qiskit/issues/13413>`__.

0 comments on commit 74b32c9

Please sign in to comment.