Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Port synth_cnot_phase_aam to Rust #12937

Draft
wants to merge 41 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
8da594c
initial commit
MozammilQ Aug 10, 2024
193058b
added some code
MozammilQ Aug 10, 2024
2ae9379
refactor code
MozammilQ Aug 22, 2024
d7f41b7
Merge branch 'main' into port-synth_cnot_phase_aam-to-rust
MozammilQ Aug 22, 2024
60379b2
done some cargo-clippy linting
MozammilQ Aug 23, 2024
671b634
added code
MozammilQ Aug 26, 2024
ae91425
added some more code
MozammilQ Aug 27, 2024
64ce56b
refactor code
MozammilQ Aug 27, 2024
fe01589
refactor code
MozammilQ Aug 27, 2024
1ecab6d
refactor code
MozammilQ Aug 28, 2024
a217522
refactor code
MozammilQ Aug 28, 2024
4a36e1e
refactor code
MozammilQ Aug 29, 2024
0b681f9
refactor code
MozammilQ Aug 29, 2024
d2142f6
refactor code
MozammilQ Aug 29, 2024
8982c2c
refactor code
MozammilQ Aug 29, 2024
032b8c2
removed associated python code
MozammilQ Aug 29, 2024
583ca17
rust lint
MozammilQ Aug 29, 2024
d1394f4
added release note; added docstring to rust algo
MozammilQ Aug 30, 2024
6956e0f
rust lint
MozammilQ Aug 30, 2024
0091c98
refactor code
MozammilQ Aug 30, 2024
92bf2aa
Merge branch 'main' into port-synth_cnot_phase_aam-to-rust
MozammilQ Aug 30, 2024
6b2d31e
Merge branch 'main' into port-synth_cnot_phase_aam-to-rust
MozammilQ Aug 31, 2024
156da41
applied suggestion partially
MozammilQ Sep 1, 2024
b236d62
reverting suggestions
MozammilQ Sep 2, 2024
d28da2a
added a test
MozammilQ Sep 4, 2024
4c32291
Merge branch 'Qiskit:main' into port-synth_cnot_phase_aam-to-rust
MozammilQ Oct 28, 2024
1c7ad1e
Merge branch 'main' into port-synth_cnot_phase_aam-to-rust
MozammilQ Oct 29, 2024
68917a0
Merge branch 'Qiskit:main' into port-synth_cnot_phase_aam-to-rust
MozammilQ Nov 1, 2024
5973f85
replace vector with iterator
MozammilQ Nov 1, 2024
353e5ff
refactor code; lint
MozammilQ Nov 1, 2024
6262d16
refactor code
MozammilQ Nov 4, 2024
41a8906
refactor code
MozammilQ Nov 5, 2024
0cd01ce
refactor code
MozammilQ Nov 5, 2024
75bc902
removed impl Iterator and applied from_fn
MozammilQ Nov 16, 2024
62aef8c
Merge branch 'Qiskit:main' into port-synth_cnot_phase_aam-to-rust
MozammilQ Nov 16, 2024
477e62e
removed moving from into_iter to vec to into_iter
MozammilQ Nov 16, 2024
f5a92c9
applied Julien suggestions
MozammilQ Nov 17, 2024
93375c5
applied some suggestions by Ivrii
MozammilQ Jan 12, 2025
cb2170c
typo added suggestion by Julien Gacon
MozammilQ Jan 13, 2025
2bdaaae
Merge branch 'Qiskit:main' into port-synth_cnot_phase_aam-to-rust
MozammilQ Jan 13, 2025
843c220
renamed variables; added comments
MozammilQ Jan 14, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/accelerate/src/synthesis/linear/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use crate::QiskitError;
use numpy::{IntoPyArray, PyArray2, PyReadonlyArray2, PyReadwriteArray2};
use pyo3::prelude::*;

mod pmh;
pub mod pmh;
pub mod utils;

#[pyfunction]
Expand Down
19 changes: 15 additions & 4 deletions crates/accelerate/src/synthesis/linear/pmh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
use hashbrown::HashMap;
use ndarray::{s, Array1, Array2, ArrayViewMut2, Axis};
use numpy::PyReadonlyArray2;
use smallvec::smallvec;
use smallvec::{smallvec, SmallVec};
use std::cmp;

use qiskit_circuit::circuit_data::CircuitData;
Expand Down Expand Up @@ -159,7 +159,18 @@ pub fn synth_cnot_count_full_pmh(
section_size: Option<i64>,
) -> PyResult<CircuitData> {
let arrayview = matrix.as_array();
let mut mat: Array2<bool> = arrayview.to_owned();
let mat: Array2<bool> = arrayview.to_owned();
let num_qubits = mat.nrows();
MozammilQ marked this conversation as resolved.
Show resolved Hide resolved

let instructions = _synth_cnot_count_full_pmh(mat, section_size);
CircuitData::from_standard_gates(py, num_qubits as u32, instructions, Param::Float(0.0))
}


type Instructions = (StandardGate, SmallVec<[Param; 3]>, SmallVec<[Qubit; 2]>);
pub fn _synth_cnot_count_full_pmh(mat: Array2<bool>, sec_size: Option<i64>) -> Vec<Instructions>
{
let mut mat = mat;
let num_qubits = mat.nrows(); // is a quadratic matrix

// If given, use the user-specified input size. If None, we default to
Expand All @@ -168,7 +179,7 @@ pub fn synth_cnot_count_full_pmh(
// In addition, we at least set a block size of 2, which, in practice, minimizes the bound
// until ~100 qubits.
let alpha = 0.56;
let blocksize = match section_size {
let blocksize = match sec_size {
Some(section_size) => section_size as usize,
None => std::cmp::max(2, (alpha * (num_qubits as f64).log2()).floor() as usize),
};
Expand All @@ -190,6 +201,6 @@ pub fn synth_cnot_count_full_pmh(
smallvec![Qubit(ctrl as u32), Qubit(target as u32)],
)
});
instructions.collect()

CircuitData::from_standard_gates(py, num_qubits as u32, instructions, Param::Float(0.0))
}
250 changes: 250 additions & 0 deletions crates/accelerate/src/synthesis/linear_phase/cnot_phase_synth.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,250 @@
// 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.

use ndarray::{Array2};
use numpy::{PyReadonlyArray2, PyReadonlyArray1};
use smallvec::smallvec;
use qiskit_circuit::circuit_data::CircuitData;
use qiskit_circuit::operations::{Param, StandardGate};
use qiskit_circuit::Qubit;
use crate::synthesis::linear::pmh::_synth_cnot_count_full_pmh;
use pyo3::prelude::*;
use std::f64::consts::PI;

#[pyfunction]
#[pyo3(signature = (cnots, angles, section_size=2))]
pub fn synth_cnot_phase_aam(
py:Python,
cnots: PyReadonlyArray2<u8>,
MozammilQ marked this conversation as resolved.
Show resolved Hide resolved
angles: PyReadonlyArray1<PyObject>,
section_size: Option<i64>,
) -> PyResult<CircuitData> {

let s = cnots.as_array().to_owned();
let angles_arr = angles.as_array().to_owned();
let num_qubits = s.shape()[0];
let mut s_cpy = s.clone();
let mut instructions = vec![];

let mut rust_angles = Vec::new();
for obj in angles_arr
{
rust_angles.push(obj.extract::<String>(py)?);
}

let mut state = Array2::<u8>::eye(num_qubits);
MozammilQ marked this conversation as resolved.
Show resolved Hide resolved

for qubit_idx in 0..num_qubits
{
let mut index = 0_usize;

loop
{
let icnot = s_cpy.column(index).to_vec();

if icnot == state.row(qubit_idx).to_vec()
{
match rust_angles.get(index)
{
Some(gate) if gate == "t" => instructions.push((StandardGate::TGate, smallvec![], smallvec![Qubit(qubit_idx as u32)])),
Some(gate) if gate == "tdg" => instructions.push((StandardGate::TdgGate, smallvec![], smallvec![Qubit(qubit_idx as u32)])),
Some(gate) if gate == "s" => instructions.push((StandardGate::SGate, smallvec![], smallvec![Qubit(qubit_idx as u32)])),
Some(gate) if gate == "sdg" => instructions.push((StandardGate::SdgGate, smallvec![], smallvec![Qubit(qubit_idx as u32)])),
Some(gate) if gate == "z" => instructions.push((StandardGate::ZGate, smallvec![], smallvec![Qubit(qubit_idx as u32)])),
Some(angles_in_pi) => instructions.push((StandardGate::PhaseGate, smallvec![Param::Float((angles_in_pi.parse::<f64>()?) % PI)], smallvec![Qubit(qubit_idx as u32)])),
None => (),
};

rust_angles.remove(index);
s_cpy.remove_index(numpy::ndarray::Axis(1), index);
if index == s_cpy.shape()[1] {break;}
index -=1;
}
index +=1;
}
}


let epsilion = num_qubits;
let mut q = vec![(s, (0..num_qubits).collect::<Vec<usize>>(), epsilion)];

loop
{
if q.is_empty()
{
break;
}

let (_s, _i, _ep) = q.pop().unwrap();

if _s.is_empty() {continue;}

if 0 <= _ep as i32 && _ep < num_qubits
{
let mut condition = true;
while condition
{
condition = false;

for _j in 0..num_qubits
{
if (_j != _ep) && (u32::from(_s.row(_j).sum()) == _s.row(_j).len() as u32)
{
condition = true;
instructions.push((StandardGate::CXGate, smallvec![], smallvec![Qubit(_j as u32), Qubit(_ep as u32)]));

for _k in 0..state.ncols()
{
state[(_ep, _k)] ^= state[(_j, _k)];
}

let mut index = 0_usize;

for _s_idx in 0..state.nrows()
{
let icnot = s_cpy.column(_s_idx).to_vec();

if icnot == state.row(_ep).to_vec()
{

match rust_angles.get(index)
{
Some(gate) if gate == "t" => instructions.push((StandardGate::TGate, smallvec![], smallvec![Qubit(_ep as u32)])),
Some(gate) if gate == "tdg" => instructions.push((StandardGate::TdgGate, smallvec![], smallvec![Qubit(_ep as u32)])),
Some(gate) if gate == "s" => instructions.push((StandardGate::SGate, smallvec![], smallvec![Qubit(_ep as u32)])),
Some(gate) if gate == "sdg" => instructions.push((StandardGate::SdgGate, smallvec![], smallvec![Qubit(_ep as u32)])),
Some(gate) if gate == "z" => instructions.push((StandardGate::ZGate, smallvec![], smallvec![Qubit(_ep as u32)])),
Some(angles_in_pi) => instructions.push((StandardGate::PhaseGate, smallvec![Param::Float((angles_in_pi.parse::<f64>()?) % PI)], smallvec![Qubit(_ep as u32)])),
None => (),
};

rust_angles.remove(index);
s_cpy.remove_index(numpy::ndarray::Axis(1), index);
if index == s_cpy.shape()[1] { break; }
index -=1;
}
index +=1;
}

let temp_var = (_s.clone(), _i.clone(), _ep);
if !q.contains(&temp_var)
{
q.push(temp_var);
}

for data in &mut q
{
let (ref mut _temp_s, _temp_i, _temp_ep) = data;

if _temp_s.is_empty() {continue;}

for idx in 0.._temp_s.row(_j).len()
{
_temp_s[(_j, idx)] ^= _temp_s[(_ep, idx)];
}
}
}
}
}
}

if _i.is_empty() {continue;}

let mut maxes: Vec<usize> = vec![];
for row in _s.rows()
{
maxes.push(std::cmp::max(row.iter().filter(|&&x| x == 0).count(), row.iter().filter(|&&x| x == 1).count()));
}

let mut maxes2: Vec<usize> = vec![];
for _i_idx in _i.clone()
{
maxes2.push(maxes[_i_idx]);
}

let mut _temp_max = maxes2[0];
let mut _temp_argmax = 0_usize;

for (idx, &ele) in maxes2.iter().enumerate()
{
if ele > _temp_max
{
_temp_max = ele;
_temp_argmax = idx;
}
}

let _j = _i[_temp_argmax];

let mut cnots0_t = vec![];
let mut cnots1_t = vec![];

let mut cnots0_shape_data = (0_usize, 0_usize);
let mut cnots1_shape_data = (0_usize, 0_usize);
for cols in _s.columns()
{
if cols[_j] == 0
{
cnots0_shape_data.0 += 1;
cnots0_shape_data.1 = cols.to_vec().len();
for ele in cols.to_vec()
{
cnots0_t.push(ele);
}
}
else if cols[_j] == 1
{
cnots1_shape_data.0 += 1;
cnots1_shape_data.1 = cols.to_vec().len();
for ele in cols.to_vec()
{
cnots1_t.push(ele);
}
}
}


let cnots0 = Array2::from_shape_vec((cnots0_shape_data.0, cnots0_shape_data.1), cnots0_t).unwrap();
let cnots1 = Array2::from_shape_vec((cnots1_shape_data.0, cnots1_shape_data.1), cnots1_t).unwrap();

let cnots0 = cnots0.t().to_owned();
let cnots1 = cnots1.t().to_owned();

if _ep == num_qubits
{
let _temp_data = (cnots1, _i.clone().into_iter().filter(|&x| x != _j).collect(), _j);
if !q.contains(&_temp_data)
{
q.push(_temp_data);
}
}
else
{
let _temp_data = (cnots1, _i.clone().into_iter().filter(|&x| x != _j).collect(), _ep);
if !q.contains(&_temp_data)
{
q.push(_temp_data);
}
}

q.push((cnots0, _i.clone().into_iter().filter(|&x| x != _j).collect(), _ep));


}

let state_bool = state.mapv(|x| x != 0);
let data_back = _synth_cnot_count_full_pmh(state_bool, section_size);



CircuitData::from_standard_gates(py, num_qubits as u32, instructions, Param::Float(0.0))
}
2 changes: 2 additions & 0 deletions crates/accelerate/src/synthesis/linear_phase/mod.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.

mod cnot_phase_synth;
use numpy::PyReadonlyArray2;
use pyo3::{
prelude::*,
Expand Down Expand Up @@ -42,5 +43,6 @@ fn synth_cz_depth_line_mr(py: Python, mat: PyReadonlyArray2<bool>) -> PyResult<C

pub fn linear_phase(m: &Bound<PyModule>) -> PyResult<()> {
m.add_wrapped(wrap_pyfunction!(synth_cz_depth_line_mr))?;
m.add_wrapped(wrap_pyfunction!(cnot_phase_synth::synth_cnot_phase_aam))?;
Ok(())
}
7 changes: 7 additions & 0 deletions qiskit/synthesis/linear_phase/cnot_phase_synth.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,13 @@
from qiskit.exceptions import QiskitError
from qiskit.synthesis.linear import synth_cnot_count_full_pmh

from qiskit._accelerate.synthesis.linear_phase import synth_cnot_phase_aam as synth_cnot_phase_aam_xlated

def synth_cnot_pahse_aam_xlated(cnots: list[list[int]], angles: list[str], section_size:int 2) -> QuantumCircuit
_circuit_data = synth_cnot_phase_aam_xlated(cnots, angles, section_size)
qc_from_rust = QuantumCircuit._from_circuit_data(_circuit_data)
return qc_from_rust

Copy link
Contributor

@alexanderivrii alexanderivrii Aug 27, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This function has a small typo, you want section_size: int = 2.

More importantly, there are still some problems with passing cnots and angles from the Python code to the Rust code. I am also learning Rust/Pyo3 and am not sure if the following is optimal, but one possible way to fix these is to modify the Python function to

def synth_cnot_phase_aam_xlated(cnots: list[list[int]], angles: list[str], section_size: int = 2) -> QuantumCircuit:
    cnots = np.asarray(cnots, dtype=np.uint8)
    _circuit_data = _synth_cnot_phase_aam_xlated(cnots, angles, section_size)
    qc_from_rust = QuantumCircuit._from_circuit_data(_circuit_data)
    return qc_from_rust

and the Rust function to:

#[pyfunction]
#[pyo3(signature = (cnots, angles, section_size=2))]
pub fn synth_cnot_phase_aam(
    py: Python,
    cnots: PyReadonlyArray2<u8>,
    angles: &Bound<PyList>,
    section_size: Option<i64>,
) -> PyResult<CircuitData> {
...
    let mut rust_angles: Vec::<String> = Vec::new();
    for angle in angles.iter() {
        let rust_string: String = angle.extract()?;
        rust_angles.push(rust_string);
    }
    ...

(you could write the above loop more compactly, but let's not worry about this right now).

Now running the first example in test_cnot_phase_synthesis.py makes the Rust code throw a panic exception, so you will need to debug what's going on.

One pitfall that I noticed when experimenting with the Python version of synth_cnot_phase_aam is that it clears the list of angles passed to it as input, so pay attention to this. :)


def synth_cnot_phase_aam(
cnots: list[list[int]], angles: list[str], section_size: int = 2
Expand Down
Loading