Skip to content
Closed
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
119 changes: 107 additions & 12 deletions crates/binding-c/src/compile/decompose.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ use cqlib_core::compile::transform::decompose::unitary::{
synthesize_numeric_2q_unitary as core_synthesize_numeric_2q_unitary,
};
use cqlib_core::compile::transform::decompose::{
DecompositionRuleStats, McGateDecomposeConfig, UnitaryDecomposeConfig,
BlockZxzDecomposeOptions, DecompositionRuleStats, McGateDecomposeConfig,
UnitaryDecomposeConfig, decompose_block_zxz_with_options,
decompose_mc_gates_with_rule_stats as core_decompose_mc_gates_with_rule_stats,
decompose_unitaries_with_rule_stats as core_decompose_unitaries_with_rule_stats,
expand_definitions as core_expand_definitions,
Expand Down Expand Up @@ -71,6 +72,18 @@ pub const KAK_FACTOR_K1R: u8 = 1;
pub const KAK_FACTOR_K2L: u8 = 2;
pub const KAK_FACTOR_K2R: u8 = 3;

/// Hard side-length cap matching `MAX_UNITARY_QUBITS = 20` in `circuit_unitary`.
const BLOCK_ZXZ_MAX_DIM: usize = 1usize << 20;

/// Absorb two outer controlled rotations' boundary CX gates per recursive layer.
pub const BLOCK_ZXZ_OPT_A1: u8 = 1;
/// Use a diagonal remainder between consecutive two-qubit leaves.
pub const BLOCK_ZXZ_OPT_A2: u8 = 2;
/// Permit A.2 on block-diagonal inputs when BLOCK_ZXZ_OPT_A2 is set.
pub const BLOCK_ZXZ_OPT_A2_FORCE: u8 = 4;
/// Default optimizations, with automatic block-diagonal handling.
pub const BLOCK_ZXZ_OPT_ALL: u8 = BLOCK_ZXZ_OPT_A1 | BLOCK_ZXZ_OPT_A2;

/// C snapshot of pass-local decomposition-rule cache statistics.
#[repr(C)]
pub struct CDecompositionRuleStats {
Expand All @@ -91,8 +104,16 @@ pub struct CDecompositionRuleStats {
pub struct CUnitaryDecomposeConfig {
/// 1 recurses into control-flow bodies, 0 does not.
pub recurse_control_flow: u8,
/// When nonzero, `block_zxz_options` selects the Block-ZXZ optimization
/// bitmask; when 0 (including zero-initialized structs), default
/// optimizations (`BLOCK_ZXZ_OPT_ALL`) are used.
pub has_block_zxz_options: u8,
/// Block-ZXZ optimization mask applied to three-or-more-qubit unitary gates
/// when `has_block_zxz_options != 0` (bitwise OR of `BLOCK_ZXZ_OPT_*`, or
/// 0 for unoptimized synthesis).
pub block_zxz_options: u8,
/// Reserved padding to keep the struct layout stable.
pub _reserved: [u8; 7],
pub _reserved: [u8; 5],
}

/// C form of [`McGateDecomposeConfig`].
Expand Down Expand Up @@ -174,7 +195,9 @@ pub struct CTargetBasisLowerer {
pub extern "C" fn decompose_unitary_config_default() -> CUnitaryDecomposeConfig {
CUnitaryDecomposeConfig {
recurse_control_flow: 1,
_reserved: [0; 7],
has_block_zxz_options: 1,
block_zxz_options: BLOCK_ZXZ_OPT_ALL,
_reserved: [0; 5],
}
}

Expand Down Expand Up @@ -297,20 +320,32 @@ pub extern "C" fn decompose_unitaries_with_rule_stats(
if circuit.is_null() {
return std::ptr::null_mut();
}
let block_zxz_options = if config.has_block_zxz_options == 0 {
BlockZxzDecomposeOptions::default()
} else {
let Some(options) = block_zxz_options_from_mask(config.block_zxz_options) else {
return std::ptr::null_mut();
};
options
};
let config = UnitaryDecomposeConfig {
two_qubit_target: Default::default(),
recurse_control_flow: config.recurse_control_flow != 0,
block_zxz_options,
};
let circuit = unsafe { &(*circuit).inner };
match core_decompose_unitaries_with_rule_stats(circuit, config) {
Ok((outcome, rule_stats)) => {
write_rule_stats(stats, &rule_stats);
Box::into_raw(Box::new(CCircuit {
inner: outcome.into_circuit(circuit),
}))
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let circuit = unsafe { &(*circuit).inner };
match core_decompose_unitaries_with_rule_stats(circuit, config) {
Ok((outcome, rule_stats)) => {
write_rule_stats(stats, &rule_stats);
Box::into_raw(Box::new(CCircuit {
inner: outcome.into_circuit(circuit),
}))
}
Err(_) => std::ptr::null_mut(),
}
Err(_) => std::ptr::null_mut(),
}
}))
.unwrap_or(std::ptr::null_mut())
}

/// Rewrites multi-controlled gates of `circuit` and returns the rebuilt
Expand Down Expand Up @@ -1143,3 +1178,63 @@ pub extern "C" fn decompose_unitary_target_cost_of_fixed_operations(
}
CqlibError::Ok as i32
}

fn block_zxz_options_from_mask(options: u8) -> Option<BlockZxzDecomposeOptions> {
if options & !(BLOCK_ZXZ_OPT_ALL | BLOCK_ZXZ_OPT_A2_FORCE) != 0 {
return None;
}
Some(BlockZxzDecomposeOptions {
opt_a1: options & BLOCK_ZXZ_OPT_A1 != 0,
opt_a2: options & BLOCK_ZXZ_OPT_A2 != 0,
opt_a2_force: options & BLOCK_ZXZ_OPT_A2_FORCE != 0,
})
}

/// Synthesizes a row-major unitary into an owned circuit including global phase.
/// `dim` must be a power of two in `[2, 2^20]`. `atol` must be finite and nonnegative.
/// Pass a bitwise OR of BLOCK_ZXZ_OPT_* flags, or zero to disable both.
/// Returns NULL on invalid input or synthesis failure. Release a successful
/// result with circuit_free.
///
/// # Safety
/// A non-null matrix pointer with a valid shape must be aligned and point to
/// at least dim * dim initialized contiguous Complex64 values, each containing
/// two doubles (real, imaginary). The caller owns the input for this call.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn block_zxz_decompose(
matrix: *const Complex64,
dim: usize,
atol: f64,
options: u8,
) -> *mut CCircuit {
let Some(options) = block_zxz_options_from_mask(options) else {
return std::ptr::null_mut();
};
if matrix.is_null()
|| !matrix.is_aligned()
|| !(2..=BLOCK_ZXZ_MAX_DIM).contains(&dim)
|| !dim.is_power_of_two()
|| !atol.is_finite()
|| atol < 0.
{
return std::ptr::null_mut();
}
let Some(len) = dim.checked_mul(dim) else {
return std::ptr::null_mut();
};
if len > isize::MAX as usize / size_of::<Complex64>() {
return std::ptr::null_mut();
}
std::panic::catch_unwind(|| {
// Shape, multiplication and byte extent have been checked before the first read.
let slice = unsafe { std::slice::from_raw_parts(matrix, len) };
let matrix = ndarray::ArrayView2::from_shape((dim, dim), slice)
.ok()?
.to_owned();
let inner = decompose_block_zxz_with_options(&matrix, atol, &options).ok()?;
Some(Box::into_raw(Box::new(CCircuit { inner })))
})
.ok()
.flatten()
.unwrap_or(std::ptr::null_mut())
}
127 changes: 127 additions & 0 deletions crates/binding-c/tests/test_circuit.c
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,134 @@ static void test_circuit_gate_operation_matrix(void) {
}
}

static void test_block_zxz(void) {
Complex64 u[64] = {0};
for (size_t j = 0; j < 8; ++j) {
u[8 * ((j + 1) % 8) + j] = (Complex64){cos(0.37), sin(0.37)};
}
for (uint8_t opt = 0; opt <= (BLOCK_ZXZ_OPT_ALL | BLOCK_ZXZ_OPT_A2_FORCE); ++opt) {
CCircuit* c = block_zxz_decompose(u, 8, 1e-10, opt);
assert(c != NULL);
double actual[128];
assert(circuit_to_matrix(c, NULL, 0, actual, 128) == 64);
for (size_t i = 0; i < 64; ++i) {
assert(hypot(actual[2 * i] - u[i].re, actual[2 * i + 1] - u[i].im) <= 1e-10);
}
circuit_free(c);
}

/* Check 1q, 2q, and 4q dimensions with non-trivial global phase. */
size_t dims[3] = {2, 4, 16};
for (size_t k = 0; k < 3; ++k) {
size_t dim = dims[k];
size_t n2 = dim * dim;
Complex64* qft = (Complex64*)calloc(n2, sizeof(Complex64));
double* actual = (double*)malloc(2 * n2 * sizeof(double));
assert(qft != NULL && actual != NULL);
double scale = 1.0 / sqrt((double)dim);
double tau = 6.283185307179586476925286766559;
for (size_t r = 0; r < dim; ++r) {
for (size_t col = 0; col < dim; ++col) {
double ang = tau * (double)(r * col) / (double)dim + 0.51;
qft[r * dim + col] = (Complex64){scale * cos(ang), scale * sin(ang)};
}
}
CCircuit* c = block_zxz_decompose(qft, dim, 1e-10, BLOCK_ZXZ_OPT_ALL);
assert(c != NULL);
assert(circuit_to_matrix(c, NULL, 0, actual, 2 * n2) == (int64_t)n2);
for (size_t i = 0; i < n2; ++i) {
assert(hypot(actual[2 * i] - qft[i].re, actual[2 * i + 1] - qft[i].im) <= 1e-10);
}
circuit_free(c);
free(actual);
free(qft);
}

/* Slightly noisy input within a loose tolerance (> 1e-8) succeeds via unitary projection. */
Complex64 noisy[64];
for (size_t i = 0; i < 64; ++i) {
noisy[i] = (Complex64){u[i].re * (1.0 + 2e-7), u[i].im * (1.0 + 2e-7)};
}
CCircuit* cn = block_zxz_decompose(noisy, 8, 1e-5, BLOCK_ZXZ_OPT_ALL);
assert(cn != NULL);
double actual_noisy[128];
assert(circuit_to_matrix(cn, NULL, 0, actual_noisy, 128) == 64);
for (size_t i = 0; i < 64; ++i) {
assert(hypot(actual_noisy[2 * i] - noisy[i].re, actual_noisy[2 * i + 1] - noisy[i].im) <=
1e-5);
}
circuit_free(cn);

/* Exact zero and negative-zero tolerance on exact identity. */
Complex64 eye8[64] = {0};
for (size_t i = 0; i < 8; ++i) eye8[i * 8 + i] = (Complex64){1.0, 0.0};
CCircuit* c0 = block_zxz_decompose(eye8, 8, 0.0, BLOCK_ZXZ_OPT_ALL);
assert(c0 != NULL);
circuit_free(c0);
CCircuit* cneg0 = block_zxz_decompose(eye8, 8, -0.0, BLOCK_ZXZ_OPT_ALL);
assert(cneg0 != NULL);
circuit_free(cneg0);

/* Invalid inputs: null, unaligned, bad dims, overflow, unknown option bits, bad atol,
* non-finite. */
assert(block_zxz_decompose(NULL, 8, 1e-10, 0) == NULL);
unsigned char raw[64 * sizeof(Complex64) + 16] = {0};
uintptr_t aligned_addr = ((uintptr_t)raw + 7) & ~(uintptr_t)7;
assert(block_zxz_decompose((const Complex64*)(aligned_addr + 1), 2, 1e-10, 0) == NULL);
assert(block_zxz_decompose(u, 0, 1e-10, 0) == NULL);
assert(block_zxz_decompose(u, 1, 1e-10, 0) == NULL);
assert(block_zxz_decompose(u, 3, 1e-10, 0) == NULL);
assert(block_zxz_decompose(u, (size_t)1 << 21, 1e-10, 0) == NULL);
assert(block_zxz_decompose(u, SIZE_MAX / 2 + 1, 1e-10, 0) == NULL);
assert(block_zxz_decompose(u, (size_t)1 << (sizeof(size_t) * 4 - 1), 1e-10, 0) == NULL);
assert(block_zxz_decompose(u, 8, 1e-10, 8) == NULL);
assert(block_zxz_decompose(u, 8, 1e-10, 255) == NULL);

/* CUnitaryDecomposeConfig exposes block_zxz_options and rejects unknown option bits. */
CUnitaryDecomposeConfig cfg = decompose_unitary_config_default();
assert(cfg.has_block_zxz_options == 1);
assert(cfg.block_zxz_options == BLOCK_ZXZ_OPT_ALL);
CCircuit* src3 = circuit_new(3);
assert(src3 != NULL);
uint32_t qargs3[3] = {2, 1, 0};
assert(circuit_unitary(src3, "roll3", 3, u, qargs3, 3) == 0);
CCircuit* opt_out = decompose_unitaries(src3, cfg);
assert(opt_out != NULL);
double actual_pass[128];
assert(circuit_to_matrix(opt_out, NULL, 0, actual_pass, 128) == 64);
for (size_t i = 0; i < 64; ++i) {
assert(hypot(actual_pass[2 * i] - u[i].re, actual_pass[2 * i + 1] - u[i].im) <= 1e-10);
}
circuit_free(opt_out);
/* Zero-initialized CUnitaryDecomposeConfig uses default Block-ZXZ options. */
CUnitaryDecomposeConfig zero_cfg = {0};
zero_cfg.recurse_control_flow = 1;
CCircuit* zero_out = decompose_unitaries(src3, zero_cfg);
assert(zero_out != NULL);
circuit_free(zero_out);
cfg.block_zxz_options = 0;
CCircuit* unopt_out = decompose_unitaries(src3, cfg);
assert(unopt_out != NULL);
circuit_free(unopt_out);
cfg.block_zxz_options = 8;
assert(decompose_unitaries(src3, cfg) == NULL);
circuit_free(src3);
assert(block_zxz_decompose(u, 8, NAN, 0) == NULL);
assert(block_zxz_decompose(u, 8, INFINITY, 0) == NULL);
assert(block_zxz_decompose(u, 8, -INFINITY, 0) == NULL);
assert(block_zxz_decompose(u, 8, -1e-300, 0) == NULL);
assert(block_zxz_decompose(u, 8, -1, 0) == NULL);
u[0].re = 2.0;
assert(block_zxz_decompose(u, 8, 1e-10, 0) == NULL);
u[0].re = INFINITY;
assert(block_zxz_decompose(u, 8, 1e-10, 0) == NULL);
u[0].re = 0.0;
u[0].im = NAN;
assert(block_zxz_decompose(u, 8, 1e-10, 0) == NULL);
}

int main(void) {
test_block_zxz();
test_basic_circuit();
test_errors();
test_symbolic_parameters();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,14 @@
"""

from ...._native import compile as _compile_module
from . import block_zxz as block_zxz
from . import mc_gate as mc_gate
from . import unitary as unitary
from .block_zxz import (
BlockZxzDecomposeOptions,
decompose_block_zxz,
decompose_block_zxz_with_options,
)

_decompose_module = _compile_module.transform.decompose

Expand All @@ -50,6 +56,10 @@
decompose_mc_gates_for_device = _decompose_module.decompose_mc_gates_for_device

__all__ = [
"block_zxz",
"BlockZxzDecomposeOptions",
"decompose_block_zxz",
"decompose_block_zxz_with_options",
"mc_gate",
"unitary",
"TwoQubitUnitaryDecomposeBasis",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,14 @@ from cqlib.circuit import Circuit, Instruction
from cqlib.compile.resource import ResourceLimits, ResourcePolicy
from cqlib.device import Device
from .. import TransformResult
from . import block_zxz as block_zxz
from . import mc_gate as mc_gate
from . import unitary as unitary
from .block_zxz import (
BlockZxzDecomposeOptions,
decompose_block_zxz,
decompose_block_zxz_with_options,
)

class TwoQubitUnitaryDecomposeBasis:
"""Output interaction basis for numeric two-qubit unitary synthesis."""
Expand Down Expand Up @@ -56,6 +62,7 @@ class UnitaryDecomposeConfig:
two_qubit_basis: TwoQubitUnitaryDecomposeBasis | None = None,
target_basis: list[Instruction | str] | None = None,
recurse_control_flow: bool = True,
block_zxz_options: BlockZxzDecomposeOptions | None = None,
) -> None: ...
@property
def two_qubit_basis(self) -> TwoQubitUnitaryDecomposeBasis | None:
Expand All @@ -77,6 +84,10 @@ class UnitaryDecomposeConfig:
def recurse_control_flow(self) -> bool:
"""Whether unitary gates in control-flow bodies are synthesized."""
...
@property
def block_zxz_options(self) -> BlockZxzDecomposeOptions:
"""Optimization switches for three-or-more-qubit Block-ZXZ synthesis."""
...
def __copy__(self) -> UnitaryDecomposeConfig: ...
def __deepcopy__(self, memo: dict[int, object]) -> UnitaryDecomposeConfig: ...
def __eq__(self, other: object) -> bool: ...
Expand Down Expand Up @@ -135,7 +146,7 @@ def decompose_unitaries(
circuit: Circuit,
config: UnitaryDecomposeConfig | None = None,
) -> TransformResult:
"""Synthesize matrix-backed one- and two-qubit unitary gates.
"""Synthesize matrix-backed numeric unitary gates.

Raises:
CompilerConfigError: If a unitary is unresolved, invalid, or
Expand Down Expand Up @@ -186,6 +197,10 @@ def decompose_mc_gates_for_device(
...

__all__ = [
"block_zxz",
"BlockZxzDecomposeOptions",
"decompose_block_zxz",
"decompose_block_zxz_with_options",
"mc_gate",
"unitary",
"TwoQubitUnitaryDecomposeBasis",
Expand Down
Loading
Loading