use pyo3::prelude::*;
use pyo3::types::{IntoPyDict, PyDict, PyModule};
use pyo3::wrap_pyfunction;
use pyo3::Bound;
use pyo3::PyResult;
pub mod calibration;
pub mod circuit;
pub mod de;
pub mod logging;
pub mod observable;
pub mod pso;
pub mod qng;
use calibration::calibrate_parallel_threshold;
use circuit::{qft, statevector, Circuit, Param};
use de::DE;
use logging::init_logger;
use observable::{CachedCost, Ising, Qubo};
use pso::PSO;
use qng::QNG;
use crate::evaluation::{
CircuitSource, CostObservable, OracleErrorSlot, PyCallbackObservable, PyVarianceOracle,
QmlOracleFactory, VqcOracleFactory,
};
use crate::infrastructure::execution_config::random_seed;
#[cfg(feature = "qmio")]
use crate::infrastructure::execution_config::QmioProgramFormat;
use crate::infrastructure::{
BackendConfig, BoundCircuit, Counts, ExecutionConfig, Infrastructure, InfrastructureError,
OptLevel, Planner, ShotDistributingPlanner,
};
use crate::orchestration::{
DeConfig, Method, OracleError, PsoConfig, QngConfig, Resources, RunCircuitFlow, Scheduler,
TrainFlow,
};
use polypus_optimizers::{OptimizationOutcome, VarianceOracle};
use std::sync::Arc;
use std::time::Instant;
use uuid::Uuid;
#[pyclass(module = "polypus", frozen)]
pub struct RunResult {
#[pyo3(get)]
pub counts: PyObject,
#[pyo3(get)]
pub id: String,
#[pyo3(get)]
pub seed: Option<u64>,
#[pyo3(get)]
pub backend: String,
#[pyo3(get)]
pub infrastructure: String,
}
#[pymethods]
impl RunResult {
fn __repr__(&self) -> String {
format!(
"RunResult(id={:?}, seed={:?}, backend={:?}, infrastructure={:?})",
self.id, self.seed, self.backend, self.infrastructure
)
}
}
#[pyclass(module = "polypus", frozen)]
pub struct TrainResult {
#[pyo3(get)]
pub best_params: Vec<f64>,
#[pyo3(get)]
pub best_fitness: f64,
#[pyo3(get)]
pub iterations_run: usize,
#[pyo3(get)]
pub converged: bool,
#[pyo3(get)]
pub fitness_history: Vec<f64>,
#[pyo3(get)]
pub seed: u64,
#[pyo3(get)]
pub id: String,
}
#[pymethods]
impl TrainResult {
fn __repr__(&self) -> String {
format!(
"TrainResult(id={:?}, best_fitness={}, iterations_run={}, converged={}, seed={}, best_params={:?})",
self.id, self.best_fitness, self.iterations_run, self.converged, self.seed, self.best_params
)
}
}
fn outcome_to_train_result(
py: Python<'_>,
outcome: OptimizationOutcome,
seed: u64,
id: String,
) -> PyResult<PyObject> {
Py::new(
py,
TrainResult {
best_params: outcome.best_params,
best_fitness: outcome.best_fitness,
iterations_run: outcome.iterations_run,
converged: outcome.converged,
fitness_history: outcome.fitness_history,
seed,
id,
},
)
.map(|result| result.into_any())
}
fn resolve_optimizer_seed(kwarg_seed: Option<u64>, method_seed: Option<u64>) -> u64 {
kwarg_seed.or(method_seed).unwrap_or_else(random_seed)
}
fn unique_id(base: &str) -> String {
format!("{}_{}", base, Uuid::new_v4())
}
fn log_training_start(
id: &str,
infrastructure: &str,
backend: &str,
n_qpus: u32,
shots: u32,
seed: u64,
) {
log::info!(
"training run {id} starting: infrastructure={infrastructure}, backend={backend}, \
n_qpus={n_qpus}, shots={shots}, seed={seed}"
);
}
fn method_seed(method: &Bound<'_, PyAny>) -> Option<u64> {
if let Ok(de) = method.extract::<PyRef<DE>>() {
return de.seed;
}
if let Ok(pso) = method.extract::<PyRef<PSO>>() {
return pso.seed;
}
if let Ok(qng) = method.extract::<PyRef<QNG>>() {
return qng.seed;
}
None
}
fn finish_optimization(
py: Python<'_>,
result: Result<OptimizationOutcome, OracleError>,
seed: u64,
id: String,
start: Instant,
) -> PyResult<PyObject> {
let outcome = match result {
Ok(outcome) => outcome,
Err(OracleError::Evaluation(boxed)) => {
return Err(
match boxed.downcast::<crate::evaluation::EvaluationError>() {
Ok(eval_err) => crate::exceptions::evaluation_error_to_pyerr(*eval_err),
Err(other) => crate::exceptions::EvaluationError::new_err(other.to_string()),
},
);
}
Err(OracleError::Config(config_err)) => {
log::error!("run {id}: optimizer rejected the configuration: {config_err}");
return Err(pyo3::exceptions::PyValueError::new_err(
config_err.to_string(),
));
}
};
log::info!(
"training run {id} completed: iterations_run={}, converged={}, duration={:?}",
outcome.iterations_run,
outcome.converged,
start.elapsed()
);
outcome_to_train_result(py, outcome, seed, id)
}
fn method_from_pyclass(
method: &Bound<'_, PyAny>,
errors: &OracleErrorSlot,
run_id: &str,
) -> PyResult<Method> {
if let Ok(de) = method.extract::<PyRef<DE>>() {
return Ok(Method::De(DeConfig {
generations: de.generations,
population_size: de.population_size,
tolerance: de.tolerance,
patience: de.patience,
}));
}
if let Ok(pso) = method.extract::<PyRef<PSO>>() {
return Ok(Method::Pso(PsoConfig {
generations: pso.generations,
population_size: pso.population_size,
bounds: pso.bounds,
inertia_weight: pso.inertia_weight,
cognitive_weight: pso.cognitive_weight,
social_weight: pso.social_weight,
tolerance: pso.tolerance,
}));
}
if let Ok(qng) = method.extract::<PyRef<QNG>>() {
let variance_oracle: Box<dyn VarianceOracle> = Box::new(PyVarianceOracle {
variance_function: qng.variance_function.clone_ref(method.py()),
errors: errors.clone(),
run_id: run_id.to_string(),
});
return Ok(Method::Qng(
QngConfig {
max_iters: qng.max_iters,
learning_rate: qng.learning_rate,
finite_difference_step: qng.finite_difference_step,
bounds: qng.bounds,
tikhonov_reg: qng.tikhonov_reg,
},
variance_oracle,
));
}
Err(pyo3::exceptions::PyTypeError::new_err(
"method must be an instance of polypus.DE, polypus.PSO, or polypus.QNG",
))
}
fn build_backend_config(
infrastructure: &str,
backend: &str,
sim_method: &str,
noise_model: Option<Py<PyAny>>,
nodes: u32,
cores_per_qpu: u32,
fusion: Option<bool>,
) -> PyResult<BackendConfig> {
let infrastructure_kind = Infrastructure::from_str(infrastructure)
.map_err(crate::exceptions::backend_error_to_pyerr)?;
let is_native = matches!(infrastructure_kind, Infrastructure::Local)
&& matches!(backend, "polypus" | "statevector" | "polypus_statevector");
if fusion == Some(true) && !is_native {
return Err(pyo3::exceptions::PyValueError::new_err(format!(
"fusion=True applies only to the native backend=\"polypus\"; backend \"{backend}\" \
on infrastructure \"{infrastructure}\" cannot fuse gates. Omit fusion, or pass \
fusion=False for a gate-by-gate run."
)));
}
match infrastructure_kind {
Infrastructure::Local => match backend {
"aer" | "AerSimulator" => Ok(BackendConfig::Local {
backend: "AerSimulator".to_string(),
sim_method: sim_method.to_string(),
noise_model,
}),
"polypus" | "statevector" | "polypus_statevector" => {
if noise_model.is_some() {
return Err(pyo3::exceptions::PyValueError::new_err(
"the native 'polypus' backend is a noiseless statevector simulator \
and does not accept a noise_model; use backend=\"aer\"",
));
}
Ok(BackendConfig::LocalNative {
fusion: fusion.unwrap_or(true),
})
}
other => Err(pyo3::exceptions::PyValueError::new_err(format!(
"unknown local backend '{other}'; expected \"aer\" or \"polypus\""
))),
},
Infrastructure::Cunqa => Ok(BackendConfig::Cunqa {
backend: "AerSimulator".to_string(),
sim_method: sim_method.to_string(),
nodes,
cores_per_qpu,
}),
Infrastructure::Qmio => build_qmio_backend_config(backend),
}
}
#[cfg(feature = "qmio")]
fn build_qmio_backend_config(backend: &str) -> PyResult<BackendConfig> {
const DEFAULT_QMIO_ENDPOINT: &str = "tcp://10.133.29.226:5556";
let endpoint =
std::env::var("ZMQ_SERVER").unwrap_or_else(|_| DEFAULT_QMIO_ENDPOINT.to_string());
let program_format = match backend {
"aer" | "qmio" | "openqasm" | "qasm" => QmioProgramFormat::OpenQasm,
"qir" | "qir_text" => QmioProgramFormat::QirText,
"qir_bitcode" | "qir_compiled" => QmioProgramFormat::QirBitcode,
other => {
return Err(pyo3::exceptions::PyValueError::new_err(format!(
"unknown qmio program format '{other}'; expected \"openqasm\", \"qir\", or \"qir_bitcode\""
)))
}
};
Ok(BackendConfig::Qmio {
endpoint,
program_format,
optimization: 0,
repetition_period: None,
res_format: "binary_count".to_string(),
})
}
#[cfg(not(feature = "qmio"))]
fn build_qmio_backend_config(_backend: &str) -> PyResult<BackendConfig> {
Err(pyo3::exceptions::PyValueError::new_err(
"the 'qmio' infrastructure requires compiling polypus with --features qmio",
))
}
fn is_native_backend(backend: &str) -> bool {
matches!(backend, "polypus" | "statevector" | "polypus_statevector")
}
fn validate_shots_and_qpus(shots: u32, n_qpus: u32) -> PyResult<()> {
if shots < 1 {
return Err(pyo3::exceptions::PyValueError::new_err(format!(
"shots must be >= 1, got {shots}"
)));
}
if n_qpus < 1 {
return Err(pyo3::exceptions::PyValueError::new_err(format!(
"n_qpus must be >= 1, got {n_qpus}"
)));
}
Ok(())
}
fn validate_cunqa_allocation(infrastructure: &str, nodes: u32, cores_per_qpu: u32) -> PyResult<()> {
if infrastructure != "cunqa" {
return Ok(());
}
if nodes < 1 {
return Err(pyo3::exceptions::PyValueError::new_err(format!(
"nodes must be >= 1 for the 'cunqa' infrastructure, got {nodes}"
)));
}
if cores_per_qpu < 1 {
return Err(pyo3::exceptions::PyValueError::new_err(format!(
"cores_per_qpu must be >= 1 for the 'cunqa' infrastructure, got {cores_per_qpu}"
)));
}
Ok(())
}
const MAX_ID_LEN: usize = 64;
fn validate_id(id: &str) -> PyResult<()> {
if id.is_empty() {
return Err(pyo3::exceptions::PyValueError::new_err(
"id must not be empty",
));
}
if let Some(c) = id
.chars()
.find(|c| !(c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')))
{
return Err(pyo3::exceptions::PyValueError::new_err(format!(
"id contains invalid character {c:?}; only ASCII letters, digits, \
'.', '_' and '-' are allowed (got {id:?})"
)));
}
if id.len() > MAX_ID_LEN {
return Err(pyo3::exceptions::PyValueError::new_err(format!(
"id must be at most {MAX_ID_LEN} characters, got {} ({id:?})",
id.len()
)));
}
Ok(())
}
fn extract_circuit_source(qc: &Bound<'_, PyAny>) -> CircuitSource {
if let Ok(native) = qc.extract::<PyRef<'_, Circuit>>() {
CircuitSource::Native(native.native().clone())
} else {
CircuitSource::Qiskit(qc.clone().unbind())
}
}
fn extract_bound_circuit(qc: &Bound<'_, PyAny>) -> PyResult<BoundCircuit> {
if let Ok(native) = qc.extract::<PyRef<'_, Circuit>>() {
let concrete = native.native().assign_parameters(&[]).map_err(|e| {
pyo3::exceptions::PyValueError::new_err(format!(
"circuit has unbound parameters and cannot be executed directly: {e}. \
Bind values first via to_qasm2(params) or use polypus.train"
))
})?;
return Ok(BoundCircuit::Native(concrete));
}
if let Ok(qasm) = qc.extract::<String>() {
return Ok(BoundCircuit::Qasm2(qasm));
}
Ok(BoundCircuit::Qiskit(qc.clone().unbind()))
}
fn extract_cost_observable(obj: &Bound<'_, PyAny>) -> PyResult<Arc<dyn CostObservable>> {
if let Ok(q) = obj.extract::<PyRef<'_, Qubo>>() {
let concrete = Arc::clone(&q.inner);
let obs: Arc<dyn CostObservable> = concrete;
return Ok(obs);
}
if let Ok(i) = obj.extract::<PyRef<'_, Ising>>() {
let concrete = Arc::clone(&i.inner);
let obs: Arc<dyn CostObservable> = concrete;
return Ok(obs);
}
if let Ok(cached) = obj.extract::<PyRef<'_, CachedCost>>() {
let obs: Arc<dyn CostObservable> = Arc::new(PyCallbackObservable::new(
cached.cost_fn.clone_ref(obj.py()),
true,
));
return Ok(obs);
}
if obj.is_callable() {
let obs: Arc<dyn CostObservable> =
Arc::new(PyCallbackObservable::new(obj.clone().unbind(), false));
return Ok(obs);
}
Err(pyo3::exceptions::PyTypeError::new_err(
"expectation_function must be a callable (bitstring -> float), a \
polypus.CachedCost(callable), or a polypus.Qubo / polypus.Ising observable",
))
}
#[pyfunction(signature=(qc, shots, infrastructure, n_qpus=1, nodes=1, cores_per_qpu=2, sim_method="automatic", noise_model=None, backend="aer", seed=None, fusion=None))]
pub fn run_quantum_circuit<'py>(
qc: Bound<'py, PyAny>,
shots: u32,
infrastructure: String,
n_qpus: u32,
nodes: u32,
cores_per_qpu: u32,
sim_method: &str,
noise_model: Option<Bound<'py, PyAny>>,
backend: &str,
seed: Option<u64>,
fusion: Option<bool>,
) -> PyResult<pyo3::PyObject> {
let start = Instant::now();
log::debug!(
"run_quantum_circuit called with qc: {qc:?}, shots: {shots}, \
infrastructure: {infrastructure}, n_qpus: {n_qpus}, backend: {backend}, seed: {seed:?}"
);
validate_shots_and_qpus(shots, n_qpus)?;
validate_cunqa_allocation(&infrastructure, nodes, cores_per_qpu)?;
let bound_qc = extract_bound_circuit(&qc)?;
if is_native_backend(backend) {
if let BoundCircuit::Qiskit(_) = &bound_qc {
return Err(pyo3::exceptions::PyValueError::new_err(
"the native 'polypus' backend cannot execute a Qiskit QuantumCircuit; \
pass a polypus.Circuit or an OpenQASM 2.0 string, or use backend=\"aer\"",
));
}
}
if infrastructure == "qmio" {
if let BoundCircuit::Qiskit(_) = &bound_qc {
return Err(pyo3::exceptions::PyValueError::new_err(
"the 'qmio' infrastructure runs entirely in Rust (GIL-free) and cannot \
serialize a Qiskit QuantumCircuit; pass a polypus.Circuit or an OpenQASM \
2.0 string",
));
}
}
let effective_seed: Option<u64> = if infrastructure == "qmio" {
if seed.is_some() {
return Err(pyo3::exceptions::PyValueError::new_err(
"seed is not supported for the 'qmio' infrastructure (real quantum hardware)",
));
}
None
} else {
Some(seed.unwrap_or_else(random_seed))
};
let id = unique_id(&format!("run_{}_{}", n_qpus, infrastructure));
let backend_config = build_backend_config(
&infrastructure,
backend,
sim_method,
noise_model.map(|nm| nm.unbind()),
nodes,
cores_per_qpu,
fusion,
)?;
if matches!(backend_config, BackendConfig::LocalNative { .. }) {
calibration::warn_if_using_default_threshold(qc.py())?;
}
let config = ExecutionConfig {
id: id.clone(),
shots,
n_qpus,
infrastructure: infrastructure.clone(),
backend_config,
opt_level: OptLevel::default(),
seed: effective_seed,
};
log::info!(
"run {id} starting: infrastructure={infrastructure}, backend={backend}, \
n_qpus={n_qpus}, shots={shots}, seed={effective_seed:?}"
);
let counts_result =
qc.py()
.allow_threads(move || -> Result<Vec<Counts>, InfrastructureError> {
let backend = Infrastructure::create_backend(&config)
.map_err(InfrastructureError::Backend)?;
let planner: Option<Arc<dyn Planner>> = if n_qpus == 1 {
None
} else {
Some(Arc::new(ShotDistributingPlanner))
};
let resources = Resources::new(backend, planner, Arc::new(config))?;
let scheduler = Scheduler::ephemeral(resources);
let out = scheduler.run(RunCircuitFlow {
circuits: vec![bound_qc],
shots,
});
scheduler.close();
out
});
let counts_vec = counts_result.map_err(crate::exceptions::infrastructure_error_to_pyerr)?;
log::info!("run {id} completed: duration={:?}", start.elapsed());
let counts: PyObject = Python::with_gil(|py| -> PyResult<PyObject> {
if n_qpus == 1 {
Ok(counts_vec.into_pyobject(py)?.into_any().unbind())
} else {
let total = counts_vec.into_iter().next().unwrap_or_default();
let py_dict = PyDict::new(py);
for (k, v) in total {
py_dict.set_item(k, v)?;
}
Ok(py_dict.into_any().unbind())
}
})?;
Python::with_gil(|py| {
Py::new(
py,
RunResult {
counts,
id,
seed: effective_seed,
backend: backend.to_string(),
infrastructure,
},
)
.map(|result| result.into_any())
})
}
#[pyfunction(signature = (qc, method, shots, n_qpus, dimensions, expectation_function, infrastructure, nodes, cores_per_qpu, id, sim_method="automatic", noise_model=None, backend="aer", seed=None, fusion=None))]
pub fn train<'py>(
qc: Bound<'py, PyAny>,
method: Bound<'py, PyAny>,
shots: u32,
n_qpus: u32,
dimensions: u32,
expectation_function: Bound<'py, PyAny>,
infrastructure: String,
nodes: u32,
cores_per_qpu: u32,
id: String,
sim_method: &str,
noise_model: Option<Bound<'py, PyAny>>,
backend: &str,
seed: Option<u64>,
fusion: Option<bool>,
) -> PyResult<PyObject> {
let start = Instant::now();
validate_shots_and_qpus(shots, n_qpus)?;
validate_cunqa_allocation(&infrastructure, nodes, cores_per_qpu)?;
validate_id(&id)?;
let effective_seed = resolve_optimizer_seed(seed, method_seed(&method));
let circuit_source = extract_circuit_source(&qc);
if let Some(num_params) = circuit_source.num_params() {
if num_params != dimensions as usize {
return Err(pyo3::exceptions::PyValueError::new_err(format!(
"dimensions ({dimensions}) does not match the circuit's free parameters ({num_params})"
)));
}
}
if is_native_backend(backend) {
if let CircuitSource::Qiskit(_) = &circuit_source {
return Err(pyo3::exceptions::PyValueError::new_err(
"the native 'polypus' backend requires a native polypus.Circuit; \
got a Qiskit circuit. Build it with polypus.Circuit or use backend=\"aer\"",
));
}
}
if infrastructure == "qmio" {
if let CircuitSource::Qiskit(_) = &circuit_source {
return Err(pyo3::exceptions::PyValueError::new_err(
"the 'qmio' infrastructure requires a native polypus.Circuit (GIL-free \
serialization); got a Qiskit circuit. Build it with polypus.Circuit",
));
}
}
let backend_config = build_backend_config(
&infrastructure,
backend,
sim_method,
noise_model.map(|nm| nm.unbind()),
nodes,
cores_per_qpu,
fusion,
)?;
let effective_id = unique_id(&id);
let config = Arc::new(ExecutionConfig {
id: effective_id.clone(),
shots,
n_qpus,
infrastructure: infrastructure.clone(),
backend_config,
opt_level: OptLevel::default(),
seed: Some(effective_seed),
});
log_training_start(
&effective_id,
&infrastructure,
backend,
n_qpus,
shots,
effective_seed,
);
let backend = Infrastructure::create_backend(&config)
.map_err(crate::exceptions::backend_error_to_pyerr)?;
let errors = OracleErrorSlot::new();
let observable = extract_cost_observable(&expectation_function)?;
let method_enum = method_from_pyclass(&method, &errors, &effective_id)?;
let resources = Resources::new(backend, None, Arc::clone(&config))
.map_err(crate::exceptions::infrastructure_error_to_pyerr)?;
let scheduler = Scheduler::ephemeral(resources);
let flow = TrainFlow {
factory: VqcOracleFactory {
circuit: circuit_source,
observable,
},
method: method_enum,
dimensions,
seed: effective_seed,
errors: errors.clone(),
};
let result = method.py().allow_threads(|| scheduler.run(flow));
scheduler.close();
finish_optimization(method.py(), result, effective_seed, effective_id, start)
}
#[pyfunction(name = "train", signature = (feature_map, ansatz, x_train, method, shots, n_qpus, dimensions, expectation_function, infrastructure, nodes, cores_per_qpu, id, sim_method="automatic", noise_model=None, backend="aer", seed=None))]
pub fn qml_train<'py>(
feature_map: Bound<'py, PyAny>,
ansatz: Bound<'py, PyAny>,
x_train: Bound<'py, PyAny>,
method: Bound<'py, PyAny>,
shots: u32,
n_qpus: u32,
dimensions: u32,
expectation_function: Bound<'py, PyAny>,
infrastructure: String,
nodes: u32,
cores_per_qpu: u32,
id: String,
sim_method: &str,
noise_model: Option<Bound<'py, PyAny>>,
backend: &str,
seed: Option<u64>,
) -> PyResult<PyObject> {
let start = Instant::now();
validate_shots_and_qpus(shots, n_qpus)?;
validate_cunqa_allocation(&infrastructure, nodes, cores_per_qpu)?;
validate_id(&id)?;
let effective_seed = resolve_optimizer_seed(seed, method_seed(&method));
if is_native_backend(backend) {
return Err(pyo3::exceptions::PyValueError::new_err(
"the native 'polypus' backend is not supported for qml.train (feature maps \
and ansätze are Qiskit circuits); use backend=\"aer\"",
));
}
let num_ansatz_params = ansatz.getattr("parameters")?.len()?;
if num_ansatz_params != dimensions as usize {
return Err(pyo3::exceptions::PyValueError::new_err(format!(
"dimensions ({dimensions}) does not match the ansatz's free parameters ({num_ansatz_params})"
)));
}
let py = feature_map.py();
let composed = feature_map.call_method1("compose", (&ansatz,))?;
let num_clbits: usize = composed.getattr("num_clbits")?.extract()?;
if num_clbits == 0 {
composed.call_method0("measure_all")?;
}
let fm_params = feature_map.getattr("parameters")?;
let builtins = PyModule::import(py, "builtins")?;
let fm_params_list = builtins.call_method1("list", (&fm_params,))?;
let kwargs_assign = [("inplace", false)].into_py_dict(py)?;
let mut qcs: Vec<Py<PyAny>> = Vec::new();
let fm_len = fm_params_list.len()?;
for (row_idx, row_result) in x_train.try_iter()?.enumerate() {
let row = row_result?;
let row_len = row.len()?;
if row_len != fm_len {
return Err(pyo3::exceptions::PyValueError::new_err(format!(
"x_train row {row_idx} has {row_len} features, but feature_map expects {fm_len} \
(len(feature_map.parameters))"
)));
}
let param_dict = PyDict::new(py);
for (param, val) in fm_params_list.try_iter()?.zip(row.try_iter()?) {
param_dict.set_item(param?, val?)?;
}
let bound_qc = composed
.call_method("assign_parameters", (¶m_dict,), Some(&kwargs_assign))?
.unbind();
qcs.push(bound_qc);
}
if qcs.is_empty() {
return Err(pyo3::exceptions::PyValueError::new_err(
"x_train must contain at least one training sample",
));
}
let backend_config = build_backend_config(
&infrastructure,
backend,
sim_method,
noise_model.map(|nm| nm.unbind()),
nodes,
cores_per_qpu,
None,
)?;
let effective_id = unique_id(&id);
let config = Arc::new(ExecutionConfig {
id: effective_id.clone(),
shots,
n_qpus,
infrastructure: infrastructure.clone(),
backend_config,
opt_level: OptLevel::default(),
seed: Some(effective_seed),
});
log_training_start(
&effective_id,
&infrastructure,
backend,
n_qpus,
shots,
effective_seed,
);
let backend = Infrastructure::create_backend(&config)
.map_err(crate::exceptions::backend_error_to_pyerr)?;
let errors = OracleErrorSlot::new();
let observable = extract_cost_observable(&expectation_function)?;
let method_enum = method_from_pyclass(&method, &errors, &effective_id)?;
let resources = Resources::new(backend, None, Arc::clone(&config))
.map_err(crate::exceptions::infrastructure_error_to_pyerr)?;
let scheduler = Scheduler::ephemeral(resources);
let flow = TrainFlow {
factory: QmlOracleFactory {
training_circuits: qcs,
observable,
},
method: method_enum,
dimensions,
seed: effective_seed,
errors: errors.clone(),
};
let result = py.allow_threads(|| scheduler.run(flow));
scheduler.close();
finish_optimization(py, result, effective_seed, effective_id, start)
}
#[pyfunction]
fn backend_cleanup_failures() -> u64 {
crate::infrastructure::cleanup_failure_count()
}
#[pymodule]
pub fn polypus(m: &Bound<'_, PyModule>) -> PyResult<()> {
crate::exceptions::register(m)?;
m.add_class::<DE>()?;
m.add_class::<PSO>()?;
m.add_class::<QNG>()?;
m.add_class::<Circuit>()?;
m.add_class::<Param>()?;
m.add_class::<RunResult>()?;
m.add_class::<TrainResult>()?;
m.add_class::<Qubo>()?;
m.add_class::<Ising>()?;
m.add_class::<CachedCost>()?;
m.add_function(wrap_pyfunction!(train, m)?)?;
m.add_function(wrap_pyfunction!(run_quantum_circuit, m)?)?;
m.add_function(wrap_pyfunction!(statevector, m)?)?;
m.add_function(wrap_pyfunction!(init_logger, m)?)?;
m.add_function(wrap_pyfunction!(calibrate_parallel_threshold, m)?)?;
m.add_function(wrap_pyfunction!(backend_cleanup_failures, m)?)?;
let py = m.py();
let qml = PyModule::new(py, "polypus.qml")?;
qml.add_function(wrap_pyfunction!(qml_train, &qml)?)?;
m.add("qml", &qml)?;
let sys = PyModule::import(py, "sys")?;
sys.getattr("modules")?.set_item("polypus.qml", &qml)?;
let circuits = PyModule::new(py, "polypus.circuits")?;
let templates = PyModule::new(py, "polypus.circuits.templates")?;
templates.add_function(wrap_pyfunction!(qft, &templates)?)?;
circuits.add("templates", &templates)?;
m.add("circuits", &circuits)?;
let modules = sys.getattr("modules")?;
modules.set_item("polypus.circuits", &circuits)?;
modules.set_item("polypus.circuits.templates", &templates)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use pyo3::types::PyString;
use std::collections::HashMap;
fn uniform3_qasm() -> String {
polypus_circuit::ParameterizedCircuit::new(3)
.h(0)
.h(1)
.h(2)
.measure_all()
.assign_parameters(&[])
.expect("no free parameters")
.to_qasm2()
}
fn native_run(
py: Python<'_>,
qasm: &str,
seed: Option<u64>,
) -> (Option<u64>, Vec<HashMap<String, u64>>) {
let qc = PyString::new(py, qasm).into_any();
let result = run_quantum_circuit(
qc,
500,
"local".to_string(),
1,
1,
2,
"automatic",
None,
"polypus",
seed,
None,
)
.expect("native run_quantum_circuit succeeds");
let bound = result.bind(py);
let reported = bound
.getattr("seed")
.unwrap()
.extract::<Option<u64>>()
.unwrap();
let counts = bound
.getattr("counts")
.unwrap()
.extract::<Vec<HashMap<String, u64>>>()
.unwrap();
(reported, counts)
}
#[test]
fn native_seed_round_trips_and_reproduces_counts() {
pyo3::prepare_freethreaded_python();
Python::with_gil(|py| {
let qasm = uniform3_qasm();
let (s1, c1) = native_run(py, &qasm, Some(42));
let (s2, c2) = native_run(py, &qasm, Some(42));
assert_eq!(s1, Some(42));
assert_eq!(s2, Some(42));
assert_eq!(c1, c2, "same seed must reproduce counts");
});
}
#[test]
fn native_omitted_seed_is_entropy_and_differs() {
pyo3::prepare_freethreaded_python();
Python::with_gil(|py| {
let qasm = uniform3_qasm();
let (s1, c1) = native_run(py, &qasm, None);
let (s2, c2) = native_run(py, &qasm, None);
assert!(
s1.is_some() && s2.is_some(),
"an entropy seed must be reported"
);
assert_ne!(s1, s2, "each unseeded run must draw a fresh seed");
assert_ne!(c1, c2, "unseeded runs must produce independent noise");
});
}
#[test]
fn native_manifest_reports_run_metadata() {
pyo3::prepare_freethreaded_python();
Python::with_gil(|py| {
let qc = PyString::new(py, &uniform3_qasm()).into_any();
let result = run_quantum_circuit(
qc,
100,
"local".to_string(),
1,
1,
2,
"automatic",
None,
"polypus",
Some(7),
None,
)
.expect("native run succeeds");
let bound = result.bind(py);
let get = |name: &str| bound.getattr(name).unwrap().extract::<String>().unwrap();
assert_eq!(get("backend"), "polypus");
assert_eq!(get("infrastructure"), "local");
assert!(
get("id").starts_with("run_1_local_"),
"id must keep the run_{{n}}_{{infra}}_ prefix, got {}",
get("id")
);
assert_eq!(
bound
.getattr("seed")
.unwrap()
.extract::<Option<u64>>()
.unwrap(),
Some(7)
);
});
}
#[test]
fn auto_generated_id_is_unique_per_call() {
pyo3::prepare_freethreaded_python();
Python::with_gil(|py| {
let qasm = uniform3_qasm();
let id_of = || {
let qc = PyString::new(py, &qasm).into_any();
let result = run_quantum_circuit(
qc,
100,
"local".to_string(),
1,
1,
2,
"automatic",
None,
"polypus",
Some(7),
None,
)
.expect("native run succeeds");
result
.bind(py)
.getattr("id")
.unwrap()
.extract::<String>()
.unwrap()
};
let id1 = id_of();
let id2 = id_of();
assert!(id1.starts_with("run_1_local_") && id2.starts_with("run_1_local_"));
assert_ne!(
id1, id2,
"ids from identical calls must differ (unique per run)"
);
});
}
#[test]
fn unique_id_keeps_prefix_and_is_unique_per_call() {
for base in ["run1", "qml_run", "run_1_local"] {
let id1 = unique_id(base);
let id2 = unique_id(base);
let prefix = format!("{base}_");
assert!(
id1.starts_with(&prefix) && id2.starts_with(&prefix),
"the caller-supplied id must survive as a prefix, got {id1} / {id2}"
);
assert_ne!(
id1, id2,
"ids built from an identical base must differ (unique per call)"
);
}
}
#[test]
fn seed_rejected_for_qmio_hardware() {
pyo3::prepare_freethreaded_python();
Python::with_gil(|py| {
let qasm = uniform3_qasm();
let qc = pyo3::types::PyString::new(py, &qasm).into_any();
let result = run_quantum_circuit(
qc,
100,
"qmio".to_string(),
1,
1,
2,
"automatic",
None,
"aer",
Some(3),
None,
);
assert!(
result.is_err(),
"an explicit seed must be rejected for infrastructure=qmio"
);
});
}
#[test]
fn resolve_optimizer_seed_follows_precedence() {
assert_eq!(resolve_optimizer_seed(Some(7), Some(9)), 7);
assert_eq!(resolve_optimizer_seed(None, Some(9)), 9);
assert_ne!(
resolve_optimizer_seed(None, None),
resolve_optimizer_seed(None, None)
);
}
#[test]
fn resolved_seed_drives_the_optimizer_deterministically() {
use polypus_optimizers::{
AlgorithmDifferentialEvolution, AlgorithmDifferentialEvolutionArgs, EvaluationOracle,
Optimizer,
};
struct Quadratic;
impl EvaluationOracle for Quadratic {
fn evaluate_batch(&self, candidates: &[Vec<f64>]) -> Vec<f64> {
candidates
.iter()
.map(|c| -c.iter().map(|x| (x - 0.7).powi(2)).sum::<f64>())
.collect()
}
}
let run = |kwarg: Option<u64>, field: Option<u64>| {
let seed = resolve_optimizer_seed(kwarg, field);
AlgorithmDifferentialEvolution
.optimize(AlgorithmDifferentialEvolutionArgs {
oracle: Box::new(Quadratic),
population_size: 20,
generations: 40,
dimensions: 3,
tolerance: 1e-9,
patience: 20,
seed: Some(seed),
})
.expect("valid DE args optimize successfully")
};
assert_eq!(run(Some(123), None), run(Some(123), None));
assert_eq!(run(None, Some(55)), run(None, Some(55)));
assert_ne!(run(None, None), run(None, None));
}
#[test]
fn validate_shots_and_qpus_accepts_the_minimum() {
assert!(validate_shots_and_qpus(1, 1).is_ok());
assert!(validate_shots_and_qpus(1024, 8).is_ok());
}
#[test]
fn validate_shots_and_qpus_rejects_zero() {
assert!(validate_shots_and_qpus(0, 1).is_err());
assert!(validate_shots_and_qpus(1, 0).is_err());
assert!(validate_shots_and_qpus(0, 0).is_err());
}
#[test]
fn build_backend_config_selects_the_local_variants() {
let aer = build_backend_config("local", "aer", "automatic", None, 1, 2, None)
.expect("aer is a valid local backend");
assert!(matches!(
aer,
BackendConfig::Local {
ref backend,
ref sim_method,
noise_model: None,
} if backend == "AerSimulator" && sim_method == "automatic"
));
for name in ["polypus", "statevector", "polypus_statevector"] {
let native = build_backend_config("local", name, "automatic", None, 1, 2, Some(true))
.unwrap_or_else(|_| panic!("'{name}' selects the native backend"));
assert!(matches!(
native,
BackendConfig::LocalNative { fusion: true }
));
}
}
#[test]
fn build_backend_config_forwards_fusion_for_the_native_backend() {
let with_fusion =
build_backend_config("local", "polypus", "automatic", None, 1, 2, Some(true))
.expect("polypus is a valid local backend");
assert!(matches!(
with_fusion,
BackendConfig::LocalNative { fusion: true }
));
let without_fusion =
build_backend_config("local", "polypus", "automatic", None, 1, 2, Some(false))
.expect("polypus is a valid local backend");
assert!(matches!(
without_fusion,
BackendConfig::LocalNative { fusion: false }
));
}
#[test]
fn build_backend_config_defaults_fusion_to_enabled_when_omitted() {
let native = build_backend_config("local", "polypus", "automatic", None, 1, 2, None)
.expect("polypus is a valid local backend");
assert!(matches!(
native,
BackendConfig::LocalNative { fusion: true }
));
}
#[test]
fn build_backend_config_rejects_fusion_true_on_non_fusing_backends() {
pyo3::prepare_freethreaded_python();
for (infra, backend) in [("local", "aer"), ("cunqa", "aer")] {
let err = build_backend_config(infra, backend, "automatic", None, 1, 2, Some(true))
.expect_err("fusion=True on a non-fusing backend must be rejected");
Python::with_gil(|py| {
assert!(err.is_instance_of::<pyo3::exceptions::PyValueError>(py));
assert!(
err.to_string().contains("fusion=True applies only to"),
"unexpected error: {err}"
);
});
build_backend_config(infra, backend, "automatic", None, 1, 2, Some(false))
.expect("fusion=False is accepted everywhere");
build_backend_config(infra, backend, "automatic", None, 1, 2, None)
.expect("omitted fusion is accepted everywhere");
}
}
#[test]
fn build_backend_config_rejects_an_unknown_local_backend() {
let err = build_backend_config("local", "does-not-exist", "automatic", None, 1, 2, None)
.expect_err("an unknown local backend must be rejected");
pyo3::prepare_freethreaded_python();
Python::with_gil(|py| {
assert!(err.is_instance_of::<pyo3::exceptions::PyValueError>(py));
assert!(err.to_string().contains("unknown local backend"));
});
}
#[test]
fn build_backend_config_rejects_a_noise_model_on_the_native_backend() {
pyo3::prepare_freethreaded_python();
let noise_model = Python::with_gil(|py| py.None());
let err = build_backend_config(
"local",
"polypus",
"automatic",
Some(noise_model),
1,
2,
None,
)
.expect_err("a noise model on the native backend must be rejected");
Python::with_gil(|py| {
assert!(err.is_instance_of::<pyo3::exceptions::PyValueError>(py));
assert!(
err.to_string().contains("noise_model"),
"the message must name the offending kwarg: {err}"
);
});
}
#[test]
fn build_backend_config_keeps_a_noise_model_for_aer() {
pyo3::prepare_freethreaded_python();
let noise_model = Python::with_gil(|py| py.None());
let config = build_backend_config(
"local",
"aer",
"density_matrix",
Some(noise_model),
1,
2,
None,
)
.expect("aer accepts a noise model");
assert!(matches!(
config,
BackendConfig::Local {
noise_model: Some(_),
ref sim_method,
..
} if sim_method == "density_matrix"
));
}
#[test]
fn build_backend_config_forwards_the_cunqa_allocation() {
let config = build_backend_config("cunqa", "aer", "statevector", None, 3, 4, None)
.expect("cunqa is a valid infrastructure");
assert!(matches!(
config,
BackendConfig::Cunqa {
nodes: 3,
cores_per_qpu: 4,
ref sim_method,
..
} if sim_method == "statevector"
));
}
#[test]
fn build_backend_config_rejects_an_unknown_infrastructure() {
let err = build_backend_config("quantum-cloud", "aer", "automatic", None, 1, 2, None)
.expect_err("an unknown infrastructure must be rejected");
pyo3::prepare_freethreaded_python();
Python::with_gil(|py| {
assert!(err.is_instance_of::<pyo3::exceptions::PyValueError>(py));
assert!(err.to_string().contains("unknown infrastructure"));
});
}
#[test]
fn extract_bound_circuit_reads_a_qasm_string() {
pyo3::prepare_freethreaded_python();
Python::with_gil(|py| {
let qasm = uniform3_qasm();
let bound = extract_bound_circuit(&PyString::new(py, &qasm).into_any())
.expect("a str is an OpenQASM 2.0 program");
match bound {
BoundCircuit::Qasm2(text) => assert_eq!(text, qasm),
_ => panic!("a str must become BoundCircuit::Qasm2"),
}
});
}
#[test]
fn extract_bound_circuit_treats_anything_else_as_a_qiskit_circuit() {
pyo3::prepare_freethreaded_python();
Python::with_gil(|py| {
let bound = extract_bound_circuit(py.None().bind(py))
.expect("a non-Circuit, non-str object is assumed to be a Qiskit circuit");
assert!(matches!(bound, BoundCircuit::Qiskit(_)));
});
}
#[test]
fn extract_bound_circuit_reads_a_fully_bound_native_circuit() {
pyo3::prepare_freethreaded_python();
Python::with_gil(|py| {
let circuit = Py::new(
py,
Circuit {
inner: polypus_circuit::ParameterizedCircuit::new(1)
.x(0)
.measure_all(),
},
)
.expect("the pyclass instantiates");
let bound = extract_bound_circuit(circuit.bind(py).as_any())
.expect("a parameter-free polypus.Circuit is executable as-is");
assert!(matches!(bound, BoundCircuit::Native(_)));
});
}
#[test]
fn extract_bound_circuit_rejects_a_native_circuit_with_free_parameters() {
pyo3::prepare_freethreaded_python();
Python::with_gil(|py| {
let circuit = Py::new(
py,
Circuit {
inner: polypus_circuit::ParameterizedCircuit::new(1)
.ry(0, polypus_circuit::GateParam::Param(0))
.measure_all(),
},
)
.expect("the pyclass instantiates");
let err = match extract_bound_circuit(circuit.bind(py).as_any()) {
Err(err) => err,
Ok(_) => panic!("an unbound template cannot be executed directly"),
};
assert!(err.is_instance_of::<pyo3::exceptions::PyValueError>(py));
assert!(
err.to_string().contains("unbound parameters"),
"the message must explain what to do instead: {err}"
);
});
}
}