Skip to content

Commit 41fe453

Browse files
committed
Fully port CheckMap to Rust
This commit migrates the entirety of the CheckMap analysis pass to Rust. The pass operates solely in the rust domain and returns an `Option<(String, [u32; 2])>` to Python which is used to set the two property set fields appropriately. All the analysis of the dag is done in Rust. There is still Python interaction required though because control flow operations are only defined in Python. However the interaction is minimal and only to get the circuits for control flow blocks and converting them into DAGs (at least until Qiskit#13001 is complete). This commit is based on top of Qiskit#12959 and will need to be rebased after that merges. Closes Qiskit#12251 Part of Qiskit#12208
1 parent 2c0aad5 commit 41fe453

File tree

5 files changed

+114
-31
lines changed

5 files changed

+114
-31
lines changed

crates/accelerate/src/check_map.rs

+93
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
// This code is part of Qiskit.
2+
//
3+
// (C) Copyright IBM 2024
4+
//
5+
// This code is licensed under the Apache License, Version 2.0. You may
6+
// obtain a copy of this license in the LICENSE.txt file in the root directory
7+
// of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
8+
//
9+
// Any modifications or derivative works of this code must retain this
10+
// copyright notice, and modified files need to carry a notice indicating
11+
// that they have been altered from the originals.
12+
13+
use hashbrown::{HashMap, HashSet};
14+
use pyo3::intern;
15+
use pyo3::prelude::*;
16+
use pyo3::wrap_pyfunction;
17+
18+
use qiskit_circuit::circuit_data::CircuitData;
19+
use qiskit_circuit::dag_circuit::{DAGCircuit, NodeType};
20+
use qiskit_circuit::imports::CIRCUIT_TO_DAG;
21+
use qiskit_circuit::operations::{Operation, OperationRef};
22+
use qiskit_circuit::Qubit;
23+
24+
fn recurse<'py>(
25+
py: Python<'py>,
26+
dag: &'py DAGCircuit,
27+
edge_set: &'py HashSet<[u32; 2]>,
28+
wire_map: Option<&'py HashMap<Qubit, Qubit>>,
29+
) -> PyResult<Option<(String, [u32; 2])>> {
30+
let check_qubits = |qubits: &[Qubit]| -> bool {
31+
match wire_map {
32+
Some(wire_map) => {
33+
let mapped_bits = [wire_map[&qubits[0]], wire_map[&qubits[1]]];
34+
edge_set.contains(&[mapped_bits[0].into(), mapped_bits[1].into()])
35+
}
36+
None => edge_set.contains(&[qubits[0].into(), qubits[1].into()]),
37+
}
38+
};
39+
for node in dag.op_nodes(false) {
40+
if let NodeType::Operation(inst) = &dag.dag[node] {
41+
let qubits = dag.get_qubits(inst.qubits);
42+
if inst.op.control_flow() {
43+
if let OperationRef::Instruction(py_inst) = inst.op.view() {
44+
let raw_blocks = py_inst.instruction.getattr(py, "blocks")?;
45+
let circuit_to_dag = CIRCUIT_TO_DAG.get_bound(py);
46+
for raw_block in raw_blocks.bind(py).iter().unwrap() {
47+
let block_obj = raw_block?;
48+
let block = block_obj
49+
.getattr(intern!(py, "_data"))?
50+
.extract::<CircuitData>()?;
51+
let new_dag: DAGCircuit =
52+
circuit_to_dag.call1((block_obj.clone(),))?.extract()?;
53+
let wire_map = (0..block.num_qubits())
54+
.map(|x| Qubit(x as u32))
55+
.zip(qubits)
56+
.map(|(inner, outer)| match wire_map {
57+
Some(wire_map) => (inner, wire_map[outer]),
58+
None => (inner, *outer),
59+
})
60+
.collect();
61+
let res = recurse(py, &new_dag, edge_set, Some(&wire_map))?;
62+
if res.is_some() {
63+
return Ok(res);
64+
}
65+
}
66+
}
67+
} else if qubits.len() == 2
68+
&& (dag.calibrations_empty() || !dag.has_calibration_for_index(py, node)?)
69+
&& !check_qubits(qubits)
70+
{
71+
return Ok(Some((
72+
inst.op.name().to_string(),
73+
[qubits[0].0, qubits[1].0],
74+
)));
75+
}
76+
}
77+
}
78+
Ok(None)
79+
}
80+
81+
#[pyfunction]
82+
pub fn check_map(
83+
py: Python,
84+
dag: &DAGCircuit,
85+
edge_set: HashSet<[u32; 2]>,
86+
) -> PyResult<Option<(String, [u32; 2])>> {
87+
recurse(py, dag, &edge_set, None)
88+
}
89+
90+
pub fn check_map_mod(m: &Bound<PyModule>) -> PyResult<()> {
91+
m.add_wrapped(wrap_pyfunction!(check_map))?;
92+
Ok(())
93+
}

crates/accelerate/src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ use std::env;
1414

1515
use pyo3::import_exception;
1616

17+
pub mod check_map;
1718
pub mod convert_2q_block_matrix;
1819
pub mod dense_layout;
1920
pub mod edge_collections;

crates/pyext/src/lib.rs

+9-8
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,14 @@
1313
use pyo3::prelude::*;
1414

1515
use qiskit_accelerate::{
16-
convert_2q_block_matrix::convert_2q_block_matrix, dense_layout::dense_layout,
17-
error_map::error_map, euler_one_qubit_decomposer::euler_one_qubit_decomposer,
18-
isometry::isometry, nlayout::nlayout, optimize_1q_gates::optimize_1q_gates,
19-
pauli_exp_val::pauli_expval, results::results, sabre::sabre, sampled_exp_val::sampled_exp_val,
20-
sparse_pauli_op::sparse_pauli_op, star_prerouting::star_prerouting,
21-
stochastic_swap::stochastic_swap, synthesis::synthesis, target_transpiler::target,
22-
two_qubit_decompose::two_qubit_decompose, uc_gate::uc_gate, utils::utils,
23-
vf2_layout::vf2_layout,
16+
check_map::check_map_mod, convert_2q_block_matrix::convert_2q_block_matrix,
17+
dense_layout::dense_layout, error_map::error_map,
18+
euler_one_qubit_decomposer::euler_one_qubit_decomposer, isometry::isometry, nlayout::nlayout,
19+
optimize_1q_gates::optimize_1q_gates, pauli_exp_val::pauli_expval, results::results,
20+
sabre::sabre, sampled_exp_val::sampled_exp_val, sparse_pauli_op::sparse_pauli_op,
21+
star_prerouting::star_prerouting, stochastic_swap::stochastic_swap, synthesis::synthesis,
22+
target_transpiler::target, two_qubit_decompose::two_qubit_decompose, uc_gate::uc_gate,
23+
utils::utils, vf2_layout::vf2_layout,
2424
};
2525

2626
#[inline(always)]
@@ -39,6 +39,7 @@ fn _accelerate(m: &Bound<PyModule>) -> PyResult<()> {
3939
add_submodule(m, qiskit_circuit::circuit, "circuit")?;
4040
add_submodule(m, qiskit_qasm2::qasm2, "qasm2")?;
4141
add_submodule(m, qiskit_qasm3::qasm3, "qasm3")?;
42+
add_submodule(m, check_map_mod, "check_map")?;
4243
add_submodule(m, convert_2q_block_matrix, "convert_2q_block_matrix")?;
4344
add_submodule(m, dense_layout, "dense_layout")?;
4445
add_submodule(m, error_map, "error_map")?;

qiskit/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@
8686
sys.modules["qiskit._accelerate.synthesis.linear"] = _accelerate.synthesis.linear
8787
sys.modules["qiskit._accelerate.synthesis.clifford"] = _accelerate.synthesis.clifford
8888
sys.modules["qiskit._accelerate.synthesis.linear_phase"] = _accelerate.synthesis.linear_phase
89+
sys.modules["qiskit._accelerate.check_map"] = _accelerate.check_map
8990

9091
from qiskit.exceptions import QiskitError, MissingOptionalLibraryError
9192

qiskit/transpiler/passes/utils/check_map.py

+10-23
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@
1414

1515
from qiskit.transpiler.basepasses import AnalysisPass
1616
from qiskit.transpiler.target import Target
17-
from qiskit.converters import circuit_to_dag
17+
18+
from qiskit._accelerate import check_map
1819

1920

2021
class CheckMap(AnalysisPass):
@@ -67,25 +68,11 @@ def run(self, dag):
6768
if not self.qargs:
6869
self.property_set[self.property_set_field] = True
6970
return
70-
wire_map = {bit: index for index, bit in enumerate(dag.qubits)}
71-
self.property_set[self.property_set_field] = self._recurse(dag, wire_map)
72-
73-
def _recurse(self, dag, wire_map) -> bool:
74-
for node in dag.op_nodes(include_directives=False):
75-
if node.is_control_flow():
76-
for block in node.op.blocks:
77-
inner_wire_map = {
78-
inner: wire_map[outer] for inner, outer in zip(block.qubits, node.qargs)
79-
}
80-
if not self._recurse(circuit_to_dag(block), inner_wire_map):
81-
return False
82-
elif (
83-
len(node.qargs) == 2
84-
and not dag.has_calibration_for(node)
85-
and (wire_map[node.qargs[0]], wire_map[node.qargs[1]]) not in self.qargs
86-
):
87-
self.property_set["check_map_msg"] = (
88-
f"{node.name}({wire_map[node.qargs[0]]}, {wire_map[node.qargs[1]]}) failed"
89-
)
90-
return False
91-
return True
71+
res = check_map.check_map(dag, self.qargs)
72+
if res is None:
73+
self.property_set[self.property_set_field] = True
74+
return
75+
self.property_set[self.property_set_field] = False
76+
self.property_set["check_map_msg"] = (
77+
f"{res[0]}({dag.qubits[res[1][0]]}, {dag.qubits[res[1][1]]}) failed"
78+
)

0 commit comments

Comments
 (0)