Skip to content

Add qk_obs_apply_layout plus necessary tooling #14106

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

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

30 changes: 19 additions & 11 deletions crates/accelerate/src/nlayout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@ impl PhysicalQubit {
}
}

unsafe impl ::bytemuck::NoUninit for PhysicalQubit {}

qubit_newtype!(VirtualQubit);
impl VirtualQubit {
/// Get the physical qubit that currently corresponds to this index of virtual qubit in the
Expand All @@ -91,8 +93,8 @@ impl VirtualQubit {
#[pyclass(module = "qiskit._accelerate.nlayout")]
#[derive(Clone, Debug)]
pub struct NLayout {
virt_to_phys: Vec<PhysicalQubit>,
phys_to_virt: Vec<VirtualQubit>,
pub virt_to_phys: Vec<PhysicalQubit>,
Copy link
Contributor Author

Choose a reason for hiding this comment

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

These are made public to be able to easily call SparseObservable::apply_layout, which takes the virt_to_phys vector. This could be worked around by using the available public methods, but I think that would require a copy that I wanted to avoid.

pub phys_to_virt: Vec<VirtualQubit>,
}

#[pymethods]
Expand Down Expand Up @@ -179,15 +181,9 @@ impl NLayout {
}

#[staticmethod]
pub fn from_virtual_to_physical(virt_to_phys: Vec<PhysicalQubit>) -> PyResult<Self> {
let mut phys_to_virt = vec![VirtualQubit(u32::MAX); virt_to_phys.len()];
for (virt, phys) in virt_to_phys.iter().enumerate() {
phys_to_virt[phys.index()] = VirtualQubit(virt.try_into()?);
}
Ok(NLayout {
virt_to_phys,
phys_to_virt,
})
#[pyo3 (name = "from_virtual_to_physical", signature = (virt_to_phys))]
pub fn py_from_virtual_to_physical(virt_to_phys: Vec<PhysicalQubit>) -> PyResult<Self> {
Ok(Self::from_virtual_to_physical(virt_to_phys))
}
}

Expand All @@ -210,6 +206,18 @@ impl NLayout {
.enumerate()
.map(|(p, v)| (PhysicalQubit::new(p as u32), *v))
}

pub fn from_virtual_to_physical(virt_to_phys: Vec<PhysicalQubit>) -> Self {
let mut phys_to_virt = vec![VirtualQubit(u32::MAX); virt_to_phys.len()];
for (virt, phys) in virt_to_phys.iter().enumerate() {
phys_to_virt[phys.index()] = VirtualQubit(virt as u32);
}

Self {
virt_to_phys,
phys_to_virt,
}
}
}

pub fn nlayout(m: &Bound<PyModule>) -> PyResult<()> {
Expand Down
2 changes: 1 addition & 1 deletion crates/accelerate/src/sabre/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ fn layout_trial(
physical_qubits.shuffle(&mut rng);
physical_qubits
};
NLayout::from_virtual_to_physical(physical_qubits).unwrap()
NLayout::from_virtual_to_physical(physical_qubits)
};

// Sabre routing currently enforces that control-flow blocks return to their starting layout,
Expand Down
1 change: 1 addition & 0 deletions crates/cext/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ crate-type = ["rlib"]
workspace = true

[dependencies]
bytemuck.workspace = true
thiserror.workspace = true
num-complex.workspace = true
qiskit-accelerate.workspace = true
Expand Down
1 change: 1 addition & 0 deletions crates/cext/cbindgen.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,4 @@ prefix_with_name = true
"CSparseTerm" = "QkObsTerm"
"BitTerm" = "QkBitTerm"
"Complex64" = "QkComplex64"
"NLayout" = "QkLayout"
78 changes: 78 additions & 0 deletions crates/cext/src/layout.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// This code is part of Qiskit.
//
// (C) Copyright IBM 2025
//
// 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 super::sparse_observable::check_ptr;
use qiskit_accelerate::nlayout::{NLayout, PhysicalQubit};

/// @ingroup QkLayout
/// Create a layout object from a virtual-to-physical qubit map.
///
/// @param virt_to_phys A pointer to an array of length ``len``, defining the mapping
/// from virtual to physical qubits. A null-pointer is not allowed.
/// @param len The length of the above array.
///
/// @return The layout.
///
/// # Example
///
/// uint32_t virt_to_phys[5] = {0, 2, 3, 4, 1};
/// QkLayout layout = qk_layout_new(virt_to_phys, 5);
///
/// # Safety
///
/// Behavior is undefined if ``virt_to_phys`` is not a non-null pointer to an array of ``uint32_t``,
/// readable for ``len`` elements.
#[no_mangle]
#[cfg(feature = "cbinding")]
pub unsafe extern "C" fn qk_layout_new(virt_to_phys: *const u32, len: usize) -> *mut NLayout {
check_ptr(virt_to_phys).unwrap();

// SAFETY: The pointer is non-null and aligned and the user promises it is readable
// for the required length.
let data = unsafe { ::std::slice::from_raw_parts(virt_to_phys, len) };

let vector = data.iter().map(|q| PhysicalQubit(*q)).collect();
let layout = NLayout::from_virtual_to_physical(vector);

Box::into_raw(Box::new(layout))
}

/// @ingroup QkLayout
/// Free the layout object.
///
/// @param obs A pointer to the layout to free.
///
/// # Example
///
/// uint32_t virt_to_phys[5] = {0, 2, 3, 4, 1};
/// QkLayout layout = qk_layout_new(virt_to_phys, 5);
/// qk_layout_free(layout);
///
/// # Safety
///
/// Behavior is undefined if ``layout`` is not either null or a valid pointer to a
/// [NLayout].
#[no_mangle]
#[cfg(feature = "cbinding")]
pub unsafe extern "C" fn qk_layout_free(layout: *mut NLayout) {
if !layout.is_null() {
if !layout.is_aligned() {
panic!("Attempted to free a non-aligned pointer.")
}

// SAFETY: We have verified the pointer is non-null and aligned, so it should be
// readable by Box.
unsafe {
let _ = Box::from_raw(layout);
}
}
}
1 change: 1 addition & 0 deletions crates/cext/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@
// that they have been altered from the originals.

pub mod exit_codes;
pub mod layout;
pub mod sparse_observable;
55 changes: 54 additions & 1 deletion crates/cext/src/sparse_observable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ use std::ffi::{c_char, CString};
use crate::exit_codes::{CInputError, ExitCode};
use num_complex::Complex64;

use qiskit_accelerate::nlayout::NLayout;
use qiskit_accelerate::sparse_observable::{BitTerm, SparseObservable, SparseTermView};

#[cfg(feature = "python_binding")]
Expand Down Expand Up @@ -68,7 +69,7 @@ impl TryFrom<&CSparseTerm> for SparseTermView<'_> {
}

/// Check the pointer is not null and is aligned.
fn check_ptr<T>(ptr: *const T) -> Result<(), CInputError> {
pub(crate) fn check_ptr<T>(ptr: *const T) -> Result<(), CInputError> {
if ptr.is_null() {
return Err(CInputError::NullPointerError);
};
Expand Down Expand Up @@ -820,6 +821,58 @@ pub unsafe extern "C" fn qk_obs_equal(
obs.eq(other)
}

/// @ingroup QkObs
/// Apply a [NLayout] to the observable.
///
/// @param obs A pointer to the observable.
/// @param layout A pointer to the layout.
///
/// @return The observable with the layout applied, or null if the layout was incompatible
/// with the observable.
///
/// # Example
///
/// QkObs *obs = qk_obs_zero(4);
///
/// QkBitTerm bit_terms[3] = {QkBitTerm_X, QkBitTerm_Y, QkBitTerm_Z};
/// uint32_t qubits[3] = {1, 2, 3};
/// complex double coeff = 1;
/// QkObsTerm term = {coeff, 3, bit_terms, qubits, 4};
///
/// int err = qk_obs_add_term(obs, &term);
/// if (err != 0) {
/// qk_obs_free(obs);
/// return err;
/// }
///
/// uint32_t virt_to_phys[3] = {0, 3, 2, 1};
/// QkLayout *layout = qk_layout_new(virt_to_phys, num_qubits);
/// QkObs *obs_with_layout = qk_obs_apply_layout(obs, layout);
///
/// # Safety
///
/// Behavior is undefined if ``obs`` is not a valid, non-null pointer to ``QkObs`` or if ``layout``
/// is not a valid, non-null pointer to ``QkLayout``.
#[no_mangle]
#[cfg(feature = "cbinding")]
pub unsafe extern "C" fn qk_obs_apply_layout(
obs: *const SparseObservable,
layout: *const NLayout,
) -> *mut SparseObservable {
let obs = unsafe { const_ptr_as_ref(obs) };
let layout = unsafe { const_ptr_as_ref(layout) };

// Cast the slice of PhysicalQubit (which is u32) to plain u32, which is required
// by the apply_layout method.
let as_slice: &[u32] = ::bytemuck::cast_slice(&layout.virt_to_phys);
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This line (and the NoUninit for PhysicalQubit) warrants extra care since it's the first time I'm using bytemuck 😄

let obs_with_layout = match obs.apply_layout(Some(as_slice), obs.num_qubits()) {
Ok(obs_with_layout) => obs_with_layout,
Err(_) => return ::std::ptr::null_mut(),
};

Box::into_raw(Box::new(obs_with_layout))
}

/// @ingroup QkObs
/// Return a string representation of a ``SparseObservable``.
///
Expand Down
31 changes: 31 additions & 0 deletions releasenotes/notes/qk-layout-df9805232e7d6ca4.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
features_c:
- |
Added ``qk_obs_apply_layout`` to apply a layout, in form of ``QkLayout``, to an
observable.
- |
Introduce ``QkLayout`` to represent the mapping of virtual to physical qubits,
along with the related functions ``qk_layout_new`` and ``qk_layout_free``.
A layout can be constructed by passing an array containing the virtual-to-physical
mapping into ``qk_layout_new``, for example

.. code-block:: c

QkObs *obs = qk_obs_zero(4);

QkBitTerm bit_terms[3] = {QkBitTerm_X, QkBitTerm_Y, QkBitTerm_Z};
uint32_t qubits[3] = {1, 2, 3};
complex double coeff = 1;
QkObsTerm term = {coeff, 3, bit_terms, qubits, 4};

qk_obs_add_term(obs, &term);

uint32_t virt_to_phys[3] = {0, 3, 2, 1};
QkLayout *layout = qk_layout_new(virt_to_phys, num_qubits);
QkObs *obs_with_layout = qk_obs_apply_layout(obs, layout);

Ensure to free the layout at the end of the computation, via

.. code-block:: c

qk_layout_free(layout);

75 changes: 75 additions & 0 deletions test/c/test_sparse_observable.c
Original file line number Diff line number Diff line change
Expand Up @@ -720,6 +720,79 @@ int test_obsterm_str() {
return result;
}

/**
* Test applying a layout
*/
int test_apply_layout() {
uint32_t num_qubits = 6;
QkObs *obs = qk_obs_zero(num_qubits);

// Add the term X1 +2 -3 Y4 Z5
QkBitTerm bit_terms[5] = {QkBitTerm_X, QkBitTerm_Plus, QkBitTerm_Left, QkBitTerm_Y,
QkBitTerm_Z};
uint32_t qubits[5] = {1, 2, 3, 4, 5};
complex double coeff = 1;
QkObsTerm term = {coeff, 5, bit_terms, qubits, num_qubits};
int err = qk_obs_add_term(obs, &term);

if (err != 0) {
qk_obs_free(obs);
return RuntimeError;
}

// now apply a custom layout reverting to X5 +4 -3 Y2 Z1
uint32_t virt_to_phys[6] = {0, 5, 4, 3, 2, 1};
QkLayout *layout = qk_layout_new(virt_to_phys, num_qubits);
QkObs *obs_with_layout = qk_obs_apply_layout(obs, layout);

// compare against expectations
QkBitTerm bits_l[5] = {QkBitTerm_Z, QkBitTerm_Y, QkBitTerm_Left, QkBitTerm_Plus, QkBitTerm_X};
QkObsTerm term_l = {coeff, 5, bits_l, qubits, num_qubits};
QkObs *expected = qk_obs_zero(num_qubits);
qk_obs_add_term(expected, &term_l);

bool is_equal = qk_obs_equal(expected, obs_with_layout);

qk_obs_free(obs);
qk_obs_free(expected);
qk_obs_free(obs_with_layout);
qk_layout_free(layout);

if (!is_equal)
return EqualityError;
return Ok;
}

/**
* Test wrong layouts return null
*/
int test_apply_faulty_layout() {
uint32_t num_qubits = 6;
QkObs *obs = qk_obs_identity(num_qubits);

uint32_t virt_to_phys[6] = {0, 0, 4, 3, 2, 1};
QkLayout *wrong_layout = qk_layout_new(virt_to_phys, num_qubits);
QkObs *obs_with_wrong_layout = qk_obs_apply_layout(obs, wrong_layout);
qk_layout_free(wrong_layout);

if (obs_with_wrong_layout) {
qk_obs_free(obs_with_wrong_layout);
return EqualityError;
}

uint32_t too_small[2] = {0, 1}; // wrong size
QkLayout *too_small_layout = qk_layout_new(too_small, 2);
QkObs *obs_too_small = qk_obs_apply_layout(obs, too_small_layout);
qk_layout_free(too_small_layout);

if (obs_too_small) {
qk_obs_free(obs_too_small);
return EqualityError;
}

return Ok;
}

int test_sparse_observable() {
int num_failed = 0;
num_failed += RUN_TEST(test_zero);
Expand All @@ -745,6 +818,8 @@ int test_sparse_observable() {
num_failed += RUN_TEST(test_direct_fail);
num_failed += RUN_TEST(test_obs_str);
num_failed += RUN_TEST(test_obsterm_str);
num_failed += RUN_TEST(test_apply_layout);
num_failed += RUN_TEST(test_apply_faulty_layout);

fflush(stderr);
fprintf(stderr, "=== Number of failed subtests: %i\n", num_failed);
Expand Down