Skip to content

Commit

Permalink
Fix random seed initialization between runs in SabreSwap (#9127)
Browse files Browse the repository at this point in the history
* Fix random seed initialization between runs in SabreSwap

This commit fixes an issue in the case no random seed is provided by the
user when initializing an instance of SabreSwap. The pass was previously
potentially reusing the random seed between runs even if no seed was
specified. This was an artifact of storing the initial seed as an
instance variable. Instead this commit just relies on the the Rust RNG
to initialize from entropy if no seed is specified.

* Remove unused numpy import

(cherry picked from commit dfbc738)
  • Loading branch information
mtreinish authored and mergify[bot] committed Nov 15, 2022
1 parent 93791df commit 97d7f07
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 9 deletions.
8 changes: 1 addition & 7 deletions qiskit/transpiler/passes/routing/sabre_swap.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
import logging
from copy import copy, deepcopy

import numpy as np
import retworkx

from qiskit.circuit.library.standard_gates import SwapGate
Expand Down Expand Up @@ -151,12 +150,7 @@ def __init__(self, coupling_map, heuristic="basic", seed=None, fake_run=False, t
self._neighbor_table = NeighborTable(retworkx.adjacency_matrix(self.coupling_map.graph))

self.heuristic = heuristic

if seed is None:
ii32 = np.iinfo(np.int32)
self.seed = np.random.default_rng(None).integers(0, ii32.max, dtype=int)
else:
self.seed = seed
self.seed = seed
if trials is None:
self.trials = CPU_COUNT
else:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
fixes:
- |
Fixed an issue with the :class:`~.SabreSwap` pass which would cause the
output of multiple runs of the pass without the ``seed`` argument specified
to reuse the same random number generator seed between runs instead of
using different seeds. This previously caused identical results to be
returned between runs even when no ``seed`` was specified.
7 changes: 5 additions & 2 deletions src/sabre_swap/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,14 +158,17 @@ pub fn build_swap_map(
neighbor_table: &NeighborTable,
distance_matrix: PyReadonlyArray2<f64>,
heuristic: &Heuristic,
seed: u64,
seed: Option<u64>,
layout: &mut NLayout,
num_trials: usize,
) -> (SwapMap, PyObject) {
let run_in_parallel = getenv_use_multiple_threads();
let dist = distance_matrix.as_array();
let coupling_graph: DiGraph<(), ()> = cmap_from_neighor_table(neighbor_table);
let outer_rng = Pcg64Mcg::seed_from_u64(seed);
let outer_rng = match seed {
Some(seed) => Pcg64Mcg::seed_from_u64(seed),
None => Pcg64Mcg::from_entropy(),
};
let seed_vec: Vec<u64> = outer_rng
.sample_iter(&rand::distributions::Standard)
.take(num_trials)
Expand Down

0 comments on commit 97d7f07

Please sign in to comment.