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 37 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 21 commits
Commits
Show all changes
37 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
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
18 changes: 13 additions & 5 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,16 @@ 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();
Comment on lines +162 to +163
Copy link
Contributor

Choose a reason for hiding this comment

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

It seems that you are copying the matrix twice: first, when you call mat = arrayview.to_owned(), and second, when you call let mut mat = mat in synth_pmh.


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> {
Copy link
Contributor

Choose a reason for hiding this comment

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

Some comments on this:

  • It's likely better to keep this returning an iterator instead of collecting into a vector, this way the CircuitData constructor can simply iterate over the inputs. If you do need a vector you could collect where you call this function 🙂
  • Since this is a Rust internal function, it might be better to have section_size be a usize directly. We were only using i64 as input from Python, but logically, this should be an unsigned integer (also is there a reason for renaming? 🙂)
  • We might want to promote this as public function, so I would think we don't want a leading underscore in the name here. To avoid the naming conflict you could maybe rename it to synth_pmh?

Copy link
Contributor Author

@MozammilQ MozammilQ Sep 1, 2024

Choose a reason for hiding this comment

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

1> Done!

2> Done! (Since, its internal function its indeed logical to have section_size as usize directly.)

3> Done!

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 +177,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 +199,5 @@ pub fn synth_cnot_count_full_pmh(
smallvec![Qubit(ctrl as u32), Qubit(target as u32)],
)
});

CircuitData::from_standard_gates(py, num_qubits as u32, instructions, Param::Float(0.0))
instructions.collect()
}
292 changes: 292 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,292 @@
// 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 crate::synthesis::linear::pmh::_synth_cnot_count_full_pmh;
use ndarray::Array2;
use numpy::PyReadonlyArray2;
use pyo3::{prelude::*, types::PyList};
use qiskit_circuit::circuit_data::CircuitData;
use qiskit_circuit::operations::{Param, StandardGate};
use qiskit_circuit::Qubit;
use smallvec::smallvec;
use std::f64::consts::PI;

/// This function implements a Gray-code inspired algorithm of synthesizing a circuit
/// over CNOT and phase-gates with minimal-CNOT for a given phase-polynomial.
/// The algorithm is described as "Gray-Synth" algorithm in Algorithm-1, page 12
/// of paper "https://arxiv.org/abs/1712.01859".
#[pyfunction]
#[pyo3(signature = (cnots, angles, section_size=2))]
pub fn synth_cnot_phase_aam(
py: Python,
cnots: PyReadonlyArray2<u8>,
Copy link
Contributor

Choose a reason for hiding this comment

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

Is there a specific reason for u8? 🙂

Copy link
Contributor Author

@MozammilQ MozammilQ Sep 1, 2024

Choose a reason for hiding this comment

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

Its now bool

angles: &Bound<PyList>,
section_size: Option<i64>,
) -> PyResult<CircuitData> {
let s = cnots.as_array().to_owned();
let num_qubits = s.nrows();
let mut s_cpy = s.clone();
let mut instructions = vec![];

let mut rust_angles: Vec<String> = angles
.iter()
.filter_map(|data| data.extract::<String>().ok())
.collect();
Copy link
Contributor

Choose a reason for hiding this comment

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

I know the Python code does the same, but this seems highly volatile and we should change this: the input type should be properly differentiated in either floats or strings, but not a mix. You can leave this for now @MozammilQ but maybe we can find a better solution @alexanderivrii and @ShellyGarion 🙂

Copy link
Member

Choose a reason for hiding this comment

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

Indeed, it's quite strange that the API of angles can accept strings e.g. s, t, sdg, tdg or z or float.
in the test we see that the angles are only strings, e.g. s, t, sdg, tdg or z. It would be good to add some tests of angles which are float to check that the code works well for any angle.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@ShellyGarion ,
I had already taken care of this by angles = [angle if isinstance(angle, str) else f"{angle}" for angle in angles] in cnot_phase_synth.py. This converts all occurrences of float in the list of angles to String which rust subsequently accepts.

Anyways, I have added a test. Take a note of the change in circuit. I have just changed the circuit in the docstring to the actual circuit I am getting here locally, but not have changed the circuit in the code, just to make sure the code works for the circuit generated from the older python implementation of synth_cnot_phase_aam, there by proving the circuit generated by rust is merely "equivalent" to the circuit generated by python version and not different.

Nevertheless, I am surprised because there is no random steps in the rust or the python implementation of the algorithm, so both the rust and python implementation should produce exact same circuit, but this is not the case.
Maybe, the difference is because when I append the output of synth_pmh I just do .rev() but not the actual .inverse() in python space as it has been done originally in python implementation.
I decided to do only .rev() thinking inverse of a cx is itself. So, just reversing the strings of cxs in the circuit should be equivalent to doing .inverse() on QuantumCircuit in python space. Please, guide me if you feel I am lost :)

let mut state = Array2::<u8>::eye(num_qubits);
Copy link
Contributor

Choose a reason for hiding this comment

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

Could this be made into a matrix of bools right away? It seems like it is treated as one.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done!


for qubit_idx in 0..num_qubits {
let mut index = 0_usize;
let mut swtch: bool = true;

while index < s_cpy.ncols() {
let icnot = s_cpy.column(index).to_vec();
if icnot == state.row(qubit_idx).to_vec() {
match rust_angles.remove(index) {
gate if gate == "t" => instructions.push((
Copy link
Contributor

Choose a reason for hiding this comment

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

Could this (and below) be written more concisely by matching the gate name to the StandardGate and then pushing the gate afterwards (to avoid repeating the same instruction creation)?

Copy link
Contributor Author

@MozammilQ MozammilQ Sep 1, 2024

Choose a reason for hiding this comment

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

The logic is abstracted into a function now.

StandardGate::TGate,
smallvec![],
smallvec![Qubit(qubit_idx as u32)],
)),
gate if gate == "tdg" => instructions.push((
StandardGate::TdgGate,
smallvec![],
smallvec![Qubit(qubit_idx as u32)],
)),
gate if gate == "s" => instructions.push((
StandardGate::SGate,
smallvec![],
smallvec![Qubit(qubit_idx as u32)],
)),
gate if gate == "sdg" => instructions.push((
StandardGate::SdgGate,
smallvec![],
smallvec![Qubit(qubit_idx as u32)],
)),
gate if gate == "z" => instructions.push((
StandardGate::ZGate,
smallvec![],
smallvec![Qubit(qubit_idx as u32)],
)),
angles_in_pi => instructions.push((
StandardGate::PhaseGate,
smallvec![Param::Float((angles_in_pi.parse::<f64>()?) % PI)],
smallvec![Qubit(qubit_idx as u32)],
)),
};
s_cpy.remove_index(numpy::ndarray::Axis(1), index);
if index == s_cpy.ncols() {
break;
}
if index == 0 {
swtch = false;
} else {
index -= 1;
}
}
if swtch {
index += 1;
} else {
swtch = true;
}
}
}

let epsilion: usize = num_qubits;
Cryoris marked this conversation as resolved.
Show resolved Hide resolved
let mut q = vec![(s, (0..num_qubits).collect::<Vec<usize>>(), epsilion)];

while !q.is_empty() {
let (mut _s, mut _i, mut _ep) = q.pop().unwrap();

if _s.is_empty() {
continue;
}

if _ep < num_qubits {
let mut condition = true;
while condition {
condition = false;

for _j in 0..num_qubits {
if (_j != _ep) && (_s.row(_j).sum() as usize == _s.row(_j).len()) {
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;
let mut swtch: bool = true;
while index < s_cpy.ncols() {
let icnot = s_cpy.column(index).to_vec();
if icnot == state.row(_ep).to_vec() {
match rust_angles.remove(index) {
gate if gate == "t" => instructions.push((
StandardGate::TGate,
smallvec![],
smallvec![Qubit(_ep as u32)],
)),
gate if gate == "tdg" => instructions.push((
StandardGate::TdgGate,
smallvec![],
smallvec![Qubit(_ep as u32)],
)),
gate if gate == "s" => instructions.push((
StandardGate::SGate,
smallvec![],
smallvec![Qubit(_ep as u32)],
)),
gate if gate == "sdg" => instructions.push((
StandardGate::SdgGate,
smallvec![],
smallvec![Qubit(_ep as u32)],
)),
gate if gate == "z" => instructions.push((
StandardGate::ZGate,
smallvec![],
smallvec![Qubit(_ep as u32)],
)),
angles_in_pi => instructions.push((
StandardGate::PhaseGate,
smallvec![Param::Float(
(angles_in_pi.parse::<f64>()?) % PI
)],
smallvec![Qubit(_ep as u32)],
)),
};
s_cpy.remove_index(numpy::ndarray::Axis(1), index);
if index == s_cpy.ncols() {
break;
}
if index == 0 {
swtch = false;
} else {
index -= 1;
}
}
if swtch {
index += 1;
} else {
swtch = true;
}
}

q.push((_s, _i, _ep));
let mut unique_q = vec![];
for data in q.into_iter() {
if !unique_q.contains(&data) {
unique_q.push(data);
}
}

q = unique_q;

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

if _temp_s.is_empty() {
continue;
}

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

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

if _i.is_empty() {
continue;
}

let maxes: Vec<usize> = _s
.axis_iter(numpy::ndarray::Axis(0))
.map(|row| {
std::cmp::max(
row.iter().filter(|&&x| x == 0).count(),
row.iter().filter(|&&x| x == 1).count(),
)
})
.collect();

let maxes2: Vec<usize> = _i.iter().map(|&_i_idx| maxes[_i_idx]).collect();

let _temp_argmax = maxes2
.iter()
.enumerate()
.max_by(|(_, x), (_, y)| x.cmp(y))
.map(|(idx, _)| idx)
.unwrap();

let _j = _i[_temp_argmax];

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

let mut cnots0_t_shape = (0_usize, _s.column(0).len());
let mut cnots1_t_shape = (0_usize, 0_usize);
cnots1_t_shape.1 = cnots0_t_shape.1;
for cols in _s.columns() {
if cols[_j] == 0 {
cnots0_t_shape.0 += 1;
cnots0_t.append(&mut cols.to_vec());
} else if cols[_j] == 1 {
cnots1_t_shape.0 += 1;
cnots1_t.append(&mut cols.to_vec());
}
}

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

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

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

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

let state_bool = state.mapv(|x| x != 0);
let mut instrs = _synth_cnot_count_full_pmh(state_bool, section_size)
Copy link
Contributor

Choose a reason for hiding this comment

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

Does this need to be mutable?

Copy link
Contributor Author

@MozammilQ MozammilQ Sep 1, 2024

Choose a reason for hiding this comment

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

removed the logic!

.into_iter()
.rev()
.collect();
instructions.append(&mut instrs);
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(())
}
Loading
Loading