Skip to content

Commit

Permalink
Port star_preroute to rust (#12761)
Browse files Browse the repository at this point in the history
* This commit ports the core logic of `star_preroute` from Python to Rust. The changes involve creating a new Rust module for the star prerouting algorithm and updating the corresponding Python code to integrate with this new Rust functionality.

Details:
- New Rust file: Added `star_preroute.rs` to handle the core logic of the function `star_preroute` from the python side. This file defines the type aliases for node and block representations, which matches the current block representation of the `StarBlock` (except that the center is just a bool, as we only need to know if there is a center), and the node representation matches how the nodes used in `SabreDAG`. The `star_preroute` function processes the star blocks witihin the `SabreDAG`  and finds the linear routing equivalent and then returns the result as a `SabreResult`. Thus we can use the same methods we used in Sabre, such as `_build_sabre_dag` and `_apply_sabre_result`.
- Node representation: A key part of this implementation is how it takes advantage of `SabreResult` and `SabreDAG`, so the node representation is a tuple of the node id, list of qubit indices, a set of classical bit indices, and a directive flag. However, once we update the regular DAG to rust, this part may change significantly.
- Updates in the SABRE rust module: To use `sabre_dag.rs` and `swap_map.rs` in `star_prerouting`, I change them to be public in `crates/accelerate/src/sabre/mod.rs`. Not sure if it makes more sense to do it this way or to move `star_prerouting` to `crates/accelerate/src/sabre/` since it mimics the methods used in Sabre to change the dag.
- Python side updates: Imported the necessary modules and only modified the function `star_preroute` so that now the function performs the heavy lifting of transforming the DAG within the Rust space, leveraging `_build_sabre_dag` and `_apply_sabre_result`.
- Possible issues: I was not sure how correctly handle control flow from the rust side. I know that `route.rs` handles this with `route_control_flow_block` to populate the `node_block_results` for `SabreResult`, but I was not sure how to best take advantage of this function for `star_prerouting`. Currently, the `node_block_results` for `star_prerouting` essentially always empty and just there to have`SabreResult`. There also seems to be no unit tests for `star_prerouting` that includes control flow.

* lint

* Added additional test and adjust the swap map result

- Added the additional test of qft linearization and that the resultings circuit has `n-2` swap gates where `n` is the number of cp gates.
- Changed the `node_id` in `apply_swap` of `star_preroute.rs` to use the current node id as it is more efficient, but just does not match how we do it in Sabre. This makes it so that we apply the gate first then the swap, which fixes an error we had before where we never placed a swap gate at the end of the processing a block. This only affected tests where we had multiple blocks to process. To make sure we apply the results correctly from `SabreResult`, I added a flag to `_apply_sabre_result` to treat the case of `StarPrerouting` differently so that it applies the swap after applying the node.
- Added a hasp map from node to block to make processing each node in the given processing order have `n + n` time complexity instead of `n^2`. As a result, we can also remove the function `find_block_id`

* Reverted changes to `_apply_sabre_result` and fixed handling on rust side

- Removed `apply_swap_first` flag in `_apply_sabre_result` as it did not make sense to have it as there are no other scenario where a user may want to have control over applying the swap first.
- To adjust for this and make `star_preroute` consistent with `apply_sabre_result` to apply swaps before the node id on the swap map, I adjusted `star_preroute.rs` to first process the blocks to gather the swap locations and the gate order. Once we have the full gate order, we can use the swap locations to apply the swaps while knowing the `qargs` of the node before the swap and the `node_id` of the node after the swap.
- Since the above in done in the main `star_preroute` function, I removed `qubit_ampping` and `out_map` as arguments for `process_blocks`.
  • Loading branch information
henryzou50 authored Jul 29, 2024
1 parent bfd2eea commit b23c545
Show file tree
Hide file tree
Showing 8 changed files with 333 additions and 108 deletions.
1 change: 1 addition & 0 deletions crates/accelerate/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ pub mod results;
pub mod sabre;
pub mod sampled_exp_val;
pub mod sparse_pauli_op;
pub mod star_prerouting;
pub mod stochastic_swap;
pub mod synthesis;
pub mod target_transpiler;
Expand Down
4 changes: 2 additions & 2 deletions crates/accelerate/src/sabre/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ mod layer;
mod layout;
mod neighbor_table;
mod route;
mod sabre_dag;
mod swap_map;
pub mod sabre_dag;
pub mod swap_map;

use hashbrown::HashMap;
use numpy::{IntoPyArray, ToPyArray};
Expand Down
214 changes: 214 additions & 0 deletions crates/accelerate/src/star_prerouting.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
// This code is part of Qiskit.
//
// (C) Copyright IBM 2024
//
// This code is licensed under the Apache License, Version 2.0. You may
// obtain a copy of this license in the LICENSE.txt file in the root directory
// of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
//
// Any modifications or derivative works of this code must retain this
// copyright notice, and modified files need to carry a notice indicating
// that they have been altered from the originals.

/// Type alias for a node representation.
/// Each node is represented as a tuple containing:
/// - Node id (usize)
/// - List of involved qubit indices (Vec<VirtualQubit>)
/// - Set of involved classical bit indices (HashSet<usize>)
/// - Directive flag (bool)
type Nodes = (usize, Vec<VirtualQubit>, HashSet<usize>, bool);

/// Type alias for a block representation.
/// Each block is represented by a tuple containing:
/// - A boolean indicating the presence of a center (bool)
/// - A list of nodes (Vec<Nodes>)
type Block = (bool, Vec<Nodes>);

use crate::nlayout::PhysicalQubit;
use crate::nlayout::VirtualQubit;
use crate::sabre::sabre_dag::SabreDAG;
use crate::sabre::swap_map::SwapMap;
use crate::sabre::BlockResult;
use crate::sabre::NodeBlockResults;
use crate::sabre::SabreResult;
use hashbrown::HashMap;
use hashbrown::HashSet;
use numpy::IntoPyArray;
use pyo3::prelude::*;

/// Python function to perform star prerouting on a SabreDAG.
/// This function processes star blocks and updates the DAG and qubit mapping.
#[pyfunction]
#[pyo3(text_signature = "(dag, blocks, processing_order, /)")]
fn star_preroute(
py: Python,
dag: &mut SabreDAG,
blocks: Vec<Block>,
processing_order: Vec<Nodes>,
) -> (SwapMap, PyObject, NodeBlockResults, PyObject) {
let mut qubit_mapping: Vec<usize> = (0..dag.num_qubits).collect();
let mut processed_block_ids: HashSet<usize> = HashSet::with_capacity(blocks.len());
let last_2q_gate = processing_order.iter().rev().find(|node| node.1.len() == 2);
let mut is_first_star = true;

// Structures for SabreResult
let mut out_map: HashMap<usize, Vec<[PhysicalQubit; 2]>> =
HashMap::with_capacity(dag.dag.node_count());
let mut gate_order: Vec<usize> = Vec::with_capacity(dag.dag.node_count());
let node_block_results: HashMap<usize, Vec<BlockResult>> = HashMap::new();

// Create a HashMap to store the node-to-block mapping
let mut node_to_block: HashMap<usize, usize> = HashMap::with_capacity(processing_order.len());
for (block_id, block) in blocks.iter().enumerate() {
for node in &block.1 {
node_to_block.insert(node.0, block_id);
}
}
// Store nodes where swaps will be placed.
let mut swap_locations: Vec<&Nodes> = Vec::with_capacity(processing_order.len());

// Process blocks, gathering swap locations and updating the gate order
for node in &processing_order {
if let Some(&block_id) = node_to_block.get(&node.0) {
// Skip if the block has already been processed
if !processed_block_ids.insert(block_id) {
continue;
}
process_block(
&blocks[block_id],
last_2q_gate,
&mut is_first_star,
&mut gate_order,
&mut swap_locations,
);
} else {
// Apply operation for nodes not part of any block
gate_order.push(node.0);
}
}

// Apply the swaps based on the gathered swap locations and gate order
for (index, node_id) in gate_order.iter().enumerate() {
for swap_location in &swap_locations {
if *node_id == swap_location.0 {
if let Some(next_node_id) = gate_order.get(index + 1) {
apply_swap(
&mut qubit_mapping,
&swap_location.1,
*next_node_id,
&mut out_map,
);
}
}
}
}

let res = SabreResult {
map: SwapMap { map: out_map },
node_order: gate_order,
node_block_results: NodeBlockResults {
results: node_block_results,
},
};

let final_res = (
res.map,
res.node_order.into_pyarray_bound(py).into(),
res.node_block_results,
qubit_mapping.into_pyarray_bound(py).into(),
);

final_res
}

/// Processes a star block, applying operations and handling swaps.
///
/// Args:
///
/// * `block` - A tuple containing a boolean indicating the presence of a center and a vector of nodes representing the star block.
/// * `last_2q_gate` - The last two-qubit gate in the processing order.
/// * `is_first_star` - A mutable reference to a boolean indicating if this is the first star block being processed.
/// * `gate_order` - A mutable reference to the gate order vector.
/// * `swap_locations` - A mutable reference to the nodes where swaps will be placed after
fn process_block<'a>(
block: &'a Block,
last_2q_gate: Option<&'a Nodes>,
is_first_star: &mut bool,
gate_order: &mut Vec<usize>,
swap_locations: &mut Vec<&'a Nodes>,
) {
let (has_center, sequence) = block;

// If the block contains exactly 2 nodes, apply them directly
if sequence.len() == 2 {
for inner_node in sequence {
gate_order.push(inner_node.0);
}
return;
}

let mut prev_qargs = None;
let mut swap_source = false;

// Process each node in the block
for inner_node in sequence.iter() {
// Apply operation directly if it's a single-qubit operation or the same as previous qargs
if inner_node.1.len() == 1 || prev_qargs == Some(&inner_node.1) {
gate_order.push(inner_node.0);
continue;
}

// If this is the first star and no swap source has been identified, set swap_source
if *is_first_star && !swap_source {
swap_source = *has_center;
gate_order.push(inner_node.0);
prev_qargs = Some(&inner_node.1);
continue;
}

// Place 2q-gate and subsequent swap gate
gate_order.push(inner_node.0);

if inner_node != last_2q_gate.unwrap() && inner_node.1.len() == 2 {
swap_locations.push(inner_node);
}
prev_qargs = Some(&inner_node.1);
}
*is_first_star = false;
}

/// Applies a swap operation to the DAG and updates the qubit mapping.
///
/// # Args:
///
/// * `qubit_mapping` - A mutable reference to the qubit mapping vector.
/// * `qargs` - Qubit indices for the swap operation (node before the swap)
/// * `next_node_id` - ID of the next node in the gate order (node after the swap)
/// * `out_map` - A mutable reference to the output map.
fn apply_swap(
qubit_mapping: &mut [usize],
qargs: &[VirtualQubit],
next_node_id: usize,
out_map: &mut HashMap<usize, Vec<[PhysicalQubit; 2]>>,
) {
if qargs.len() == 2 {
let idx0 = qargs[0].index();
let idx1 = qargs[1].index();

// Update the `qubit_mapping` and `out_map` to reflect the swap operation
qubit_mapping.swap(idx0, idx1);
out_map.insert(
next_node_id,
vec![[
PhysicalQubit::new(qubit_mapping[idx0].try_into().unwrap()),
PhysicalQubit::new(qubit_mapping[idx1].try_into().unwrap()),
]],
);
}
}

#[pymodule]
pub fn star_prerouting(m: &Bound<PyModule>) -> PyResult<()> {
m.add_wrapped(wrap_pyfunction!(star_preroute))?;
Ok(())
}
8 changes: 5 additions & 3 deletions crates/pyext/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@ use qiskit_accelerate::{
error_map::error_map, euler_one_qubit_decomposer::euler_one_qubit_decomposer,
isometry::isometry, nlayout::nlayout, optimize_1q_gates::optimize_1q_gates,
pauli_exp_val::pauli_expval, results::results, sabre::sabre, sampled_exp_val::sampled_exp_val,
sparse_pauli_op::sparse_pauli_op, stochastic_swap::stochastic_swap, synthesis::synthesis,
target_transpiler::target, two_qubit_decompose::two_qubit_decompose, uc_gate::uc_gate,
utils::utils, vf2_layout::vf2_layout,
sparse_pauli_op::sparse_pauli_op, star_prerouting::star_prerouting,
stochastic_swap::stochastic_swap, synthesis::synthesis, target_transpiler::target,
two_qubit_decompose::two_qubit_decompose, uc_gate::uc_gate, utils::utils,
vf2_layout::vf2_layout,
};

#[pymodule]
Expand All @@ -41,6 +42,7 @@ fn _accelerate(m: &Bound<PyModule>) -> PyResult<()> {
m.add_wrapped(wrap_pymodule!(sabre))?;
m.add_wrapped(wrap_pymodule!(sampled_exp_val))?;
m.add_wrapped(wrap_pymodule!(sparse_pauli_op))?;
m.add_wrapped(wrap_pymodule!(star_prerouting))?;
m.add_wrapped(wrap_pymodule!(stochastic_swap))?;
m.add_wrapped(wrap_pymodule!(target))?;
m.add_wrapped(wrap_pymodule!(two_qubit_decompose))?;
Expand Down
1 change: 1 addition & 0 deletions qiskit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@
sys.modules["qiskit._accelerate.sabre"] = _accelerate.sabre
sys.modules["qiskit._accelerate.sampled_exp_val"] = _accelerate.sampled_exp_val
sys.modules["qiskit._accelerate.sparse_pauli_op"] = _accelerate.sparse_pauli_op
sys.modules["qiskit._accelerate.star_prerouting"] = _accelerate.star_prerouting
sys.modules["qiskit._accelerate.stochastic_swap"] = _accelerate.stochastic_swap
sys.modules["qiskit._accelerate.target"] = _accelerate.target
sys.modules["qiskit._accelerate.two_qubit_decompose"] = _accelerate.two_qubit_decompose
Expand Down
Loading

0 comments on commit b23c545

Please sign in to comment.